From ed5640d8b587fbcfed7dd7967f3de04b37a76f26 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:06:44 +0200 Subject: Adding upstream version 4:7.4.7. Signed-off-by: Daniel Baumann --- include/IwyuFilter_include.yaml | 952 ++++++ include/LibreOfficeKit/LibreOfficeKit.h | 491 +++ include/LibreOfficeKit/LibreOfficeKit.hxx | 1119 ++++++ include/LibreOfficeKit/LibreOfficeKitEnums.h | 1066 ++++++ include/LibreOfficeKit/LibreOfficeKitGtk.h | 381 +++ include/LibreOfficeKit/LibreOfficeKitInit.h | 364 ++ include/LibreOfficeKit/LibreOfficeKitTypes.h | 34 + include/android/compatibility.hxx | 44 + include/animations/animationnodehelper.hxx | 78 + include/apple_remote/RemoteControl.h | 117 + include/apple_remote/RemoteMainController.h | 57 + include/avmedia/MediaControlBase.hxx | 74 + include/avmedia/avmediadllapi.h | 34 + include/avmedia/mediaitem.hxx | 169 + include/avmedia/mediaplayer.hxx | 78 + include/avmedia/mediatoolbox.hxx | 55 + include/avmedia/mediawindow.hxx | 158 + include/basegfx/DrawCommands.hxx | 158 + include/basegfx/basegfxdllapi.h | 43 + include/basegfx/color/bcolor.hxx | 185 + include/basegfx/color/bcolormodifier.hxx | 336 ++ include/basegfx/color/bcolortools.hxx | 43 + include/basegfx/curve/b2dbeziertools.hxx | 52 + include/basegfx/curve/b2dcubicbezier.hxx | 198 ++ include/basegfx/matrix/b2dhommatrix.hxx | 153 + include/basegfx/matrix/b2dhommatrixtools.hxx | 218 ++ include/basegfx/matrix/b3dhommatrix.hxx | 127 + include/basegfx/matrix/b3dhommatrixtools.hxx | 44 + include/basegfx/numeric/ftools.hxx | 209 ++ include/basegfx/pixel/bpixel.hxx | 98 + include/basegfx/point/b2dpoint.hxx | 134 + include/basegfx/point/b2ipoint.hxx | 99 + include/basegfx/point/b3dpoint.hxx | 123 + include/basegfx/polygon/WaveLine.hxx | 38 + include/basegfx/polygon/b2dlinegeometry.hxx | 147 + include/basegfx/polygon/b2dpolygon.hxx | 279 ++ include/basegfx/polygon/b2dpolygonclipper.hxx | 65 + include/basegfx/polygon/b2dpolygoncutandtouch.hxx | 47 + include/basegfx/polygon/b2dpolygontools.hxx | 529 +++ include/basegfx/polygon/b2dpolygontriangulator.hxx | 71 + include/basegfx/polygon/b2dpolypolygon.hxx | 170 + include/basegfx/polygon/b2dpolypolygoncutter.hxx | 144 + include/basegfx/polygon/b2dpolypolygontools.hxx | 297 ++ include/basegfx/polygon/b2dtrapezoid.hxx | 108 + include/basegfx/polygon/b3dpolygon.hxx | 121 + include/basegfx/polygon/b3dpolygontools.hxx | 129 + include/basegfx/polygon/b3dpolypolygon.hxx | 113 + include/basegfx/polygon/b3dpolypolygontools.hxx | 132 + include/basegfx/range/Range2D.hxx | 178 + include/basegfx/range/b1drange.hxx | 151 + include/basegfx/range/b2dconnectedranges.hxx | 239 ++ include/basegfx/range/b2dpolyrange.hxx | 93 + include/basegfx/range/b2drange.hxx | 175 + include/basegfx/range/b2drangeclipper.hxx | 39 + include/basegfx/range/b2drectangle.hxx | 33 + include/basegfx/range/b2ibox.hxx | 190 ++ include/basegfx/range/b2irange.hxx | 141 + include/basegfx/range/b2irectangle.hxx | 33 + include/basegfx/range/b3drange.hxx | 227 ++ include/basegfx/range/basicbox.hxx | 68 + include/basegfx/range/basicrange.hxx | 313 ++ include/basegfx/raster/bzpixelraster.hxx | 91 + include/basegfx/raster/rasterconvert3d.hxx | 421 +++ include/basegfx/tuple/Tuple2D.hxx | 157 + include/basegfx/tuple/Tuple3D.hxx | 134 + include/basegfx/tuple/b2dtuple.hxx | 177 + include/basegfx/tuple/b2i64tuple.hxx | 87 + include/basegfx/tuple/b2ituple.hxx | 95 + include/basegfx/tuple/b3dtuple.hxx | 237 ++ include/basegfx/tuple/b3ituple.hxx | 93 + include/basegfx/utils/b2dclipstate.hxx | 92 + include/basegfx/utils/canvastools.hxx | 165 + include/basegfx/utils/common.hxx | 33 + include/basegfx/utils/gradienttools.hxx | 399 +++ include/basegfx/utils/keystoplerp.hxx | 85 + include/basegfx/utils/lerp.hxx | 43 + include/basegfx/utils/rectcliptools.hxx | 72 + include/basegfx/utils/systemdependentdata.hxx | 107 + include/basegfx/utils/tools.hxx | 124 + include/basegfx/utils/unopolypolygon.hxx | 104 + include/basegfx/utils/zoomtools.hxx | 23 + include/basegfx/vector/b2dsize.hxx | 33 + include/basegfx/vector/b2dvector.hxx | 237 ++ include/basegfx/vector/b2enums.hxx | 65 + include/basegfx/vector/b2isize.hxx | 33 + include/basegfx/vector/b2ivector.hxx | 129 + include/basegfx/vector/b3dvector.hxx | 258 ++ include/basic/basicdllapi.h | 23 + include/basic/basicmanagerrepository.hxx | 138 + include/basic/basmgr.hxx | 221 ++ include/basic/basrdll.hxx | 43 + include/basic/codecompletecache.hxx | 93 + include/basic/modsizeexceeded.hxx | 65 + include/basic/sbdef.hxx | 79 + include/basic/sberrors.hxx | 176 + include/basic/sbmeth.hxx | 88 + include/basic/sbmod.hxx | 165 + include/basic/sbstar.hxx | 157 + include/basic/sbuno.hxx | 47 + include/basic/sbx.hxx | 213 ++ include/basic/sbxcore.hxx | 135 + include/basic/sbxdef.hxx | 219 ++ include/basic/sbxmeth.hxx | 43 + include/basic/sbxobj.hxx | 85 + include/basic/sbxvar.hxx | 336 ++ include/basic/vbahelper.hxx | 94 + include/canvas/canvastools.hxx | 560 +++ include/canvas/canvastoolsdllapi.h | 35 + include/canvas/elapsedtime.hxx | 163 + include/codemaker/codemaker.hxx | 38 + include/codemaker/commoncpp.hxx | 64 + include/codemaker/commonjava.hxx | 44 + include/codemaker/exceptiontree.hxx | 119 + include/codemaker/generatedtypeset.hxx | 70 + include/codemaker/global.hxx | 96 + include/codemaker/options.hxx | 72 + include/codemaker/typemanager.hxx | 77 + include/codemaker/unotype.hxx | 88 + include/com/sun/star/uno/Any.h | 493 +++ include/com/sun/star/uno/Any.hxx | 765 +++++ include/com/sun/star/uno/Reference.h | 571 ++++ include/com/sun/star/uno/Reference.hxx | 481 +++ include/com/sun/star/uno/Sequence.h | 361 ++ include/com/sun/star/uno/Sequence.hxx | 406 +++ include/com/sun/star/uno/Type.h | 502 +++ include/com/sun/star/uno/Type.hxx | 231 ++ include/com/sun/star/uno/genfunc.h | 62 + include/com/sun/star/uno/genfunc.hxx | 84 + .../comphelper/AccessibleImplementationHelper.hxx | 45 + include/comphelper/ChainablePropertySet.hxx | 148 + include/comphelper/ChainablePropertySetInfo.hxx | 64 + include/comphelper/DirectoryHelper.hxx | 38 + include/comphelper/IdPropArrayHelper.hxx | 106 + include/comphelper/MasterPropertySet.hxx | 135 + include/comphelper/MasterPropertySetInfo.hxx | 56 + include/comphelper/PropertyInfoHash.hxx | 57 + include/comphelper/SelectionMultiplex.hxx | 93 + include/comphelper/SetFlagContextHelper.hxx | 71 + include/comphelper/accessiblecomponenthelper.hxx | 142 + include/comphelper/accessiblecontexthelper.hxx | 219 ++ include/comphelper/accessibleeventnotifier.hxx | 116 + include/comphelper/accessiblekeybindinghelper.hxx | 70 + include/comphelper/accessibleselectionhelper.hxx | 135 + include/comphelper/accessibletexthelper.hxx | 176 + include/comphelper/accessiblewrapper.hxx | 401 +++ include/comphelper/accimplaccess.hxx | 73 + include/comphelper/anycompare.hxx | 219 ++ include/comphelper/anytohash.hxx | 48 + include/comphelper/anytostring.hxx | 45 + include/comphelper/asyncnotification.hxx | 226 ++ include/comphelper/asyncquithandler.hxx | 44 + include/comphelper/attributelist.hxx | 92 + include/comphelper/automationinvokedzone.hxx | 36 + include/comphelper/backupfilehelper.hxx | 216 ++ include/comphelper/base64.hxx | 62 + include/comphelper/basicio.hxx | 88 + include/comphelper/broadcasthelper.hxx | 51 + include/comphelper/bytereader.hxx | 44 + include/comphelper/classids.hxx | 334 ++ include/comphelper/compbase.hxx | 118 + include/comphelper/comphelperdllapi.h | 33 + include/comphelper/componentbase.hxx | 139 + include/comphelper/componentguard.hxx | 58 + include/comphelper/configuration.hxx | 342 ++ include/comphelper/configurationhelper.hxx | 239 ++ include/comphelper/configurationlistener.hxx | 121 + include/comphelper/container.hxx | 76 + include/comphelper/containermultiplexer.hxx | 106 + include/comphelper/crashzone.hxx | 70 + include/comphelper/debuggerinfo.hxx | 38 + include/comphelper/dispatchcommand.hxx | 43 + include/comphelper/docpasswordhelper.hxx | 447 +++ include/comphelper/docpasswordrequest.hxx | 110 + include/comphelper/documentconstants.hxx | 130 + include/comphelper/documentinfo.hxx | 51 + include/comphelper/doublecheckedinit.hxx | 64 + include/comphelper/embeddedobjectcontainer.hxx | 193 ++ include/comphelper/enumhelper.hxx | 122 + include/comphelper/eventattachermgr.hxx | 48 + include/comphelper/evtlistenerhlp.hxx | 49 + include/comphelper/evtmethodhelper.hxx | 32 + include/comphelper/extract.hxx | 113 + include/comphelper/fileformat.h | 34 + include/comphelper/fileurl.hxx | 36 + include/comphelper/flagguard.hxx | 80 + include/comphelper/genericpropertyset.hxx | 43 + include/comphelper/getexpandeduri.hxx | 42 + include/comphelper/graphicmimetype.hxx | 49 + include/comphelper/guarding.hxx | 55 + include/comphelper/hash.hxx | 121 + include/comphelper/indexedpropertyvalues.hxx | 55 + include/comphelper/interaction.hxx | 119 + include/comphelper/interfacecontainer2.hxx | 290 ++ include/comphelper/interfacecontainer3.hxx | 379 +++ include/comphelper/interfacecontainer4.hxx | 401 +++ include/comphelper/logging.hxx | 460 +++ include/comphelper/lok.hxx | 117 + include/comphelper/make_shared_from_uno.hxx | 68 + include/comphelper/mimeconfighelper.hxx | 142 + include/comphelper/multicontainer2.hxx | 133 + include/comphelper/multiinterfacecontainer3.hxx | 217 ++ include/comphelper/multiinterfacecontainer4.hxx | 190 ++ include/comphelper/namecontainer.hxx | 40 + include/comphelper/namedvaluecollection.hxx | 322 ++ include/comphelper/newarray.hxx | 42 + include/comphelper/numberedcollection.hxx | 168 + include/comphelper/numbers.hxx | 56 + include/comphelper/ofopxmlhelper.hxx | 101 + include/comphelper/oslfile2streamwrap.hxx | 78 + include/comphelper/parallelsort.hxx | 373 ++ include/comphelper/processfactory.hxx | 72 + include/comphelper/profilezone.hxx | 92 + include/comphelper/propagg.hxx | 325 ++ include/comphelper/proparrhlp.hxx | 141 + include/comphelper/property.hxx | 131 + include/comphelper/propertybag.hxx | 226 ++ include/comphelper/propertycontainer.hxx | 87 + include/comphelper/propertycontainerhelper.hxx | 197 ++ include/comphelper/propertysequence.hxx | 62 + include/comphelper/propertysethelper.hxx | 96 + include/comphelper/propertysetinfo.hxx | 123 + include/comphelper/propertystatecontainer.hxx | 110 + include/comphelper/propertyvalue.hxx | 45 + include/comphelper/propmultiplex.hxx | 115 + include/comphelper/propstate.hxx | 102 + include/comphelper/proxyaggregation.hxx | 218 ++ include/comphelper/random.hxx | 39 + include/comphelper/refcountedmutex.hxx | 43 + include/comphelper/scopeguard.hxx | 92 + include/comphelper/seekableinput.hxx | 83 + include/comphelper/seqstream.hxx | 135 + include/comphelper/sequence.hxx | 322 ++ include/comphelper/sequenceashashmap.hxx | 426 +++ include/comphelper/servicedecl.hxx | 155 + include/comphelper/servicehelper.hxx | 152 + include/comphelper/sharedmutex.hxx | 77 + include/comphelper/simplefileaccessinteraction.hxx | 52 + include/comphelper/solarmutex.hxx | 98 + include/comphelper/stillreadwriteinteraction.hxx | 62 + include/comphelper/stl_types.hxx | 176 + include/comphelper/storagehelper.hxx | 206 ++ include/comphelper/streamsection.hxx | 79 + include/comphelper/string.hxx | 386 +++ include/comphelper/synchronousdispatch.hxx | 64 + include/comphelper/syntaxhighlight.hxx | 84 + include/comphelper/threadpool.hxx | 114 + include/comphelper/traceevent.hxx | 222 ++ include/comphelper/types.hxx | 88 + include/comphelper/unique_disposing_ptr.hxx | 187 + include/comphelper/uno3.hxx | 169 + include/comphelper/unwrapargs.hxx | 122 + include/comphelper/weak.hxx | 64 + include/comphelper/weakbag.hxx | 84 + include/comphelper/weakeventlistener.hxx | 183 + include/comphelper/windowsStart.hxx | 27 + include/comphelper/windowsdebugoutput.hxx | 796 +++++ include/comphelper/windowserrorstring.hxx | 68 + include/comphelper/xmlsechelper.hxx | 46 + include/comphelper/xmltools.hxx | 24 + include/connectivity/BlobHelper.hxx | 41 + include/connectivity/CommonTools.hxx | 167 + include/connectivity/ConnectionWrapper.hxx | 92 + include/connectivity/DriversConfig.hxx | 82 + include/connectivity/FValue.hxx | 490 +++ include/connectivity/IParseContext.hxx | 101 + include/connectivity/PColumn.hxx | 148 + include/connectivity/TColumnsHelper.hxx | 62 + include/connectivity/TIndexes.hxx | 49 + include/connectivity/TKeys.hxx | 57 + include/connectivity/TTableHelper.hxx | 168 + include/connectivity/conncleanup.hxx | 90 + include/connectivity/dbcharset.hxx | 149 + include/connectivity/dbconversion.hxx | 185 + include/connectivity/dbexception.hxx | 332 ++ include/connectivity/dbmetadata.hxx | 194 ++ include/connectivity/dbtools.hxx | 867 +++++ include/connectivity/dbtoolsdllapi.hxx | 35 + include/connectivity/filtermanager.hxx | 114 + include/connectivity/formattedcolumnvalue.hxx | 98 + include/connectivity/internalnode.hxx | 51 + include/connectivity/odbc.hxx | 94 + include/connectivity/parameters.hxx | 415 +++ include/connectivity/paramwrapper.hxx | 196 ++ include/connectivity/predicateinput.hxx | 129 + include/connectivity/sdbcx/IRefreshable.hxx | 56 + include/connectivity/sdbcx/VCollection.hxx | 225 ++ include/connectivity/sdbcx/VColumn.hxx | 116 + include/connectivity/sdbcx/VDescriptor.hxx | 83 + include/connectivity/sdbcx/VTable.hxx | 142 + include/connectivity/sdbcx/VView.hxx | 93 + include/connectivity/sqlbison_exports.hxx | 21 + include/connectivity/sqlerror.hxx | 239 ++ include/connectivity/sqliterator.hxx | 341 ++ include/connectivity/sqlnode.hxx | 455 +++ include/connectivity/sqlparse.hxx | 230 ++ include/connectivity/sqlscan.hxx | 67 + include/connectivity/standardsqlstate.hxx | 57 + include/connectivity/statementcomposer.hxx | 105 + include/connectivity/warningscontainer.hxx | 84 + include/cppcanvas/basegfxfactory.hxx | 76 + include/cppcanvas/bitmap.hxx | 70 + include/cppcanvas/bitmapcanvas.hxx | 49 + include/cppcanvas/canvas.hxx | 103 + include/cppcanvas/canvasgraphic.hxx | 80 + include/cppcanvas/color.hxx | 70 + include/cppcanvas/cppcanvasdllapi.h | 31 + include/cppcanvas/customsprite.hxx | 44 + include/cppcanvas/polypolygon.hxx | 76 + include/cppcanvas/renderer.hxx | 140 + include/cppcanvas/sprite.hxx | 96 + include/cppcanvas/spritecanvas.hxx | 63 + include/cppcanvas/vclfactory.hxx | 87 + include/cppu/Enterable.hxx | 112 + include/cppu/EnvDcp.hxx | 70 + include/cppu/EnvGuards.hxx | 107 + include/cppu/Map.hxx | 109 + include/cppu/cppudllapi.h | 24 + include/cppu/helper/purpenv/Environment.hxx | 46 + include/cppu/helper/purpenv/Mapping.hxx | 66 + include/cppu/macros.hxx | 64 + include/cppu/unotype.hxx | 412 +++ include/cppuhelper/TODO | 3 + include/cppuhelper/access_control.hxx | 115 + include/cppuhelper/basemutex.hxx | 47 + include/cppuhelper/bootstrap.hxx | 169 + include/cppuhelper/compbase.hxx | 133 + include/cppuhelper/compbase1.hxx | 152 + include/cppuhelper/compbase10.hxx | 152 + include/cppuhelper/compbase11.hxx | 152 + include/cppuhelper/compbase12.hxx | 152 + include/cppuhelper/compbase2.hxx | 153 + include/cppuhelper/compbase3.hxx | 152 + include/cppuhelper/compbase4.hxx | 152 + include/cppuhelper/compbase5.hxx | 152 + include/cppuhelper/compbase6.hxx | 152 + include/cppuhelper/compbase7.hxx | 152 + include/cppuhelper/compbase8.hxx | 152 + include/cppuhelper/compbase9.hxx | 151 + include/cppuhelper/compbase_ex.hxx | 162 + include/cppuhelper/component.hxx | 110 + include/cppuhelper/component_context.hxx | 97 + include/cppuhelper/cppuhelperdllapi.h | 38 + include/cppuhelper/exc_hlp.hxx | 95 + include/cppuhelper/factory.hxx | 278 ++ include/cppuhelper/findsofficepath.h | 49 + include/cppuhelper/implbase.hxx | 186 + include/cppuhelper/implbase1.hxx | 311 ++ include/cppuhelper/implbase10.hxx | 317 ++ include/cppuhelper/implbase11.hxx | 318 ++ include/cppuhelper/implbase12.hxx | 319 ++ include/cppuhelper/implbase13.hxx | 320 ++ include/cppuhelper/implbase2.hxx | 308 ++ include/cppuhelper/implbase3.hxx | 310 ++ include/cppuhelper/implbase4.hxx | 311 ++ include/cppuhelper/implbase5.hxx | 312 ++ include/cppuhelper/implbase6.hxx | 313 ++ include/cppuhelper/implbase7.hxx | 314 ++ include/cppuhelper/implbase8.hxx | 315 ++ include/cppuhelper/implbase9.hxx | 316 ++ include/cppuhelper/implbase_ex.hxx | 167 + include/cppuhelper/implbase_ex_post.hxx | 172 + include/cppuhelper/implbase_ex_pre.hxx | 37 + include/cppuhelper/implementationentry.hxx | 115 + include/cppuhelper/interfacecontainer.h | 614 ++++ include/cppuhelper/interfacecontainer.hxx | 197 ++ include/cppuhelper/propertysetmixin.hxx | 423 +++ include/cppuhelper/propshlp.hxx | 729 ++++ include/cppuhelper/proptypehlp.h | 62 + include/cppuhelper/proptypehlp.hxx | 286 ++ include/cppuhelper/queryinterface.hxx | 526 +++ include/cppuhelper/shlib.hxx | 87 + include/cppuhelper/supportsservice.hxx | 53 + include/cppuhelper/typeprovider.hxx | 232 ++ include/cppuhelper/unourl.hxx | 188 ++ include/cppuhelper/weak.hxx | 176 + include/cppuhelper/weakagg.hxx | 107 + include/cppuhelper/weakref.hxx | 228 ++ include/cppunittester/protectorfactory.hxx | 41 + include/cui/cuicharmap.hxx | 194 ++ include/cui/cuidllapi.h | 23 + include/cui/numberingpreview.hxx | 31 + include/dbaccess/AsynchronousLink.hxx | 60 + include/dbaccess/IController.hxx | 120 + include/dbaccess/controllerframe.hxx | 79 + include/dbaccess/dataview.hxx | 91 + include/dbaccess/dbaccessdllapi.h | 34 + include/dbaccess/dbaundomanager.hxx | 111 + include/dbaccess/dbsubcomponentcontroller.hxx | 208 ++ include/dbaccess/genericcontroller.hxx | 506 +++ include/default.rc | 64 + include/desktop/crashreport.hxx | 118 + include/desktop/dllapi.h | 30 + include/desktop/exithelper.h | 37 + include/desktop/minidump.hxx | 35 + include/drawinglayer/XShapeDumper.hxx | 29 + include/drawinglayer/animation/animationtiming.hxx | 132 + .../attribute/fillgradientattribute.hxx | 83 + .../attribute/fillgraphicattribute.hxx | 68 + .../drawinglayer/attribute/fillhatchattribute.hxx | 90 + include/drawinglayer/attribute/fontattribute.hxx | 76 + include/drawinglayer/attribute/lineattribute.hxx | 75 + .../attribute/linestartendattribute.hxx | 69 + .../drawinglayer/attribute/materialattribute3d.hxx | 78 + .../drawinglayer/attribute/sdrallattribute3d.hxx | 71 + .../drawinglayer/attribute/sdrfillattribute.hxx | 88 + .../attribute/sdrfillgraphicattribute.hxx | 94 + .../drawinglayer/attribute/sdrglowattribute.hxx | 45 + .../drawinglayer/attribute/sdrlightattribute3d.hxx | 75 + .../attribute/sdrlightingattribute3d.hxx | 86 + .../drawinglayer/attribute/sdrlineattribute.hxx | 89 + .../attribute/sdrlinestartendattribute.hxx | 88 + .../attribute/sdrobjectattribute3d.hxx | 92 + .../drawinglayer/attribute/sdrsceneattribute3d.hxx | 80 + .../drawinglayer/attribute/sdrshadowattribute.hxx | 83 + include/drawinglayer/attribute/strokeattribute.hxx | 63 + include/drawinglayer/converters.hxx | 42 + include/drawinglayer/drawinglayerdllapi.h | 30 + .../drawinglayer/geometry/viewinformation2d.hxx | 150 + .../drawinglayer/geometry/viewinformation3d.hxx | 162 + .../BufferedDecompositionPrimitive2D.hxx | 115 + include/drawinglayer/primitive2d/CommonTypes.hxx | 33 + .../primitive2d/PolyPolygonColorPrimitive2D.hxx | 67 + .../primitive2d/PolyPolygonGradientPrimitive2D.hxx | 76 + .../primitive2d/PolyPolygonGraphicPrimitive2D.hxx | 73 + .../primitive2d/PolyPolygonHairlinePrimitive2D.hxx | 73 + .../primitive2d/PolyPolygonHatchPrimitive2D.hxx | 83 + .../primitive2d/PolyPolygonMarkerPrimitive2D.hxx | 82 + .../PolyPolygonSelectionPrimitive2D.hxx | 86 + .../primitive2d/PolyPolygonStrokePrimitive2D.hxx | 82 + .../primitive2d/PolygonHairlinePrimitive2D.hxx | 68 + .../primitive2d/PolygonMarkerPrimitive2D.hxx | 91 + .../primitive2d/PolygonStrokeArrowPrimitive2D.hxx | 78 + .../primitive2d/PolygonStrokePrimitive2D.hxx | 83 + .../primitive2d/PolygonWavePrimitive2D.hxx | 72 + .../primitive2d/Primitive2DContainer.hxx | 96 + .../primitive2d/Primitive2DVisitor.hxx | 41 + include/drawinglayer/primitive2d/Tools.hxx | 51 + .../primitive2d/animatedprimitive2d.hxx | 158 + .../primitive2d/backgroundcolorprimitive2d.hxx | 84 + .../drawinglayer/primitive2d/baseprimitive2d.hxx | 211 ++ .../drawinglayer/primitive2d/bitmapprimitive2d.hxx | 78 + .../primitive2d/borderlineprimitive2d.hxx | 146 + .../primitive2d/controlprimitive2d.hxx | 117 + .../primitive2d/discretebitmapprimitive2d.hxx | 70 + .../primitive2d/discreteshadowprimitive2d.hxx | 113 + .../primitive2d/drawinglayer_primitivetypes2d.hxx | 110 + .../primitive2d/embedded3dprimitive2d.hxx | 113 + .../drawinglayer/primitive2d/epsprimitive2d.hxx | 69 + .../primitive2d/fillgradientprimitive2d.hxx | 114 + .../primitive2d/fillgraphicprimitive2d.hxx | 80 + .../primitive2d/fillhatchprimitive2d.hxx | 97 + .../drawinglayer/primitive2d/glowprimitive2d.hxx | 58 + .../primitive2d/graphicprimitive2d.hxx | 87 + .../drawinglayer/primitive2d/gridprimitive2d.hxx | 111 + .../drawinglayer/primitive2d/groupprimitive2d.hxx | 93 + .../primitive2d/helplineprimitive2d.hxx | 106 + .../primitive2d/hiddengeometryprimitive2d.hxx | 56 + .../drawinglayer/primitive2d/invertprimitive2d.hxx | 51 + .../primitive2d/markerarrayprimitive2d.hxx | 79 + .../drawinglayer/primitive2d/maskprimitive2d.hxx | 71 + .../drawinglayer/primitive2d/mediaprimitive2d.hxx | 87 + .../primitive2d/metafileprimitive2d.hxx | 90 + .../primitive2d/modifiedcolorprimitive2d.hxx | 71 + .../primitive2d/objectinfoprimitive2d.hxx | 65 + .../primitive2d/pagehierarchyprimitive2d.hxx | 46 + .../primitive2d/pagepreviewprimitive2d.hxx | 90 + .../primitive2d/patternfillprimitive2d.hxx | 104 + .../primitive2d/pointarrayprimitive2d.hxx | 74 + .../drawinglayer/primitive2d/primitivetools2d.hxx | 151 + .../drawinglayer/primitive2d/sceneprimitive2d.hxx | 147 + .../primitive2d/sdrdecompositiontools2d.hxx | 62 + .../drawinglayer/primitive2d/shadowprimitive2d.hxx | 85 + .../primitive2d/softedgeprimitive2d.hxx | 51 + .../primitive2d/structuretagprimitive2d.hxx | 80 + .../primitive2d/svggradientprimitive2d.hxx | 369 ++ .../drawinglayer/primitive2d/textbreakuphelper.hxx | 75 + .../primitive2d/textdecoratedprimitive2d.hxx | 124 + .../primitive2d/textenumsprimitive2d.hxx | 95 + .../primitive2d/texthierarchyprimitive2d.hxx | 179 + .../drawinglayer/primitive2d/textlayoutdevice.hxx | 127 + .../drawinglayer/primitive2d/textprimitive2d.hxx | 184 + .../primitive2d/transformprimitive2d.hxx | 75 + .../primitive2d/transparenceprimitive2d.hxx | 80 + .../primitive2d/unifiedtransparenceprimitive2d.hxx | 68 + .../primitive2d/wrongspellprimitive2d.hxx | 83 + include/drawinglayer/primitive3d/Tools.hxx | 21 + .../drawinglayer/primitive3d/baseprimitive3d.hxx | 210 ++ .../primitive3d/drawinglayer_primitivetypes3d.hxx | 54 + .../drawinglayer/primitive3d/groupprimitive3d.hxx | 77 + .../primitive3d/modifiedcolorprimitive3d.hxx | 65 + .../primitive3d/polygonprimitive3d.hxx | 121 + .../primitive3d/polypolygonprimitive3d.hxx | 78 + .../primitive3d/sdrcubeprimitive3d.hxx | 61 + .../primitive3d/sdrextrudelathetools3d.hxx | 122 + .../primitive3d/sdrextrudeprimitive3d.hxx | 122 + .../primitive3d/sdrlatheprimitive3d.hxx | 128 + .../primitive3d/sdrpolypolygonprimitive3d.hxx | 76 + .../drawinglayer/primitive3d/sdrprimitive3d.hxx | 86 + .../primitive3d/sdrsphereprimitive3d.hxx | 75 + .../primitive3d/transformprimitive3d.hxx | 70 + .../drawinglayer/processor2d/baseprocessor2d.hxx | 200 ++ .../processor2d/contourextractor2d.hxx | 62 + .../processor2d/hittestprocessor2d.hxx | 96 + .../processor2d/linegeometryextractor2d.hxx | 61 + .../processor2d/objectinfoextractor2d.hxx | 54 + .../drawinglayer/processor2d/processor2dtools.hxx | 71 + .../processor2d/processorfromoutputdevice.hxx | 47 + .../processor2d/textaspolygonextractor2d.hxx | 94 + .../drawinglayer/processor3d/baseprocessor3d.hxx | 71 + .../processor3d/cutfindprocessor3d.hxx | 73 + include/drawinglayer/tools/primitive2dxmldump.hxx | 53 + include/editeng/AccessibleComponentBase.hxx | 109 + include/editeng/AccessibleContextBase.hxx | 341 ++ include/editeng/AccessibleEditableTextPara.hxx | 388 +++ include/editeng/AccessibleParaManager.hxx | 272 ++ include/editeng/AccessibleSelectionBase.hxx | 67 + include/editeng/AccessibleStaticTextBase.hxx | 233 ++ include/editeng/CustomPropertyField.hxx | 61 + include/editeng/SpellPortions.hxx | 90 + include/editeng/Trie.hxx | 39 + include/editeng/UnoForbiddenCharsTable.hxx | 58 + include/editeng/acorrcfg.hxx | 123 + include/editeng/adjustitem.hxx | 143 + include/editeng/autokernitem.hxx | 51 + include/editeng/blinkitem.hxx | 48 + include/editeng/borderline.hxx | 246 ++ include/editeng/boxitem.hxx | 271 ++ include/editeng/brushitem.hxx | 123 + include/editeng/bulletitem.hxx | 94 + include/editeng/charhiddenitem.hxx | 46 + include/editeng/charreliefitem.hxx | 59 + include/editeng/charrotateitem.hxx | 107 + include/editeng/charscaleitem.hxx | 57 + include/editeng/cmapitem.hxx | 59 + include/editeng/colritem.hxx | 115 + include/editeng/contouritem.hxx | 50 + include/editeng/crossedoutitem.hxx | 67 + include/editeng/editdata.hxx | 359 ++ include/editeng/editeng.hxx | 655 ++++ include/editeng/editengdllapi.h | 34 + include/editeng/editerr.hxx | 29 + include/editeng/editids.hrc | 162 + include/editeng/editobj.hxx | 138 + include/editeng/editrids.hrc | 318 ++ include/editeng/editstat.hxx | 144 + include/editeng/editund2.hxx | 71 + include/editeng/editview.hxx | 382 +++ include/editeng/edtdlg.hxx | 105 + include/editeng/eedata.hxx | 48 + include/editeng/eeitem.hxx | 148 + include/editeng/eerdll.hxx | 52 + include/editeng/emphasismarkitem.hxx | 60 + include/editeng/escapementitem.hxx | 97 + include/editeng/fhgtitem.hxx | 92 + include/editeng/fieldupdater.hxx | 46 + include/editeng/flditem.hxx | 438 +++ include/editeng/flstitem.hxx | 65 + include/editeng/fontitem.hxx | 113 + include/editeng/forbiddencharacterstable.hxx | 52 + include/editeng/forbiddenruleitem.hxx | 49 + include/editeng/formatbreakitem.hxx | 71 + include/editeng/frmdir.hxx | 62 + include/editeng/frmdiritem.hxx | 64 + include/editeng/hangulhanja.hxx | 288 ++ include/editeng/hngpnctitem.hxx | 48 + include/editeng/hyphenzoneitem.hxx | 92 + include/editeng/itemtype.hxx | 41 + include/editeng/justifyitem.hxx | 104 + include/editeng/keepitem.hxx | 59 + include/editeng/kernitem.hxx | 58 + include/editeng/langitem.hxx | 68 + include/editeng/legacyitem.hxx | 193 ++ include/editeng/lineitem.hxx | 71 + include/editeng/lrspitem.hxx | 168 + include/editeng/lspcitem.hxx | 101 + include/editeng/macros.hxx | 17 + include/editeng/measfld.hxx | 48 + include/editeng/memberids.h | 195 ++ include/editeng/misspellrange.hxx | 38 + include/editeng/nhypitem.hxx | 42 + include/editeng/numdef.hxx | 28 + include/editeng/numitem.hxx | 359 ++ include/editeng/opaqitem.hxx | 53 + include/editeng/optitems.hxx | 54 + include/editeng/orphitem.hxx | 50 + include/editeng/outliner.hxx | 989 ++++++ include/editeng/outlobj.hxx | 204 ++ include/editeng/overflowingtxt.hxx | 130 + include/editeng/paperinf.hxx | 66 + include/editeng/paragraphdata.hxx | 48 + include/editeng/paravertalignitem.hxx | 60 + include/editeng/pbinitem.hxx | 58 + include/editeng/pgrditem.hxx | 51 + include/editeng/pmdlitem.hxx | 70 + include/editeng/postitem.hxx | 67 + include/editeng/prntitem.hxx | 55 + include/editeng/protitem.hxx | 76 + include/editeng/rsiditem.hxx | 37 + include/editeng/scriptspaceitem.hxx | 50 + include/editeng/scripttypeitem.hxx | 52 + include/editeng/section.hxx | 35 + include/editeng/shaditem.hxx | 84 + include/editeng/shdditem.hxx | 53 + include/editeng/sizeitem.hxx | 69 + include/editeng/spltitem.hxx | 61 + include/editeng/splwrap.hxx | 113 + include/editeng/svxacorr.hxx | 447 +++ include/editeng/svxenum.hxx | 218 ++ include/editeng/svxfont.hxx | 119 + include/editeng/svxrtf.hxx | 295 ++ include/editeng/swafopt.hxx | 140 + include/editeng/tstpitem.hxx | 149 + include/editeng/twolinesitem.hxx | 63 + include/editeng/txtrange.hxx | 83 + include/editeng/udlnitem.hxx | 102 + include/editeng/ulspitem.hxx | 93 + include/editeng/unoedhlp.hxx | 156 + include/editeng/unoedprx.hxx | 172 + include/editeng/unoedsrc.hxx | 533 +++ include/editeng/unofdesc.hxx | 50 + include/editeng/unofield.hxx | 111 + include/editeng/unofored.hxx | 93 + include/editeng/unoforou.hxx | 121 + include/editeng/unoipset.hxx | 87 + include/editeng/unolingu.hxx | 133 + include/editeng/unonames.hxx | 52 + include/editeng/unonrule.hxx | 90 + include/editeng/unoprnms.hxx | 361 ++ include/editeng/unotext.hxx | 677 ++++ include/editeng/unoviwou.hxx | 56 + include/editeng/urlfieldhelper.hxx | 28 + include/editeng/wghtitem.hxx | 74 + include/editeng/widwitem.hxx | 50 + include/editeng/writingmodeitem.hxx | 55 + include/editeng/wrlmitem.hxx | 52 + include/editeng/xmlcnitm.hxx | 73 + include/embeddedobj/embeddedupdate.hxx | 52 + include/embeddedobj/embobjdllapi.h | 20 + include/filter/dllapi.h | 34 + include/filter/msfilter/classids.hxx | 47 + include/filter/msfilter/countryid.hxx | 307 ++ include/filter/msfilter/dffpropset.hxx | 74 + include/filter/msfilter/dffrecordheader.hxx | 64 + include/filter/msfilter/escherex.hxx | 1221 +++++++ include/filter/msfilter/mscodec.hxx | 499 +++ include/filter/msfilter/msdffimp.hxx | 809 +++++ include/filter/msfilter/msfilterdllapi.h | 35 + include/filter/msfilter/msocximex.hxx | 84 + include/filter/msfilter/msoleexp.hxx | 56 + include/filter/msfilter/mstoolbar.hxx | 355 ++ include/filter/msfilter/msvbahelper.hxx | 116 + include/filter/msfilter/rtfutil.hxx | 78 + include/filter/msfilter/svdfppt.hxx | 1488 ++++++++ include/filter/msfilter/svxmsbas.hxx | 73 + include/filter/msfilter/util.hxx | 145 + include/filter/msfilter/ww8fields.hxx | 130 + include/formula/ExternalReferenceHelper.hxx | 44 + include/formula/FormulaCompiler.hxx | 506 +++ include/formula/FormulaOpCodeMapperObj.hxx | 79 + include/formula/IControlReferenceHandler.hxx | 44 + include/formula/IFunctionDescription.hxx | 161 + include/formula/compiler.hxx | 531 +++ include/formula/errorcodes.hxx | 190 ++ include/formula/formdata.hxx | 71 + include/formula/formula.hxx | 125 + include/formula/formuladllapi.h | 34 + include/formula/formulahelper.hxx | 86 + include/formula/funcutl.hxx | 182 + include/formula/funcvarargs.h | 49 + include/formula/grammar.hxx | 247 ++ include/formula/opcode.hxx | 995 ++++++ include/formula/paramclass.hxx | 81 + include/formula/token.hxx | 482 +++ include/formula/tokenarray.hxx | 669 ++++ include/formula/types.hxx | 34 + include/formula/vectortoken.hxx | 110 + include/fpicker/fpsofficeResMgr.hxx | 15 + include/fpicker/strings.hrc | 42 + .../ContextChangeEventMultiplexerTunnel.hxx | 30 + include/framework/actiontriggerhelper.hxx | 65 + include/framework/addonsoptions.hxx | 264 ++ include/framework/configimporter.hxx | 49 + include/framework/desktop.hxx | 455 +++ include/framework/dispatchhelper.hxx | 111 + include/framework/documentundoguard.hxx | 61 + include/framework/framecontainer.hxx | 91 + include/framework/framelistanalyzer.hxx | 204 ++ include/framework/fwkdllapi.h | 22 + include/framework/gate.hxx | 146 + include/framework/generictoolbarcontroller.hxx | 73 + include/framework/imutex.hxx | 43 + include/framework/interaction.hxx | 105 + include/framework/sfxhelperfunctions.hxx | 107 + include/framework/titlehelper.hxx | 181 + include/framework/transactionmanager.hxx | 123 + include/framework/undomanagerhelper.hxx | 162 + include/helpcompiler/HelpIndexer.hxx | 90 + include/helpcompiler/HelpSearch.hxx | 42 + include/helpcompiler/compilehelp.hxx | 74 + include/helpcompiler/dllapi.h | 34 + include/i18nlangtag/applelangid.hxx | 145 + include/i18nlangtag/i18nlangtagdllapi.h | 34 + include/i18nlangtag/lang.h | 803 +++++ include/i18nlangtag/languagetag.hxx | 592 ++++ include/i18nlangtag/languagetagicu.hxx | 73 + include/i18nlangtag/mslangid.hxx | 338 ++ include/i18npool/reservedconstants.hxx | 29 + include/i18nutil/calendar.hxx | 23 + include/i18nutil/casefolding.hxx | 91 + include/i18nutil/i18nutildllapi.h | 34 + include/i18nutil/oneToOneMapping.hxx | 90 + include/i18nutil/paper.hxx | 158 + include/i18nutil/scripttypedetector.hxx | 38 + include/i18nutil/searchopt.hxx | 138 + include/i18nutil/transliteration.hxx | 133 + include/i18nutil/unicode.hxx | 132 + include/i18nutil/widthfolding.hxx | 57 + include/jvmaccess/classpath.hxx | 87 + include/jvmaccess/jvmaccessdllapi.h | 24 + include/jvmaccess/unovirtualmachine.hxx | 100 + include/jvmaccess/virtualmachine.hxx | 154 + include/jvmfwk/framework.hxx | 671 ++++ include/jvmfwk/jvmfwkdllapi.hxx | 23 + include/linguistic/hyphdta.hxx | 110 + include/linguistic/lngdllapi.h | 35 + include/linguistic/lngprophelp.hxx | 306 ++ include/linguistic/lngprops.hxx | 31 + include/linguistic/misc.hxx | 196 ++ include/linguistic/spelldta.hxx | 95 + include/o3tl/any.hxx | 325 ++ include/o3tl/char16_t2wchar_t.hxx | 59 + include/o3tl/cow_wrapper.hxx | 387 +++ include/o3tl/cppunittraitshelper.hxx | 28 + include/o3tl/deleter.hxx | 68 + include/o3tl/enumarray.hxx | 140 + include/o3tl/enumrange.hxx | 87 + include/o3tl/float_int_conversion.hxx | 72 + include/o3tl/functional.hxx | 63 + include/o3tl/hash_combine.hxx | 55 + include/o3tl/intcmp.hxx | 132 + include/o3tl/lazy_update.hxx | 89 + include/o3tl/lru_map.hxx | 299 ++ include/o3tl/make_shared.hxx | 46 + include/o3tl/numeric.hxx | 28 + include/o3tl/runtimetooustring.hxx | 47 + include/o3tl/safeCoInitUninit.hxx | 58 + include/o3tl/safeint.hxx | 236 ++ include/o3tl/sorted_vector.hxx | 421 +++ include/o3tl/span.hxx | 100 + include/o3tl/sprintf.hxx | 41 + include/o3tl/string_view.hxx | 487 +++ include/o3tl/strong_int.hxx | 156 + include/o3tl/temporary.hxx | 27 + include/o3tl/typed_flags_set.hxx | 325 ++ include/o3tl/underlyingenumvalue.hxx | 29 + include/o3tl/unit_conversion.hxx | 261 ++ include/o3tl/unreachable.hxx | 48 + include/o3tl/unsafe_downcast.hxx | 35 + include/o3tl/vector_pool.hxx | 123 + include/o3tl/vector_utils.hxx | 29 + include/onlineupdate/mar.h | 198 ++ include/onlineupdate/mar_cmdline.h | 110 + include/onlineupdate/mar_private.h | 79 + include/onlineupdate/mozilla/Assertions.h | 503 +++ include/onlineupdate/mozilla/Attributes.h | 481 +++ include/onlineupdate/mozilla/Compiler.h | 110 + include/onlineupdate/mozilla/Likely.h | 23 + include/onlineupdate/mozilla/MacroArgs.h | 105 + include/onlineupdate/mozilla/TypeTraits.h | 1116 ++++++ include/onlineupdate/mozilla/Types.h | 134 + include/onlineupdate/mozilla/nsTraceRefcnt.h | 67 + include/oox/core/binarycodec.hxx | 42 + include/oox/core/contexthandler.hxx | 115 + include/oox/core/contexthandler2.hxx | 291 ++ include/oox/core/fastparser.hxx | 118 + include/oox/core/fasttokenhandler.hxx | 68 + include/oox/core/filterbase.hxx | 274 ++ include/oox/core/filterdetect.hxx | 172 + include/oox/core/fragmenthandler.hxx | 139 + include/oox/core/fragmenthandler2.hxx | 115 + include/oox/core/recordparser.hxx | 88 + include/oox/core/relations.hxx | 120 + include/oox/core/relationshandler.hxx | 58 + include/oox/core/xmlfilterbase.hxx | 297 ++ include/oox/crypto/AgileEngine.hxx | 147 + include/oox/crypto/CryptTools.hxx | 120 + include/oox/crypto/CryptoEngine.hxx | 66 + include/oox/crypto/DocumentDecryption.hxx | 54 + include/oox/crypto/DocumentEncryption.hxx | 52 + include/oox/crypto/Standard2007Engine.hxx | 61 + include/oox/crypto/StrongEncryptionDataSpace.hxx | 76 + include/oox/dllapi.h | 33 + include/oox/drawingml/chart/chartconverter.hxx | 100 + include/oox/drawingml/chart/datasourcemodel.hxx | 66 + include/oox/drawingml/chart/modelbase.hxx | 121 + include/oox/drawingml/clrscheme.hxx | 103 + include/oox/drawingml/color.hxx | 167 + include/oox/drawingml/connectorshapecontext.hxx | 59 + include/oox/drawingml/diagram/diagram.hxx | 51 + include/oox/drawingml/drawingmltypes.hxx | 235 ++ include/oox/drawingml/graphicshapecontext.hxx | 111 + include/oox/drawingml/shape.hxx | 430 +++ include/oox/drawingml/shapecontext.hxx | 53 + include/oox/drawingml/shapegroupcontext.hxx | 45 + include/oox/drawingml/shapepropertymap.hxx | 168 + include/oox/drawingml/theme.hxx | 123 + include/oox/drawingml/themefragmenthandler.hxx | 57 + include/oox/dump/dffdumper.hxx | 64 + include/oox/dump/dumperbase.hxx | 1740 ++++++++++ include/oox/dump/oledumper.hxx | 849 +++++ include/oox/dump/pptxdumper.hxx | 73 + include/oox/dump/xlsbdumper.hxx | 90 + include/oox/export/DMLPresetShapeExport.hxx | 140 + include/oox/export/chartexport.hxx | 279 ++ include/oox/export/drawingml.hxx | 382 +++ include/oox/export/shapes.hxx | 213 ++ include/oox/export/utils.hxx | 80 + include/oox/export/vmlexport.hxx | 209 ++ include/oox/helper/addtosequence.hxx | 41 + include/oox/helper/attributelist.hxx | 192 ++ include/oox/helper/binaryinputstream.hxx | 385 +++ include/oox/helper/binaryoutputstream.hxx | 208 ++ include/oox/helper/binarystreambase.hxx | 179 + include/oox/helper/containerhelper.hxx | 298 ++ include/oox/helper/grabbagstack.hxx | 61 + include/oox/helper/graphichelper.hxx | 161 + include/oox/helper/helper.hxx | 301 ++ include/oox/helper/modelobjecthelper.hxx | 131 + include/oox/helper/progressbar.hxx | 132 + include/oox/helper/propertymap.hxx | 130 + include/oox/helper/propertyset.hxx | 151 + include/oox/helper/refmap.hxx | 144 + include/oox/helper/refvector.hxx | 163 + include/oox/helper/storagebase.hxx | 192 ++ include/oox/helper/textinputstream.hxx | 121 + include/oox/helper/zipstorage.hxx | 94 + include/oox/mathml/export.hxx | 45 + include/oox/mathml/import.hxx | 51 + include/oox/mathml/importutils.hxx | 255 ++ include/oox/ole/axbinaryreader.hxx | 251 ++ include/oox/ole/axbinarywriter.hxx | 164 + include/oox/ole/axcontrol.hxx | 993 ++++++ include/oox/ole/axcontrolfragment.hxx | 76 + include/oox/ole/axfontdata.hxx | 86 + include/oox/ole/olehelper.hxx | 198 ++ include/oox/ole/oleobjecthelper.hxx | 87 + include/oox/ole/olestorage.hxx | 115 + include/oox/ole/vbacontrol.hxx | 214 ++ include/oox/ole/vbaexport.hxx | 155 + include/oox/ole/vbahelper.hxx | 91 + include/oox/ole/vbainputstream.hxx | 74 + include/oox/ole/vbamodule.hxx | 123 + include/oox/ole/vbaproject.hxx | 211 ++ include/oox/ppt/animationspersist.hxx | 125 + include/oox/ppt/backgroundproperties.hxx | 47 + include/oox/ppt/comments.hxx | 117 + include/oox/ppt/customshowlistcontext.hxx | 59 + include/oox/ppt/headerfooter.hxx | 43 + include/oox/ppt/layoutfragmenthandler.hxx | 48 + include/oox/ppt/pptfilterhelpers.hxx | 99 + include/oox/ppt/pptgraphicshapecontext.hxx | 47 + include/oox/ppt/pptimport.hxx | 107 + include/oox/ppt/pptshape.hxx | 98 + include/oox/ppt/pptshapecontext.hxx | 47 + include/oox/ppt/pptshapegroupcontext.hxx | 66 + include/oox/ppt/pptshapepropertiescontext.hxx | 47 + include/oox/ppt/presPropsfragmenthandler.hxx | 44 + include/oox/ppt/presentationfragmenthandler.hxx | 74 + include/oox/ppt/slidefragmenthandler.hxx | 63 + include/oox/ppt/slidemastertextstylescontext.hxx | 47 + include/oox/ppt/slidepersist.hxx | 173 + include/oox/ppt/slidetimingcontext.hxx | 48 + include/oox/ppt/slidetransition.hxx | 82 + include/oox/ppt/slidetransitioncontext.hxx | 58 + include/oox/ppt/soundactioncontext.hxx | 58 + include/oox/ppt/timenode.hxx | 128 + include/oox/ppt/timenodelistcontext.hxx | 71 + include/oox/shape/ShapeContextHandler.hxx | 156 + include/oox/shape/ShapeFilterBase.hxx | 92 + include/oox/token/namespacemap.hxx | 49 + include/oox/token/propertynames.hxx | 33 + include/oox/token/relationship.hxx | 76 + include/oox/token/tokenmap.hxx | 95 + include/oox/vml/vmldrawing.hxx | 206 ++ include/oox/vml/vmldrawingfragment.hxx | 67 + include/oox/vml/vmlformatting.hxx | 285 ++ include/oox/vml/vmlinputstream.hxx | 95 + include/oox/vml/vmlshape.hxx | 476 +++ include/oox/vml/vmlshapecontainer.hxx | 144 + include/oox/vml/vmlshapecontext.hxx | 191 ++ include/oox/vml/vmltextbox.hxx | 113 + include/oox/vml/vmltextboxcontext.hxx | 88 + include/opencl/OpenCLZone.hxx | 32 + include/opencl/openclconfig.hxx | 100 + include/opencl/opencldllapi.h | 34 + include/opencl/openclwrapper.hxx | 98 + include/opencl/platforminfo.hxx | 51 + include/osl/conditn.h | 101 + include/osl/conditn.hxx | 172 + include/osl/detail/android-bootstrap.h | 59 + include/osl/detail/component-defines.h | 47 + include/osl/detail/component-mapping.h | 48 + include/osl/detail/file.h | 32 + include/osl/diagnose.h | 124 + include/osl/diagnose.hxx | 200 ++ include/osl/doublecheckedlocking.h | 81 + include/osl/endian.h | 155 + include/osl/file.h | 1677 +++++++++ include/osl/file.hxx | 1951 +++++++++++ include/osl/getglobalmutex.hxx | 44 + include/osl/interlck.h | 108 + include/osl/module.h | 230 ++ include/osl/module.hxx | 178 + include/osl/mutex.h | 84 + include/osl/mutex.hxx | 260 ++ include/osl/nlsupport.h | 60 + include/osl/pipe.h | 127 + include/osl/pipe.hxx | 224 ++ include/osl/pipe_decl.hxx | 242 ++ include/osl/process.h | 425 +++ include/osl/profile.h | 151 + include/osl/profile.hxx | 212 ++ include/osl/security.h | 177 + include/osl/security.hxx | 110 + include/osl/security_decl.hxx | 133 + include/osl/signal.h | 112 + include/osl/socket.h | 862 +++++ include/osl/socket.hxx | 571 ++++ include/osl/socket_decl.hxx | 750 +++++ include/osl/test/uniquepipename.hxx | 45 + include/osl/thread.h | 232 ++ include/osl/thread.hxx | 240 ++ include/osl/time.h | 187 + include/package/Deflater.hxx | 62 + include/package/Inflater.hxx | 57 + include/package/packagedllapi.hxx | 22 + include/postmac.h | 25 + include/postwin.h | 60 + include/premac.h | 25 + include/prewin.h | 49 + include/registry/reader.hxx | 606 ++++ include/registry/refltype.hxx | 77 + include/registry/regdllapi.h | 33 + include/registry/registry.hxx | 1059 ++++++ include/registry/regtype.h | 141 + include/registry/typereg_reader.hxx | 565 ++++ include/registry/types.hxx | 339 ++ include/registry/version.h | 69 + include/registry/writer.h | 262 ++ include/registry/writer.hxx | 291 ++ include/rtl/alloc.h | 336 ++ include/rtl/bootstrap.h | 224 ++ include/rtl/bootstrap.hxx | 231 ++ include/rtl/byteseq.h | 331 ++ include/rtl/byteseq.hxx | 144 + include/rtl/character.hxx | 526 +++ include/rtl/cipher.h | 282 ++ include/rtl/crc.h | 56 + include/rtl/digest.h | 644 ++++ include/rtl/instance.hxx | 643 ++++ include/rtl/locale.h | 139 + include/rtl/malformeduriexception.hxx | 72 + include/rtl/math.h | 509 +++ include/rtl/math.hxx | 511 +++ include/rtl/process.h | 83 + include/rtl/random.h | 103 + include/rtl/ref.hxx | 316 ++ include/rtl/strbuf.h | 143 + include/rtl/strbuf.hxx | 1131 +++++++ include/rtl/string.h | 1462 ++++++++ include/rtl/string.hxx | 2314 +++++++++++++ include/rtl/stringconcat.hxx | 588 ++++ include/rtl/stringutils.hxx | 391 +++ include/rtl/tencinfo.h | 284 ++ include/rtl/textcvt.h | 194 ++ include/rtl/textenc.h | 266 ++ include/rtl/unload.h | 96 + include/rtl/uri.h | 357 ++ include/rtl/uri.hxx | 179 + include/rtl/ustrbuf.h | 218 ++ include/rtl/ustrbuf.hxx | 1796 ++++++++++ include/rtl/ustring.h | 2414 +++++++++++++ include/rtl/ustring.hxx | 3560 ++++++++++++++++++++ include/rtl/uuid.h | 186 + include/sal/alloca.h | 57 + include/sal/backtrace.hxx | 49 + include/sal/config.h | 122 + include/sal/detail/log.h | 108 + include/sal/log-areas.dox | 654 ++++ include/sal/log.hxx | 436 +++ include/sal/macros.h | 62 + include/sal/main.h | 157 + include/sal/mathconf.h | 172 + include/sal/saldllapi.h | 39 + include/sal/types.h | 687 ++++ include/sal/typesizes.h | 20 + include/salhelper/condition.hxx | 115 + include/salhelper/dynload.hxx | 209 ++ include/salhelper/linkhelper.hxx | 79 + include/salhelper/refobj.hxx | 102 + include/salhelper/salhelperdllapi.h | 38 + include/salhelper/simplereferenceobject.hxx | 122 + include/salhelper/singletonref.hxx | 203 ++ include/salhelper/thread.hxx | 96 + include/salhelper/timer.hxx | 225 ++ include/sax/fastattribs.hxx | 237 ++ include/sax/fastparser.hxx | 79 + include/sax/fastsaxdllapi.h | 33 + include/sax/fshelper.hxx | 178 + include/sax/saxdllapi.h | 33 + include/sax/tools/converter.hxx | 313 ++ include/sax/tools/documenthandleradapter.hxx | 214 ++ include/sfx2/AccessibilityCheck.hxx | 34 + include/sfx2/AccessibilityIssue.hxx | 59 + include/sfx2/DocumentMetadataAccess.hxx | 152 + include/sfx2/DocumentSigner.hxx | 47 + include/sfx2/LokControlHandler.hxx | 155 + include/sfx2/Metadatable.hxx | 170 + include/sfx2/QuerySaveDocument.hxx | 43 + include/sfx2/StyleManager.hxx | 51 + include/sfx2/StylePreviewRenderer.hxx | 57 + include/sfx2/XmlIdRegistry.hxx | 67 + include/sfx2/app.hxx | 233 ++ include/sfx2/basedlgs.hxx | 136 + include/sfx2/bindings.hxx | 208 ++ include/sfx2/brokenpackageint.hxx | 63 + include/sfx2/chalign.hxx | 55 + include/sfx2/charwin.hxx | 72 + include/sfx2/childwin.hxx | 235 ++ include/sfx2/classificationhelper.hxx | 227 ++ include/sfx2/ctrlitem.hxx | 97 + .../sfx2/devtools/DevelopmentToolChildWindow.hxx | 27 + .../sfx2/devtools/DevelopmentToolDockingWindow.hxx | 72 + include/sfx2/devtools/DocumentModelTreeHandler.hxx | 52 + .../sfx2/devtools/ObjectInspectorTreeHandler.hxx | 101 + include/sfx2/devtools/ObjectInspectorWidgets.hxx | 55 + include/sfx2/dialoghelper.hxx | 41 + include/sfx2/digitalsignatures.hxx | 38 + include/sfx2/dinfdlg.hxx | 579 ++++ include/sfx2/dispatch.hxx | 184 + include/sfx2/dllapi.h | 36 + include/sfx2/docfac.hxx | 96 + include/sfx2/docfile.hxx | 309 ++ include/sfx2/docfilt.hxx | 125 + include/sfx2/docinf.hxx | 75 + include/sfx2/docinsert.hxx | 77 + include/sfx2/dockwin.hxx | 130 + include/sfx2/docmacromode.hxx | 307 ++ include/sfx2/docstoragemodifylistener.hxx | 82 + include/sfx2/doctempl.hxx | 117 + include/sfx2/event.hxx | 268 ++ include/sfx2/evntconf.hxx | 102 + include/sfx2/fcontnr.hxx | 119 + include/sfx2/filedlghelper.hxx | 313 ++ include/sfx2/flatpak.hxx | 33 + include/sfx2/frame.hxx | 203 ++ include/sfx2/frmdescr.hxx | 102 + include/sfx2/frmhtml.hxx | 38 + include/sfx2/frmhtmlw.hxx | 71 + include/sfx2/groupid.hxx | 74 + include/sfx2/htmlmode.hxx | 31 + include/sfx2/infobar.hxx | 140 + include/sfx2/inputdlg.hxx | 38 + include/sfx2/ipclient.hxx | 101 + include/sfx2/linkmgr.hxx | 187 + include/sfx2/linksrc.hxx | 118 + include/sfx2/listview.hxx | 116 + include/sfx2/lnkbase.hxx | 179 + include/sfx2/lokcallback.hxx | 51 + include/sfx2/lokcomponenthelpers.hxx | 90 + include/sfx2/lokhelper.hxx | 171 + include/sfx2/mailmodelapi.hxx | 104 + include/sfx2/mieclip.hxx | 43 + include/sfx2/minfitem.hxx | 70 + include/sfx2/module.hxx | 103 + include/sfx2/msg.hxx | 264 ++ include/sfx2/msgpool.hxx | 74 + include/sfx2/navigat.hxx | 43 + include/sfx2/new.hxx | 108 + include/sfx2/newstyle.hxx | 55 + include/sfx2/notebookbar/SfxNotebookBar.hxx | 89 + include/sfx2/objface.hxx | 121 + include/sfx2/objitem.hxx | 48 + include/sfx2/objsh.hxx | 918 +++++ include/sfx2/opengrf.hxx | 72 + include/sfx2/pageids.hxx | 71 + include/sfx2/passwd.hxx | 130 + include/sfx2/printer.hxx | 62 + include/sfx2/printopt.hxx | 86 + include/sfx2/progress.hxx | 63 + include/sfx2/request.hxx | 129 + include/sfx2/safemode.hxx | 73 + include/sfx2/sfxbasecontroller.hxx | 218 ++ include/sfx2/sfxbasemodel.hxx | 753 +++++ include/sfx2/sfxdlg.hxx | 155 + include/sfx2/sfxhelp.hxx | 64 + include/sfx2/sfxhtml.hxx | 113 + include/sfx2/sfxmodelfactory.hxx | 66 + include/sfx2/sfxresid.hxx | 30 + include/sfx2/sfxsids.hrc | 739 ++++ include/sfx2/sfxstatuslistener.hxx | 74 + include/sfx2/sfxuno.hxx | 50 + include/sfx2/shell.hxx | 587 ++++ include/sfx2/sidebar/AsynchronousCall.hxx | 52 + include/sfx2/sidebar/Context.hxx | 58 + include/sfx2/sidebar/ControllerItem.hxx | 79 + include/sfx2/sidebar/Deck.hxx | 87 + include/sfx2/sidebar/FocusManager.hxx | 140 + include/sfx2/sidebar/IContextChangeReceiver.hxx | 40 + include/sfx2/sidebar/ILayoutableWindow.hxx | 40 + include/sfx2/sidebar/Panel.hxx | 123 + include/sfx2/sidebar/PanelLayout.hxx | 52 + include/sfx2/sidebar/ResourceManager.hxx | 132 + include/sfx2/sidebar/Sidebar.hxx | 67 + include/sfx2/sidebar/SidebarChildWindow.hxx | 46 + include/sfx2/sidebar/SidebarController.hxx | 302 ++ include/sfx2/sidebar/SidebarDockingWindow.hxx | 66 + include/sfx2/sidebar/SidebarModelUpdate.hxx | 33 + include/sfx2/sidebar/SidebarPanelBase.hxx | 102 + include/sfx2/sidebar/TabBar.hxx | 136 + include/sfx2/sidebar/Theme.hxx | 184 + include/sfx2/signaturestate.hxx | 54 + include/sfx2/stbitem.hxx | 134 + include/sfx2/strings.hrc | 361 ++ include/sfx2/styfitem.hxx | 62 + include/sfx2/styledlg.hxx | 52 + include/sfx2/tabdlg.hxx | 269 ++ include/sfx2/tbxctrl.hxx | 142 + include/sfx2/templatedlg.hxx | 193 ++ include/sfx2/templatedlglocalview.hxx | 72 + include/sfx2/templatelocalview.hxx | 192 ++ include/sfx2/templateproperties.hxx | 29 + include/sfx2/templdlg.hxx | 46 + include/sfx2/thumbnailview.hxx | 331 ++ include/sfx2/thumbnailviewitem.hxx | 138 + include/sfx2/toolbarids.hxx | 77 + include/sfx2/tplpitem.hxx | 53 + include/sfx2/userinputinterception.hxx | 82 + include/sfx2/viewfac.hxx | 60 + include/sfx2/viewfrm.hxx | 277 ++ include/sfx2/viewsh.hxx | 435 +++ include/sfx2/watermarkitem.hxx | 47 + include/sfx2/weldutils.hxx | 67 + include/sfx2/xmldump.hxx | 29 + include/sfx2/zoomitem.hxx | 81 + include/sot/exchange.hxx | 152 + include/sot/filelist.hxx | 49 + include/sot/formats.hxx | 193 ++ include/sot/object.hxx | 53 + include/sot/sotdllapi.h | 34 + include/sot/stg.hxx | 317 ++ include/sot/storage.hxx | 172 + include/sot/storinfo.hxx | 63 + include/store/store.h | 217 ++ include/store/store.hxx | 353 ++ include/store/storedllapi.h | 29 + include/store/types.h | 130 + include/svl/IndexedStyleSheets.hxx | 182 + include/svl/PasswordHelper.hxx | 55 + include/svl/SfxBroadcaster.hxx | 71 + include/svl/adrparse.hxx | 50 + include/svl/aeitem.hxx | 46 + include/svl/asiancfg.hxx | 78 + include/svl/broadcast.hxx | 103 + include/svl/cenumitm.hxx | 60 + include/svl/cintitem.hxx | 176 + include/svl/cjkoptions.hxx | 50 + include/svl/converter.hxx | 33 + include/svl/cryptosign.hxx | 98 + include/svl/ctloptions.hxx | 85 + include/svl/currencytable.hxx | 43 + include/svl/custritm.hxx | 70 + include/svl/documentlockfile.hxx | 69 + include/svl/eitem.hxx | 107 + include/svl/filenotation.hxx | 62 + include/svl/flagitem.hxx | 56 + include/svl/fstathelper.hxx | 58 + include/svl/globalnameitem.hxx | 54 + include/svl/grabbagitem.hxx | 46 + include/svl/gridprinter.hxx | 38 + include/svl/hint.hxx | 225 ++ include/svl/ilstitem.hxx | 55 + include/svl/imageitm.hxx | 54 + include/svl/inethist.hxx | 99 + include/svl/inettype.hxx | 263 ++ include/svl/instrm.hxx | 63 + include/svl/int64item.hxx | 51 + include/svl/intitem.hxx | 130 + include/svl/isethint.hxx | 40 + include/svl/itemiter.hxx | 60 + include/svl/itempool.hxx | 228 ++ include/svl/itemprop.hxx | 203 ++ include/svl/itemset.hxx | 287 ++ include/svl/languageoptions.hxx | 85 + include/svl/lckbitem.hxx | 53 + include/svl/legacyitem.hxx | 52 + include/svl/listener.hxx | 69 + include/svl/lngmisc.hxx | 56 + include/svl/lockfilecommon.hxx | 77 + include/svl/lstner.hxx | 75 + include/svl/macitem.hxx | 152 + include/svl/memberid.h | 85 + include/svl/metitem.hxx | 37 + include/svl/msodocumentlockfile.hxx | 55 + include/svl/nfkeytab.hxx | 102 + include/svl/nfsymbol.hxx | 63 + include/svl/numformat.hxx | 750 +++++ include/svl/numuno.hxx | 71 + include/svl/ondemand.hxx | 349 ++ include/svl/outstrm.hxx | 54 + include/svl/ownlist.hxx | 75 + include/svl/pickerhistoryaccess.hxx | 44 + include/svl/poolcach.hxx | 57 + include/svl/poolitem.hxx | 333 ++ include/svl/ptitem.hxx | 62 + include/svl/rectitem.hxx | 55 + include/svl/rngitem.hxx | 48 + include/svl/setitem.hxx | 51 + include/svl/sharecontrolfile.hxx | 71 + include/svl/sharedstring.hxx | 158 + include/svl/sharedstringpool.hxx | 65 + include/svl/sigstruct.hxx | 177 + include/svl/slstitm.hxx | 72 + include/svl/solar.hrc | 96 + include/svl/srchdefs.hxx | 50 + include/svl/srchitem.hxx | 326 ++ include/svl/stritem.hxx | 45 + include/svl/style.hxx | 359 ++ include/svl/stylepool.hxx | 88 + include/svl/stylesheetuser.hxx | 41 + include/svl/svdde.hxx | 326 ++ include/svl/svl.hrc | 37 + include/svl/svldllapi.h | 34 + include/svl/svlresid.hxx | 21 + include/svl/typedwhich.hxx | 62 + include/svl/undo.hxx | 343 ++ include/svl/urihelper.hxx | 173 + include/svl/urlbmk.hxx | 53 + include/svl/visitem.hxx | 59 + include/svl/whichranges.hxx | 128 + include/svl/whiter.hxx | 52 + include/svl/zforlist.hxx | 381 +++ include/svl/zformat.hxx | 760 +++++ include/svtools/DocumentToGraphicRenderer.hxx | 108 + include/svtools/HtmlWriter.hxx | 64 + include/svtools/PlaceEditDialog.hxx | 100 + include/svtools/acceleratorexecute.hxx | 206 ++ include/svtools/accessibilityoptions.hxx | 46 + include/svtools/addresstemplate.hxx | 128 + include/svtools/apearcfg.hxx | 83 + include/svtools/asynclink.hxx | 61 + include/svtools/bindablecontrolhelper.hxx | 46 + include/svtools/borderhelper.hxx | 47 + include/svtools/borderline.hxx | 78 + include/svtools/brwbox.hxx | 849 +++++ include/svtools/brwhead.hxx | 44 + include/svtools/cliplistener.hxx | 52 + include/svtools/collatorres.hxx | 54 + include/svtools/colorcfg.hxx | 140 + include/svtools/colrdlg.hxx | 61 + include/svtools/ctrlbox.hxx | 505 +++ include/svtools/ctrltool.hxx | 213 ++ include/svtools/dialogclosedlistener.hxx | 61 + include/svtools/editbrowsebox.hxx | 1119 ++++++ include/svtools/ehdl.hxx | 70 + include/svtools/embedhlp.hxx | 135 + include/svtools/embedtransfer.hxx | 58 + include/svtools/extcolorcfg.hxx | 107 + include/svtools/filechangedchecker.hxx | 45 + include/svtools/fontsubstconfig.hxx | 41 + include/svtools/genericunodialog.hxx | 160 + include/svtools/helpids.h | 49 + include/svtools/htmlcfg.hxx | 43 + include/svtools/htmlkywd.hxx | 689 ++++ include/svtools/htmlout.hxx | 96 + include/svtools/htmltokn.h | 479 +++ include/svtools/imagemgr.hxx | 137 + include/svtools/imageresourceaccess.hxx | 69 + include/svtools/imgdef.hxx | 30 + include/svtools/indexentryres.hxx | 54 + include/svtools/inettbc.hxx | 107 + include/svtools/insdlg.hxx | 71 + include/svtools/javacontext.hxx | 69 + include/svtools/javainteractionhandler.hxx | 62 + include/svtools/langhelp.hxx | 29 + include/svtools/langtab.hxx | 52 + include/svtools/languagetoolcfg.hxx | 59 + include/svtools/miscopt.hxx | 70 + include/svtools/openfiledroptargetlistener.hxx | 75 + include/svtools/optionsdrawinglayer.hxx | 103 + include/svtools/parhtml.hxx | 293 ++ include/svtools/parrtf.hxx | 71 + include/svtools/place.hxx | 39 + include/svtools/popupmenucontrollerbase.hxx | 124 + include/svtools/popupwindowcontroller.hxx | 92 + include/svtools/printoptions.hxx | 34 + include/svtools/prnsetup.hxx | 79 + include/svtools/querydelete.hxx | 48 + include/svtools/recorditemwindow.hxx | 53 + include/svtools/restartdialog.hxx | 85 + include/svtools/rtfkeywd.hxx | 1230 +++++++ include/svtools/rtfout.hxx | 37 + include/svtools/rtftoken.h | 1267 +++++++ include/svtools/ruler.hxx | 799 +++++ include/svtools/sampletext.hxx | 40 + include/svtools/scriptedtext.hxx | 91 + include/svtools/sfxecode.hxx | 74 + include/svtools/slidesorterbaropt.hxx | 62 + include/svtools/soerr.hxx | 39 + include/svtools/statusbarcontroller.hxx | 132 + include/svtools/strings.hrc | 344 ++ include/svtools/stringtransfer.hxx | 66 + include/svtools/svparser.hxx | 214 ++ include/svtools/svtdllapi.h | 31 + include/svtools/svtresid.hxx | 30 + include/svtools/tabbar.hxx | 505 +++ include/svtools/templatefoldercache.hxx | 89 + include/svtools/toolbarmenu.hxx | 102 + include/svtools/toolboxcontroller.hxx | 195 ++ include/svtools/unitconv.hxx | 51 + include/svtools/unoevent.hxx | 259 ++ include/svtools/unoimap.hxx | 38 + include/svtools/urlfilter.hxx | 42 + include/svtools/valueset.hxx | 412 +++ include/svx/AccessibilityCheckDialog.hxx | 59 + include/svx/AccessibleControlShape.hxx | 207 ++ include/svx/AccessibleGraphicShape.hxx | 105 + include/svx/AccessibleOLEShape.hxx | 112 + include/svx/AccessibleShape.hxx | 439 +++ include/svx/AccessibleShapeInfo.hxx | 97 + include/svx/AccessibleShapeTreeInfo.hxx | 201 ++ include/svx/AccessibleTextHelper.hxx | 374 ++ include/svx/ActionDescriptionProvider.hxx | 55 + include/svx/ChildrenManager.hxx | 214 ++ include/svx/ClassificationCommon.hxx | 65 + include/svx/ClassificationDialog.hxx | 99 + include/svx/ClassificationField.hxx | 98 + include/svx/ColorSets.hxx | 122 + include/svx/CommonStyleManager.hxx | 41 + include/svx/EnhancedCustomShape2d.hxx | 224 ++ include/svx/EnhancedCustomShapeFunctionParser.hxx | 249 ++ include/svx/EnhancedCustomShapeGeometry.hxx | 105 + include/svx/EnhancedCustomShapeTypeNames.hxx | 35 + include/svx/FileExportedDialog.hxx | 23 + include/svx/GenericCheckDialog.hxx | 104 + include/svx/IAccessibleParent.hxx | 103 + include/svx/IAccessibleViewForwarder.hxx | 97 + include/svx/IAccessibleViewForwarderListener.hxx | 50 + include/svx/ImageMapInfo.hxx | 55 + include/svx/MediaShellHelpers.hxx | 40 + include/svx/Palette.hxx | 67 + include/svx/PaletteManager.hxx | 86 + include/svx/ParaSpacingControl.hxx | 128 + include/svx/ParseContext.hxx | 78 + include/svx/ShapeTypeHandler.hxx | 199 ++ include/svx/SmartTagItem.hxx | 82 + include/svx/SmartTagMgr.hxx | 231 ++ include/svx/SpellDialogChildWindow.hxx | 115 + include/svx/SvxColorChildWindow.hxx | 40 + include/svx/SvxColorValueSet.hxx | 51 + include/svx/SvxNumOptionsTabPageHelper.hxx | 50 + include/svx/SvxPresetListBox.hxx | 66 + include/svx/SvxShapeTypes.hxx | 72 + include/svx/SvxXTextColumns.hxx | 22 + include/svx/UnoNamespaceMap.hxx | 36 + include/svx/XPropertyEntry.hxx | 52 + include/svx/algitem.hxx | 98 + include/svx/anchorid.hxx | 46 + include/svx/autoformathelper.hxx | 222 ++ include/svx/bmpmask.hxx | 176 + include/svx/camera3d.hxx | 67 + include/svx/charmap.hxx | 162 + include/svx/charthelper.hxx | 61 + include/svx/chrtitem.hxx | 152 + include/svx/clipboardctl.hxx | 51 + include/svx/clipfmtitem.hxx | 62 + include/svx/colorbox.hxx | 100 + include/svx/colorwindow.hxx | 136 + include/svx/compressgraphicdialog.hxx | 106 + include/svx/connctrl.hxx | 68 + include/svx/contdlg.hxx | 76 + include/svx/ctredlin.hxx | 339 ++ include/svx/cube3d.hxx | 93 + include/svx/dataaccessdescriptor.hxx | 131 + include/svx/databaselocationinput.hxx | 82 + include/svx/databaseregistrationui.hxx | 42 + include/svx/dbaexchange.hxx | 277 ++ include/svx/dbaobjectex.hxx | 66 + include/svx/def3d.hxx | 43 + include/svx/deflt3d.hxx | 97 + include/svx/diagram/IDiagramHelper.hxx | 118 + include/svx/diagram/datamodel.hxx | 274 ++ include/svx/dialcontrol.hxx | 170 + include/svx/dialmgr.hxx | 31 + include/svx/dialogs.hrc | 122 + include/svx/dlgctl3d.hxx | 183 + include/svx/dlgctrl.hxx | 410 +++ include/svx/dlgutil.hxx | 40 + include/svx/drawitem.hxx | 201 ++ include/svx/e3ditem.hxx | 49 + include/svx/e3dsceneupdater.hxx | 67 + include/svx/e3dundo.hxx | 107 + include/svx/extedit.hxx | 62 + include/svx/extrusionbar.hxx | 56 + include/svx/f3dchild.hxx | 42 + include/svx/fillctrl.hxx | 109 + include/svx/flagsdef.hxx | 126 + include/svx/float3d.hxx | 288 ++ include/svx/fmdmod.hxx | 39 + include/svx/fmdpage.hxx | 64 + include/svx/fmgridcl.hxx | 202 ++ include/svx/fmgridif.hxx | 534 +++ include/svx/fmmodel.hxx | 84 + include/svx/fmobjfac.hxx | 39 + include/svx/fmpage.hxx | 79 + include/svx/fmsearch.hxx | 66 + include/svx/fmshell.hxx | 171 + include/svx/fmsrccfg.hxx | 145 + include/svx/fmsrcimp.hxx | 350 ++ include/svx/fmtools.hxx | 175 + include/svx/fmview.hxx | 156 + include/svx/fntctrl.hxx | 74 + include/svx/fontwork.hxx | 142 + include/svx/fontworkbar.hxx | 58 + include/svx/fontworkgallery.hxx | 80 + include/svx/formatpaintbrushctrl.hxx | 59 + include/svx/framebordertype.hxx | 56 + include/svx/framelink.hxx | 185 + include/svx/framelinkarray.hxx | 326 ++ include/svx/frmdirlbox.hxx | 80 + include/svx/frmsel.hxx | 194 ++ include/svx/galctrl.hxx | 119 + include/svx/gallery.hxx | 137 + include/svx/gallery1.hxx | 146 + include/svx/gallerybinaryengine.hxx | 111 + include/svx/gallerybinaryengineentry.hxx | 67 + include/svx/gallerybinarystoragelocations.hxx | 52 + include/svx/galleryfilestorage.hxx | 28 + include/svx/galleryfilestorageentry.hxx | 28 + include/svx/galleryitem.hxx | 68 + include/svx/galleryobjectcollection.hxx | 70 + include/svx/galleryobjectstorage.hxx | 32 + include/svx/gallerystoragelocations.hxx | 33 + include/svx/galmisc.hxx | 202 ++ include/svx/galtheme.hxx | 169 + include/svx/grafctrl.hxx | 121 + include/svx/graphctl.hxx | 159 + include/svx/graphichelper.hxx | 54 + include/svx/grfcrop.hxx | 69 + include/svx/grfflt.hxx | 43 + include/svx/gridctrl.hxx | 600 ++++ include/svx/hdft.hxx | 134 + include/svx/helperhittest3d.hxx | 99 + include/svx/hexcolorcontrol.hxx | 57 + include/svx/hlnkitem.hxx | 105 + include/svx/hyperdlg.hxx | 50 + include/svx/ifaceids.hxx | 36 + include/svx/imapdlg.hxx | 145 + include/svx/insctrl.hxx | 46 + include/svx/ipolypolygoneditorcontroller.hxx | 76 + include/svx/itemwin.hxx | 64 + include/svx/itextprovider.hxx | 42 + include/svx/labelitemwindow.hxx | 30 + include/svx/langbox.hxx | 119 + include/svx/lathe3d.hxx | 123 + include/svx/legacyitem.hxx | 60 + include/svx/linectrl.hxx | 92 + include/svx/linkwarn.hxx | 38 + include/svx/measctrl.hxx | 56 + include/svx/modctrl.hxx | 55 + include/svx/msdffdef.hxx | 858 +++++ include/svx/nbdtmg.hxx | 210 ++ include/svx/nbdtmgfact.hxx | 31 + include/svx/numfmtsh.hxx | 229 ++ include/svx/numinf.hxx | 74 + include/svx/numvset.hxx | 107 + include/svx/obj3d.hxx | 188 ++ include/svx/objfac3d.hxx | 45 + include/svx/ofaitem.hxx | 55 + include/svx/optgenrl.hxx | 45 + include/svx/optgrid.hxx | 136 + include/svx/pagectrl.hxx | 153 + include/svx/pageitem.hxx | 115 + include/svx/pagenumberlistbox.hxx | 42 + include/svx/papersizelistbox.hxx | 58 + include/svx/paraprev.hxx | 103 + include/svx/passwd.hxx | 55 + include/svx/polypolygoneditor.hxx | 67 + include/svx/postattr.hxx | 100 + include/svx/pszctrl.hxx | 48 + include/svx/rectenum.hxx | 37 + include/svx/relfld.hxx | 70 + include/svx/rotmodit.hxx | 61 + include/svx/rubydialog.hxx | 140 + include/svx/ruler.hxx | 286 ++ include/svx/rulritem.hxx | 236 ++ include/svx/samecontentlistbox.hxx | 32 + include/svx/scene3d.hxx | 192 ++ include/svx/sdangitm.hxx | 46 + include/svx/sdasitm.hxx | 112 + include/svx/sderitm.hxx | 32 + include/svx/sdgcpitm.hxx | 45 + include/svx/sdggaitm.hxx | 46 + include/svx/sdgluitm.hxx | 58 + include/svx/sdgmoitm.hxx | 52 + include/svx/sdmetitm.hxx | 48 + include/svx/sdooitm.hxx | 45 + include/svx/sdprcitm.hxx | 59 + include/svx/sdr/animation/animationstate.hxx | 58 + include/svx/sdr/animation/objectanimator.hxx | 41 + include/svx/sdr/animation/scheduler.hxx | 99 + .../sdr/attribute/sdrallfillattributeshelper.hxx | 88 + include/svx/sdr/contact/displayinfo.hxx | 105 + include/svx/sdr/contact/objectcontact.hxx | 176 + .../svx/sdr/contact/objectcontactofpageview.hxx | 118 + include/svx/sdr/contact/viewcontact.hxx | 154 + include/svx/sdr/contact/viewcontactofe3dscene.hxx | 103 + .../svx/sdr/contact/viewcontactofsdrmediaobj.hxx | 74 + include/svx/sdr/contact/viewcontactofsdrobj.hxx | 80 + include/svx/sdr/contact/viewcontactofvirtobj.hxx | 54 + include/svx/sdr/contact/viewobjectcontact.hxx | 142 + .../svx/sdr/contact/viewobjectcontactofsdrobj.hxx | 64 + .../sdr/contact/viewobjectcontactredirector.hxx | 56 + .../svx/sdr/overlay/overlayanimatedbitmapex.hxx | 81 + include/svx/sdr/overlay/overlaybitmapex.hxx | 61 + include/svx/sdr/overlay/overlaymanager.hxx | 130 + include/svx/sdr/overlay/overlayobject.hxx | 197 ++ include/svx/sdr/overlay/overlayobjectlist.hxx | 70 + include/svx/sdr/overlay/overlaypolypolygon.hxx | 71 + .../overlay/overlayprimitive2dsequenceobject.hxx | 48 + include/svx/sdr/overlay/overlayselection.hxx | 77 + .../sdr/primitive2d/sdrframeborderprimitive2d.hxx | 129 + .../svx/sdr/primitive2d/svx_primitivetypes2d.hxx | 57 + include/svx/sdr/properties/defaultproperties.hxx | 116 + include/svx/sdr/properties/properties.hxx | 190 ++ include/svx/sdr/table/tablecontroller.hxx | 201 ++ include/svx/sdr/table/tabledesign.hxx | 46 + include/svx/sdrhittesthelper.hxx | 73 + include/svx/sdrmasterpagedescriptor.hxx | 73 + include/svx/sdrobjectfilter.hxx | 50 + include/svx/sdrobjectuser.hxx | 51 + include/svx/sdrpageuser.hxx | 51 + include/svx/sdrpagewindow.hxx | 97 + include/svx/sdrpaintwindow.hxx | 144 + include/svx/sdrundomanager.hxx | 73 + include/svx/sdshcitm.hxx | 32 + include/svx/sdshitm.hxx | 32 + include/svx/sdshtitm.hxx | 32 + include/svx/sdsxyitm.hxx | 37 + include/svx/sdtaaitm.hxx | 38 + include/svx/sdtacitm.hxx | 36 + include/svx/sdtaditm.hxx | 50 + include/svx/sdtagitm.hxx | 37 + include/svx/sdtaiitm.hxx | 51 + include/svx/sdtaitm.hxx | 74 + include/svx/sdtakitm.hxx | 94 + include/svx/sdtayitm.hxx | 35 + include/svx/sdtcfitm.hxx | 32 + include/svx/sdtditm.hxx | 47 + include/svx/sdtfchim.hxx | 44 + include/svx/sdtfsitm.hxx | 66 + include/svx/sdtmfitm.hxx | 47 + include/svx/sdynitm.hxx | 41 + include/svx/searchcharmap.hxx | 71 + include/svx/selctrl.hxx | 48 + include/svx/selectioncontroller.hxx | 87 + include/svx/shapepropertynotifier.hxx | 142 + include/svx/sidebar/AreaPropertyPanelBase.hxx | 175 + .../svx/sidebar/AreaTransparencyGradientPopup.hxx | 66 + .../svx/sidebar/ContextChangeEventMultiplexer.hxx | 65 + include/svx/sidebar/InspectorTextPanel.hxx | 61 + include/svx/sidebar/LinePropertyPanelBase.hxx | 140 + include/svx/sidebar/LineWidthPopup.hxx | 71 + include/svx/sidebar/SelectionAnalyzer.hxx | 76 + include/svx/sidebar/SelectionChangeHandler.hxx | 75 + include/svx/sidebar/ValueSetWithTextControl.hxx | 61 + include/svx/signaturelinehelper.hxx | 70 + include/svx/spacinglistbox.hxx | 41 + include/svx/sphere3d.hxx | 89 + include/svx/srchdlg.hxx | 270 ++ include/svx/strarray.hxx | 53 + include/svx/strings.hrc | 1838 ++++++++++ include/svx/svdcrtv.hxx | 168 + include/svx/svddef.hxx | 439 +++ include/svx/svddrag.hxx | 177 + include/svx/svddrgmt.hxx | 304 ++ include/svx/svddrgv.hxx | 230 ++ include/svx/svdedtv.hxx | 418 +++ include/svx/svdedxv.hxx | 325 ++ include/svx/svdetc.hxx | 211 ++ include/svx/svdglev.hxx | 85 + include/svx/svdglue.hxx | 228 ++ include/svx/svdhdl.hxx | 535 +++ include/svx/svdhlpln.hxx | 91 + include/svx/svditer.hxx | 74 + include/svx/svdlayer.hxx | 164 + include/svx/svdmark.hxx | 261 ++ include/svx/svdmodel.hxx | 641 ++++ include/svx/svdmrkv.hxx | 469 +++ include/svx/svdoashp.hxx | 253 ++ include/svx/svdoattr.hxx | 66 + include/svx/svdobj.hxx | 1036 ++++++ include/svx/svdobjkind.hxx | 154 + include/svx/svdocapt.hxx | 154 + include/svx/svdocirc.hxx | 143 + include/svx/svdoedge.hxx | 411 +++ include/svx/svdograf.hxx | 301 ++ include/svx/svdogrp.hxx | 122 + include/svx/svdomeas.hxx | 203 ++ include/svx/svdomedia.hxx | 83 + include/svx/svdoole2.hxx | 213 ++ include/svx/svdopage.hxx | 69 + include/svx/svdopath.hxx | 175 + include/svx/svdorect.hxx | 127 + include/svx/svdotable.hxx | 294 ++ include/svx/svdotext.hxx | 633 ++++ include/svx/svdouno.hxx | 145 + include/svx/svdoutl.hxx | 51 + include/svx/svdovirt.hxx | 156 + include/svx/svdpage.hxx | 545 +++ include/svx/svdpagv.hxx | 254 ++ include/svx/svdpntv.hxx | 504 +++ include/svx/svdpoev.hxx | 82 + include/svx/svdpool.hxx | 46 + include/svx/svdsnpv.hxx | 287 ++ include/svx/svdsob.hxx | 94 + include/svx/svdtext.hxx | 81 + include/svx/svdtrans.hxx | 286 ++ include/svx/svdtypes.hxx | 90 + include/svx/svdundo.hxx | 785 +++++ include/svx/svdview.hxx | 281 ++ include/svx/svdviter.hxx | 83 + include/svx/svdxcgv.hxx | 113 + include/svx/svx3ditems.hxx | 319 ++ include/svx/svxdlg.hxx | 451 +++ include/svx/svxdllapi.h | 41 + include/svx/svxerr.hxx | 62 + include/svx/svxgraphicitem.hxx | 41 + include/svx/svxids.hrc | 1068 ++++++ include/svx/svxitems.hrc | 95 + include/svx/swframeexample.hxx | 94 + include/svx/swframeposstrings.hxx | 84 + include/svx/swframetypes.hxx | 48 + include/svx/swframevalidation.hxx | 85 + include/svx/sxcecitm.hxx | 98 + include/svx/sxcgitm.hxx | 44 + include/svx/sxciaitm.hxx | 37 + include/svx/sxcllitm.hxx | 61 + include/svx/sxctitm.hxx | 41 + include/svx/sxekitm.hxx | 44 + include/svx/sxelditm.hxx | 55 + include/svx/sxenditm.hxx | 72 + include/svx/sxmbritm.hxx | 46 + include/svx/sxmlhitm.hxx | 70 + include/svx/sxmtfitm.hxx | 70 + include/svx/sxmtpitm.hxx | 62 + include/svx/sxmtritm.hxx | 54 + include/svx/sxmuitm.hxx | 44 + include/svx/tabarea.hxx | 37 + include/svx/tabline.hxx | 35 + include/svx/tbcontrl.hxx | 281 ++ include/svx/tbxcolor.hxx | 59 + include/svx/tbxctl.hxx | 54 + include/svx/transfrmhelper.hxx | 51 + include/svx/txencbox.hxx | 158 + include/svx/txenctab.hxx | 35 + include/svx/ucsubset.hxx | 74 + include/svx/uiobject.hxx | 61 + include/svx/unoapi.hxx | 94 + include/svx/unobrushitemhelper.hxx | 54 + include/svx/unodraw/SvxTableShape.hxx | 44 + include/svx/unofill.hxx | 37 + include/svx/unomaster.hxx | 76 + include/svx/unomid.hxx | 97 + include/svx/unomod.hxx | 71 + include/svx/unomodel.hxx | 109 + include/svx/unopage.hxx | 139 + include/svx/unopool.hxx | 98 + include/svx/unoprov.hxx | 115 + include/svx/unoshape.hxx | 871 +++++ include/svx/unoshprp.hxx | 577 ++++ include/svx/unoshtxt.hxx | 89 + include/svx/view3d.hxx | 120 + include/svx/viewlayoutitem.hxx | 51 + include/svx/viewpt3d.hxx | 95 + include/svx/weldeditview.hxx | 114 + include/svx/xbitmap.hxx | 59 + include/svx/xbtmpit.hxx | 67 + include/svx/xcolit.hxx | 62 + include/svx/xdash.hxx | 69 + include/svx/xdef.hxx | 151 + include/svx/xenum.hxx | 31 + include/svx/xfillit0.hxx | 55 + include/svx/xfilluseslidebackgrounditem.hxx | 31 + include/svx/xflasit.hxx | 42 + include/svx/xflbckit.hxx | 49 + include/svx/xflbmpit.hxx | 46 + include/svx/xflbmsli.hxx | 41 + include/svx/xflbmsxy.hxx | 60 + include/svx/xflbmtit.hxx | 42 + include/svx/xflboxy.hxx | 54 + include/svx/xflbstit.hxx | 42 + include/svx/xflbtoxy.hxx | 54 + include/svx/xflclit.hxx | 56 + include/svx/xflftrit.hxx | 63 + include/svx/xflgrit.hxx | 64 + include/svx/xflhtit.hxx | 63 + include/svx/xfltrit.hxx | 46 + include/svx/xftadit.hxx | 48 + include/svx/xftdiit.hxx | 42 + include/svx/xftmrit.hxx | 42 + include/svx/xftouit.hxx | 44 + include/svx/xftshcit.hxx | 44 + include/svx/xftshit.hxx | 48 + include/svx/xftshxy.hxx | 57 + include/svx/xftstit.hxx | 43 + include/svx/xgrad.hxx | 86 + include/svx/xgrscit.hxx | 45 + include/svx/xhatch.hxx | 59 + include/svx/xit.hxx | 70 + include/svx/xlineit0.hxx | 48 + include/svx/xlinjoit.hxx | 49 + include/svx/xlnasit.hxx | 42 + include/svx/xlncapit.hxx | 50 + include/svx/xlnclit.hxx | 49 + include/svx/xlndsit.hxx | 66 + include/svx/xlnedcit.hxx | 45 + include/svx/xlnedit.hxx | 61 + include/svx/xlnedwit.hxx | 48 + include/svx/xlnstcit.hxx | 45 + include/svx/xlnstit.hxx | 61 + include/svx/xlnstwit.hxx | 48 + include/svx/xlntrit.hxx | 45 + include/svx/xlnwtit.hxx | 46 + include/svx/xmleohlp.hxx | 124 + include/svx/xmlexchg.hxx | 83 + include/svx/xmlgrhlp.hxx | 128 + include/svx/xmlsecctrl.hxx | 46 + include/svx/xoutbmp.hxx | 74 + include/svx/xpoly.hxx | 155 + include/svx/xpool.hxx | 50 + include/svx/xsflclit.hxx | 40 + include/svx/xtable.hxx | 394 +++ include/svx/xtextit0.hxx | 61 + include/svx/zoom_def.hxx | 30 + include/svx/zoomctrl.hxx | 63 + include/svx/zoomsliderctrl.hxx | 56 + include/svx/zoomslideritem.hxx | 54 + include/systools/win32/comtools.hxx | 249 ++ include/systools/win32/oleauto.hxx | 84 + include/systools/win32/qswin32.h | 29 + include/systools/win32/retry_if_failed.hxx | 38 + include/systools/win32/uwinapi.h | 41 + include/test/beans/xpropertyset.hxx | 74 + include/test/bootstrapfixture.hxx | 73 + include/test/calc_unoapi_test.hxx | 31 + include/test/callgrind.hxx | 21 + include/test/chart/xchartdata.hxx | 35 + include/test/container/xchild.hxx | 34 + include/test/container/xelementaccess.hxx | 46 + include/test/container/xenumeration.hxx | 36 + include/test/container/xenumerationaccess.hxx | 34 + include/test/container/xindexaccess.hxx | 46 + include/test/container/xnameaccess.hxx | 46 + include/test/container/xnamecontainer.hxx | 60 + include/test/container/xnamed.hxx | 49 + include/test/container/xnamereplace.hxx | 48 + include/test/cppunitasserthelper.hxx | 104 + include/test/document/xactionlockable.hxx | 36 + include/test/document/xembeddedobjectsupplier.hxx | 35 + include/test/document/xlinktargetsupplier.hxx | 34 + include/test/drawing/captionshape.hxx | 33 + include/test/drawing/xdrawpages.hxx | 37 + include/test/drawing/xgluepointssupplier.hxx | 33 + include/test/drawing/xshape.hxx | 42 + include/test/drawing/xshapedescriptor.hxx | 40 + include/test/drawing/xshapegrouper.hxx | 44 + include/test/drawing/xshapes.hxx | 43 + include/test/helper/form.hxx | 64 + include/test/helper/shape.hxx | 92 + include/test/helper/transferable.hxx | 29 + include/test/htmltesttools.hxx | 32 + include/test/lang/xcomponent.hxx | 39 + include/test/lang/xserviceinfo.hxx | 55 + include/test/lokcallback.hxx | 62 + include/test/screenshot_test.hxx | 96 + include/test/sheet/cellarealink.hxx | 47 + include/test/sheet/cellproperties.hxx | 34 + include/test/sheet/databaseimportdescriptor.hxx | 35 + include/test/sheet/databaserange.hxx | 43 + include/test/sheet/datapilotfield.hxx | 36 + include/test/sheet/datapilotitem.hxx | 33 + include/test/sheet/documentsettings.hxx | 34 + include/test/sheet/functiondescription.hxx | 34 + include/test/sheet/globalsheetsettings.hxx | 34 + include/test/sheet/scenario.hxx | 34 + include/test/sheet/shape.hxx | 36 + include/test/sheet/sheetcell.hxx | 34 + include/test/sheet/sheetcellrange.hxx | 34 + include/test/sheet/sheetcellranges.hxx | 34 + include/test/sheet/sheetfilterdescriptor.hxx | 34 + include/test/sheet/sheetlink.hxx | 34 + include/test/sheet/sheetsortdescriptor2.hxx | 34 + include/test/sheet/spreadsheet.hxx | 35 + include/test/sheet/spreadsheetdocumentsettings.hxx | 34 + include/test/sheet/spreadsheetviewsettings.hxx | 34 + include/test/sheet/subtotaldescriptor.hxx | 34 + include/test/sheet/tableautoformat.hxx | 34 + include/test/sheet/tablevalidation.hxx | 34 + include/test/sheet/xactivationbroadcaster.hxx | 36 + include/test/sheet/xarealink.hxx | 34 + include/test/sheet/xarealinks.hxx | 36 + include/test/sheet/xarrayformularange.hxx | 32 + include/test/sheet/xcalculatable.hxx | 39 + include/test/sheet/xcelladdressable.hxx | 31 + include/test/sheet/xcellformatrangessupplier.hxx | 34 + include/test/sheet/xcellrangeaddressable.hxx | 34 + include/test/sheet/xcellrangedata.hxx | 36 + include/test/sheet/xcellrangeformula.hxx | 34 + include/test/sheet/xcellrangemovement.hxx | 37 + include/test/sheet/xcellrangereferrer.hxx | 40 + include/test/sheet/xcellrangesquery.hxx | 39 + include/test/sheet/xcellseries.hxx | 38 + include/test/sheet/xconsolidatable.hxx | 35 + include/test/sheet/xconsolidationdescriptor.hxx | 45 + include/test/sheet/xdatabaserange.hxx | 38 + include/test/sheet/xdatabaseranges.hxx | 34 + include/test/sheet/xdatapilotdescriptor.hxx | 52 + include/test/sheet/xdatapilotfield.hxx | 34 + include/test/sheet/xdatapilotfieldgrouping.hxx | 35 + include/test/sheet/xdatapilottable.hxx | 39 + include/test/sheet/xdatapilottable2.hxx | 58 + include/test/sheet/xdatapilottables.hxx | 35 + include/test/sheet/xdatapilottablessupplier.hxx | 34 + include/test/sheet/xddelink.hxx | 42 + include/test/sheet/xddelinks.hxx | 44 + include/test/sheet/xdocumentauditing.hxx | 44 + include/test/sheet/xformulaquery.hxx | 57 + include/test/sheet/xfunctiondescriptions.hxx | 34 + include/test/sheet/xgoalseek.hxx | 32 + include/test/sheet/xheaderfootercontent.hxx | 36 + include/test/sheet/xlabelrange.hxx | 35 + include/test/sheet/xlabelranges.hxx | 35 + include/test/sheet/xmultiformulatokens.hxx | 39 + include/test/sheet/xmultipleoperation.hxx | 39 + include/test/sheet/xnamedrange.hxx | 41 + include/test/sheet/xnamedranges.hxx | 59 + include/test/sheet/xprintareas.hxx | 41 + include/test/sheet/xrecentfunctions.hxx | 36 + include/test/sheet/xscenario.hxx | 34 + include/test/sheet/xscenarioenhanced.hxx | 34 + include/test/sheet/xscenarios.hxx | 35 + include/test/sheet/xscenariossupplier.hxx | 34 + include/test/sheet/xsheetannotation.hxx | 42 + include/test/sheet/xsheetannotationanchor.hxx | 34 + include/test/sheet/xsheetannotations.hxx | 43 + .../test/sheet/xsheetannotationshapesupplier.hxx | 32 + include/test/sheet/xsheetannotationssupplier.hxx | 34 + include/test/sheet/xsheetauditing.hxx | 38 + include/test/sheet/xsheetcellcursor.hxx | 39 + include/test/sheet/xsheetcellrange.hxx | 34 + include/test/sheet/xsheetcellrangecontainer.hxx | 39 + include/test/sheet/xsheetcellranges.hxx | 36 + include/test/sheet/xsheetcondition.hxx | 37 + include/test/sheet/xsheetconditionalentries.hxx | 41 + include/test/sheet/xsheetconditionalentry.hxx | 34 + include/test/sheet/xsheetfilterable.hxx | 38 + include/test/sheet/xsheetfilterableex.hxx | 35 + include/test/sheet/xsheetfilterdescriptor.hxx | 35 + include/test/sheet/xsheetfilterdescriptor2.hxx | 35 + include/test/sheet/xsheetfilterdescriptor3.hxx | 35 + include/test/sheet/xsheetlinkable.hxx | 35 + include/test/sheet/xsheetoperation.hxx | 35 + include/test/sheet/xsheetoutline.hxx | 38 + include/test/sheet/xsheetpagebreak.hxx | 34 + include/test/sheet/xspreadsheet.hxx | 34 + include/test/sheet/xspreadsheetdocument.hxx | 37 + include/test/sheet/xspreadsheets.hxx | 34 + include/test/sheet/xspreadsheets2.hxx | 64 + include/test/sheet/xspreadsheetview.hxx | 33 + include/test/sheet/xsubtotalcalculatable.hxx | 34 + include/test/sheet/xsubtotaldescriptor.hxx | 33 + include/test/sheet/xsubtotalfield.hxx | 33 + .../test/sheet/xuniquecellformatrangessupplier.hxx | 34 + include/test/sheet/xusedareacursor.hxx | 33 + include/test/sheet/xviewfreezable.hxx | 31 + include/test/sheet/xviewpane.hxx | 35 + include/test/sheet/xviewsplitable.hxx | 33 + include/test/style/xstyleloader.hxx | 51 + include/test/table/tablecolumn.hxx | 41 + include/test/table/tablerow.hxx | 36 + include/test/table/xcell.hxx | 37 + include/test/table/xcellcursor.hxx | 39 + include/test/table/xcellrange.hxx | 49 + include/test/table/xcolumnrowrange.hxx | 35 + include/test/table/xtablechart.hxx | 37 + include/test/table/xtablecharts.hxx | 36 + include/test/table/xtablechartssupplier.hxx | 34 + include/test/table/xtablecolumns.hxx | 57 + include/test/table/xtablerows.hxx | 38 + include/test/testdllapi.hxx | 39 + include/test/testinteractionhandler.hxx | 154 + include/test/text/baseindex.hxx | 30 + include/test/text/textcontent.hxx | 51 + include/test/text/textdocumentindex.hxx | 30 + include/test/text/textdocumentsettings.hxx | 29 + include/test/text/textprintersettings.hxx | 30 + include/test/text/textsettings.hxx | 30 + include/test/text/xdocumentindex.hxx | 36 + include/test/text/xsimpletext.hxx | 36 + include/test/text/xtext.hxx | 33 + include/test/text/xtextcontent.hxx | 39 + include/test/text/xtextfield.hxx | 37 + include/test/text/xtextrange.hxx | 38 + include/test/unoapi_property_testers.hxx | 173 + include/test/unoapi_test.hxx | 42 + include/test/util/searchdescriptor.hxx | 33 + include/test/util/xindent.hxx | 35 + include/test/util/xmergeable.hxx | 34 + include/test/util/xrefreshable.hxx | 36 + include/test/util/xreplaceable.hxx | 40 + include/test/util/xreplacedescriptor.hxx | 33 + include/test/util/xsearchable.hxx | 41 + include/test/util/xsearchdescriptor.hxx | 33 + include/test/view/xcontrolaccess.hxx | 35 + include/test/view/xformlayeraccess.hxx | 43 + include/test/xmldiff.hxx | 21 + include/test/xmldocptr.hxx | 20 + include/test/xmltesttools.hxx | 110 + include/toolkit/awt/vclxaccessiblecomponent.hxx | 150 + include/toolkit/awt/vclxdevice.hxx | 88 + include/toolkit/awt/vclxfont.hxx | 78 + include/toolkit/awt/vclxmenu.hxx | 162 + include/toolkit/awt/vclxwindow.hxx | 236 ++ include/toolkit/awt/vclxwindows.hxx | 743 ++++ include/toolkit/controls/unocontrol.hxx | 231 ++ include/toolkit/controls/unocontrolbase.hxx | 66 + include/toolkit/controls/unocontrolmodel.hxx | 183 + include/toolkit/controls/unocontrols.hxx | 1490 ++++++++ include/toolkit/dllapi.h | 34 + include/toolkit/helper/accessiblefactory.hxx | 145 + include/toolkit/helper/convert.hxx | 61 + include/toolkit/helper/emptyfontdescriptor.hxx | 40 + include/toolkit/helper/formpdfexport.hxx | 55 + include/toolkit/helper/listenermultiplexer.hxx | 273 ++ include/toolkit/helper/macros.hxx | 156 + include/toolkit/helper/mutexandbroadcasthelper.hxx | 44 + include/toolkit/helper/property.hxx | 247 ++ include/toolkit/helper/vclunohelper.hxx | 157 + include/tools/GenericTypeSerializer.hxx | 60 + include/tools/Guid.hxx | 165 + include/tools/UnitConversion.hxx | 122 + include/tools/XmlWalker.hxx | 59 + include/tools/XmlWriter.hxx | 68 + include/tools/b3dtrans.hxx | 217 ++ include/tools/bigint.hxx | 253 ++ include/tools/color.hxx | 516 +++ include/tools/config.hxx | 69 + include/tools/contnr.hxx | 29 + include/tools/cpuid.hxx | 109 + include/tools/date.hxx | 259 ++ include/tools/datetime.hxx | 131 + include/tools/datetimeutils.hxx | 26 + include/tools/debug.hxx | 62 + include/tools/degree.hxx | 60 + include/tools/diagnose_ex.h | 194 ++ include/tools/extendapplicationenvironment.hxx | 34 + include/tools/fileutil.hxx | 26 + include/tools/fix16.hxx | 40 + include/tools/fldunit.hxx | 51 + include/tools/fontenum.hxx | 457 +++ include/tools/fract.hxx | 119 + include/tools/gen.hxx | 793 +++++ include/tools/globname.hxx | 77 + include/tools/helpers.hxx | 104 + include/tools/inetmime.hxx | 241 ++ include/tools/inetmsg.hxx | 187 + include/tools/inetstrm.hxx | 64 + include/tools/json_writer.hxx | 166 + include/tools/line.hxx | 56 + include/tools/lineend.hxx | 33 + include/tools/link.hxx | 180 + include/tools/long.hxx | 39 + include/tools/mapunit.hxx | 37 + include/tools/multisel.hxx | 170 + include/tools/pathutils.hxx | 72 + include/tools/poly.hxx | 315 ++ include/tools/ref.hxx | 234 ++ include/tools/resary.hxx | 26 + include/tools/simd.hxx | 30 + include/tools/simdsupport.hxx | 83 + include/tools/solar.h | 119 + include/tools/stream.hxx | 682 ++++ include/tools/svborder.hxx | 73 + include/tools/svlibrary.h | 15 + include/tools/tenccvt.hxx | 58 + include/tools/time.hxx | 177 + include/tools/toolsdllapi.h | 34 + include/tools/urlobj.hxx | 1312 ++++++++ include/tools/vcompat.hxx | 65 + include/tools/weakbase.h | 159 + include/tools/weakbase.hxx | 162 + include/tools/wintypes.hxx | 265 ++ include/tools/wldcrd.hxx | 65 + include/tools/zcodec.hxx | 82 + include/typelib/typeclass.h | 107 + include/typelib/typedescription.h | 1046 ++++++ include/typelib/typedescription.hxx | 239 ++ include/typelib/uik.h | 51 + include/ucbhelper/activedatasink.hxx | 57 + include/ucbhelper/authenticationfallback.hxx | 48 + include/ucbhelper/cancelcommandexecution.hxx | 100 + include/ucbhelper/commandenvironment.hxx | 79 + include/ucbhelper/content.hxx | 680 ++++ include/ucbhelper/contenthelper.hxx | 448 +++ include/ucbhelper/contentidentifier.hxx | 57 + include/ucbhelper/fd_inputstream.hxx | 93 + include/ucbhelper/interactionrequest.hxx | 547 +++ include/ucbhelper/interceptedinteraction.hxx | 281 ++ include/ucbhelper/macros.hxx | 146 + include/ucbhelper/propertyvalueset.hxx | 203 ++ include/ucbhelper/providerhelper.hxx | 246 ++ include/ucbhelper/proxydecider.hxx | 135 + include/ucbhelper/registerucb.hxx | 96 + include/ucbhelper/resultset.hxx | 435 +++ include/ucbhelper/resultsethelper.hxx | 164 + include/ucbhelper/resultsetmetadata.hxx | 341 ++ include/ucbhelper/simpleauthenticationrequest.hxx | 139 + .../simplecertificatevalidationrequest.hxx | 64 + include/ucbhelper/simpleinteractionrequest.hxx | 95 + .../ucbhelper/simplenameclashresolverequest.hxx | 72 + include/ucbhelper/ucbhelperdllapi.h | 34 + include/uno/Enterable.h | 110 + include/uno/EnvDcp.h | 62 + include/uno/any2.h | 174 + include/uno/current_context.h | 67 + include/uno/current_context.hxx | 122 + include/uno/data.h | 255 ++ include/uno/dispatcher.h | 92 + include/uno/dispatcher.hxx | 190 ++ include/uno/environment.h | 389 +++ include/uno/environment.hxx | 290 ++ include/uno/lbnames.h | 57 + include/uno/mapping.h | 216 ++ include/uno/mapping.hxx | 360 ++ include/uno/sequence2.h | 199 ++ include/uno/threadpool.h | 194 ++ include/unoidl/detail/dllapi.hxx | 25 + include/unoidl/unoidl.hxx | 715 ++++ include/unotest/bootstrapfixturebase.hxx | 74 + include/unotest/detail/unotestdllapi.hxx | 34 + include/unotest/directories.hxx | 52 + include/unotest/filters-test.hxx | 95 + include/unotest/getargument.hxx | 38 + include/unotest/gettestargument.hxx | 42 + include/unotest/macros_test.hxx | 114 + include/unotest/officeconnection.hxx | 65 + include/unotest/toabsolutefileurl.hxx | 39 + include/unotools/VersionConfig.hxx | 56 + include/unotools/ZipPackageHelper.hxx | 64 + include/unotools/accessiblerelationsethelper.hxx | 126 + include/unotools/accessiblestatesethelper.hxx | 137 + include/unotools/bootstrap.hxx | 120 + include/unotools/calendarwrapper.hxx | 124 + include/unotools/caserotate.hxx | 34 + include/unotools/charclass.hxx | 181 + include/unotools/closeveto.hxx | 55 + include/unotools/cmdoptions.hxx | 119 + include/unotools/collatorwrapper.hxx | 64 + include/unotools/compatibility.hxx | 200 ++ include/unotools/configitem.hxx | 215 ++ include/unotools/configmgr.hxx | 104 + include/unotools/confignode.hxx | 272 ++ include/unotools/configpaths.hxx | 162 + include/unotools/configvaluecontainer.hxx | 153 + include/unotools/datetime.hxx | 59 + include/unotools/defaultencoding.hxx | 31 + include/unotools/defaultoptions.hxx | 30 + include/unotools/desktopterminationobserver.hxx | 64 + include/unotools/digitgroupingiterator.hxx | 194 ++ include/unotools/docinfohelper.hxx | 35 + include/unotools/dynamicmenuoptions.hxx | 73 + include/unotools/eventcfg.hxx | 88 + include/unotools/eventlisteneradapter.hxx | 65 + include/unotools/extendedsecurityoptions.hxx | 32 + include/unotools/fltrcfg.hxx | 106 + include/unotools/fontcfg.hxx | 184 + include/unotools/fontcvt.hxx | 64 + include/unotools/fontdefs.hxx | 111 + include/unotools/historyoptions.hxx | 83 + include/unotools/intlwrapper.hxx | 91 + include/unotools/itemholderbase.hxx | 68 + include/unotools/lingucfg.hxx | 209 ++ include/unotools/linguprops.hxx | 119 + include/unotools/localedatawrapper.hxx | 394 +++ include/unotools/localfilehelper.hxx | 42 + include/unotools/mediadescriptor.hxx | 339 ++ include/unotools/moduleoptions.hxx | 176 + include/unotools/nativenumberwrapper.hxx | 68 + include/unotools/options.hxx | 114 + include/unotools/optionsdlg.hxx | 48 + include/unotools/pathoptions.hxx | 137 + include/unotools/progresshandlerwrap.hxx | 53 + include/unotools/resmgr.hxx | 76 + include/unotools/saveopt.hxx | 82 + include/unotools/searchopt.hxx | 114 + include/unotools/securityoptions.hxx | 157 + include/unotools/sharedunocomponent.hxx | 269 ++ include/unotools/streamhelper.hxx | 70 + include/unotools/streamwrap.hxx | 184 + include/unotools/syslocale.hxx | 73 + include/unotools/syslocaleoptions.hxx | 152 + include/unotools/tempfile.hxx | 145 + include/unotools/textsearch.hxx | 225 ++ include/unotools/transliterationwrapper.hxx | 122 + include/unotools/ucbhelper.hxx | 113 + include/unotools/ucbstreamhelper.hxx | 54 + include/unotools/unotoolsdllapi.h | 34 + include/unotools/useroptions.hxx | 100 + include/unotools/viewoptions.hxx | 223 ++ include/unotools/weakref.hxx | 133 + include/unotools/wincodepage.hxx | 36 + include/vbahelper/vbaaccesshelper.hxx | 78 + include/vbahelper/vbaapplicationbase.hxx | 86 + include/vbahelper/vbacollectionimpl.hxx | 354 ++ include/vbahelper/vbadialogbase.hxx | 60 + include/vbahelper/vbadialogsbase.hxx | 59 + include/vbahelper/vbadllapi.h | 34 + include/vbahelper/vbadocumentbase.hxx | 87 + include/vbahelper/vbadocumentsbase.hxx | 81 + include/vbahelper/vbaeventshelperbase.hxx | 228 ++ include/vbahelper/vbafontbase.hxx | 112 + include/vbahelper/vbaglobalbase.hxx | 64 + include/vbahelper/vbahelper.hxx | 281 ++ include/vbahelper/vbahelperinterface.hxx | 142 + include/vbahelper/vbapagesetupbase.hxx | 79 + include/vbahelper/vbapropvalue.hxx | 59 + include/vbahelper/vbareturntypes.hxx | 54 + include/vbahelper/vbashape.hxx | 136 + include/vbahelper/vbashaperange.hxx | 105 + include/vbahelper/vbashapes.hxx | 100 + include/vbahelper/vbatextframe.hxx | 79 + include/vbahelper/vbawindowbase.hxx | 101 + include/vcl/AccessibleBrowseBoxObjType.hxx | 35 + include/vcl/BinaryDataContainer.hxx | 66 + include/vcl/BinaryDataContainerTools.hxx | 23 + include/vcl/BitmapAccessMode.hxx | 32 + include/vcl/BitmapAlphaClampFilter.hxx | 34 + include/vcl/BitmapBasicMorphologyFilter.hxx | 71 + include/vcl/BitmapBuffer.hxx | 54 + include/vcl/BitmapColor.hxx | 82 + include/vcl/BitmapColorQuantizationFilter.hxx | 43 + include/vcl/BitmapConvolutionMatrixFilter.hxx | 36 + include/vcl/BitmapDuoToneFilter.hxx | 36 + include/vcl/BitmapEmbossGreyFilter.hxx | 36 + include/vcl/BitmapFilter.hxx | 60 + include/vcl/BitmapFilterStackBlur.hxx | 33 + include/vcl/BitmapGaussianSeparableBlurFilter.hxx | 52 + include/vcl/BitmapInfoAccess.hxx | 148 + include/vcl/BitmapMedianFilter.hxx | 28 + include/vcl/BitmapMonochromeFilter.hxx | 43 + include/vcl/BitmapMosaicFilter.hxx | 40 + include/vcl/BitmapPalette.hxx | 78 + include/vcl/BitmapPopArtFilter.hxx | 33 + include/vcl/BitmapReadAccess.hxx | 195 ++ include/vcl/BitmapSeparableUnsharpenFilter.hxx | 37 + include/vcl/BitmapSepiaFilter.hxx | 38 + include/vcl/BitmapShadowFilter.hxx | 31 + include/vcl/BitmapSharpenFilter.hxx | 24 + .../vcl/BitmapSimpleColorQuantizationFilter.hxx | 37 + include/vcl/BitmapSmoothenFilter.hxx | 34 + include/vcl/BitmapSobelGreyFilter.hxx | 26 + include/vcl/BitmapSolarizeFilter.hxx | 34 + include/vcl/BitmapTools.hxx | 104 + include/vcl/ColorMask.hxx | 193 ++ include/vcl/EnumContext.hxx | 167 + include/vcl/FilterConfigItem.hxx | 94 + include/vcl/GestureEvent.hxx | 61 + include/vcl/GraphicAttributes.hxx | 148 + include/vcl/GraphicExternalLink.hxx | 31 + include/vcl/GraphicLoader.hxx | 27 + include/vcl/GraphicNativeMetadata.hxx | 40 + include/vcl/GraphicNativeTransform.hxx | 43 + include/vcl/GraphicObject.hxx | 302 ++ include/vcl/IContext.hxx | 44 + include/vcl/IDialogRenderable.hxx | 47 + include/vcl/ITiledRenderable.hxx | 348 ++ include/vcl/IconThemeInfo.hxx | 98 + include/vcl/ImageTree.hxx | 95 + include/vcl/InterimItemWindow.hxx | 76 + include/vcl/NotebookbarContextControl.hxx | 24 + include/vcl/PrinterSupport.hxx | 34 + include/vcl/QueueInfo.hxx | 55 + include/vcl/RawBitmap.hxx | 79 + include/vcl/Scanline.hxx | 61 + include/vcl/TaskStopwatch.hxx | 117 + include/vcl/TypeSerializer.hxx | 60 + include/vcl/VectorGraphicSearch.hxx | 71 + include/vcl/WeldedTabbedNotebookbar.hxx | 36 + include/vcl/abstdlg.hxx | 193 ++ include/vcl/accessiblefactory.hxx | 173 + include/vcl/accessibletable.hxx | 174 + include/vcl/accessibletableprovider.hxx | 233 ++ include/vcl/alpha.hxx | 75 + include/vcl/animate/Animation.hxx | 118 + include/vcl/animate/AnimationBitmap.hxx | 78 + include/vcl/bitmap.hxx | 570 ++++ include/vcl/bitmap/BitmapTypes.hxx | 68 + include/vcl/bitmapex.hxx | 512 +++ include/vcl/builder.hxx | 450 +++ include/vcl/builderfactory.hxx | 51 + include/vcl/builderpage.hxx | 50 + include/vcl/cairo.hxx | 69 + include/vcl/canvastools.hxx | 167 + include/vcl/checksum.hxx | 84 + include/vcl/commandevent.hxx | 354 ++ include/vcl/commandinfoprovider.hxx | 107 + include/vcl/ctrl.hxx | 239 ++ include/vcl/cursor.hxx | 113 + include/vcl/customweld.hxx | 191 ++ include/vcl/cvtgrf.hxx | 50 + include/vcl/decoview.hxx | 95 + include/vcl/devicecoordinate.hxx | 27 + include/vcl/dialoghelper.hxx | 35 + include/vcl/dibtools.hxx | 87 + include/vcl/dllapi.h | 47 + include/vcl/dndhelp.hxx | 110 + include/vcl/dockingarea.hxx | 58 + include/vcl/dockwin.hxx | 255 ++ include/vcl/embeddedfontshelper.hxx | 110 + include/vcl/errcode.hxx | 279 ++ include/vcl/errinf.hxx | 229 ++ include/vcl/event.hxx | 387 +++ include/vcl/evntpost.hxx | 46 + include/vcl/exceptiontypes.hxx | 32 + include/vcl/extoutdevdata.hxx | 36 + include/vcl/fieldvalues.hxx | 80 + include/vcl/fileregistration.hxx | 28 + include/vcl/filter/PDFiumLibrary.hxx | 236 ++ include/vcl/filter/PngImageReader.hxx | 56 + include/vcl/filter/SvmReader.hxx | 94 + include/vcl/filter/SvmWriter.hxx | 94 + include/vcl/filter/pdfdocument.hxx | 645 ++++ include/vcl/filter/pdfobjectcontainer.hxx | 40 + include/vcl/fntstyle.hxx | 41 + include/vcl/font.hxx | 194 ++ include/vcl/font/Feature.hxx | 121 + include/vcl/font/FeatureParser.hxx | 48 + include/vcl/fontcapabilities.hxx | 203 ++ include/vcl/fontcharmap.hxx | 174 + include/vcl/formatter.hxx | 316 ++ include/vcl/gdimetafiletools.hxx | 55 + include/vcl/gdimtf.hxx | 195 ++ include/vcl/gfxlink.hxx | 114 + include/vcl/glyphitem.hxx | 57 + include/vcl/glyphitemcache.hxx | 111 + include/vcl/gradient.hxx | 99 + include/vcl/graph.hxx | 208 ++ include/vcl/graphicfilter.hxx | 392 +++ include/vcl/graphictools.hxx | 369 ++ include/vcl/hatch.hxx | 79 + include/vcl/headbar.hxx | 319 ++ include/vcl/help.hxx | 114 + include/vcl/i18nhelp.hxx | 77 + include/vcl/idle.hxx | 70 + include/vcl/image.hxx | 75 + include/vcl/imap.hxx | 138 + include/vcl/imapcirc.hxx | 69 + include/vcl/imapobj.hxx | 129 + include/vcl/imappoly.hxx | 73 + include/vcl/imaprect.hxx | 67 + include/vcl/inetimg.hxx | 58 + include/vcl/inputctx.hxx | 81 + include/vcl/inputtypes.hxx | 43 + include/vcl/introwin.hxx | 40 + include/vcl/jobset.hxx | 63 + include/vcl/jsdialog/executor.hxx | 93 + include/vcl/keycod.hxx | 116 + include/vcl/keycodes.hxx | 200 ++ include/vcl/layout.hxx | 842 +++++ include/vcl/lazydelete.hxx | 138 + include/vcl/lineinfo.hxx | 119 + include/vcl/locktoplevels.hxx | 38 + include/vcl/lok.hxx | 31 + include/vcl/mapmod.hxx | 93 + include/vcl/menu.hxx | 539 +++ include/vcl/menubarupdateicon.hxx | 89 + include/vcl/metaact.hxx | 1752 ++++++++++ include/vcl/metaactiontypes.hxx | 85 + include/vcl/metric.hxx | 109 + include/vcl/mnemonic.hxx | 75 + include/vcl/mtfxmldump.hxx | 63 + include/vcl/naturalsort.hxx | 20 + .../vcl/notebookbar/NotebookBarAddonsMerger.hxx | 62 + include/vcl/notebookbar/notebookbar.hxx | 77 + include/vcl/oldprintadaptor.hxx | 53 + include/vcl/opengl/OpenGLContext.hxx | 130 + include/vcl/opengl/OpenGLHelper.hxx | 124 + include/vcl/opengl/OpenGLWrapper.hxx | 31 + include/vcl/outdev.hxx | 1930 +++++++++++ include/vcl/outdev/ScopedStates.hxx | 41 + include/vcl/pdf/PDFAnnotationMarker.hxx | 77 + include/vcl/pdf/PDFAnnotationSubType.hxx | 50 + include/vcl/pdf/PDFBitmapType.hxx | 26 + include/vcl/pdf/PDFErrorType.hxx | 28 + include/vcl/pdf/PDFFillMode.hxx | 24 + include/vcl/pdf/PDFFindFlags.hxx | 35 + include/vcl/pdf/PDFObjectType.hxx | 31 + include/vcl/pdf/PDFPageObjectType.hxx | 27 + include/vcl/pdf/PDFSegmentType.hxx | 25 + include/vcl/pdf/PDFTextRenderMode.hxx | 30 + include/vcl/pdfextoutdevdata.hxx | 488 +++ include/vcl/pdfread.hxx | 107 + include/vcl/pdfwriter.hxx | 1227 +++++++ include/vcl/pngwrite.hxx | 60 + include/vcl/print.hxx | 615 ++++ include/vcl/printer/Options.hxx | 120 + include/vcl/prntypes.hxx | 93 + include/vcl/ptrstyle.hxx | 125 + include/vcl/quickselectionengine.hxx | 91 + include/vcl/region.hxx | 167 + .../vcl/rendercontext/AddFontSubstituteFlags.hxx | 38 + include/vcl/rendercontext/AntialiasingFlags.hxx | 38 + include/vcl/rendercontext/DrawGridFlags.hxx | 38 + include/vcl/rendercontext/DrawImageFlags.hxx | 41 + include/vcl/rendercontext/DrawModeFlags.hxx | 57 + include/vcl/rendercontext/DrawTextFlags.hxx | 53 + include/vcl/rendercontext/GetDefaultFontFlags.hxx | 36 + include/vcl/rendercontext/ImplMapRes.hxx | 36 + include/vcl/rendercontext/InvertFlags.hxx | 37 + include/vcl/rendercontext/RasterOp.hxx | 31 + include/vcl/rendercontext/SalLayoutFlags.hxx | 44 + include/vcl/rendercontext/State.hxx | 120 + include/vcl/rendercontext/SystemTextColorFlags.hxx | 37 + include/vcl/roadmapwizard.hxx | 189 ++ include/vcl/salctype.hxx | 64 + include/vcl/salgtype.hxx | 86 + include/vcl/salnativewidgets.hxx | 520 +++ include/vcl/scheduler.hxx | 88 + include/vcl/scopedbitmapaccess.hxx | 123 + include/vcl/scrbar.hxx | 158 + include/vcl/seleng.hxx | 240 ++ include/vcl/settings.hxx | 726 ++++ include/vcl/skia/SkiaHelper.hxx | 42 + include/vcl/sound.hxx | 30 + include/vcl/specialchars.hxx | 46 + include/vcl/split.hxx | 105 + include/vcl/splitwin.hxx | 187 + include/vcl/status.hxx | 193 ++ include/vcl/stdtext.hxx | 53 + include/vcl/svapp.hxx | 1482 ++++++++ include/vcl/svmain.hxx | 33 + include/vcl/svtaccessiblefactory.hxx | 59 + include/vcl/syschild.hxx | 67 + include/vcl/sysdata.hxx | 201 ++ include/vcl/syswin.hxx | 249 ++ include/vcl/tabctrl.hxx | 232 ++ include/vcl/tabpage.hxx | 77 + include/vcl/task.hxx | 115 + include/vcl/taskpanelist.hxx | 54 + include/vcl/test/GraphicsRenderTests.hxx | 167 + include/vcl/test/TestResult.hxx | 26 + include/vcl/textdata.hxx | 143 + include/vcl/texteng.hxx | 302 ++ include/vcl/textfilter.hxx | 31 + include/vcl/textrectinfo.hxx | 61 + include/vcl/textview.hxx | 229 ++ include/vcl/threadex.hxx | 174 + include/vcl/timer.hxx | 77 + include/vcl/toolbox.hxx | 537 +++ include/vcl/toolboxid.hxx | 23 + include/vcl/toolkit/README | 2 + include/vcl/toolkit/button.hxx | 507 +++ include/vcl/toolkit/calendar.hxx | 98 + include/vcl/toolkit/combobox.hxx | 197 ++ include/vcl/toolkit/dialog.hxx | 169 + include/vcl/toolkit/edit.hxx | 249 ++ include/vcl/toolkit/field.hxx | 627 ++++ include/vcl/toolkit/fixed.hxx | 181 + include/vcl/toolkit/fixedhyper.hxx | 118 + include/vcl/toolkit/floatwin.hxx | 140 + include/vcl/toolkit/fmtfield.hxx | 100 + include/vcl/toolkit/group.hxx | 57 + include/vcl/toolkit/imgctrl.hxx | 52 + include/vcl/toolkit/ivctrl.hxx | 259 ++ include/vcl/toolkit/longcurr.hxx | 74 + include/vcl/toolkit/lstbox.hxx | 266 ++ include/vcl/toolkit/menubtn.hxx | 97 + include/vcl/toolkit/morebtn.hxx | 56 + include/vcl/toolkit/prgsbar.hxx | 80 + include/vcl/toolkit/roadmap.hxx | 116 + include/vcl/toolkit/spin.hxx | 98 + include/vcl/toolkit/spinfld.hxx | 104 + include/vcl/toolkit/svlbitm.hxx | 287 ++ include/vcl/toolkit/svtabbx.hxx | 208 ++ include/vcl/toolkit/tabdlg.hxx | 49 + include/vcl/toolkit/throbber.hxx | 85 + include/vcl/toolkit/treelist.hxx | 296 ++ include/vcl/toolkit/treelistbox.hxx | 690 ++++ include/vcl/toolkit/treelistentries.hxx | 23 + include/vcl/toolkit/treelistentry.hxx | 131 + include/vcl/toolkit/unowrap.hxx | 93 + include/vcl/toolkit/vclmedit.hxx | 173 + include/vcl/toolkit/viewdataentry.hxx | 85 + include/vcl/transfer.hxx | 521 +++ include/vcl/txtattr.hxx | 189 ++ include/vcl/uitest/eventdescription.hxx | 24 + include/vcl/uitest/factory.hxx | 27 + include/vcl/uitest/formattedfielduiobject.hxx | 37 + include/vcl/uitest/logger.hxx | 68 + include/vcl/uitest/metricfielduiobject.hxx | 37 + include/vcl/uitest/uiobject.hxx | 589 ++++ include/vcl/uitest/uitest.hxx | 40 + include/vcl/unohelp.hxx | 50 + include/vcl/unohelp2.hxx | 68 + include/vcl/vclenum.hxx | 418 +++ include/vcl/vclevent.hxx | 220 ++ include/vcl/vcllayout.hxx | 125 + include/vcl/vclmain.hxx | 33 + include/vcl/vclptr.hxx | 442 +++ include/vcl/vclreferencebase.hxx | 72 + include/vcl/vectorgraphicdata.hxx | 139 + include/vcl/virdev.hxx | 189 ++ include/vcl/wall.hxx | 117 + include/vcl/weld.hxx | 2637 +++++++++++++++ include/vcl/weldutils.hxx | 471 +++ include/vcl/window.hxx | 1586 +++++++++ include/vcl/windowstate.hxx | 83 + include/vcl/winscheduler.hxx | 44 + include/vcl/wizardmachine.hxx | 356 ++ include/vcl/wmf.hxx | 41 + include/vcl/wmfexternal.hxx | 59 + include/vcl/wrkwin.hxx | 104 + include/vcl/xtextedt.hxx | 39 + include/version.hrc | 42 + include/xmloff/DashStyle.hxx | 62 + include/xmloff/DocumentSettingsContext.hxx | 58 + include/xmloff/EnumPropertyHdl.hxx | 49 + include/xmloff/GradientStyle.hxx | 64 + include/xmloff/HatchStyle.hxx | 61 + include/xmloff/ImageStyle.hxx | 45 + include/xmloff/MarkerStyle.hxx | 63 + include/xmloff/NamedBoolPropertyHdl.hxx | 54 + include/xmloff/ProgressBarHelper.hxx | 69 + include/xmloff/SchXMLExportHelper.hxx | 62 + include/xmloff/SchXMLImportHelper.hxx | 115 + include/xmloff/SchXMLSeriesHelper.hxx | 62 + include/xmloff/SettingsExportHelper.hxx | 101 + include/xmloff/SinglePropertySetInfoCache.hxx | 67 + include/xmloff/XMLBase64ImportContext.hxx | 49 + include/xmloff/XMLCharContext.hxx | 59 + include/xmloff/XMLConstantsPropertyHandler.hxx | 64 + include/xmloff/XMLDrawingPageStyleContext.hxx | 42 + include/xmloff/XMLEventExport.hxx | 128 + include/xmloff/XMLEventsImportContext.hxx | 102 + include/xmloff/XMLFilterServiceNames.h | 40 + include/xmloff/XMLFontAutoStylePool.hxx | 92 + include/xmloff/XMLFontStylesContext.hxx | 74 + include/xmloff/XMLGraphicsDefaultStyle.hxx | 44 + include/xmloff/XMLPageExport.hxx | 97 + include/xmloff/XMLSettingsExportContext.hxx | 60 + include/xmloff/XMLShapeStyleContext.hxx | 60 + include/xmloff/XMLTextListAutoStylePool.hxx | 76 + include/xmloff/XMLTextMasterPageContext.hxx | 81 + include/xmloff/XMLTextMasterPageExport.hxx | 50 + include/xmloff/XMLTextMasterStylesContext.hxx | 44 + include/xmloff/XMLTextShapeImportHelper.hxx | 44 + include/xmloff/XMLTextShapeStyleContext.hxx | 53 + include/xmloff/XMLTextTableContext.hxx | 36 + include/xmloff/animationexport.hxx | 55 + include/xmloff/animexp.hxx | 54 + include/xmloff/attrlist.hxx | 79 + include/xmloff/autolayout.hxx | 67 + include/xmloff/contextid.hxx | 43 + include/xmloff/controlpropertyhdl.hxx | 128 + include/xmloff/dllapi.h | 34 + include/xmloff/families.hxx | 115 + include/xmloff/formlayerexport.hxx | 185 + include/xmloff/formlayerimport.hxx | 133 + include/xmloff/i18nmap.hxx | 66 + include/xmloff/languagetagodf.hxx | 40 + include/xmloff/maptype.hxx | 152 + include/xmloff/namespacemap.hxx | 164 + include/xmloff/numehelp.hxx | 117 + include/xmloff/odffields.hxx | 61 + include/xmloff/prhdlfac.hxx | 106 + include/xmloff/prstylei.hxx | 118 + include/xmloff/settingsstore.hxx | 43 + include/xmloff/shapeexport.hxx | 311 ++ include/xmloff/shapeimport.hxx | 263 ++ include/xmloff/styleexp.hxx | 112 + include/xmloff/table/XMLTableExport.hxx | 105 + include/xmloff/table/XMLTableImport.hxx | 74 + include/xmloff/txtimp.hxx | 443 +++ include/xmloff/txtimppr.hxx | 69 + include/xmloff/txtparae.hxx | 582 ++++ include/xmloff/txtprmap.hxx | 233 ++ include/xmloff/txtstyli.hxx | 100 + include/xmloff/unoatrcn.hxx | 82 + .../unointerfacetouniqueidentifiermapper.hxx | 94 + include/xmloff/xformsexport.hxx | 53 + include/xmloff/xformsimport.hxx | 75 + include/xmloff/xmlaustp.hxx | 135 + include/xmloff/xmlcnimp.hxx | 78 + include/xmloff/xmlement.hxx | 86 + include/xmloff/xmlerror.hxx | 140 + include/xmloff/xmlevent.hxx | 141 + include/xmloff/xmlexp.hxx | 677 ++++ include/xmloff/xmlexppr.hxx | 182 + include/xmloff/xmlictxt.hxx | 125 + include/xmloff/xmlimp.hxx | 664 ++++ include/xmloff/xmlimppr.hxx | 212 ++ include/xmloff/xmlmetae.hxx | 102 + include/xmloff/xmlmetai.hxx | 63 + include/xmloff/xmlnamespace.hxx | 142 + include/xmloff/xmlnume.hxx | 76 + include/xmloff/xmlnumfe.hxx | 131 + include/xmloff/xmlnumfi.hxx | 217 ++ include/xmloff/xmlnumi.hxx | 82 + include/xmloff/xmlprcon.hxx | 68 + include/xmloff/xmlprhdl.hxx | 59 + include/xmloff/xmlprmap.hxx | 128 + include/xmloff/xmlscripti.hxx | 47 + include/xmloff/xmlstyle.hxx | 205 ++ include/xmloff/xmltkmap.hxx | 65 + include/xmloff/xmltoken.hxx | 3532 +++++++++++++++++++ include/xmloff/xmltypes.hxx | 301 ++ include/xmloff/xmluconv.hxx | 330 ++ include/xmlreader/README | 28 + include/xmlreader/detail/xmlreaderdllapi.hxx | 32 + include/xmlreader/pad.hxx | 54 + include/xmlreader/span.hxx | 82 + include/xmlreader/xmlreader.hxx | 186 + include/xmlscript/xml_helper.hxx | 121 + include/xmlscript/xmldlg_imexp.hxx | 63 + include/xmlscript/xmllib_imexp.hxx | 82 + include/xmlscript/xmlmod_imexp.hxx | 54 + include/xmlscript/xmlns.h | 38 + include/xmlscript/xmlscriptdllapi.h | 30 + 2539 files changed, 376076 insertions(+) create mode 100644 include/IwyuFilter_include.yaml create mode 100644 include/LibreOfficeKit/LibreOfficeKit.h create mode 100644 include/LibreOfficeKit/LibreOfficeKit.hxx create mode 100644 include/LibreOfficeKit/LibreOfficeKitEnums.h create mode 100644 include/LibreOfficeKit/LibreOfficeKitGtk.h create mode 100644 include/LibreOfficeKit/LibreOfficeKitInit.h create mode 100644 include/LibreOfficeKit/LibreOfficeKitTypes.h create mode 100644 include/android/compatibility.hxx create mode 100644 include/animations/animationnodehelper.hxx create mode 100644 include/apple_remote/RemoteControl.h create mode 100644 include/apple_remote/RemoteMainController.h create mode 100644 include/avmedia/MediaControlBase.hxx create mode 100644 include/avmedia/avmediadllapi.h create mode 100644 include/avmedia/mediaitem.hxx create mode 100644 include/avmedia/mediaplayer.hxx create mode 100644 include/avmedia/mediatoolbox.hxx create mode 100644 include/avmedia/mediawindow.hxx create mode 100644 include/basegfx/DrawCommands.hxx create mode 100644 include/basegfx/basegfxdllapi.h create mode 100644 include/basegfx/color/bcolor.hxx create mode 100644 include/basegfx/color/bcolormodifier.hxx create mode 100644 include/basegfx/color/bcolortools.hxx create mode 100644 include/basegfx/curve/b2dbeziertools.hxx create mode 100644 include/basegfx/curve/b2dcubicbezier.hxx create mode 100644 include/basegfx/matrix/b2dhommatrix.hxx create mode 100644 include/basegfx/matrix/b2dhommatrixtools.hxx create mode 100644 include/basegfx/matrix/b3dhommatrix.hxx create mode 100644 include/basegfx/matrix/b3dhommatrixtools.hxx create mode 100644 include/basegfx/numeric/ftools.hxx create mode 100644 include/basegfx/pixel/bpixel.hxx create mode 100644 include/basegfx/point/b2dpoint.hxx create mode 100644 include/basegfx/point/b2ipoint.hxx create mode 100644 include/basegfx/point/b3dpoint.hxx create mode 100644 include/basegfx/polygon/WaveLine.hxx create mode 100644 include/basegfx/polygon/b2dlinegeometry.hxx create mode 100644 include/basegfx/polygon/b2dpolygon.hxx create mode 100644 include/basegfx/polygon/b2dpolygonclipper.hxx create mode 100644 include/basegfx/polygon/b2dpolygoncutandtouch.hxx create mode 100644 include/basegfx/polygon/b2dpolygontools.hxx create mode 100644 include/basegfx/polygon/b2dpolygontriangulator.hxx create mode 100644 include/basegfx/polygon/b2dpolypolygon.hxx create mode 100644 include/basegfx/polygon/b2dpolypolygoncutter.hxx create mode 100644 include/basegfx/polygon/b2dpolypolygontools.hxx create mode 100644 include/basegfx/polygon/b2dtrapezoid.hxx create mode 100644 include/basegfx/polygon/b3dpolygon.hxx create mode 100644 include/basegfx/polygon/b3dpolygontools.hxx create mode 100644 include/basegfx/polygon/b3dpolypolygon.hxx create mode 100644 include/basegfx/polygon/b3dpolypolygontools.hxx create mode 100644 include/basegfx/range/Range2D.hxx create mode 100644 include/basegfx/range/b1drange.hxx create mode 100644 include/basegfx/range/b2dconnectedranges.hxx create mode 100644 include/basegfx/range/b2dpolyrange.hxx create mode 100644 include/basegfx/range/b2drange.hxx create mode 100644 include/basegfx/range/b2drangeclipper.hxx create mode 100644 include/basegfx/range/b2drectangle.hxx create mode 100644 include/basegfx/range/b2ibox.hxx create mode 100644 include/basegfx/range/b2irange.hxx create mode 100644 include/basegfx/range/b2irectangle.hxx create mode 100644 include/basegfx/range/b3drange.hxx create mode 100644 include/basegfx/range/basicbox.hxx create mode 100644 include/basegfx/range/basicrange.hxx create mode 100644 include/basegfx/raster/bzpixelraster.hxx create mode 100644 include/basegfx/raster/rasterconvert3d.hxx create mode 100644 include/basegfx/tuple/Tuple2D.hxx create mode 100644 include/basegfx/tuple/Tuple3D.hxx create mode 100644 include/basegfx/tuple/b2dtuple.hxx create mode 100644 include/basegfx/tuple/b2i64tuple.hxx create mode 100644 include/basegfx/tuple/b2ituple.hxx create mode 100644 include/basegfx/tuple/b3dtuple.hxx create mode 100644 include/basegfx/tuple/b3ituple.hxx create mode 100644 include/basegfx/utils/b2dclipstate.hxx create mode 100644 include/basegfx/utils/canvastools.hxx create mode 100644 include/basegfx/utils/common.hxx create mode 100644 include/basegfx/utils/gradienttools.hxx create mode 100644 include/basegfx/utils/keystoplerp.hxx create mode 100644 include/basegfx/utils/lerp.hxx create mode 100644 include/basegfx/utils/rectcliptools.hxx create mode 100644 include/basegfx/utils/systemdependentdata.hxx create mode 100644 include/basegfx/utils/tools.hxx create mode 100644 include/basegfx/utils/unopolypolygon.hxx create mode 100644 include/basegfx/utils/zoomtools.hxx create mode 100644 include/basegfx/vector/b2dsize.hxx create mode 100644 include/basegfx/vector/b2dvector.hxx create mode 100644 include/basegfx/vector/b2enums.hxx create mode 100644 include/basegfx/vector/b2isize.hxx create mode 100644 include/basegfx/vector/b2ivector.hxx create mode 100644 include/basegfx/vector/b3dvector.hxx create mode 100644 include/basic/basicdllapi.h create mode 100644 include/basic/basicmanagerrepository.hxx create mode 100644 include/basic/basmgr.hxx create mode 100644 include/basic/basrdll.hxx create mode 100644 include/basic/codecompletecache.hxx create mode 100644 include/basic/modsizeexceeded.hxx create mode 100644 include/basic/sbdef.hxx create mode 100644 include/basic/sberrors.hxx create mode 100644 include/basic/sbmeth.hxx create mode 100644 include/basic/sbmod.hxx create mode 100644 include/basic/sbstar.hxx create mode 100644 include/basic/sbuno.hxx create mode 100644 include/basic/sbx.hxx create mode 100644 include/basic/sbxcore.hxx create mode 100644 include/basic/sbxdef.hxx create mode 100644 include/basic/sbxmeth.hxx create mode 100644 include/basic/sbxobj.hxx create mode 100644 include/basic/sbxvar.hxx create mode 100644 include/basic/vbahelper.hxx create mode 100644 include/canvas/canvastools.hxx create mode 100644 include/canvas/canvastoolsdllapi.h create mode 100644 include/canvas/elapsedtime.hxx create mode 100644 include/codemaker/codemaker.hxx create mode 100644 include/codemaker/commoncpp.hxx create mode 100644 include/codemaker/commonjava.hxx create mode 100644 include/codemaker/exceptiontree.hxx create mode 100644 include/codemaker/generatedtypeset.hxx create mode 100644 include/codemaker/global.hxx create mode 100644 include/codemaker/options.hxx create mode 100644 include/codemaker/typemanager.hxx create mode 100644 include/codemaker/unotype.hxx create mode 100644 include/com/sun/star/uno/Any.h create mode 100644 include/com/sun/star/uno/Any.hxx create mode 100644 include/com/sun/star/uno/Reference.h create mode 100644 include/com/sun/star/uno/Reference.hxx create mode 100644 include/com/sun/star/uno/Sequence.h create mode 100644 include/com/sun/star/uno/Sequence.hxx create mode 100644 include/com/sun/star/uno/Type.h create mode 100644 include/com/sun/star/uno/Type.hxx create mode 100644 include/com/sun/star/uno/genfunc.h create mode 100644 include/com/sun/star/uno/genfunc.hxx create mode 100644 include/comphelper/AccessibleImplementationHelper.hxx create mode 100644 include/comphelper/ChainablePropertySet.hxx create mode 100644 include/comphelper/ChainablePropertySetInfo.hxx create mode 100644 include/comphelper/DirectoryHelper.hxx create mode 100644 include/comphelper/IdPropArrayHelper.hxx create mode 100644 include/comphelper/MasterPropertySet.hxx create mode 100644 include/comphelper/MasterPropertySetInfo.hxx create mode 100644 include/comphelper/PropertyInfoHash.hxx create mode 100644 include/comphelper/SelectionMultiplex.hxx create mode 100644 include/comphelper/SetFlagContextHelper.hxx create mode 100644 include/comphelper/accessiblecomponenthelper.hxx create mode 100644 include/comphelper/accessiblecontexthelper.hxx create mode 100644 include/comphelper/accessibleeventnotifier.hxx create mode 100644 include/comphelper/accessiblekeybindinghelper.hxx create mode 100644 include/comphelper/accessibleselectionhelper.hxx create mode 100644 include/comphelper/accessibletexthelper.hxx create mode 100644 include/comphelper/accessiblewrapper.hxx create mode 100644 include/comphelper/accimplaccess.hxx create mode 100644 include/comphelper/anycompare.hxx create mode 100644 include/comphelper/anytohash.hxx create mode 100644 include/comphelper/anytostring.hxx create mode 100644 include/comphelper/asyncnotification.hxx create mode 100644 include/comphelper/asyncquithandler.hxx create mode 100644 include/comphelper/attributelist.hxx create mode 100644 include/comphelper/automationinvokedzone.hxx create mode 100644 include/comphelper/backupfilehelper.hxx create mode 100644 include/comphelper/base64.hxx create mode 100644 include/comphelper/basicio.hxx create mode 100644 include/comphelper/broadcasthelper.hxx create mode 100644 include/comphelper/bytereader.hxx create mode 100644 include/comphelper/classids.hxx create mode 100644 include/comphelper/compbase.hxx create mode 100644 include/comphelper/comphelperdllapi.h create mode 100644 include/comphelper/componentbase.hxx create mode 100644 include/comphelper/componentguard.hxx create mode 100644 include/comphelper/configuration.hxx create mode 100644 include/comphelper/configurationhelper.hxx create mode 100644 include/comphelper/configurationlistener.hxx create mode 100644 include/comphelper/container.hxx create mode 100644 include/comphelper/containermultiplexer.hxx create mode 100644 include/comphelper/crashzone.hxx create mode 100644 include/comphelper/debuggerinfo.hxx create mode 100644 include/comphelper/dispatchcommand.hxx create mode 100644 include/comphelper/docpasswordhelper.hxx create mode 100644 include/comphelper/docpasswordrequest.hxx create mode 100644 include/comphelper/documentconstants.hxx create mode 100644 include/comphelper/documentinfo.hxx create mode 100644 include/comphelper/doublecheckedinit.hxx create mode 100644 include/comphelper/embeddedobjectcontainer.hxx create mode 100644 include/comphelper/enumhelper.hxx create mode 100644 include/comphelper/eventattachermgr.hxx create mode 100644 include/comphelper/evtlistenerhlp.hxx create mode 100644 include/comphelper/evtmethodhelper.hxx create mode 100644 include/comphelper/extract.hxx create mode 100644 include/comphelper/fileformat.h create mode 100644 include/comphelper/fileurl.hxx create mode 100644 include/comphelper/flagguard.hxx create mode 100644 include/comphelper/genericpropertyset.hxx create mode 100644 include/comphelper/getexpandeduri.hxx create mode 100644 include/comphelper/graphicmimetype.hxx create mode 100644 include/comphelper/guarding.hxx create mode 100644 include/comphelper/hash.hxx create mode 100644 include/comphelper/indexedpropertyvalues.hxx create mode 100644 include/comphelper/interaction.hxx create mode 100644 include/comphelper/interfacecontainer2.hxx create mode 100644 include/comphelper/interfacecontainer3.hxx create mode 100644 include/comphelper/interfacecontainer4.hxx create mode 100644 include/comphelper/logging.hxx create mode 100644 include/comphelper/lok.hxx create mode 100644 include/comphelper/make_shared_from_uno.hxx create mode 100644 include/comphelper/mimeconfighelper.hxx create mode 100644 include/comphelper/multicontainer2.hxx create mode 100644 include/comphelper/multiinterfacecontainer3.hxx create mode 100644 include/comphelper/multiinterfacecontainer4.hxx create mode 100644 include/comphelper/namecontainer.hxx create mode 100644 include/comphelper/namedvaluecollection.hxx create mode 100644 include/comphelper/newarray.hxx create mode 100644 include/comphelper/numberedcollection.hxx create mode 100644 include/comphelper/numbers.hxx create mode 100644 include/comphelper/ofopxmlhelper.hxx create mode 100644 include/comphelper/oslfile2streamwrap.hxx create mode 100644 include/comphelper/parallelsort.hxx create mode 100644 include/comphelper/processfactory.hxx create mode 100644 include/comphelper/profilezone.hxx create mode 100644 include/comphelper/propagg.hxx create mode 100644 include/comphelper/proparrhlp.hxx create mode 100644 include/comphelper/property.hxx create mode 100644 include/comphelper/propertybag.hxx create mode 100644 include/comphelper/propertycontainer.hxx create mode 100644 include/comphelper/propertycontainerhelper.hxx create mode 100644 include/comphelper/propertysequence.hxx create mode 100644 include/comphelper/propertysethelper.hxx create mode 100644 include/comphelper/propertysetinfo.hxx create mode 100644 include/comphelper/propertystatecontainer.hxx create mode 100644 include/comphelper/propertyvalue.hxx create mode 100644 include/comphelper/propmultiplex.hxx create mode 100644 include/comphelper/propstate.hxx create mode 100644 include/comphelper/proxyaggregation.hxx create mode 100644 include/comphelper/random.hxx create mode 100644 include/comphelper/refcountedmutex.hxx create mode 100644 include/comphelper/scopeguard.hxx create mode 100644 include/comphelper/seekableinput.hxx create mode 100644 include/comphelper/seqstream.hxx create mode 100644 include/comphelper/sequence.hxx create mode 100644 include/comphelper/sequenceashashmap.hxx create mode 100644 include/comphelper/servicedecl.hxx create mode 100644 include/comphelper/servicehelper.hxx create mode 100644 include/comphelper/sharedmutex.hxx create mode 100644 include/comphelper/simplefileaccessinteraction.hxx create mode 100644 include/comphelper/solarmutex.hxx create mode 100644 include/comphelper/stillreadwriteinteraction.hxx create mode 100644 include/comphelper/stl_types.hxx create mode 100644 include/comphelper/storagehelper.hxx create mode 100644 include/comphelper/streamsection.hxx create mode 100644 include/comphelper/string.hxx create mode 100644 include/comphelper/synchronousdispatch.hxx create mode 100644 include/comphelper/syntaxhighlight.hxx create mode 100644 include/comphelper/threadpool.hxx create mode 100644 include/comphelper/traceevent.hxx create mode 100644 include/comphelper/types.hxx create mode 100644 include/comphelper/unique_disposing_ptr.hxx create mode 100644 include/comphelper/uno3.hxx create mode 100644 include/comphelper/unwrapargs.hxx create mode 100644 include/comphelper/weak.hxx create mode 100644 include/comphelper/weakbag.hxx create mode 100644 include/comphelper/weakeventlistener.hxx create mode 100644 include/comphelper/windowsStart.hxx create mode 100644 include/comphelper/windowsdebugoutput.hxx create mode 100644 include/comphelper/windowserrorstring.hxx create mode 100644 include/comphelper/xmlsechelper.hxx create mode 100644 include/comphelper/xmltools.hxx create mode 100644 include/connectivity/BlobHelper.hxx create mode 100644 include/connectivity/CommonTools.hxx create mode 100644 include/connectivity/ConnectionWrapper.hxx create mode 100644 include/connectivity/DriversConfig.hxx create mode 100644 include/connectivity/FValue.hxx create mode 100644 include/connectivity/IParseContext.hxx create mode 100644 include/connectivity/PColumn.hxx create mode 100644 include/connectivity/TColumnsHelper.hxx create mode 100644 include/connectivity/TIndexes.hxx create mode 100644 include/connectivity/TKeys.hxx create mode 100644 include/connectivity/TTableHelper.hxx create mode 100644 include/connectivity/conncleanup.hxx create mode 100644 include/connectivity/dbcharset.hxx create mode 100644 include/connectivity/dbconversion.hxx create mode 100644 include/connectivity/dbexception.hxx create mode 100644 include/connectivity/dbmetadata.hxx create mode 100644 include/connectivity/dbtools.hxx create mode 100644 include/connectivity/dbtoolsdllapi.hxx create mode 100644 include/connectivity/filtermanager.hxx create mode 100644 include/connectivity/formattedcolumnvalue.hxx create mode 100644 include/connectivity/internalnode.hxx create mode 100644 include/connectivity/odbc.hxx create mode 100644 include/connectivity/parameters.hxx create mode 100644 include/connectivity/paramwrapper.hxx create mode 100644 include/connectivity/predicateinput.hxx create mode 100644 include/connectivity/sdbcx/IRefreshable.hxx create mode 100644 include/connectivity/sdbcx/VCollection.hxx create mode 100644 include/connectivity/sdbcx/VColumn.hxx create mode 100644 include/connectivity/sdbcx/VDescriptor.hxx create mode 100644 include/connectivity/sdbcx/VTable.hxx create mode 100644 include/connectivity/sdbcx/VView.hxx create mode 100644 include/connectivity/sqlbison_exports.hxx create mode 100644 include/connectivity/sqlerror.hxx create mode 100644 include/connectivity/sqliterator.hxx create mode 100644 include/connectivity/sqlnode.hxx create mode 100644 include/connectivity/sqlparse.hxx create mode 100644 include/connectivity/sqlscan.hxx create mode 100644 include/connectivity/standardsqlstate.hxx create mode 100644 include/connectivity/statementcomposer.hxx create mode 100644 include/connectivity/warningscontainer.hxx create mode 100644 include/cppcanvas/basegfxfactory.hxx create mode 100644 include/cppcanvas/bitmap.hxx create mode 100644 include/cppcanvas/bitmapcanvas.hxx create mode 100644 include/cppcanvas/canvas.hxx create mode 100644 include/cppcanvas/canvasgraphic.hxx create mode 100644 include/cppcanvas/color.hxx create mode 100644 include/cppcanvas/cppcanvasdllapi.h create mode 100644 include/cppcanvas/customsprite.hxx create mode 100644 include/cppcanvas/polypolygon.hxx create mode 100644 include/cppcanvas/renderer.hxx create mode 100644 include/cppcanvas/sprite.hxx create mode 100644 include/cppcanvas/spritecanvas.hxx create mode 100644 include/cppcanvas/vclfactory.hxx create mode 100644 include/cppu/Enterable.hxx create mode 100644 include/cppu/EnvDcp.hxx create mode 100644 include/cppu/EnvGuards.hxx create mode 100644 include/cppu/Map.hxx create mode 100644 include/cppu/cppudllapi.h create mode 100644 include/cppu/helper/purpenv/Environment.hxx create mode 100644 include/cppu/helper/purpenv/Mapping.hxx create mode 100644 include/cppu/macros.hxx create mode 100644 include/cppu/unotype.hxx create mode 100644 include/cppuhelper/TODO create mode 100644 include/cppuhelper/access_control.hxx create mode 100644 include/cppuhelper/basemutex.hxx create mode 100644 include/cppuhelper/bootstrap.hxx create mode 100644 include/cppuhelper/compbase.hxx create mode 100644 include/cppuhelper/compbase1.hxx create mode 100644 include/cppuhelper/compbase10.hxx create mode 100644 include/cppuhelper/compbase11.hxx create mode 100644 include/cppuhelper/compbase12.hxx create mode 100644 include/cppuhelper/compbase2.hxx create mode 100644 include/cppuhelper/compbase3.hxx create mode 100644 include/cppuhelper/compbase4.hxx create mode 100644 include/cppuhelper/compbase5.hxx create mode 100644 include/cppuhelper/compbase6.hxx create mode 100644 include/cppuhelper/compbase7.hxx create mode 100644 include/cppuhelper/compbase8.hxx create mode 100644 include/cppuhelper/compbase9.hxx create mode 100644 include/cppuhelper/compbase_ex.hxx create mode 100644 include/cppuhelper/component.hxx create mode 100644 include/cppuhelper/component_context.hxx create mode 100644 include/cppuhelper/cppuhelperdllapi.h create mode 100644 include/cppuhelper/exc_hlp.hxx create mode 100644 include/cppuhelper/factory.hxx create mode 100644 include/cppuhelper/findsofficepath.h create mode 100644 include/cppuhelper/implbase.hxx create mode 100644 include/cppuhelper/implbase1.hxx create mode 100644 include/cppuhelper/implbase10.hxx create mode 100644 include/cppuhelper/implbase11.hxx create mode 100644 include/cppuhelper/implbase12.hxx create mode 100644 include/cppuhelper/implbase13.hxx create mode 100644 include/cppuhelper/implbase2.hxx create mode 100644 include/cppuhelper/implbase3.hxx create mode 100644 include/cppuhelper/implbase4.hxx create mode 100644 include/cppuhelper/implbase5.hxx create mode 100644 include/cppuhelper/implbase6.hxx create mode 100644 include/cppuhelper/implbase7.hxx create mode 100644 include/cppuhelper/implbase8.hxx create mode 100644 include/cppuhelper/implbase9.hxx create mode 100644 include/cppuhelper/implbase_ex.hxx create mode 100644 include/cppuhelper/implbase_ex_post.hxx create mode 100644 include/cppuhelper/implbase_ex_pre.hxx create mode 100644 include/cppuhelper/implementationentry.hxx create mode 100644 include/cppuhelper/interfacecontainer.h create mode 100644 include/cppuhelper/interfacecontainer.hxx create mode 100644 include/cppuhelper/propertysetmixin.hxx create mode 100644 include/cppuhelper/propshlp.hxx create mode 100644 include/cppuhelper/proptypehlp.h create mode 100644 include/cppuhelper/proptypehlp.hxx create mode 100644 include/cppuhelper/queryinterface.hxx create mode 100644 include/cppuhelper/shlib.hxx create mode 100644 include/cppuhelper/supportsservice.hxx create mode 100644 include/cppuhelper/typeprovider.hxx create mode 100644 include/cppuhelper/unourl.hxx create mode 100644 include/cppuhelper/weak.hxx create mode 100644 include/cppuhelper/weakagg.hxx create mode 100644 include/cppuhelper/weakref.hxx create mode 100644 include/cppunittester/protectorfactory.hxx create mode 100644 include/cui/cuicharmap.hxx create mode 100644 include/cui/cuidllapi.h create mode 100644 include/cui/numberingpreview.hxx create mode 100644 include/dbaccess/AsynchronousLink.hxx create mode 100644 include/dbaccess/IController.hxx create mode 100644 include/dbaccess/controllerframe.hxx create mode 100644 include/dbaccess/dataview.hxx create mode 100644 include/dbaccess/dbaccessdllapi.h create mode 100644 include/dbaccess/dbaundomanager.hxx create mode 100644 include/dbaccess/dbsubcomponentcontroller.hxx create mode 100644 include/dbaccess/genericcontroller.hxx create mode 100644 include/default.rc create mode 100644 include/desktop/crashreport.hxx create mode 100644 include/desktop/dllapi.h create mode 100644 include/desktop/exithelper.h create mode 100644 include/desktop/minidump.hxx create mode 100644 include/drawinglayer/XShapeDumper.hxx create mode 100644 include/drawinglayer/animation/animationtiming.hxx create mode 100644 include/drawinglayer/attribute/fillgradientattribute.hxx create mode 100644 include/drawinglayer/attribute/fillgraphicattribute.hxx create mode 100644 include/drawinglayer/attribute/fillhatchattribute.hxx create mode 100644 include/drawinglayer/attribute/fontattribute.hxx create mode 100644 include/drawinglayer/attribute/lineattribute.hxx create mode 100644 include/drawinglayer/attribute/linestartendattribute.hxx create mode 100644 include/drawinglayer/attribute/materialattribute3d.hxx create mode 100644 include/drawinglayer/attribute/sdrallattribute3d.hxx create mode 100644 include/drawinglayer/attribute/sdrfillattribute.hxx create mode 100644 include/drawinglayer/attribute/sdrfillgraphicattribute.hxx create mode 100644 include/drawinglayer/attribute/sdrglowattribute.hxx create mode 100644 include/drawinglayer/attribute/sdrlightattribute3d.hxx create mode 100644 include/drawinglayer/attribute/sdrlightingattribute3d.hxx create mode 100644 include/drawinglayer/attribute/sdrlineattribute.hxx create mode 100644 include/drawinglayer/attribute/sdrlinestartendattribute.hxx create mode 100644 include/drawinglayer/attribute/sdrobjectattribute3d.hxx create mode 100644 include/drawinglayer/attribute/sdrsceneattribute3d.hxx create mode 100644 include/drawinglayer/attribute/sdrshadowattribute.hxx create mode 100644 include/drawinglayer/attribute/strokeattribute.hxx create mode 100644 include/drawinglayer/converters.hxx create mode 100644 include/drawinglayer/drawinglayerdllapi.h create mode 100644 include/drawinglayer/geometry/viewinformation2d.hxx create mode 100644 include/drawinglayer/geometry/viewinformation3d.hxx create mode 100644 include/drawinglayer/primitive2d/BufferedDecompositionPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/CommonTypes.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonColorPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonGradientPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonGraphicPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonHairlinePrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonHatchPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonMarkerPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonSelectionPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolyPolygonStrokePrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolygonHairlinePrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolygonMarkerPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolygonStrokeArrowPrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolygonStrokePrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/PolygonWavePrimitive2D.hxx create mode 100644 include/drawinglayer/primitive2d/Primitive2DContainer.hxx create mode 100644 include/drawinglayer/primitive2d/Primitive2DVisitor.hxx create mode 100644 include/drawinglayer/primitive2d/Tools.hxx create mode 100644 include/drawinglayer/primitive2d/animatedprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/backgroundcolorprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/baseprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/bitmapprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/borderlineprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/controlprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/discretebitmapprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/discreteshadowprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx create mode 100644 include/drawinglayer/primitive2d/embedded3dprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/epsprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/fillgradientprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/fillgraphicprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/fillhatchprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/glowprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/graphicprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/gridprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/groupprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/helplineprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/invertprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/markerarrayprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/maskprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/mediaprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/metafileprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/modifiedcolorprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/objectinfoprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/pagehierarchyprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/pagepreviewprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/patternfillprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/pointarrayprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/primitivetools2d.hxx create mode 100644 include/drawinglayer/primitive2d/sceneprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/sdrdecompositiontools2d.hxx create mode 100644 include/drawinglayer/primitive2d/shadowprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/softedgeprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/structuretagprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/svggradientprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/textbreakuphelper.hxx create mode 100644 include/drawinglayer/primitive2d/textdecoratedprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/textenumsprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/texthierarchyprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/textlayoutdevice.hxx create mode 100644 include/drawinglayer/primitive2d/textprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/transformprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/transparenceprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/unifiedtransparenceprimitive2d.hxx create mode 100644 include/drawinglayer/primitive2d/wrongspellprimitive2d.hxx create mode 100644 include/drawinglayer/primitive3d/Tools.hxx create mode 100644 include/drawinglayer/primitive3d/baseprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/drawinglayer_primitivetypes3d.hxx create mode 100644 include/drawinglayer/primitive3d/groupprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/modifiedcolorprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/polygonprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/polypolygonprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrcubeprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrextrudeprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrlatheprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrpolypolygonprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/sdrsphereprimitive3d.hxx create mode 100644 include/drawinglayer/primitive3d/transformprimitive3d.hxx create mode 100644 include/drawinglayer/processor2d/baseprocessor2d.hxx create mode 100644 include/drawinglayer/processor2d/contourextractor2d.hxx create mode 100644 include/drawinglayer/processor2d/hittestprocessor2d.hxx create mode 100644 include/drawinglayer/processor2d/linegeometryextractor2d.hxx create mode 100644 include/drawinglayer/processor2d/objectinfoextractor2d.hxx create mode 100644 include/drawinglayer/processor2d/processor2dtools.hxx create mode 100644 include/drawinglayer/processor2d/processorfromoutputdevice.hxx create mode 100644 include/drawinglayer/processor2d/textaspolygonextractor2d.hxx create mode 100644 include/drawinglayer/processor3d/baseprocessor3d.hxx create mode 100644 include/drawinglayer/processor3d/cutfindprocessor3d.hxx create mode 100644 include/drawinglayer/tools/primitive2dxmldump.hxx create mode 100644 include/editeng/AccessibleComponentBase.hxx create mode 100644 include/editeng/AccessibleContextBase.hxx create mode 100644 include/editeng/AccessibleEditableTextPara.hxx create mode 100644 include/editeng/AccessibleParaManager.hxx create mode 100644 include/editeng/AccessibleSelectionBase.hxx create mode 100644 include/editeng/AccessibleStaticTextBase.hxx create mode 100644 include/editeng/CustomPropertyField.hxx create mode 100644 include/editeng/SpellPortions.hxx create mode 100644 include/editeng/Trie.hxx create mode 100644 include/editeng/UnoForbiddenCharsTable.hxx create mode 100644 include/editeng/acorrcfg.hxx create mode 100644 include/editeng/adjustitem.hxx create mode 100644 include/editeng/autokernitem.hxx create mode 100644 include/editeng/blinkitem.hxx create mode 100644 include/editeng/borderline.hxx create mode 100644 include/editeng/boxitem.hxx create mode 100644 include/editeng/brushitem.hxx create mode 100644 include/editeng/bulletitem.hxx create mode 100644 include/editeng/charhiddenitem.hxx create mode 100644 include/editeng/charreliefitem.hxx create mode 100644 include/editeng/charrotateitem.hxx create mode 100644 include/editeng/charscaleitem.hxx create mode 100644 include/editeng/cmapitem.hxx create mode 100644 include/editeng/colritem.hxx create mode 100644 include/editeng/contouritem.hxx create mode 100644 include/editeng/crossedoutitem.hxx create mode 100644 include/editeng/editdata.hxx create mode 100644 include/editeng/editeng.hxx create mode 100644 include/editeng/editengdllapi.h create mode 100644 include/editeng/editerr.hxx create mode 100644 include/editeng/editids.hrc create mode 100644 include/editeng/editobj.hxx create mode 100644 include/editeng/editrids.hrc create mode 100644 include/editeng/editstat.hxx create mode 100644 include/editeng/editund2.hxx create mode 100644 include/editeng/editview.hxx create mode 100644 include/editeng/edtdlg.hxx create mode 100644 include/editeng/eedata.hxx create mode 100644 include/editeng/eeitem.hxx create mode 100644 include/editeng/eerdll.hxx create mode 100644 include/editeng/emphasismarkitem.hxx create mode 100644 include/editeng/escapementitem.hxx create mode 100644 include/editeng/fhgtitem.hxx create mode 100644 include/editeng/fieldupdater.hxx create mode 100644 include/editeng/flditem.hxx create mode 100644 include/editeng/flstitem.hxx create mode 100644 include/editeng/fontitem.hxx create mode 100644 include/editeng/forbiddencharacterstable.hxx create mode 100644 include/editeng/forbiddenruleitem.hxx create mode 100644 include/editeng/formatbreakitem.hxx create mode 100644 include/editeng/frmdir.hxx create mode 100644 include/editeng/frmdiritem.hxx create mode 100644 include/editeng/hangulhanja.hxx create mode 100644 include/editeng/hngpnctitem.hxx create mode 100644 include/editeng/hyphenzoneitem.hxx create mode 100644 include/editeng/itemtype.hxx create mode 100644 include/editeng/justifyitem.hxx create mode 100644 include/editeng/keepitem.hxx create mode 100644 include/editeng/kernitem.hxx create mode 100644 include/editeng/langitem.hxx create mode 100644 include/editeng/legacyitem.hxx create mode 100644 include/editeng/lineitem.hxx create mode 100644 include/editeng/lrspitem.hxx create mode 100644 include/editeng/lspcitem.hxx create mode 100644 include/editeng/macros.hxx create mode 100644 include/editeng/measfld.hxx create mode 100644 include/editeng/memberids.h create mode 100644 include/editeng/misspellrange.hxx create mode 100644 include/editeng/nhypitem.hxx create mode 100644 include/editeng/numdef.hxx create mode 100644 include/editeng/numitem.hxx create mode 100644 include/editeng/opaqitem.hxx create mode 100644 include/editeng/optitems.hxx create mode 100644 include/editeng/orphitem.hxx create mode 100644 include/editeng/outliner.hxx create mode 100644 include/editeng/outlobj.hxx create mode 100644 include/editeng/overflowingtxt.hxx create mode 100644 include/editeng/paperinf.hxx create mode 100644 include/editeng/paragraphdata.hxx create mode 100644 include/editeng/paravertalignitem.hxx create mode 100644 include/editeng/pbinitem.hxx create mode 100644 include/editeng/pgrditem.hxx create mode 100644 include/editeng/pmdlitem.hxx create mode 100644 include/editeng/postitem.hxx create mode 100644 include/editeng/prntitem.hxx create mode 100644 include/editeng/protitem.hxx create mode 100644 include/editeng/rsiditem.hxx create mode 100644 include/editeng/scriptspaceitem.hxx create mode 100644 include/editeng/scripttypeitem.hxx create mode 100644 include/editeng/section.hxx create mode 100644 include/editeng/shaditem.hxx create mode 100644 include/editeng/shdditem.hxx create mode 100644 include/editeng/sizeitem.hxx create mode 100644 include/editeng/spltitem.hxx create mode 100644 include/editeng/splwrap.hxx create mode 100644 include/editeng/svxacorr.hxx create mode 100644 include/editeng/svxenum.hxx create mode 100644 include/editeng/svxfont.hxx create mode 100644 include/editeng/svxrtf.hxx create mode 100644 include/editeng/swafopt.hxx create mode 100644 include/editeng/tstpitem.hxx create mode 100644 include/editeng/twolinesitem.hxx create mode 100644 include/editeng/txtrange.hxx create mode 100644 include/editeng/udlnitem.hxx create mode 100644 include/editeng/ulspitem.hxx create mode 100644 include/editeng/unoedhlp.hxx create mode 100644 include/editeng/unoedprx.hxx create mode 100644 include/editeng/unoedsrc.hxx create mode 100644 include/editeng/unofdesc.hxx create mode 100644 include/editeng/unofield.hxx create mode 100644 include/editeng/unofored.hxx create mode 100644 include/editeng/unoforou.hxx create mode 100644 include/editeng/unoipset.hxx create mode 100644 include/editeng/unolingu.hxx create mode 100644 include/editeng/unonames.hxx create mode 100644 include/editeng/unonrule.hxx create mode 100644 include/editeng/unoprnms.hxx create mode 100644 include/editeng/unotext.hxx create mode 100644 include/editeng/unoviwou.hxx create mode 100644 include/editeng/urlfieldhelper.hxx create mode 100644 include/editeng/wghtitem.hxx create mode 100644 include/editeng/widwitem.hxx create mode 100644 include/editeng/writingmodeitem.hxx create mode 100644 include/editeng/wrlmitem.hxx create mode 100644 include/editeng/xmlcnitm.hxx create mode 100644 include/embeddedobj/embeddedupdate.hxx create mode 100644 include/embeddedobj/embobjdllapi.h create mode 100644 include/filter/dllapi.h create mode 100644 include/filter/msfilter/classids.hxx create mode 100644 include/filter/msfilter/countryid.hxx create mode 100644 include/filter/msfilter/dffpropset.hxx create mode 100644 include/filter/msfilter/dffrecordheader.hxx create mode 100644 include/filter/msfilter/escherex.hxx create mode 100644 include/filter/msfilter/mscodec.hxx create mode 100644 include/filter/msfilter/msdffimp.hxx create mode 100644 include/filter/msfilter/msfilterdllapi.h create mode 100644 include/filter/msfilter/msocximex.hxx create mode 100644 include/filter/msfilter/msoleexp.hxx create mode 100644 include/filter/msfilter/mstoolbar.hxx create mode 100644 include/filter/msfilter/msvbahelper.hxx create mode 100644 include/filter/msfilter/rtfutil.hxx create mode 100644 include/filter/msfilter/svdfppt.hxx create mode 100644 include/filter/msfilter/svxmsbas.hxx create mode 100644 include/filter/msfilter/util.hxx create mode 100644 include/filter/msfilter/ww8fields.hxx create mode 100644 include/formula/ExternalReferenceHelper.hxx create mode 100644 include/formula/FormulaCompiler.hxx create mode 100644 include/formula/FormulaOpCodeMapperObj.hxx create mode 100644 include/formula/IControlReferenceHandler.hxx create mode 100644 include/formula/IFunctionDescription.hxx create mode 100644 include/formula/compiler.hxx create mode 100644 include/formula/errorcodes.hxx create mode 100644 include/formula/formdata.hxx create mode 100644 include/formula/formula.hxx create mode 100644 include/formula/formuladllapi.h create mode 100644 include/formula/formulahelper.hxx create mode 100644 include/formula/funcutl.hxx create mode 100644 include/formula/funcvarargs.h create mode 100644 include/formula/grammar.hxx create mode 100644 include/formula/opcode.hxx create mode 100644 include/formula/paramclass.hxx create mode 100644 include/formula/token.hxx create mode 100644 include/formula/tokenarray.hxx create mode 100644 include/formula/types.hxx create mode 100644 include/formula/vectortoken.hxx create mode 100644 include/fpicker/fpsofficeResMgr.hxx create mode 100644 include/fpicker/strings.hrc create mode 100644 include/framework/ContextChangeEventMultiplexerTunnel.hxx create mode 100644 include/framework/actiontriggerhelper.hxx create mode 100644 include/framework/addonsoptions.hxx create mode 100644 include/framework/configimporter.hxx create mode 100644 include/framework/desktop.hxx create mode 100644 include/framework/dispatchhelper.hxx create mode 100644 include/framework/documentundoguard.hxx create mode 100644 include/framework/framecontainer.hxx create mode 100644 include/framework/framelistanalyzer.hxx create mode 100644 include/framework/fwkdllapi.h create mode 100644 include/framework/gate.hxx create mode 100644 include/framework/generictoolbarcontroller.hxx create mode 100644 include/framework/imutex.hxx create mode 100644 include/framework/interaction.hxx create mode 100644 include/framework/sfxhelperfunctions.hxx create mode 100644 include/framework/titlehelper.hxx create mode 100644 include/framework/transactionmanager.hxx create mode 100644 include/framework/undomanagerhelper.hxx create mode 100644 include/helpcompiler/HelpIndexer.hxx create mode 100644 include/helpcompiler/HelpSearch.hxx create mode 100644 include/helpcompiler/compilehelp.hxx create mode 100644 include/helpcompiler/dllapi.h create mode 100644 include/i18nlangtag/applelangid.hxx create mode 100644 include/i18nlangtag/i18nlangtagdllapi.h create mode 100644 include/i18nlangtag/lang.h create mode 100644 include/i18nlangtag/languagetag.hxx create mode 100644 include/i18nlangtag/languagetagicu.hxx create mode 100644 include/i18nlangtag/mslangid.hxx create mode 100644 include/i18npool/reservedconstants.hxx create mode 100644 include/i18nutil/calendar.hxx create mode 100644 include/i18nutil/casefolding.hxx create mode 100644 include/i18nutil/i18nutildllapi.h create mode 100644 include/i18nutil/oneToOneMapping.hxx create mode 100644 include/i18nutil/paper.hxx create mode 100644 include/i18nutil/scripttypedetector.hxx create mode 100644 include/i18nutil/searchopt.hxx create mode 100644 include/i18nutil/transliteration.hxx create mode 100644 include/i18nutil/unicode.hxx create mode 100644 include/i18nutil/widthfolding.hxx create mode 100644 include/jvmaccess/classpath.hxx create mode 100644 include/jvmaccess/jvmaccessdllapi.h create mode 100644 include/jvmaccess/unovirtualmachine.hxx create mode 100644 include/jvmaccess/virtualmachine.hxx create mode 100644 include/jvmfwk/framework.hxx create mode 100644 include/jvmfwk/jvmfwkdllapi.hxx create mode 100644 include/linguistic/hyphdta.hxx create mode 100644 include/linguistic/lngdllapi.h create mode 100644 include/linguistic/lngprophelp.hxx create mode 100644 include/linguistic/lngprops.hxx create mode 100644 include/linguistic/misc.hxx create mode 100644 include/linguistic/spelldta.hxx create mode 100644 include/o3tl/any.hxx create mode 100644 include/o3tl/char16_t2wchar_t.hxx create mode 100644 include/o3tl/cow_wrapper.hxx create mode 100644 include/o3tl/cppunittraitshelper.hxx create mode 100644 include/o3tl/deleter.hxx create mode 100644 include/o3tl/enumarray.hxx create mode 100644 include/o3tl/enumrange.hxx create mode 100644 include/o3tl/float_int_conversion.hxx create mode 100644 include/o3tl/functional.hxx create mode 100644 include/o3tl/hash_combine.hxx create mode 100644 include/o3tl/intcmp.hxx create mode 100644 include/o3tl/lazy_update.hxx create mode 100644 include/o3tl/lru_map.hxx create mode 100644 include/o3tl/make_shared.hxx create mode 100644 include/o3tl/numeric.hxx create mode 100644 include/o3tl/runtimetooustring.hxx create mode 100644 include/o3tl/safeCoInitUninit.hxx create mode 100644 include/o3tl/safeint.hxx create mode 100644 include/o3tl/sorted_vector.hxx create mode 100644 include/o3tl/span.hxx create mode 100644 include/o3tl/sprintf.hxx create mode 100644 include/o3tl/string_view.hxx create mode 100644 include/o3tl/strong_int.hxx create mode 100644 include/o3tl/temporary.hxx create mode 100644 include/o3tl/typed_flags_set.hxx create mode 100644 include/o3tl/underlyingenumvalue.hxx create mode 100644 include/o3tl/unit_conversion.hxx create mode 100644 include/o3tl/unreachable.hxx create mode 100644 include/o3tl/unsafe_downcast.hxx create mode 100644 include/o3tl/vector_pool.hxx create mode 100644 include/o3tl/vector_utils.hxx create mode 100644 include/onlineupdate/mar.h create mode 100644 include/onlineupdate/mar_cmdline.h create mode 100644 include/onlineupdate/mar_private.h create mode 100644 include/onlineupdate/mozilla/Assertions.h create mode 100644 include/onlineupdate/mozilla/Attributes.h create mode 100644 include/onlineupdate/mozilla/Compiler.h create mode 100644 include/onlineupdate/mozilla/Likely.h create mode 100644 include/onlineupdate/mozilla/MacroArgs.h create mode 100644 include/onlineupdate/mozilla/TypeTraits.h create mode 100644 include/onlineupdate/mozilla/Types.h create mode 100644 include/onlineupdate/mozilla/nsTraceRefcnt.h create mode 100644 include/oox/core/binarycodec.hxx create mode 100644 include/oox/core/contexthandler.hxx create mode 100644 include/oox/core/contexthandler2.hxx create mode 100644 include/oox/core/fastparser.hxx create mode 100644 include/oox/core/fasttokenhandler.hxx create mode 100644 include/oox/core/filterbase.hxx create mode 100644 include/oox/core/filterdetect.hxx create mode 100644 include/oox/core/fragmenthandler.hxx create mode 100644 include/oox/core/fragmenthandler2.hxx create mode 100644 include/oox/core/recordparser.hxx create mode 100644 include/oox/core/relations.hxx create mode 100644 include/oox/core/relationshandler.hxx create mode 100644 include/oox/core/xmlfilterbase.hxx create mode 100644 include/oox/crypto/AgileEngine.hxx create mode 100644 include/oox/crypto/CryptTools.hxx create mode 100644 include/oox/crypto/CryptoEngine.hxx create mode 100644 include/oox/crypto/DocumentDecryption.hxx create mode 100644 include/oox/crypto/DocumentEncryption.hxx create mode 100644 include/oox/crypto/Standard2007Engine.hxx create mode 100644 include/oox/crypto/StrongEncryptionDataSpace.hxx create mode 100644 include/oox/dllapi.h create mode 100644 include/oox/drawingml/chart/chartconverter.hxx create mode 100644 include/oox/drawingml/chart/datasourcemodel.hxx create mode 100644 include/oox/drawingml/chart/modelbase.hxx create mode 100644 include/oox/drawingml/clrscheme.hxx create mode 100644 include/oox/drawingml/color.hxx create mode 100644 include/oox/drawingml/connectorshapecontext.hxx create mode 100644 include/oox/drawingml/diagram/diagram.hxx create mode 100644 include/oox/drawingml/drawingmltypes.hxx create mode 100644 include/oox/drawingml/graphicshapecontext.hxx create mode 100644 include/oox/drawingml/shape.hxx create mode 100644 include/oox/drawingml/shapecontext.hxx create mode 100644 include/oox/drawingml/shapegroupcontext.hxx create mode 100644 include/oox/drawingml/shapepropertymap.hxx create mode 100644 include/oox/drawingml/theme.hxx create mode 100644 include/oox/drawingml/themefragmenthandler.hxx create mode 100644 include/oox/dump/dffdumper.hxx create mode 100644 include/oox/dump/dumperbase.hxx create mode 100644 include/oox/dump/oledumper.hxx create mode 100644 include/oox/dump/pptxdumper.hxx create mode 100644 include/oox/dump/xlsbdumper.hxx create mode 100644 include/oox/export/DMLPresetShapeExport.hxx create mode 100644 include/oox/export/chartexport.hxx create mode 100644 include/oox/export/drawingml.hxx create mode 100644 include/oox/export/shapes.hxx create mode 100644 include/oox/export/utils.hxx create mode 100644 include/oox/export/vmlexport.hxx create mode 100644 include/oox/helper/addtosequence.hxx create mode 100644 include/oox/helper/attributelist.hxx create mode 100644 include/oox/helper/binaryinputstream.hxx create mode 100644 include/oox/helper/binaryoutputstream.hxx create mode 100644 include/oox/helper/binarystreambase.hxx create mode 100644 include/oox/helper/containerhelper.hxx create mode 100644 include/oox/helper/grabbagstack.hxx create mode 100644 include/oox/helper/graphichelper.hxx create mode 100644 include/oox/helper/helper.hxx create mode 100644 include/oox/helper/modelobjecthelper.hxx create mode 100644 include/oox/helper/progressbar.hxx create mode 100644 include/oox/helper/propertymap.hxx create mode 100644 include/oox/helper/propertyset.hxx create mode 100644 include/oox/helper/refmap.hxx create mode 100644 include/oox/helper/refvector.hxx create mode 100644 include/oox/helper/storagebase.hxx create mode 100644 include/oox/helper/textinputstream.hxx create mode 100644 include/oox/helper/zipstorage.hxx create mode 100644 include/oox/mathml/export.hxx create mode 100644 include/oox/mathml/import.hxx create mode 100644 include/oox/mathml/importutils.hxx create mode 100644 include/oox/ole/axbinaryreader.hxx create mode 100644 include/oox/ole/axbinarywriter.hxx create mode 100644 include/oox/ole/axcontrol.hxx create mode 100644 include/oox/ole/axcontrolfragment.hxx create mode 100644 include/oox/ole/axfontdata.hxx create mode 100644 include/oox/ole/olehelper.hxx create mode 100644 include/oox/ole/oleobjecthelper.hxx create mode 100644 include/oox/ole/olestorage.hxx create mode 100644 include/oox/ole/vbacontrol.hxx create mode 100644 include/oox/ole/vbaexport.hxx create mode 100644 include/oox/ole/vbahelper.hxx create mode 100644 include/oox/ole/vbainputstream.hxx create mode 100644 include/oox/ole/vbamodule.hxx create mode 100644 include/oox/ole/vbaproject.hxx create mode 100644 include/oox/ppt/animationspersist.hxx create mode 100644 include/oox/ppt/backgroundproperties.hxx create mode 100644 include/oox/ppt/comments.hxx create mode 100644 include/oox/ppt/customshowlistcontext.hxx create mode 100644 include/oox/ppt/headerfooter.hxx create mode 100644 include/oox/ppt/layoutfragmenthandler.hxx create mode 100644 include/oox/ppt/pptfilterhelpers.hxx create mode 100644 include/oox/ppt/pptgraphicshapecontext.hxx create mode 100644 include/oox/ppt/pptimport.hxx create mode 100644 include/oox/ppt/pptshape.hxx create mode 100644 include/oox/ppt/pptshapecontext.hxx create mode 100644 include/oox/ppt/pptshapegroupcontext.hxx create mode 100644 include/oox/ppt/pptshapepropertiescontext.hxx create mode 100644 include/oox/ppt/presPropsfragmenthandler.hxx create mode 100644 include/oox/ppt/presentationfragmenthandler.hxx create mode 100644 include/oox/ppt/slidefragmenthandler.hxx create mode 100644 include/oox/ppt/slidemastertextstylescontext.hxx create mode 100644 include/oox/ppt/slidepersist.hxx create mode 100644 include/oox/ppt/slidetimingcontext.hxx create mode 100644 include/oox/ppt/slidetransition.hxx create mode 100644 include/oox/ppt/slidetransitioncontext.hxx create mode 100644 include/oox/ppt/soundactioncontext.hxx create mode 100644 include/oox/ppt/timenode.hxx create mode 100644 include/oox/ppt/timenodelistcontext.hxx create mode 100644 include/oox/shape/ShapeContextHandler.hxx create mode 100644 include/oox/shape/ShapeFilterBase.hxx create mode 100644 include/oox/token/namespacemap.hxx create mode 100644 include/oox/token/propertynames.hxx create mode 100644 include/oox/token/relationship.hxx create mode 100644 include/oox/token/tokenmap.hxx create mode 100644 include/oox/vml/vmldrawing.hxx create mode 100644 include/oox/vml/vmldrawingfragment.hxx create mode 100644 include/oox/vml/vmlformatting.hxx create mode 100644 include/oox/vml/vmlinputstream.hxx create mode 100644 include/oox/vml/vmlshape.hxx create mode 100644 include/oox/vml/vmlshapecontainer.hxx create mode 100644 include/oox/vml/vmlshapecontext.hxx create mode 100644 include/oox/vml/vmltextbox.hxx create mode 100644 include/oox/vml/vmltextboxcontext.hxx create mode 100644 include/opencl/OpenCLZone.hxx create mode 100644 include/opencl/openclconfig.hxx create mode 100644 include/opencl/opencldllapi.h create mode 100644 include/opencl/openclwrapper.hxx create mode 100644 include/opencl/platforminfo.hxx create mode 100644 include/osl/conditn.h create mode 100644 include/osl/conditn.hxx create mode 100644 include/osl/detail/android-bootstrap.h create mode 100644 include/osl/detail/component-defines.h create mode 100644 include/osl/detail/component-mapping.h create mode 100644 include/osl/detail/file.h create mode 100644 include/osl/diagnose.h create mode 100644 include/osl/diagnose.hxx create mode 100644 include/osl/doublecheckedlocking.h create mode 100644 include/osl/endian.h create mode 100644 include/osl/file.h create mode 100644 include/osl/file.hxx create mode 100644 include/osl/getglobalmutex.hxx create mode 100644 include/osl/interlck.h create mode 100644 include/osl/module.h create mode 100644 include/osl/module.hxx create mode 100644 include/osl/mutex.h create mode 100644 include/osl/mutex.hxx create mode 100644 include/osl/nlsupport.h create mode 100644 include/osl/pipe.h create mode 100644 include/osl/pipe.hxx create mode 100644 include/osl/pipe_decl.hxx create mode 100644 include/osl/process.h create mode 100644 include/osl/profile.h create mode 100644 include/osl/profile.hxx create mode 100644 include/osl/security.h create mode 100644 include/osl/security.hxx create mode 100644 include/osl/security_decl.hxx create mode 100644 include/osl/signal.h create mode 100644 include/osl/socket.h create mode 100644 include/osl/socket.hxx create mode 100644 include/osl/socket_decl.hxx create mode 100644 include/osl/test/uniquepipename.hxx create mode 100644 include/osl/thread.h create mode 100644 include/osl/thread.hxx create mode 100644 include/osl/time.h create mode 100644 include/package/Deflater.hxx create mode 100644 include/package/Inflater.hxx create mode 100644 include/package/packagedllapi.hxx create mode 100644 include/postmac.h create mode 100644 include/postwin.h create mode 100644 include/premac.h create mode 100644 include/prewin.h create mode 100644 include/registry/reader.hxx create mode 100644 include/registry/refltype.hxx create mode 100644 include/registry/regdllapi.h create mode 100644 include/registry/registry.hxx create mode 100644 include/registry/regtype.h create mode 100644 include/registry/typereg_reader.hxx create mode 100644 include/registry/types.hxx create mode 100644 include/registry/version.h create mode 100644 include/registry/writer.h create mode 100644 include/registry/writer.hxx create mode 100644 include/rtl/alloc.h create mode 100644 include/rtl/bootstrap.h create mode 100644 include/rtl/bootstrap.hxx create mode 100644 include/rtl/byteseq.h create mode 100644 include/rtl/byteseq.hxx create mode 100644 include/rtl/character.hxx create mode 100644 include/rtl/cipher.h create mode 100644 include/rtl/crc.h create mode 100644 include/rtl/digest.h create mode 100644 include/rtl/instance.hxx create mode 100644 include/rtl/locale.h create mode 100644 include/rtl/malformeduriexception.hxx create mode 100644 include/rtl/math.h create mode 100644 include/rtl/math.hxx create mode 100644 include/rtl/process.h create mode 100644 include/rtl/random.h create mode 100644 include/rtl/ref.hxx create mode 100644 include/rtl/strbuf.h create mode 100644 include/rtl/strbuf.hxx create mode 100644 include/rtl/string.h create mode 100644 include/rtl/string.hxx create mode 100644 include/rtl/stringconcat.hxx create mode 100644 include/rtl/stringutils.hxx create mode 100644 include/rtl/tencinfo.h create mode 100644 include/rtl/textcvt.h create mode 100644 include/rtl/textenc.h create mode 100644 include/rtl/unload.h create mode 100644 include/rtl/uri.h create mode 100644 include/rtl/uri.hxx create mode 100644 include/rtl/ustrbuf.h create mode 100644 include/rtl/ustrbuf.hxx create mode 100644 include/rtl/ustring.h create mode 100644 include/rtl/ustring.hxx create mode 100644 include/rtl/uuid.h create mode 100644 include/sal/alloca.h create mode 100644 include/sal/backtrace.hxx create mode 100644 include/sal/config.h create mode 100644 include/sal/detail/log.h create mode 100644 include/sal/log-areas.dox create mode 100644 include/sal/log.hxx create mode 100644 include/sal/macros.h create mode 100644 include/sal/main.h create mode 100644 include/sal/mathconf.h create mode 100644 include/sal/saldllapi.h create mode 100644 include/sal/types.h create mode 100644 include/sal/typesizes.h create mode 100644 include/salhelper/condition.hxx create mode 100644 include/salhelper/dynload.hxx create mode 100644 include/salhelper/linkhelper.hxx create mode 100644 include/salhelper/refobj.hxx create mode 100644 include/salhelper/salhelperdllapi.h create mode 100644 include/salhelper/simplereferenceobject.hxx create mode 100644 include/salhelper/singletonref.hxx create mode 100644 include/salhelper/thread.hxx create mode 100644 include/salhelper/timer.hxx create mode 100644 include/sax/fastattribs.hxx create mode 100644 include/sax/fastparser.hxx create mode 100644 include/sax/fastsaxdllapi.h create mode 100644 include/sax/fshelper.hxx create mode 100644 include/sax/saxdllapi.h create mode 100644 include/sax/tools/converter.hxx create mode 100644 include/sax/tools/documenthandleradapter.hxx create mode 100644 include/sfx2/AccessibilityCheck.hxx create mode 100644 include/sfx2/AccessibilityIssue.hxx create mode 100644 include/sfx2/DocumentMetadataAccess.hxx create mode 100644 include/sfx2/DocumentSigner.hxx create mode 100644 include/sfx2/LokControlHandler.hxx create mode 100644 include/sfx2/Metadatable.hxx create mode 100644 include/sfx2/QuerySaveDocument.hxx create mode 100644 include/sfx2/StyleManager.hxx create mode 100644 include/sfx2/StylePreviewRenderer.hxx create mode 100644 include/sfx2/XmlIdRegistry.hxx create mode 100644 include/sfx2/app.hxx create mode 100644 include/sfx2/basedlgs.hxx create mode 100644 include/sfx2/bindings.hxx create mode 100644 include/sfx2/brokenpackageint.hxx create mode 100644 include/sfx2/chalign.hxx create mode 100644 include/sfx2/charwin.hxx create mode 100644 include/sfx2/childwin.hxx create mode 100644 include/sfx2/classificationhelper.hxx create mode 100644 include/sfx2/ctrlitem.hxx create mode 100644 include/sfx2/devtools/DevelopmentToolChildWindow.hxx create mode 100644 include/sfx2/devtools/DevelopmentToolDockingWindow.hxx create mode 100644 include/sfx2/devtools/DocumentModelTreeHandler.hxx create mode 100644 include/sfx2/devtools/ObjectInspectorTreeHandler.hxx create mode 100644 include/sfx2/devtools/ObjectInspectorWidgets.hxx create mode 100644 include/sfx2/dialoghelper.hxx create mode 100644 include/sfx2/digitalsignatures.hxx create mode 100644 include/sfx2/dinfdlg.hxx create mode 100644 include/sfx2/dispatch.hxx create mode 100644 include/sfx2/dllapi.h create mode 100644 include/sfx2/docfac.hxx create mode 100644 include/sfx2/docfile.hxx create mode 100644 include/sfx2/docfilt.hxx create mode 100644 include/sfx2/docinf.hxx create mode 100644 include/sfx2/docinsert.hxx create mode 100644 include/sfx2/dockwin.hxx create mode 100644 include/sfx2/docmacromode.hxx create mode 100644 include/sfx2/docstoragemodifylistener.hxx create mode 100644 include/sfx2/doctempl.hxx create mode 100644 include/sfx2/event.hxx create mode 100644 include/sfx2/evntconf.hxx create mode 100644 include/sfx2/fcontnr.hxx create mode 100644 include/sfx2/filedlghelper.hxx create mode 100644 include/sfx2/flatpak.hxx create mode 100644 include/sfx2/frame.hxx create mode 100644 include/sfx2/frmdescr.hxx create mode 100644 include/sfx2/frmhtml.hxx create mode 100644 include/sfx2/frmhtmlw.hxx create mode 100644 include/sfx2/groupid.hxx create mode 100644 include/sfx2/htmlmode.hxx create mode 100644 include/sfx2/infobar.hxx create mode 100644 include/sfx2/inputdlg.hxx create mode 100644 include/sfx2/ipclient.hxx create mode 100644 include/sfx2/linkmgr.hxx create mode 100644 include/sfx2/linksrc.hxx create mode 100644 include/sfx2/listview.hxx create mode 100644 include/sfx2/lnkbase.hxx create mode 100644 include/sfx2/lokcallback.hxx create mode 100644 include/sfx2/lokcomponenthelpers.hxx create mode 100644 include/sfx2/lokhelper.hxx create mode 100644 include/sfx2/mailmodelapi.hxx create mode 100644 include/sfx2/mieclip.hxx create mode 100644 include/sfx2/minfitem.hxx create mode 100644 include/sfx2/module.hxx create mode 100644 include/sfx2/msg.hxx create mode 100644 include/sfx2/msgpool.hxx create mode 100644 include/sfx2/navigat.hxx create mode 100644 include/sfx2/new.hxx create mode 100644 include/sfx2/newstyle.hxx create mode 100644 include/sfx2/notebookbar/SfxNotebookBar.hxx create mode 100644 include/sfx2/objface.hxx create mode 100644 include/sfx2/objitem.hxx create mode 100644 include/sfx2/objsh.hxx create mode 100644 include/sfx2/opengrf.hxx create mode 100644 include/sfx2/pageids.hxx create mode 100644 include/sfx2/passwd.hxx create mode 100644 include/sfx2/printer.hxx create mode 100644 include/sfx2/printopt.hxx create mode 100644 include/sfx2/progress.hxx create mode 100644 include/sfx2/request.hxx create mode 100644 include/sfx2/safemode.hxx create mode 100644 include/sfx2/sfxbasecontroller.hxx create mode 100644 include/sfx2/sfxbasemodel.hxx create mode 100644 include/sfx2/sfxdlg.hxx create mode 100644 include/sfx2/sfxhelp.hxx create mode 100644 include/sfx2/sfxhtml.hxx create mode 100644 include/sfx2/sfxmodelfactory.hxx create mode 100644 include/sfx2/sfxresid.hxx create mode 100644 include/sfx2/sfxsids.hrc create mode 100644 include/sfx2/sfxstatuslistener.hxx create mode 100644 include/sfx2/sfxuno.hxx create mode 100644 include/sfx2/shell.hxx create mode 100644 include/sfx2/sidebar/AsynchronousCall.hxx create mode 100644 include/sfx2/sidebar/Context.hxx create mode 100644 include/sfx2/sidebar/ControllerItem.hxx create mode 100644 include/sfx2/sidebar/Deck.hxx create mode 100644 include/sfx2/sidebar/FocusManager.hxx create mode 100644 include/sfx2/sidebar/IContextChangeReceiver.hxx create mode 100644 include/sfx2/sidebar/ILayoutableWindow.hxx create mode 100644 include/sfx2/sidebar/Panel.hxx create mode 100644 include/sfx2/sidebar/PanelLayout.hxx create mode 100644 include/sfx2/sidebar/ResourceManager.hxx create mode 100644 include/sfx2/sidebar/Sidebar.hxx create mode 100644 include/sfx2/sidebar/SidebarChildWindow.hxx create mode 100644 include/sfx2/sidebar/SidebarController.hxx create mode 100644 include/sfx2/sidebar/SidebarDockingWindow.hxx create mode 100644 include/sfx2/sidebar/SidebarModelUpdate.hxx create mode 100644 include/sfx2/sidebar/SidebarPanelBase.hxx create mode 100644 include/sfx2/sidebar/TabBar.hxx create mode 100644 include/sfx2/sidebar/Theme.hxx create mode 100644 include/sfx2/signaturestate.hxx create mode 100644 include/sfx2/stbitem.hxx create mode 100644 include/sfx2/strings.hrc create mode 100644 include/sfx2/styfitem.hxx create mode 100644 include/sfx2/styledlg.hxx create mode 100644 include/sfx2/tabdlg.hxx create mode 100644 include/sfx2/tbxctrl.hxx create mode 100644 include/sfx2/templatedlg.hxx create mode 100644 include/sfx2/templatedlglocalview.hxx create mode 100644 include/sfx2/templatelocalview.hxx create mode 100644 include/sfx2/templateproperties.hxx create mode 100644 include/sfx2/templdlg.hxx create mode 100644 include/sfx2/thumbnailview.hxx create mode 100644 include/sfx2/thumbnailviewitem.hxx create mode 100644 include/sfx2/toolbarids.hxx create mode 100644 include/sfx2/tplpitem.hxx create mode 100644 include/sfx2/userinputinterception.hxx create mode 100644 include/sfx2/viewfac.hxx create mode 100644 include/sfx2/viewfrm.hxx create mode 100644 include/sfx2/viewsh.hxx create mode 100644 include/sfx2/watermarkitem.hxx create mode 100644 include/sfx2/weldutils.hxx create mode 100644 include/sfx2/xmldump.hxx create mode 100644 include/sfx2/zoomitem.hxx create mode 100644 include/sot/exchange.hxx create mode 100644 include/sot/filelist.hxx create mode 100644 include/sot/formats.hxx create mode 100644 include/sot/object.hxx create mode 100644 include/sot/sotdllapi.h create mode 100644 include/sot/stg.hxx create mode 100644 include/sot/storage.hxx create mode 100644 include/sot/storinfo.hxx create mode 100644 include/store/store.h create mode 100644 include/store/store.hxx create mode 100644 include/store/storedllapi.h create mode 100644 include/store/types.h create mode 100644 include/svl/IndexedStyleSheets.hxx create mode 100644 include/svl/PasswordHelper.hxx create mode 100644 include/svl/SfxBroadcaster.hxx create mode 100644 include/svl/adrparse.hxx create mode 100644 include/svl/aeitem.hxx create mode 100644 include/svl/asiancfg.hxx create mode 100644 include/svl/broadcast.hxx create mode 100644 include/svl/cenumitm.hxx create mode 100644 include/svl/cintitem.hxx create mode 100644 include/svl/cjkoptions.hxx create mode 100644 include/svl/converter.hxx create mode 100644 include/svl/cryptosign.hxx create mode 100644 include/svl/ctloptions.hxx create mode 100644 include/svl/currencytable.hxx create mode 100644 include/svl/custritm.hxx create mode 100644 include/svl/documentlockfile.hxx create mode 100644 include/svl/eitem.hxx create mode 100644 include/svl/filenotation.hxx create mode 100644 include/svl/flagitem.hxx create mode 100644 include/svl/fstathelper.hxx create mode 100644 include/svl/globalnameitem.hxx create mode 100644 include/svl/grabbagitem.hxx create mode 100644 include/svl/gridprinter.hxx create mode 100644 include/svl/hint.hxx create mode 100644 include/svl/ilstitem.hxx create mode 100644 include/svl/imageitm.hxx create mode 100644 include/svl/inethist.hxx create mode 100644 include/svl/inettype.hxx create mode 100644 include/svl/instrm.hxx create mode 100644 include/svl/int64item.hxx create mode 100644 include/svl/intitem.hxx create mode 100644 include/svl/isethint.hxx create mode 100644 include/svl/itemiter.hxx create mode 100644 include/svl/itempool.hxx create mode 100644 include/svl/itemprop.hxx create mode 100644 include/svl/itemset.hxx create mode 100644 include/svl/languageoptions.hxx create mode 100644 include/svl/lckbitem.hxx create mode 100644 include/svl/legacyitem.hxx create mode 100644 include/svl/listener.hxx create mode 100644 include/svl/lngmisc.hxx create mode 100644 include/svl/lockfilecommon.hxx create mode 100644 include/svl/lstner.hxx create mode 100644 include/svl/macitem.hxx create mode 100644 include/svl/memberid.h create mode 100644 include/svl/metitem.hxx create mode 100644 include/svl/msodocumentlockfile.hxx create mode 100644 include/svl/nfkeytab.hxx create mode 100644 include/svl/nfsymbol.hxx create mode 100644 include/svl/numformat.hxx create mode 100644 include/svl/numuno.hxx create mode 100644 include/svl/ondemand.hxx create mode 100644 include/svl/outstrm.hxx create mode 100644 include/svl/ownlist.hxx create mode 100644 include/svl/pickerhistoryaccess.hxx create mode 100644 include/svl/poolcach.hxx create mode 100644 include/svl/poolitem.hxx create mode 100644 include/svl/ptitem.hxx create mode 100644 include/svl/rectitem.hxx create mode 100644 include/svl/rngitem.hxx create mode 100644 include/svl/setitem.hxx create mode 100644 include/svl/sharecontrolfile.hxx create mode 100644 include/svl/sharedstring.hxx create mode 100644 include/svl/sharedstringpool.hxx create mode 100644 include/svl/sigstruct.hxx create mode 100644 include/svl/slstitm.hxx create mode 100644 include/svl/solar.hrc create mode 100644 include/svl/srchdefs.hxx create mode 100644 include/svl/srchitem.hxx create mode 100644 include/svl/stritem.hxx create mode 100644 include/svl/style.hxx create mode 100644 include/svl/stylepool.hxx create mode 100644 include/svl/stylesheetuser.hxx create mode 100644 include/svl/svdde.hxx create mode 100644 include/svl/svl.hrc create mode 100644 include/svl/svldllapi.h create mode 100644 include/svl/svlresid.hxx create mode 100644 include/svl/typedwhich.hxx create mode 100644 include/svl/undo.hxx create mode 100644 include/svl/urihelper.hxx create mode 100644 include/svl/urlbmk.hxx create mode 100644 include/svl/visitem.hxx create mode 100644 include/svl/whichranges.hxx create mode 100644 include/svl/whiter.hxx create mode 100644 include/svl/zforlist.hxx create mode 100644 include/svl/zformat.hxx create mode 100644 include/svtools/DocumentToGraphicRenderer.hxx create mode 100644 include/svtools/HtmlWriter.hxx create mode 100644 include/svtools/PlaceEditDialog.hxx create mode 100644 include/svtools/acceleratorexecute.hxx create mode 100644 include/svtools/accessibilityoptions.hxx create mode 100644 include/svtools/addresstemplate.hxx create mode 100644 include/svtools/apearcfg.hxx create mode 100644 include/svtools/asynclink.hxx create mode 100644 include/svtools/bindablecontrolhelper.hxx create mode 100644 include/svtools/borderhelper.hxx create mode 100644 include/svtools/borderline.hxx create mode 100644 include/svtools/brwbox.hxx create mode 100644 include/svtools/brwhead.hxx create mode 100644 include/svtools/cliplistener.hxx create mode 100644 include/svtools/collatorres.hxx create mode 100644 include/svtools/colorcfg.hxx create mode 100644 include/svtools/colrdlg.hxx create mode 100644 include/svtools/ctrlbox.hxx create mode 100644 include/svtools/ctrltool.hxx create mode 100644 include/svtools/dialogclosedlistener.hxx create mode 100644 include/svtools/editbrowsebox.hxx create mode 100644 include/svtools/ehdl.hxx create mode 100644 include/svtools/embedhlp.hxx create mode 100644 include/svtools/embedtransfer.hxx create mode 100644 include/svtools/extcolorcfg.hxx create mode 100644 include/svtools/filechangedchecker.hxx create mode 100644 include/svtools/fontsubstconfig.hxx create mode 100644 include/svtools/genericunodialog.hxx create mode 100644 include/svtools/helpids.h create mode 100644 include/svtools/htmlcfg.hxx create mode 100644 include/svtools/htmlkywd.hxx create mode 100644 include/svtools/htmlout.hxx create mode 100644 include/svtools/htmltokn.h create mode 100644 include/svtools/imagemgr.hxx create mode 100644 include/svtools/imageresourceaccess.hxx create mode 100644 include/svtools/imgdef.hxx create mode 100644 include/svtools/indexentryres.hxx create mode 100644 include/svtools/inettbc.hxx create mode 100644 include/svtools/insdlg.hxx create mode 100644 include/svtools/javacontext.hxx create mode 100644 include/svtools/javainteractionhandler.hxx create mode 100644 include/svtools/langhelp.hxx create mode 100644 include/svtools/langtab.hxx create mode 100644 include/svtools/languagetoolcfg.hxx create mode 100644 include/svtools/miscopt.hxx create mode 100644 include/svtools/openfiledroptargetlistener.hxx create mode 100644 include/svtools/optionsdrawinglayer.hxx create mode 100644 include/svtools/parhtml.hxx create mode 100644 include/svtools/parrtf.hxx create mode 100644 include/svtools/place.hxx create mode 100644 include/svtools/popupmenucontrollerbase.hxx create mode 100644 include/svtools/popupwindowcontroller.hxx create mode 100644 include/svtools/printoptions.hxx create mode 100644 include/svtools/prnsetup.hxx create mode 100644 include/svtools/querydelete.hxx create mode 100644 include/svtools/recorditemwindow.hxx create mode 100644 include/svtools/restartdialog.hxx create mode 100644 include/svtools/rtfkeywd.hxx create mode 100644 include/svtools/rtfout.hxx create mode 100644 include/svtools/rtftoken.h create mode 100644 include/svtools/ruler.hxx create mode 100644 include/svtools/sampletext.hxx create mode 100644 include/svtools/scriptedtext.hxx create mode 100644 include/svtools/sfxecode.hxx create mode 100644 include/svtools/slidesorterbaropt.hxx create mode 100644 include/svtools/soerr.hxx create mode 100644 include/svtools/statusbarcontroller.hxx create mode 100644 include/svtools/strings.hrc create mode 100644 include/svtools/stringtransfer.hxx create mode 100644 include/svtools/svparser.hxx create mode 100644 include/svtools/svtdllapi.h create mode 100644 include/svtools/svtresid.hxx create mode 100644 include/svtools/tabbar.hxx create mode 100644 include/svtools/templatefoldercache.hxx create mode 100644 include/svtools/toolbarmenu.hxx create mode 100644 include/svtools/toolboxcontroller.hxx create mode 100644 include/svtools/unitconv.hxx create mode 100644 include/svtools/unoevent.hxx create mode 100644 include/svtools/unoimap.hxx create mode 100644 include/svtools/urlfilter.hxx create mode 100644 include/svtools/valueset.hxx create mode 100644 include/svx/AccessibilityCheckDialog.hxx create mode 100644 include/svx/AccessibleControlShape.hxx create mode 100644 include/svx/AccessibleGraphicShape.hxx create mode 100644 include/svx/AccessibleOLEShape.hxx create mode 100644 include/svx/AccessibleShape.hxx create mode 100644 include/svx/AccessibleShapeInfo.hxx create mode 100644 include/svx/AccessibleShapeTreeInfo.hxx create mode 100644 include/svx/AccessibleTextHelper.hxx create mode 100644 include/svx/ActionDescriptionProvider.hxx create mode 100644 include/svx/ChildrenManager.hxx create mode 100644 include/svx/ClassificationCommon.hxx create mode 100644 include/svx/ClassificationDialog.hxx create mode 100644 include/svx/ClassificationField.hxx create mode 100644 include/svx/ColorSets.hxx create mode 100644 include/svx/CommonStyleManager.hxx create mode 100644 include/svx/EnhancedCustomShape2d.hxx create mode 100644 include/svx/EnhancedCustomShapeFunctionParser.hxx create mode 100644 include/svx/EnhancedCustomShapeGeometry.hxx create mode 100644 include/svx/EnhancedCustomShapeTypeNames.hxx create mode 100644 include/svx/FileExportedDialog.hxx create mode 100644 include/svx/GenericCheckDialog.hxx create mode 100644 include/svx/IAccessibleParent.hxx create mode 100644 include/svx/IAccessibleViewForwarder.hxx create mode 100644 include/svx/IAccessibleViewForwarderListener.hxx create mode 100644 include/svx/ImageMapInfo.hxx create mode 100644 include/svx/MediaShellHelpers.hxx create mode 100644 include/svx/Palette.hxx create mode 100644 include/svx/PaletteManager.hxx create mode 100644 include/svx/ParaSpacingControl.hxx create mode 100644 include/svx/ParseContext.hxx create mode 100644 include/svx/ShapeTypeHandler.hxx create mode 100644 include/svx/SmartTagItem.hxx create mode 100644 include/svx/SmartTagMgr.hxx create mode 100644 include/svx/SpellDialogChildWindow.hxx create mode 100644 include/svx/SvxColorChildWindow.hxx create mode 100644 include/svx/SvxColorValueSet.hxx create mode 100644 include/svx/SvxNumOptionsTabPageHelper.hxx create mode 100644 include/svx/SvxPresetListBox.hxx create mode 100644 include/svx/SvxShapeTypes.hxx create mode 100644 include/svx/SvxXTextColumns.hxx create mode 100644 include/svx/UnoNamespaceMap.hxx create mode 100644 include/svx/XPropertyEntry.hxx create mode 100644 include/svx/algitem.hxx create mode 100644 include/svx/anchorid.hxx create mode 100644 include/svx/autoformathelper.hxx create mode 100644 include/svx/bmpmask.hxx create mode 100644 include/svx/camera3d.hxx create mode 100644 include/svx/charmap.hxx create mode 100644 include/svx/charthelper.hxx create mode 100644 include/svx/chrtitem.hxx create mode 100644 include/svx/clipboardctl.hxx create mode 100644 include/svx/clipfmtitem.hxx create mode 100644 include/svx/colorbox.hxx create mode 100644 include/svx/colorwindow.hxx create mode 100644 include/svx/compressgraphicdialog.hxx create mode 100644 include/svx/connctrl.hxx create mode 100644 include/svx/contdlg.hxx create mode 100644 include/svx/ctredlin.hxx create mode 100644 include/svx/cube3d.hxx create mode 100644 include/svx/dataaccessdescriptor.hxx create mode 100644 include/svx/databaselocationinput.hxx create mode 100644 include/svx/databaseregistrationui.hxx create mode 100644 include/svx/dbaexchange.hxx create mode 100644 include/svx/dbaobjectex.hxx create mode 100644 include/svx/def3d.hxx create mode 100644 include/svx/deflt3d.hxx create mode 100644 include/svx/diagram/IDiagramHelper.hxx create mode 100644 include/svx/diagram/datamodel.hxx create mode 100644 include/svx/dialcontrol.hxx create mode 100644 include/svx/dialmgr.hxx create mode 100644 include/svx/dialogs.hrc create mode 100644 include/svx/dlgctl3d.hxx create mode 100644 include/svx/dlgctrl.hxx create mode 100644 include/svx/dlgutil.hxx create mode 100644 include/svx/drawitem.hxx create mode 100644 include/svx/e3ditem.hxx create mode 100644 include/svx/e3dsceneupdater.hxx create mode 100644 include/svx/e3dundo.hxx create mode 100644 include/svx/extedit.hxx create mode 100644 include/svx/extrusionbar.hxx create mode 100644 include/svx/f3dchild.hxx create mode 100644 include/svx/fillctrl.hxx create mode 100644 include/svx/flagsdef.hxx create mode 100644 include/svx/float3d.hxx create mode 100644 include/svx/fmdmod.hxx create mode 100644 include/svx/fmdpage.hxx create mode 100644 include/svx/fmgridcl.hxx create mode 100644 include/svx/fmgridif.hxx create mode 100644 include/svx/fmmodel.hxx create mode 100644 include/svx/fmobjfac.hxx create mode 100644 include/svx/fmpage.hxx create mode 100644 include/svx/fmsearch.hxx create mode 100644 include/svx/fmshell.hxx create mode 100644 include/svx/fmsrccfg.hxx create mode 100644 include/svx/fmsrcimp.hxx create mode 100644 include/svx/fmtools.hxx create mode 100644 include/svx/fmview.hxx create mode 100644 include/svx/fntctrl.hxx create mode 100644 include/svx/fontwork.hxx create mode 100644 include/svx/fontworkbar.hxx create mode 100644 include/svx/fontworkgallery.hxx create mode 100644 include/svx/formatpaintbrushctrl.hxx create mode 100644 include/svx/framebordertype.hxx create mode 100644 include/svx/framelink.hxx create mode 100644 include/svx/framelinkarray.hxx create mode 100644 include/svx/frmdirlbox.hxx create mode 100644 include/svx/frmsel.hxx create mode 100644 include/svx/galctrl.hxx create mode 100644 include/svx/gallery.hxx create mode 100644 include/svx/gallery1.hxx create mode 100644 include/svx/gallerybinaryengine.hxx create mode 100644 include/svx/gallerybinaryengineentry.hxx create mode 100644 include/svx/gallerybinarystoragelocations.hxx create mode 100644 include/svx/galleryfilestorage.hxx create mode 100644 include/svx/galleryfilestorageentry.hxx create mode 100644 include/svx/galleryitem.hxx create mode 100644 include/svx/galleryobjectcollection.hxx create mode 100644 include/svx/galleryobjectstorage.hxx create mode 100644 include/svx/gallerystoragelocations.hxx create mode 100644 include/svx/galmisc.hxx create mode 100644 include/svx/galtheme.hxx create mode 100644 include/svx/grafctrl.hxx create mode 100644 include/svx/graphctl.hxx create mode 100644 include/svx/graphichelper.hxx create mode 100644 include/svx/grfcrop.hxx create mode 100644 include/svx/grfflt.hxx create mode 100644 include/svx/gridctrl.hxx create mode 100644 include/svx/hdft.hxx create mode 100644 include/svx/helperhittest3d.hxx create mode 100644 include/svx/hexcolorcontrol.hxx create mode 100644 include/svx/hlnkitem.hxx create mode 100644 include/svx/hyperdlg.hxx create mode 100644 include/svx/ifaceids.hxx create mode 100644 include/svx/imapdlg.hxx create mode 100644 include/svx/insctrl.hxx create mode 100644 include/svx/ipolypolygoneditorcontroller.hxx create mode 100644 include/svx/itemwin.hxx create mode 100644 include/svx/itextprovider.hxx create mode 100644 include/svx/labelitemwindow.hxx create mode 100644 include/svx/langbox.hxx create mode 100644 include/svx/lathe3d.hxx create mode 100644 include/svx/legacyitem.hxx create mode 100644 include/svx/linectrl.hxx create mode 100644 include/svx/linkwarn.hxx create mode 100644 include/svx/measctrl.hxx create mode 100644 include/svx/modctrl.hxx create mode 100644 include/svx/msdffdef.hxx create mode 100644 include/svx/nbdtmg.hxx create mode 100644 include/svx/nbdtmgfact.hxx create mode 100644 include/svx/numfmtsh.hxx create mode 100644 include/svx/numinf.hxx create mode 100644 include/svx/numvset.hxx create mode 100644 include/svx/obj3d.hxx create mode 100644 include/svx/objfac3d.hxx create mode 100644 include/svx/ofaitem.hxx create mode 100644 include/svx/optgenrl.hxx create mode 100644 include/svx/optgrid.hxx create mode 100644 include/svx/pagectrl.hxx create mode 100644 include/svx/pageitem.hxx create mode 100644 include/svx/pagenumberlistbox.hxx create mode 100644 include/svx/papersizelistbox.hxx create mode 100644 include/svx/paraprev.hxx create mode 100644 include/svx/passwd.hxx create mode 100644 include/svx/polypolygoneditor.hxx create mode 100644 include/svx/postattr.hxx create mode 100644 include/svx/pszctrl.hxx create mode 100644 include/svx/rectenum.hxx create mode 100644 include/svx/relfld.hxx create mode 100644 include/svx/rotmodit.hxx create mode 100644 include/svx/rubydialog.hxx create mode 100644 include/svx/ruler.hxx create mode 100644 include/svx/rulritem.hxx create mode 100644 include/svx/samecontentlistbox.hxx create mode 100644 include/svx/scene3d.hxx create mode 100644 include/svx/sdangitm.hxx create mode 100644 include/svx/sdasitm.hxx create mode 100644 include/svx/sderitm.hxx create mode 100644 include/svx/sdgcpitm.hxx create mode 100644 include/svx/sdggaitm.hxx create mode 100644 include/svx/sdgluitm.hxx create mode 100644 include/svx/sdgmoitm.hxx create mode 100644 include/svx/sdmetitm.hxx create mode 100644 include/svx/sdooitm.hxx create mode 100644 include/svx/sdprcitm.hxx create mode 100644 include/svx/sdr/animation/animationstate.hxx create mode 100644 include/svx/sdr/animation/objectanimator.hxx create mode 100644 include/svx/sdr/animation/scheduler.hxx create mode 100644 include/svx/sdr/attribute/sdrallfillattributeshelper.hxx create mode 100644 include/svx/sdr/contact/displayinfo.hxx create mode 100644 include/svx/sdr/contact/objectcontact.hxx create mode 100644 include/svx/sdr/contact/objectcontactofpageview.hxx create mode 100644 include/svx/sdr/contact/viewcontact.hxx create mode 100644 include/svx/sdr/contact/viewcontactofe3dscene.hxx create mode 100644 include/svx/sdr/contact/viewcontactofsdrmediaobj.hxx create mode 100644 include/svx/sdr/contact/viewcontactofsdrobj.hxx create mode 100644 include/svx/sdr/contact/viewcontactofvirtobj.hxx create mode 100644 include/svx/sdr/contact/viewobjectcontact.hxx create mode 100644 include/svx/sdr/contact/viewobjectcontactofsdrobj.hxx create mode 100644 include/svx/sdr/contact/viewobjectcontactredirector.hxx create mode 100644 include/svx/sdr/overlay/overlayanimatedbitmapex.hxx create mode 100644 include/svx/sdr/overlay/overlaybitmapex.hxx create mode 100644 include/svx/sdr/overlay/overlaymanager.hxx create mode 100644 include/svx/sdr/overlay/overlayobject.hxx create mode 100644 include/svx/sdr/overlay/overlayobjectlist.hxx create mode 100644 include/svx/sdr/overlay/overlaypolypolygon.hxx create mode 100644 include/svx/sdr/overlay/overlayprimitive2dsequenceobject.hxx create mode 100644 include/svx/sdr/overlay/overlayselection.hxx create mode 100644 include/svx/sdr/primitive2d/sdrframeborderprimitive2d.hxx create mode 100644 include/svx/sdr/primitive2d/svx_primitivetypes2d.hxx create mode 100644 include/svx/sdr/properties/defaultproperties.hxx create mode 100644 include/svx/sdr/properties/properties.hxx create mode 100644 include/svx/sdr/table/tablecontroller.hxx create mode 100644 include/svx/sdr/table/tabledesign.hxx create mode 100644 include/svx/sdrhittesthelper.hxx create mode 100644 include/svx/sdrmasterpagedescriptor.hxx create mode 100644 include/svx/sdrobjectfilter.hxx create mode 100644 include/svx/sdrobjectuser.hxx create mode 100644 include/svx/sdrpageuser.hxx create mode 100644 include/svx/sdrpagewindow.hxx create mode 100644 include/svx/sdrpaintwindow.hxx create mode 100644 include/svx/sdrundomanager.hxx create mode 100644 include/svx/sdshcitm.hxx create mode 100644 include/svx/sdshitm.hxx create mode 100644 include/svx/sdshtitm.hxx create mode 100644 include/svx/sdsxyitm.hxx create mode 100644 include/svx/sdtaaitm.hxx create mode 100644 include/svx/sdtacitm.hxx create mode 100644 include/svx/sdtaditm.hxx create mode 100644 include/svx/sdtagitm.hxx create mode 100644 include/svx/sdtaiitm.hxx create mode 100644 include/svx/sdtaitm.hxx create mode 100644 include/svx/sdtakitm.hxx create mode 100644 include/svx/sdtayitm.hxx create mode 100644 include/svx/sdtcfitm.hxx create mode 100644 include/svx/sdtditm.hxx create mode 100644 include/svx/sdtfchim.hxx create mode 100644 include/svx/sdtfsitm.hxx create mode 100644 include/svx/sdtmfitm.hxx create mode 100644 include/svx/sdynitm.hxx create mode 100644 include/svx/searchcharmap.hxx create mode 100644 include/svx/selctrl.hxx create mode 100644 include/svx/selectioncontroller.hxx create mode 100644 include/svx/shapepropertynotifier.hxx create mode 100644 include/svx/sidebar/AreaPropertyPanelBase.hxx create mode 100644 include/svx/sidebar/AreaTransparencyGradientPopup.hxx create mode 100644 include/svx/sidebar/ContextChangeEventMultiplexer.hxx create mode 100644 include/svx/sidebar/InspectorTextPanel.hxx create mode 100644 include/svx/sidebar/LinePropertyPanelBase.hxx create mode 100644 include/svx/sidebar/LineWidthPopup.hxx create mode 100644 include/svx/sidebar/SelectionAnalyzer.hxx create mode 100644 include/svx/sidebar/SelectionChangeHandler.hxx create mode 100644 include/svx/sidebar/ValueSetWithTextControl.hxx create mode 100644 include/svx/signaturelinehelper.hxx create mode 100644 include/svx/spacinglistbox.hxx create mode 100644 include/svx/sphere3d.hxx create mode 100644 include/svx/srchdlg.hxx create mode 100644 include/svx/strarray.hxx create mode 100644 include/svx/strings.hrc create mode 100644 include/svx/svdcrtv.hxx create mode 100644 include/svx/svddef.hxx create mode 100644 include/svx/svddrag.hxx create mode 100644 include/svx/svddrgmt.hxx create mode 100644 include/svx/svddrgv.hxx create mode 100644 include/svx/svdedtv.hxx create mode 100644 include/svx/svdedxv.hxx create mode 100644 include/svx/svdetc.hxx create mode 100644 include/svx/svdglev.hxx create mode 100644 include/svx/svdglue.hxx create mode 100644 include/svx/svdhdl.hxx create mode 100644 include/svx/svdhlpln.hxx create mode 100644 include/svx/svditer.hxx create mode 100644 include/svx/svdlayer.hxx create mode 100644 include/svx/svdmark.hxx create mode 100644 include/svx/svdmodel.hxx create mode 100644 include/svx/svdmrkv.hxx create mode 100644 include/svx/svdoashp.hxx create mode 100644 include/svx/svdoattr.hxx create mode 100644 include/svx/svdobj.hxx create mode 100644 include/svx/svdobjkind.hxx create mode 100644 include/svx/svdocapt.hxx create mode 100644 include/svx/svdocirc.hxx create mode 100644 include/svx/svdoedge.hxx create mode 100644 include/svx/svdograf.hxx create mode 100644 include/svx/svdogrp.hxx create mode 100644 include/svx/svdomeas.hxx create mode 100644 include/svx/svdomedia.hxx create mode 100644 include/svx/svdoole2.hxx create mode 100644 include/svx/svdopage.hxx create mode 100644 include/svx/svdopath.hxx create mode 100644 include/svx/svdorect.hxx create mode 100644 include/svx/svdotable.hxx create mode 100644 include/svx/svdotext.hxx create mode 100644 include/svx/svdouno.hxx create mode 100644 include/svx/svdoutl.hxx create mode 100644 include/svx/svdovirt.hxx create mode 100644 include/svx/svdpage.hxx create mode 100644 include/svx/svdpagv.hxx create mode 100644 include/svx/svdpntv.hxx create mode 100644 include/svx/svdpoev.hxx create mode 100644 include/svx/svdpool.hxx create mode 100644 include/svx/svdsnpv.hxx create mode 100644 include/svx/svdsob.hxx create mode 100644 include/svx/svdtext.hxx create mode 100644 include/svx/svdtrans.hxx create mode 100644 include/svx/svdtypes.hxx create mode 100644 include/svx/svdundo.hxx create mode 100644 include/svx/svdview.hxx create mode 100644 include/svx/svdviter.hxx create mode 100644 include/svx/svdxcgv.hxx create mode 100644 include/svx/svx3ditems.hxx create mode 100644 include/svx/svxdlg.hxx create mode 100644 include/svx/svxdllapi.h create mode 100644 include/svx/svxerr.hxx create mode 100644 include/svx/svxgraphicitem.hxx create mode 100644 include/svx/svxids.hrc create mode 100644 include/svx/svxitems.hrc create mode 100644 include/svx/swframeexample.hxx create mode 100644 include/svx/swframeposstrings.hxx create mode 100644 include/svx/swframetypes.hxx create mode 100644 include/svx/swframevalidation.hxx create mode 100644 include/svx/sxcecitm.hxx create mode 100644 include/svx/sxcgitm.hxx create mode 100644 include/svx/sxciaitm.hxx create mode 100644 include/svx/sxcllitm.hxx create mode 100644 include/svx/sxctitm.hxx create mode 100644 include/svx/sxekitm.hxx create mode 100644 include/svx/sxelditm.hxx create mode 100644 include/svx/sxenditm.hxx create mode 100644 include/svx/sxmbritm.hxx create mode 100644 include/svx/sxmlhitm.hxx create mode 100644 include/svx/sxmtfitm.hxx create mode 100644 include/svx/sxmtpitm.hxx create mode 100644 include/svx/sxmtritm.hxx create mode 100644 include/svx/sxmuitm.hxx create mode 100644 include/svx/tabarea.hxx create mode 100644 include/svx/tabline.hxx create mode 100644 include/svx/tbcontrl.hxx create mode 100644 include/svx/tbxcolor.hxx create mode 100644 include/svx/tbxctl.hxx create mode 100644 include/svx/transfrmhelper.hxx create mode 100644 include/svx/txencbox.hxx create mode 100644 include/svx/txenctab.hxx create mode 100644 include/svx/ucsubset.hxx create mode 100644 include/svx/uiobject.hxx create mode 100644 include/svx/unoapi.hxx create mode 100644 include/svx/unobrushitemhelper.hxx create mode 100644 include/svx/unodraw/SvxTableShape.hxx create mode 100644 include/svx/unofill.hxx create mode 100644 include/svx/unomaster.hxx create mode 100644 include/svx/unomid.hxx create mode 100644 include/svx/unomod.hxx create mode 100644 include/svx/unomodel.hxx create mode 100644 include/svx/unopage.hxx create mode 100644 include/svx/unopool.hxx create mode 100644 include/svx/unoprov.hxx create mode 100644 include/svx/unoshape.hxx create mode 100644 include/svx/unoshprp.hxx create mode 100644 include/svx/unoshtxt.hxx create mode 100644 include/svx/view3d.hxx create mode 100644 include/svx/viewlayoutitem.hxx create mode 100644 include/svx/viewpt3d.hxx create mode 100644 include/svx/weldeditview.hxx create mode 100644 include/svx/xbitmap.hxx create mode 100644 include/svx/xbtmpit.hxx create mode 100644 include/svx/xcolit.hxx create mode 100644 include/svx/xdash.hxx create mode 100644 include/svx/xdef.hxx create mode 100644 include/svx/xenum.hxx create mode 100644 include/svx/xfillit0.hxx create mode 100644 include/svx/xfilluseslidebackgrounditem.hxx create mode 100644 include/svx/xflasit.hxx create mode 100644 include/svx/xflbckit.hxx create mode 100644 include/svx/xflbmpit.hxx create mode 100644 include/svx/xflbmsli.hxx create mode 100644 include/svx/xflbmsxy.hxx create mode 100644 include/svx/xflbmtit.hxx create mode 100644 include/svx/xflboxy.hxx create mode 100644 include/svx/xflbstit.hxx create mode 100644 include/svx/xflbtoxy.hxx create mode 100644 include/svx/xflclit.hxx create mode 100644 include/svx/xflftrit.hxx create mode 100644 include/svx/xflgrit.hxx create mode 100644 include/svx/xflhtit.hxx create mode 100644 include/svx/xfltrit.hxx create mode 100644 include/svx/xftadit.hxx create mode 100644 include/svx/xftdiit.hxx create mode 100644 include/svx/xftmrit.hxx create mode 100644 include/svx/xftouit.hxx create mode 100644 include/svx/xftshcit.hxx create mode 100644 include/svx/xftshit.hxx create mode 100644 include/svx/xftshxy.hxx create mode 100644 include/svx/xftstit.hxx create mode 100644 include/svx/xgrad.hxx create mode 100644 include/svx/xgrscit.hxx create mode 100644 include/svx/xhatch.hxx create mode 100644 include/svx/xit.hxx create mode 100644 include/svx/xlineit0.hxx create mode 100644 include/svx/xlinjoit.hxx create mode 100644 include/svx/xlnasit.hxx create mode 100644 include/svx/xlncapit.hxx create mode 100644 include/svx/xlnclit.hxx create mode 100644 include/svx/xlndsit.hxx create mode 100644 include/svx/xlnedcit.hxx create mode 100644 include/svx/xlnedit.hxx create mode 100644 include/svx/xlnedwit.hxx create mode 100644 include/svx/xlnstcit.hxx create mode 100644 include/svx/xlnstit.hxx create mode 100644 include/svx/xlnstwit.hxx create mode 100644 include/svx/xlntrit.hxx create mode 100644 include/svx/xlnwtit.hxx create mode 100644 include/svx/xmleohlp.hxx create mode 100644 include/svx/xmlexchg.hxx create mode 100644 include/svx/xmlgrhlp.hxx create mode 100644 include/svx/xmlsecctrl.hxx create mode 100644 include/svx/xoutbmp.hxx create mode 100644 include/svx/xpoly.hxx create mode 100644 include/svx/xpool.hxx create mode 100644 include/svx/xsflclit.hxx create mode 100644 include/svx/xtable.hxx create mode 100644 include/svx/xtextit0.hxx create mode 100644 include/svx/zoom_def.hxx create mode 100644 include/svx/zoomctrl.hxx create mode 100644 include/svx/zoomsliderctrl.hxx create mode 100644 include/svx/zoomslideritem.hxx create mode 100644 include/systools/win32/comtools.hxx create mode 100644 include/systools/win32/oleauto.hxx create mode 100644 include/systools/win32/qswin32.h create mode 100644 include/systools/win32/retry_if_failed.hxx create mode 100644 include/systools/win32/uwinapi.h create mode 100644 include/test/beans/xpropertyset.hxx create mode 100644 include/test/bootstrapfixture.hxx create mode 100644 include/test/calc_unoapi_test.hxx create mode 100644 include/test/callgrind.hxx create mode 100644 include/test/chart/xchartdata.hxx create mode 100644 include/test/container/xchild.hxx create mode 100644 include/test/container/xelementaccess.hxx create mode 100644 include/test/container/xenumeration.hxx create mode 100644 include/test/container/xenumerationaccess.hxx create mode 100644 include/test/container/xindexaccess.hxx create mode 100644 include/test/container/xnameaccess.hxx create mode 100644 include/test/container/xnamecontainer.hxx create mode 100644 include/test/container/xnamed.hxx create mode 100644 include/test/container/xnamereplace.hxx create mode 100644 include/test/cppunitasserthelper.hxx create mode 100644 include/test/document/xactionlockable.hxx create mode 100644 include/test/document/xembeddedobjectsupplier.hxx create mode 100644 include/test/document/xlinktargetsupplier.hxx create mode 100644 include/test/drawing/captionshape.hxx create mode 100644 include/test/drawing/xdrawpages.hxx create mode 100644 include/test/drawing/xgluepointssupplier.hxx create mode 100644 include/test/drawing/xshape.hxx create mode 100644 include/test/drawing/xshapedescriptor.hxx create mode 100644 include/test/drawing/xshapegrouper.hxx create mode 100644 include/test/drawing/xshapes.hxx create mode 100644 include/test/helper/form.hxx create mode 100644 include/test/helper/shape.hxx create mode 100644 include/test/helper/transferable.hxx create mode 100644 include/test/htmltesttools.hxx create mode 100644 include/test/lang/xcomponent.hxx create mode 100644 include/test/lang/xserviceinfo.hxx create mode 100644 include/test/lokcallback.hxx create mode 100644 include/test/screenshot_test.hxx create mode 100644 include/test/sheet/cellarealink.hxx create mode 100644 include/test/sheet/cellproperties.hxx create mode 100644 include/test/sheet/databaseimportdescriptor.hxx create mode 100644 include/test/sheet/databaserange.hxx create mode 100644 include/test/sheet/datapilotfield.hxx create mode 100644 include/test/sheet/datapilotitem.hxx create mode 100644 include/test/sheet/documentsettings.hxx create mode 100644 include/test/sheet/functiondescription.hxx create mode 100644 include/test/sheet/globalsheetsettings.hxx create mode 100644 include/test/sheet/scenario.hxx create mode 100644 include/test/sheet/shape.hxx create mode 100644 include/test/sheet/sheetcell.hxx create mode 100644 include/test/sheet/sheetcellrange.hxx create mode 100644 include/test/sheet/sheetcellranges.hxx create mode 100644 include/test/sheet/sheetfilterdescriptor.hxx create mode 100644 include/test/sheet/sheetlink.hxx create mode 100644 include/test/sheet/sheetsortdescriptor2.hxx create mode 100644 include/test/sheet/spreadsheet.hxx create mode 100644 include/test/sheet/spreadsheetdocumentsettings.hxx create mode 100644 include/test/sheet/spreadsheetviewsettings.hxx create mode 100644 include/test/sheet/subtotaldescriptor.hxx create mode 100644 include/test/sheet/tableautoformat.hxx create mode 100644 include/test/sheet/tablevalidation.hxx create mode 100644 include/test/sheet/xactivationbroadcaster.hxx create mode 100644 include/test/sheet/xarealink.hxx create mode 100644 include/test/sheet/xarealinks.hxx create mode 100644 include/test/sheet/xarrayformularange.hxx create mode 100644 include/test/sheet/xcalculatable.hxx create mode 100644 include/test/sheet/xcelladdressable.hxx create mode 100644 include/test/sheet/xcellformatrangessupplier.hxx create mode 100644 include/test/sheet/xcellrangeaddressable.hxx create mode 100644 include/test/sheet/xcellrangedata.hxx create mode 100644 include/test/sheet/xcellrangeformula.hxx create mode 100644 include/test/sheet/xcellrangemovement.hxx create mode 100644 include/test/sheet/xcellrangereferrer.hxx create mode 100644 include/test/sheet/xcellrangesquery.hxx create mode 100644 include/test/sheet/xcellseries.hxx create mode 100644 include/test/sheet/xconsolidatable.hxx create mode 100644 include/test/sheet/xconsolidationdescriptor.hxx create mode 100644 include/test/sheet/xdatabaserange.hxx create mode 100644 include/test/sheet/xdatabaseranges.hxx create mode 100644 include/test/sheet/xdatapilotdescriptor.hxx create mode 100644 include/test/sheet/xdatapilotfield.hxx create mode 100644 include/test/sheet/xdatapilotfieldgrouping.hxx create mode 100644 include/test/sheet/xdatapilottable.hxx create mode 100644 include/test/sheet/xdatapilottable2.hxx create mode 100644 include/test/sheet/xdatapilottables.hxx create mode 100644 include/test/sheet/xdatapilottablessupplier.hxx create mode 100644 include/test/sheet/xddelink.hxx create mode 100644 include/test/sheet/xddelinks.hxx create mode 100644 include/test/sheet/xdocumentauditing.hxx create mode 100644 include/test/sheet/xformulaquery.hxx create mode 100644 include/test/sheet/xfunctiondescriptions.hxx create mode 100644 include/test/sheet/xgoalseek.hxx create mode 100644 include/test/sheet/xheaderfootercontent.hxx create mode 100644 include/test/sheet/xlabelrange.hxx create mode 100644 include/test/sheet/xlabelranges.hxx create mode 100644 include/test/sheet/xmultiformulatokens.hxx create mode 100644 include/test/sheet/xmultipleoperation.hxx create mode 100644 include/test/sheet/xnamedrange.hxx create mode 100644 include/test/sheet/xnamedranges.hxx create mode 100644 include/test/sheet/xprintareas.hxx create mode 100644 include/test/sheet/xrecentfunctions.hxx create mode 100644 include/test/sheet/xscenario.hxx create mode 100644 include/test/sheet/xscenarioenhanced.hxx create mode 100644 include/test/sheet/xscenarios.hxx create mode 100644 include/test/sheet/xscenariossupplier.hxx create mode 100644 include/test/sheet/xsheetannotation.hxx create mode 100644 include/test/sheet/xsheetannotationanchor.hxx create mode 100644 include/test/sheet/xsheetannotations.hxx create mode 100644 include/test/sheet/xsheetannotationshapesupplier.hxx create mode 100644 include/test/sheet/xsheetannotationssupplier.hxx create mode 100644 include/test/sheet/xsheetauditing.hxx create mode 100644 include/test/sheet/xsheetcellcursor.hxx create mode 100644 include/test/sheet/xsheetcellrange.hxx create mode 100644 include/test/sheet/xsheetcellrangecontainer.hxx create mode 100644 include/test/sheet/xsheetcellranges.hxx create mode 100644 include/test/sheet/xsheetcondition.hxx create mode 100644 include/test/sheet/xsheetconditionalentries.hxx create mode 100644 include/test/sheet/xsheetconditionalentry.hxx create mode 100644 include/test/sheet/xsheetfilterable.hxx create mode 100644 include/test/sheet/xsheetfilterableex.hxx create mode 100644 include/test/sheet/xsheetfilterdescriptor.hxx create mode 100644 include/test/sheet/xsheetfilterdescriptor2.hxx create mode 100644 include/test/sheet/xsheetfilterdescriptor3.hxx create mode 100644 include/test/sheet/xsheetlinkable.hxx create mode 100644 include/test/sheet/xsheetoperation.hxx create mode 100644 include/test/sheet/xsheetoutline.hxx create mode 100644 include/test/sheet/xsheetpagebreak.hxx create mode 100644 include/test/sheet/xspreadsheet.hxx create mode 100644 include/test/sheet/xspreadsheetdocument.hxx create mode 100644 include/test/sheet/xspreadsheets.hxx create mode 100644 include/test/sheet/xspreadsheets2.hxx create mode 100644 include/test/sheet/xspreadsheetview.hxx create mode 100644 include/test/sheet/xsubtotalcalculatable.hxx create mode 100644 include/test/sheet/xsubtotaldescriptor.hxx create mode 100644 include/test/sheet/xsubtotalfield.hxx create mode 100644 include/test/sheet/xuniquecellformatrangessupplier.hxx create mode 100644 include/test/sheet/xusedareacursor.hxx create mode 100644 include/test/sheet/xviewfreezable.hxx create mode 100644 include/test/sheet/xviewpane.hxx create mode 100644 include/test/sheet/xviewsplitable.hxx create mode 100644 include/test/style/xstyleloader.hxx create mode 100644 include/test/table/tablecolumn.hxx create mode 100644 include/test/table/tablerow.hxx create mode 100644 include/test/table/xcell.hxx create mode 100644 include/test/table/xcellcursor.hxx create mode 100644 include/test/table/xcellrange.hxx create mode 100644 include/test/table/xcolumnrowrange.hxx create mode 100644 include/test/table/xtablechart.hxx create mode 100644 include/test/table/xtablecharts.hxx create mode 100644 include/test/table/xtablechartssupplier.hxx create mode 100644 include/test/table/xtablecolumns.hxx create mode 100644 include/test/table/xtablerows.hxx create mode 100644 include/test/testdllapi.hxx create mode 100644 include/test/testinteractionhandler.hxx create mode 100644 include/test/text/baseindex.hxx create mode 100644 include/test/text/textcontent.hxx create mode 100644 include/test/text/textdocumentindex.hxx create mode 100644 include/test/text/textdocumentsettings.hxx create mode 100644 include/test/text/textprintersettings.hxx create mode 100644 include/test/text/textsettings.hxx create mode 100644 include/test/text/xdocumentindex.hxx create mode 100644 include/test/text/xsimpletext.hxx create mode 100644 include/test/text/xtext.hxx create mode 100644 include/test/text/xtextcontent.hxx create mode 100644 include/test/text/xtextfield.hxx create mode 100644 include/test/text/xtextrange.hxx create mode 100644 include/test/unoapi_property_testers.hxx create mode 100644 include/test/unoapi_test.hxx create mode 100644 include/test/util/searchdescriptor.hxx create mode 100644 include/test/util/xindent.hxx create mode 100644 include/test/util/xmergeable.hxx create mode 100644 include/test/util/xrefreshable.hxx create mode 100644 include/test/util/xreplaceable.hxx create mode 100644 include/test/util/xreplacedescriptor.hxx create mode 100644 include/test/util/xsearchable.hxx create mode 100644 include/test/util/xsearchdescriptor.hxx create mode 100644 include/test/view/xcontrolaccess.hxx create mode 100644 include/test/view/xformlayeraccess.hxx create mode 100644 include/test/xmldiff.hxx create mode 100644 include/test/xmldocptr.hxx create mode 100644 include/test/xmltesttools.hxx create mode 100644 include/toolkit/awt/vclxaccessiblecomponent.hxx create mode 100644 include/toolkit/awt/vclxdevice.hxx create mode 100644 include/toolkit/awt/vclxfont.hxx create mode 100644 include/toolkit/awt/vclxmenu.hxx create mode 100644 include/toolkit/awt/vclxwindow.hxx create mode 100644 include/toolkit/awt/vclxwindows.hxx create mode 100644 include/toolkit/controls/unocontrol.hxx create mode 100644 include/toolkit/controls/unocontrolbase.hxx create mode 100644 include/toolkit/controls/unocontrolmodel.hxx create mode 100644 include/toolkit/controls/unocontrols.hxx create mode 100644 include/toolkit/dllapi.h create mode 100644 include/toolkit/helper/accessiblefactory.hxx create mode 100644 include/toolkit/helper/convert.hxx create mode 100644 include/toolkit/helper/emptyfontdescriptor.hxx create mode 100644 include/toolkit/helper/formpdfexport.hxx create mode 100644 include/toolkit/helper/listenermultiplexer.hxx create mode 100644 include/toolkit/helper/macros.hxx create mode 100644 include/toolkit/helper/mutexandbroadcasthelper.hxx create mode 100644 include/toolkit/helper/property.hxx create mode 100644 include/toolkit/helper/vclunohelper.hxx create mode 100644 include/tools/GenericTypeSerializer.hxx create mode 100644 include/tools/Guid.hxx create mode 100644 include/tools/UnitConversion.hxx create mode 100644 include/tools/XmlWalker.hxx create mode 100644 include/tools/XmlWriter.hxx create mode 100644 include/tools/b3dtrans.hxx create mode 100644 include/tools/bigint.hxx create mode 100644 include/tools/color.hxx create mode 100644 include/tools/config.hxx create mode 100644 include/tools/contnr.hxx create mode 100644 include/tools/cpuid.hxx create mode 100644 include/tools/date.hxx create mode 100644 include/tools/datetime.hxx create mode 100644 include/tools/datetimeutils.hxx create mode 100644 include/tools/debug.hxx create mode 100644 include/tools/degree.hxx create mode 100644 include/tools/diagnose_ex.h create mode 100644 include/tools/extendapplicationenvironment.hxx create mode 100644 include/tools/fileutil.hxx create mode 100644 include/tools/fix16.hxx create mode 100644 include/tools/fldunit.hxx create mode 100644 include/tools/fontenum.hxx create mode 100644 include/tools/fract.hxx create mode 100644 include/tools/gen.hxx create mode 100644 include/tools/globname.hxx create mode 100644 include/tools/helpers.hxx create mode 100644 include/tools/inetmime.hxx create mode 100644 include/tools/inetmsg.hxx create mode 100644 include/tools/inetstrm.hxx create mode 100644 include/tools/json_writer.hxx create mode 100644 include/tools/line.hxx create mode 100644 include/tools/lineend.hxx create mode 100644 include/tools/link.hxx create mode 100644 include/tools/long.hxx create mode 100644 include/tools/mapunit.hxx create mode 100644 include/tools/multisel.hxx create mode 100644 include/tools/pathutils.hxx create mode 100644 include/tools/poly.hxx create mode 100644 include/tools/ref.hxx create mode 100644 include/tools/resary.hxx create mode 100644 include/tools/simd.hxx create mode 100644 include/tools/simdsupport.hxx create mode 100644 include/tools/solar.h create mode 100644 include/tools/stream.hxx create mode 100644 include/tools/svborder.hxx create mode 100644 include/tools/svlibrary.h create mode 100644 include/tools/tenccvt.hxx create mode 100644 include/tools/time.hxx create mode 100644 include/tools/toolsdllapi.h create mode 100644 include/tools/urlobj.hxx create mode 100644 include/tools/vcompat.hxx create mode 100644 include/tools/weakbase.h create mode 100644 include/tools/weakbase.hxx create mode 100644 include/tools/wintypes.hxx create mode 100644 include/tools/wldcrd.hxx create mode 100644 include/tools/zcodec.hxx create mode 100644 include/typelib/typeclass.h create mode 100644 include/typelib/typedescription.h create mode 100644 include/typelib/typedescription.hxx create mode 100644 include/typelib/uik.h create mode 100644 include/ucbhelper/activedatasink.hxx create mode 100644 include/ucbhelper/authenticationfallback.hxx create mode 100644 include/ucbhelper/cancelcommandexecution.hxx create mode 100644 include/ucbhelper/commandenvironment.hxx create mode 100644 include/ucbhelper/content.hxx create mode 100644 include/ucbhelper/contenthelper.hxx create mode 100644 include/ucbhelper/contentidentifier.hxx create mode 100644 include/ucbhelper/fd_inputstream.hxx create mode 100644 include/ucbhelper/interactionrequest.hxx create mode 100644 include/ucbhelper/interceptedinteraction.hxx create mode 100644 include/ucbhelper/macros.hxx create mode 100644 include/ucbhelper/propertyvalueset.hxx create mode 100644 include/ucbhelper/providerhelper.hxx create mode 100644 include/ucbhelper/proxydecider.hxx create mode 100644 include/ucbhelper/registerucb.hxx create mode 100644 include/ucbhelper/resultset.hxx create mode 100644 include/ucbhelper/resultsethelper.hxx create mode 100644 include/ucbhelper/resultsetmetadata.hxx create mode 100644 include/ucbhelper/simpleauthenticationrequest.hxx create mode 100644 include/ucbhelper/simplecertificatevalidationrequest.hxx create mode 100644 include/ucbhelper/simpleinteractionrequest.hxx create mode 100644 include/ucbhelper/simplenameclashresolverequest.hxx create mode 100644 include/ucbhelper/ucbhelperdllapi.h create mode 100644 include/uno/Enterable.h create mode 100644 include/uno/EnvDcp.h create mode 100644 include/uno/any2.h create mode 100644 include/uno/current_context.h create mode 100644 include/uno/current_context.hxx create mode 100644 include/uno/data.h create mode 100644 include/uno/dispatcher.h create mode 100644 include/uno/dispatcher.hxx create mode 100644 include/uno/environment.h create mode 100644 include/uno/environment.hxx create mode 100644 include/uno/lbnames.h create mode 100644 include/uno/mapping.h create mode 100644 include/uno/mapping.hxx create mode 100644 include/uno/sequence2.h create mode 100644 include/uno/threadpool.h create mode 100644 include/unoidl/detail/dllapi.hxx create mode 100644 include/unoidl/unoidl.hxx create mode 100644 include/unotest/bootstrapfixturebase.hxx create mode 100644 include/unotest/detail/unotestdllapi.hxx create mode 100644 include/unotest/directories.hxx create mode 100644 include/unotest/filters-test.hxx create mode 100644 include/unotest/getargument.hxx create mode 100644 include/unotest/gettestargument.hxx create mode 100644 include/unotest/macros_test.hxx create mode 100644 include/unotest/officeconnection.hxx create mode 100644 include/unotest/toabsolutefileurl.hxx create mode 100644 include/unotools/VersionConfig.hxx create mode 100644 include/unotools/ZipPackageHelper.hxx create mode 100644 include/unotools/accessiblerelationsethelper.hxx create mode 100644 include/unotools/accessiblestatesethelper.hxx create mode 100644 include/unotools/bootstrap.hxx create mode 100644 include/unotools/calendarwrapper.hxx create mode 100644 include/unotools/caserotate.hxx create mode 100644 include/unotools/charclass.hxx create mode 100644 include/unotools/closeveto.hxx create mode 100644 include/unotools/cmdoptions.hxx create mode 100644 include/unotools/collatorwrapper.hxx create mode 100644 include/unotools/compatibility.hxx create mode 100644 include/unotools/configitem.hxx create mode 100644 include/unotools/configmgr.hxx create mode 100644 include/unotools/confignode.hxx create mode 100644 include/unotools/configpaths.hxx create mode 100644 include/unotools/configvaluecontainer.hxx create mode 100644 include/unotools/datetime.hxx create mode 100644 include/unotools/defaultencoding.hxx create mode 100644 include/unotools/defaultoptions.hxx create mode 100644 include/unotools/desktopterminationobserver.hxx create mode 100644 include/unotools/digitgroupingiterator.hxx create mode 100644 include/unotools/docinfohelper.hxx create mode 100644 include/unotools/dynamicmenuoptions.hxx create mode 100644 include/unotools/eventcfg.hxx create mode 100644 include/unotools/eventlisteneradapter.hxx create mode 100644 include/unotools/extendedsecurityoptions.hxx create mode 100644 include/unotools/fltrcfg.hxx create mode 100644 include/unotools/fontcfg.hxx create mode 100644 include/unotools/fontcvt.hxx create mode 100644 include/unotools/fontdefs.hxx create mode 100644 include/unotools/historyoptions.hxx create mode 100644 include/unotools/intlwrapper.hxx create mode 100644 include/unotools/itemholderbase.hxx create mode 100644 include/unotools/lingucfg.hxx create mode 100644 include/unotools/linguprops.hxx create mode 100644 include/unotools/localedatawrapper.hxx create mode 100644 include/unotools/localfilehelper.hxx create mode 100644 include/unotools/mediadescriptor.hxx create mode 100644 include/unotools/moduleoptions.hxx create mode 100644 include/unotools/nativenumberwrapper.hxx create mode 100644 include/unotools/options.hxx create mode 100644 include/unotools/optionsdlg.hxx create mode 100644 include/unotools/pathoptions.hxx create mode 100644 include/unotools/progresshandlerwrap.hxx create mode 100644 include/unotools/resmgr.hxx create mode 100644 include/unotools/saveopt.hxx create mode 100644 include/unotools/searchopt.hxx create mode 100644 include/unotools/securityoptions.hxx create mode 100644 include/unotools/sharedunocomponent.hxx create mode 100644 include/unotools/streamhelper.hxx create mode 100644 include/unotools/streamwrap.hxx create mode 100644 include/unotools/syslocale.hxx create mode 100644 include/unotools/syslocaleoptions.hxx create mode 100644 include/unotools/tempfile.hxx create mode 100644 include/unotools/textsearch.hxx create mode 100644 include/unotools/transliterationwrapper.hxx create mode 100644 include/unotools/ucbhelper.hxx create mode 100644 include/unotools/ucbstreamhelper.hxx create mode 100644 include/unotools/unotoolsdllapi.h create mode 100644 include/unotools/useroptions.hxx create mode 100644 include/unotools/viewoptions.hxx create mode 100644 include/unotools/weakref.hxx create mode 100644 include/unotools/wincodepage.hxx create mode 100644 include/vbahelper/vbaaccesshelper.hxx create mode 100644 include/vbahelper/vbaapplicationbase.hxx create mode 100644 include/vbahelper/vbacollectionimpl.hxx create mode 100644 include/vbahelper/vbadialogbase.hxx create mode 100644 include/vbahelper/vbadialogsbase.hxx create mode 100644 include/vbahelper/vbadllapi.h create mode 100644 include/vbahelper/vbadocumentbase.hxx create mode 100644 include/vbahelper/vbadocumentsbase.hxx create mode 100644 include/vbahelper/vbaeventshelperbase.hxx create mode 100644 include/vbahelper/vbafontbase.hxx create mode 100644 include/vbahelper/vbaglobalbase.hxx create mode 100644 include/vbahelper/vbahelper.hxx create mode 100644 include/vbahelper/vbahelperinterface.hxx create mode 100644 include/vbahelper/vbapagesetupbase.hxx create mode 100644 include/vbahelper/vbapropvalue.hxx create mode 100644 include/vbahelper/vbareturntypes.hxx create mode 100644 include/vbahelper/vbashape.hxx create mode 100644 include/vbahelper/vbashaperange.hxx create mode 100644 include/vbahelper/vbashapes.hxx create mode 100644 include/vbahelper/vbatextframe.hxx create mode 100644 include/vbahelper/vbawindowbase.hxx create mode 100644 include/vcl/AccessibleBrowseBoxObjType.hxx create mode 100644 include/vcl/BinaryDataContainer.hxx create mode 100644 include/vcl/BinaryDataContainerTools.hxx create mode 100644 include/vcl/BitmapAccessMode.hxx create mode 100644 include/vcl/BitmapAlphaClampFilter.hxx create mode 100644 include/vcl/BitmapBasicMorphologyFilter.hxx create mode 100644 include/vcl/BitmapBuffer.hxx create mode 100644 include/vcl/BitmapColor.hxx create mode 100644 include/vcl/BitmapColorQuantizationFilter.hxx create mode 100644 include/vcl/BitmapConvolutionMatrixFilter.hxx create mode 100644 include/vcl/BitmapDuoToneFilter.hxx create mode 100644 include/vcl/BitmapEmbossGreyFilter.hxx create mode 100644 include/vcl/BitmapFilter.hxx create mode 100644 include/vcl/BitmapFilterStackBlur.hxx create mode 100644 include/vcl/BitmapGaussianSeparableBlurFilter.hxx create mode 100644 include/vcl/BitmapInfoAccess.hxx create mode 100644 include/vcl/BitmapMedianFilter.hxx create mode 100644 include/vcl/BitmapMonochromeFilter.hxx create mode 100644 include/vcl/BitmapMosaicFilter.hxx create mode 100644 include/vcl/BitmapPalette.hxx create mode 100644 include/vcl/BitmapPopArtFilter.hxx create mode 100644 include/vcl/BitmapReadAccess.hxx create mode 100644 include/vcl/BitmapSeparableUnsharpenFilter.hxx create mode 100644 include/vcl/BitmapSepiaFilter.hxx create mode 100644 include/vcl/BitmapShadowFilter.hxx create mode 100644 include/vcl/BitmapSharpenFilter.hxx create mode 100644 include/vcl/BitmapSimpleColorQuantizationFilter.hxx create mode 100644 include/vcl/BitmapSmoothenFilter.hxx create mode 100644 include/vcl/BitmapSobelGreyFilter.hxx create mode 100644 include/vcl/BitmapSolarizeFilter.hxx create mode 100644 include/vcl/BitmapTools.hxx create mode 100644 include/vcl/ColorMask.hxx create mode 100644 include/vcl/EnumContext.hxx create mode 100644 include/vcl/FilterConfigItem.hxx create mode 100644 include/vcl/GestureEvent.hxx create mode 100644 include/vcl/GraphicAttributes.hxx create mode 100644 include/vcl/GraphicExternalLink.hxx create mode 100644 include/vcl/GraphicLoader.hxx create mode 100644 include/vcl/GraphicNativeMetadata.hxx create mode 100644 include/vcl/GraphicNativeTransform.hxx create mode 100644 include/vcl/GraphicObject.hxx create mode 100644 include/vcl/IContext.hxx create mode 100644 include/vcl/IDialogRenderable.hxx create mode 100644 include/vcl/ITiledRenderable.hxx create mode 100644 include/vcl/IconThemeInfo.hxx create mode 100644 include/vcl/ImageTree.hxx create mode 100644 include/vcl/InterimItemWindow.hxx create mode 100644 include/vcl/NotebookbarContextControl.hxx create mode 100644 include/vcl/PrinterSupport.hxx create mode 100644 include/vcl/QueueInfo.hxx create mode 100644 include/vcl/RawBitmap.hxx create mode 100644 include/vcl/Scanline.hxx create mode 100644 include/vcl/TaskStopwatch.hxx create mode 100644 include/vcl/TypeSerializer.hxx create mode 100644 include/vcl/VectorGraphicSearch.hxx create mode 100644 include/vcl/WeldedTabbedNotebookbar.hxx create mode 100644 include/vcl/abstdlg.hxx create mode 100644 include/vcl/accessiblefactory.hxx create mode 100644 include/vcl/accessibletable.hxx create mode 100644 include/vcl/accessibletableprovider.hxx create mode 100644 include/vcl/alpha.hxx create mode 100644 include/vcl/animate/Animation.hxx create mode 100644 include/vcl/animate/AnimationBitmap.hxx create mode 100644 include/vcl/bitmap.hxx create mode 100644 include/vcl/bitmap/BitmapTypes.hxx create mode 100644 include/vcl/bitmapex.hxx create mode 100644 include/vcl/builder.hxx create mode 100644 include/vcl/builderfactory.hxx create mode 100644 include/vcl/builderpage.hxx create mode 100644 include/vcl/cairo.hxx create mode 100644 include/vcl/canvastools.hxx create mode 100644 include/vcl/checksum.hxx create mode 100644 include/vcl/commandevent.hxx create mode 100644 include/vcl/commandinfoprovider.hxx create mode 100644 include/vcl/ctrl.hxx create mode 100644 include/vcl/cursor.hxx create mode 100644 include/vcl/customweld.hxx create mode 100644 include/vcl/cvtgrf.hxx create mode 100644 include/vcl/decoview.hxx create mode 100644 include/vcl/devicecoordinate.hxx create mode 100644 include/vcl/dialoghelper.hxx create mode 100644 include/vcl/dibtools.hxx create mode 100644 include/vcl/dllapi.h create mode 100644 include/vcl/dndhelp.hxx create mode 100644 include/vcl/dockingarea.hxx create mode 100644 include/vcl/dockwin.hxx create mode 100644 include/vcl/embeddedfontshelper.hxx create mode 100644 include/vcl/errcode.hxx create mode 100644 include/vcl/errinf.hxx create mode 100644 include/vcl/event.hxx create mode 100644 include/vcl/evntpost.hxx create mode 100644 include/vcl/exceptiontypes.hxx create mode 100644 include/vcl/extoutdevdata.hxx create mode 100644 include/vcl/fieldvalues.hxx create mode 100644 include/vcl/fileregistration.hxx create mode 100644 include/vcl/filter/PDFiumLibrary.hxx create mode 100644 include/vcl/filter/PngImageReader.hxx create mode 100644 include/vcl/filter/SvmReader.hxx create mode 100644 include/vcl/filter/SvmWriter.hxx create mode 100644 include/vcl/filter/pdfdocument.hxx create mode 100644 include/vcl/filter/pdfobjectcontainer.hxx create mode 100644 include/vcl/fntstyle.hxx create mode 100644 include/vcl/font.hxx create mode 100644 include/vcl/font/Feature.hxx create mode 100644 include/vcl/font/FeatureParser.hxx create mode 100644 include/vcl/fontcapabilities.hxx create mode 100644 include/vcl/fontcharmap.hxx create mode 100644 include/vcl/formatter.hxx create mode 100644 include/vcl/gdimetafiletools.hxx create mode 100644 include/vcl/gdimtf.hxx create mode 100644 include/vcl/gfxlink.hxx create mode 100644 include/vcl/glyphitem.hxx create mode 100644 include/vcl/glyphitemcache.hxx create mode 100644 include/vcl/gradient.hxx create mode 100644 include/vcl/graph.hxx create mode 100644 include/vcl/graphicfilter.hxx create mode 100644 include/vcl/graphictools.hxx create mode 100644 include/vcl/hatch.hxx create mode 100644 include/vcl/headbar.hxx create mode 100644 include/vcl/help.hxx create mode 100644 include/vcl/i18nhelp.hxx create mode 100644 include/vcl/idle.hxx create mode 100644 include/vcl/image.hxx create mode 100644 include/vcl/imap.hxx create mode 100644 include/vcl/imapcirc.hxx create mode 100644 include/vcl/imapobj.hxx create mode 100644 include/vcl/imappoly.hxx create mode 100644 include/vcl/imaprect.hxx create mode 100644 include/vcl/inetimg.hxx create mode 100644 include/vcl/inputctx.hxx create mode 100644 include/vcl/inputtypes.hxx create mode 100644 include/vcl/introwin.hxx create mode 100644 include/vcl/jobset.hxx create mode 100644 include/vcl/jsdialog/executor.hxx create mode 100644 include/vcl/keycod.hxx create mode 100644 include/vcl/keycodes.hxx create mode 100644 include/vcl/layout.hxx create mode 100644 include/vcl/lazydelete.hxx create mode 100644 include/vcl/lineinfo.hxx create mode 100644 include/vcl/locktoplevels.hxx create mode 100644 include/vcl/lok.hxx create mode 100644 include/vcl/mapmod.hxx create mode 100644 include/vcl/menu.hxx create mode 100644 include/vcl/menubarupdateicon.hxx create mode 100644 include/vcl/metaact.hxx create mode 100644 include/vcl/metaactiontypes.hxx create mode 100644 include/vcl/metric.hxx create mode 100644 include/vcl/mnemonic.hxx create mode 100644 include/vcl/mtfxmldump.hxx create mode 100644 include/vcl/naturalsort.hxx create mode 100644 include/vcl/notebookbar/NotebookBarAddonsMerger.hxx create mode 100644 include/vcl/notebookbar/notebookbar.hxx create mode 100644 include/vcl/oldprintadaptor.hxx create mode 100644 include/vcl/opengl/OpenGLContext.hxx create mode 100644 include/vcl/opengl/OpenGLHelper.hxx create mode 100644 include/vcl/opengl/OpenGLWrapper.hxx create mode 100644 include/vcl/outdev.hxx create mode 100644 include/vcl/outdev/ScopedStates.hxx create mode 100644 include/vcl/pdf/PDFAnnotationMarker.hxx create mode 100644 include/vcl/pdf/PDFAnnotationSubType.hxx create mode 100644 include/vcl/pdf/PDFBitmapType.hxx create mode 100644 include/vcl/pdf/PDFErrorType.hxx create mode 100644 include/vcl/pdf/PDFFillMode.hxx create mode 100644 include/vcl/pdf/PDFFindFlags.hxx create mode 100644 include/vcl/pdf/PDFObjectType.hxx create mode 100644 include/vcl/pdf/PDFPageObjectType.hxx create mode 100644 include/vcl/pdf/PDFSegmentType.hxx create mode 100644 include/vcl/pdf/PDFTextRenderMode.hxx create mode 100644 include/vcl/pdfextoutdevdata.hxx create mode 100644 include/vcl/pdfread.hxx create mode 100644 include/vcl/pdfwriter.hxx create mode 100644 include/vcl/pngwrite.hxx create mode 100644 include/vcl/print.hxx create mode 100644 include/vcl/printer/Options.hxx create mode 100644 include/vcl/prntypes.hxx create mode 100644 include/vcl/ptrstyle.hxx create mode 100644 include/vcl/quickselectionengine.hxx create mode 100644 include/vcl/region.hxx create mode 100644 include/vcl/rendercontext/AddFontSubstituteFlags.hxx create mode 100644 include/vcl/rendercontext/AntialiasingFlags.hxx create mode 100644 include/vcl/rendercontext/DrawGridFlags.hxx create mode 100644 include/vcl/rendercontext/DrawImageFlags.hxx create mode 100644 include/vcl/rendercontext/DrawModeFlags.hxx create mode 100644 include/vcl/rendercontext/DrawTextFlags.hxx create mode 100644 include/vcl/rendercontext/GetDefaultFontFlags.hxx create mode 100644 include/vcl/rendercontext/ImplMapRes.hxx create mode 100644 include/vcl/rendercontext/InvertFlags.hxx create mode 100644 include/vcl/rendercontext/RasterOp.hxx create mode 100644 include/vcl/rendercontext/SalLayoutFlags.hxx create mode 100644 include/vcl/rendercontext/State.hxx create mode 100644 include/vcl/rendercontext/SystemTextColorFlags.hxx create mode 100644 include/vcl/roadmapwizard.hxx create mode 100644 include/vcl/salctype.hxx create mode 100644 include/vcl/salgtype.hxx create mode 100644 include/vcl/salnativewidgets.hxx create mode 100644 include/vcl/scheduler.hxx create mode 100644 include/vcl/scopedbitmapaccess.hxx create mode 100644 include/vcl/scrbar.hxx create mode 100644 include/vcl/seleng.hxx create mode 100644 include/vcl/settings.hxx create mode 100644 include/vcl/skia/SkiaHelper.hxx create mode 100644 include/vcl/sound.hxx create mode 100644 include/vcl/specialchars.hxx create mode 100644 include/vcl/split.hxx create mode 100644 include/vcl/splitwin.hxx create mode 100644 include/vcl/status.hxx create mode 100644 include/vcl/stdtext.hxx create mode 100644 include/vcl/svapp.hxx create mode 100644 include/vcl/svmain.hxx create mode 100644 include/vcl/svtaccessiblefactory.hxx create mode 100644 include/vcl/syschild.hxx create mode 100644 include/vcl/sysdata.hxx create mode 100644 include/vcl/syswin.hxx create mode 100644 include/vcl/tabctrl.hxx create mode 100644 include/vcl/tabpage.hxx create mode 100644 include/vcl/task.hxx create mode 100644 include/vcl/taskpanelist.hxx create mode 100644 include/vcl/test/GraphicsRenderTests.hxx create mode 100644 include/vcl/test/TestResult.hxx create mode 100644 include/vcl/textdata.hxx create mode 100644 include/vcl/texteng.hxx create mode 100644 include/vcl/textfilter.hxx create mode 100644 include/vcl/textrectinfo.hxx create mode 100644 include/vcl/textview.hxx create mode 100644 include/vcl/threadex.hxx create mode 100644 include/vcl/timer.hxx create mode 100644 include/vcl/toolbox.hxx create mode 100644 include/vcl/toolboxid.hxx create mode 100644 include/vcl/toolkit/README create mode 100644 include/vcl/toolkit/button.hxx create mode 100644 include/vcl/toolkit/calendar.hxx create mode 100644 include/vcl/toolkit/combobox.hxx create mode 100644 include/vcl/toolkit/dialog.hxx create mode 100644 include/vcl/toolkit/edit.hxx create mode 100644 include/vcl/toolkit/field.hxx create mode 100644 include/vcl/toolkit/fixed.hxx create mode 100644 include/vcl/toolkit/fixedhyper.hxx create mode 100644 include/vcl/toolkit/floatwin.hxx create mode 100644 include/vcl/toolkit/fmtfield.hxx create mode 100644 include/vcl/toolkit/group.hxx create mode 100644 include/vcl/toolkit/imgctrl.hxx create mode 100644 include/vcl/toolkit/ivctrl.hxx create mode 100644 include/vcl/toolkit/longcurr.hxx create mode 100644 include/vcl/toolkit/lstbox.hxx create mode 100644 include/vcl/toolkit/menubtn.hxx create mode 100644 include/vcl/toolkit/morebtn.hxx create mode 100644 include/vcl/toolkit/prgsbar.hxx create mode 100644 include/vcl/toolkit/roadmap.hxx create mode 100644 include/vcl/toolkit/spin.hxx create mode 100644 include/vcl/toolkit/spinfld.hxx create mode 100644 include/vcl/toolkit/svlbitm.hxx create mode 100644 include/vcl/toolkit/svtabbx.hxx create mode 100644 include/vcl/toolkit/tabdlg.hxx create mode 100644 include/vcl/toolkit/throbber.hxx create mode 100644 include/vcl/toolkit/treelist.hxx create mode 100644 include/vcl/toolkit/treelistbox.hxx create mode 100644 include/vcl/toolkit/treelistentries.hxx create mode 100644 include/vcl/toolkit/treelistentry.hxx create mode 100644 include/vcl/toolkit/unowrap.hxx create mode 100644 include/vcl/toolkit/vclmedit.hxx create mode 100644 include/vcl/toolkit/viewdataentry.hxx create mode 100644 include/vcl/transfer.hxx create mode 100644 include/vcl/txtattr.hxx create mode 100644 include/vcl/uitest/eventdescription.hxx create mode 100644 include/vcl/uitest/factory.hxx create mode 100644 include/vcl/uitest/formattedfielduiobject.hxx create mode 100644 include/vcl/uitest/logger.hxx create mode 100644 include/vcl/uitest/metricfielduiobject.hxx create mode 100644 include/vcl/uitest/uiobject.hxx create mode 100644 include/vcl/uitest/uitest.hxx create mode 100644 include/vcl/unohelp.hxx create mode 100644 include/vcl/unohelp2.hxx create mode 100644 include/vcl/vclenum.hxx create mode 100644 include/vcl/vclevent.hxx create mode 100644 include/vcl/vcllayout.hxx create mode 100644 include/vcl/vclmain.hxx create mode 100644 include/vcl/vclptr.hxx create mode 100644 include/vcl/vclreferencebase.hxx create mode 100644 include/vcl/vectorgraphicdata.hxx create mode 100644 include/vcl/virdev.hxx create mode 100644 include/vcl/wall.hxx create mode 100644 include/vcl/weld.hxx create mode 100644 include/vcl/weldutils.hxx create mode 100644 include/vcl/window.hxx create mode 100644 include/vcl/windowstate.hxx create mode 100644 include/vcl/winscheduler.hxx create mode 100644 include/vcl/wizardmachine.hxx create mode 100644 include/vcl/wmf.hxx create mode 100644 include/vcl/wmfexternal.hxx create mode 100644 include/vcl/wrkwin.hxx create mode 100644 include/vcl/xtextedt.hxx create mode 100644 include/version.hrc create mode 100644 include/xmloff/DashStyle.hxx create mode 100644 include/xmloff/DocumentSettingsContext.hxx create mode 100644 include/xmloff/EnumPropertyHdl.hxx create mode 100644 include/xmloff/GradientStyle.hxx create mode 100644 include/xmloff/HatchStyle.hxx create mode 100644 include/xmloff/ImageStyle.hxx create mode 100644 include/xmloff/MarkerStyle.hxx create mode 100644 include/xmloff/NamedBoolPropertyHdl.hxx create mode 100644 include/xmloff/ProgressBarHelper.hxx create mode 100644 include/xmloff/SchXMLExportHelper.hxx create mode 100644 include/xmloff/SchXMLImportHelper.hxx create mode 100644 include/xmloff/SchXMLSeriesHelper.hxx create mode 100644 include/xmloff/SettingsExportHelper.hxx create mode 100644 include/xmloff/SinglePropertySetInfoCache.hxx create mode 100644 include/xmloff/XMLBase64ImportContext.hxx create mode 100644 include/xmloff/XMLCharContext.hxx create mode 100644 include/xmloff/XMLConstantsPropertyHandler.hxx create mode 100644 include/xmloff/XMLDrawingPageStyleContext.hxx create mode 100644 include/xmloff/XMLEventExport.hxx create mode 100644 include/xmloff/XMLEventsImportContext.hxx create mode 100644 include/xmloff/XMLFilterServiceNames.h create mode 100644 include/xmloff/XMLFontAutoStylePool.hxx create mode 100644 include/xmloff/XMLFontStylesContext.hxx create mode 100644 include/xmloff/XMLGraphicsDefaultStyle.hxx create mode 100644 include/xmloff/XMLPageExport.hxx create mode 100644 include/xmloff/XMLSettingsExportContext.hxx create mode 100644 include/xmloff/XMLShapeStyleContext.hxx create mode 100644 include/xmloff/XMLTextListAutoStylePool.hxx create mode 100644 include/xmloff/XMLTextMasterPageContext.hxx create mode 100644 include/xmloff/XMLTextMasterPageExport.hxx create mode 100644 include/xmloff/XMLTextMasterStylesContext.hxx create mode 100644 include/xmloff/XMLTextShapeImportHelper.hxx create mode 100644 include/xmloff/XMLTextShapeStyleContext.hxx create mode 100644 include/xmloff/XMLTextTableContext.hxx create mode 100644 include/xmloff/animationexport.hxx create mode 100644 include/xmloff/animexp.hxx create mode 100644 include/xmloff/attrlist.hxx create mode 100644 include/xmloff/autolayout.hxx create mode 100644 include/xmloff/contextid.hxx create mode 100644 include/xmloff/controlpropertyhdl.hxx create mode 100644 include/xmloff/dllapi.h create mode 100644 include/xmloff/families.hxx create mode 100644 include/xmloff/formlayerexport.hxx create mode 100644 include/xmloff/formlayerimport.hxx create mode 100644 include/xmloff/i18nmap.hxx create mode 100644 include/xmloff/languagetagodf.hxx create mode 100644 include/xmloff/maptype.hxx create mode 100644 include/xmloff/namespacemap.hxx create mode 100644 include/xmloff/numehelp.hxx create mode 100644 include/xmloff/odffields.hxx create mode 100644 include/xmloff/prhdlfac.hxx create mode 100644 include/xmloff/prstylei.hxx create mode 100644 include/xmloff/settingsstore.hxx create mode 100644 include/xmloff/shapeexport.hxx create mode 100644 include/xmloff/shapeimport.hxx create mode 100644 include/xmloff/styleexp.hxx create mode 100644 include/xmloff/table/XMLTableExport.hxx create mode 100644 include/xmloff/table/XMLTableImport.hxx create mode 100644 include/xmloff/txtimp.hxx create mode 100644 include/xmloff/txtimppr.hxx create mode 100644 include/xmloff/txtparae.hxx create mode 100644 include/xmloff/txtprmap.hxx create mode 100644 include/xmloff/txtstyli.hxx create mode 100644 include/xmloff/unoatrcn.hxx create mode 100644 include/xmloff/unointerfacetouniqueidentifiermapper.hxx create mode 100644 include/xmloff/xformsexport.hxx create mode 100644 include/xmloff/xformsimport.hxx create mode 100644 include/xmloff/xmlaustp.hxx create mode 100644 include/xmloff/xmlcnimp.hxx create mode 100644 include/xmloff/xmlement.hxx create mode 100644 include/xmloff/xmlerror.hxx create mode 100644 include/xmloff/xmlevent.hxx create mode 100644 include/xmloff/xmlexp.hxx create mode 100644 include/xmloff/xmlexppr.hxx create mode 100644 include/xmloff/xmlictxt.hxx create mode 100644 include/xmloff/xmlimp.hxx create mode 100644 include/xmloff/xmlimppr.hxx create mode 100644 include/xmloff/xmlmetae.hxx create mode 100644 include/xmloff/xmlmetai.hxx create mode 100644 include/xmloff/xmlnamespace.hxx create mode 100644 include/xmloff/xmlnume.hxx create mode 100644 include/xmloff/xmlnumfe.hxx create mode 100644 include/xmloff/xmlnumfi.hxx create mode 100644 include/xmloff/xmlnumi.hxx create mode 100644 include/xmloff/xmlprcon.hxx create mode 100644 include/xmloff/xmlprhdl.hxx create mode 100644 include/xmloff/xmlprmap.hxx create mode 100644 include/xmloff/xmlscripti.hxx create mode 100644 include/xmloff/xmlstyle.hxx create mode 100644 include/xmloff/xmltkmap.hxx create mode 100644 include/xmloff/xmltoken.hxx create mode 100644 include/xmloff/xmltypes.hxx create mode 100644 include/xmloff/xmluconv.hxx create mode 100644 include/xmlreader/README create mode 100644 include/xmlreader/detail/xmlreaderdllapi.hxx create mode 100644 include/xmlreader/pad.hxx create mode 100644 include/xmlreader/span.hxx create mode 100644 include/xmlreader/xmlreader.hxx create mode 100644 include/xmlscript/xml_helper.hxx create mode 100644 include/xmlscript/xmldlg_imexp.hxx create mode 100644 include/xmlscript/xmllib_imexp.hxx create mode 100644 include/xmlscript/xmlmod_imexp.hxx create mode 100644 include/xmlscript/xmlns.h create mode 100644 include/xmlscript/xmlscriptdllapi.h (limited to 'include') diff --git a/include/IwyuFilter_include.yaml b/include/IwyuFilter_include.yaml new file mode 100644 index 000000000..758ba37a6 --- /dev/null +++ b/include/IwyuFilter_include.yaml @@ -0,0 +1,952 @@ +--- +assumeFilename: desktop/source/app/app.cxx +excludelist: + include/sal/typesizes.h: + # needed for build to work + - config_typesizes.h + include/sal/types.h: + # needed for build to work + - sal/typesizes.h + include/sal/mathconf.h: + # Platform dependent + - cmath + include/osl/endian.h: + # needed for base types used in macros + - sal/types.h + include/osl/conditn.h: + # ODK API test would fail with fw decl here + - osl/time.h + include/osl/socket.h: + # ODK API test would fail with fw decl here + - osl/time.h + include/osl/thread.h: + # ODK API test would fail with fw decl here + - osl/time.h + include/osl/conditn.hxx: + # ODK API test would fail with fw decl here + - osl/time.h + include/osl/pipe_decl.hxx: + # ODK API test would fail with fw decl here + - osl/security.hxx + include/osl/socket_decl.hxx: + # Needed by socket.hxx for inline function + - rtl/byteseq.hxx + include/osl/thread.hxx: + # ODK API test would fail with fw decl here + - osl/time.h + include/rtl/instance.hxx: + # Needed for template functions + - osl/getglobalmutex.hxx + include/rtl/math.hxx: + # TODO MSVC does not compile basegfx/numeric/ftools.hxx when this is replaced + - math.h + include/android/compatibility.hxx: + # TODO check whether actually needed, just silence this for now + - math.h + include/LibreOfficeKit/LibreOfficeKit.h: + # the unstable API needs C99's bool + - stdbool.h + - stdint.h + include/sfx2/toolbarids.hxx: + # needed for enum definition + - sal/types.h + include/cppuhelper/compbase1.hxx: + # Needed for template functions + - cppuhelper/implbase1.hxx + include/cppuhelper/compbase2.hxx: + # Needed for template functions + - cppuhelper/implbase2.hxx + include/cppuhelper/compbase3.hxx: + # Needed for template functions + - cppuhelper/implbase3.hxx + include/cppuhelper/compbase4.hxx: + # Needed for template functions + - cppuhelper/implbase4.hxx + include/cppuhelper/compbase5.hxx: + # Needed for template functions + - cppuhelper/implbase5.hxx + include/cppuhelper/compbase6.hxx: + # Needed for template functions + - cppuhelper/implbase6.hxx + include/cppuhelper/compbase7.hxx: + # Needed for template functions + - cppuhelper/implbase7.hxx + include/cppuhelper/compbase8.hxx: + # Needed for template functions + - cppuhelper/implbase8.hxx + include/cppuhelper/compbase9.hxx: + # Needed for template functions + - cppuhelper/implbase9.hxx + include/cppuhelper/compbase10.hxx: + # Needed for template functions + - cppuhelper/implbase10.hxx + include/cppuhelper/compbase11.hxx: + # Needed for template functions + - cppuhelper/implbase11.hxx + include/cppuhelper/compbase12.hxx: + # Needed for template functions + - cppuhelper/implbase12.hxx + include/cppuhelper/exc_hlp.hxx: + #Needed for implicit destructor + - com/sun/star/uno/Any.hxx + include/cppuhelper/propertysetmixin.hxx: + #Needed for implicit destructor + - com/sun/star/uno/Sequence.hxx + include/cppuhelper/interfacecontainer.h: + #Needed for implicit destructor + - com/sun/star/uno/Sequence.hxx + include/ucbhelper/activedatasink.hxx: + # base class has to be a complete type + - com/sun/star/io/XActiveDataSink.hpp + include/ucbhelper/commandenvironment.hxx: + # base class has to be a complete type + - com/sun/star/ucb/XCommandEnvironment.hpp + include/ucbhelper/interceptedinteraction.hxx: + # base class has to be a complete type + - com/sun/star/task/XInteractionHandler.hpp + include/ucbhelper/fd_inputstream.hxx: + # Needed for typedef + - com/sun/star/io/XInputStream.hpp + - com/sun/star/io/XSeekable.hpp + include/ucbhelper/macros.hxx: + # Used in macros defined here + - cppuhelper/typeprovider.hxx + - cppuhelper/supportsservice.hxx + - cppuhelper/factory.hxx + include/comphelper/accessiblekeybindinghelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleKeyBinding.hpp + include/comphelper/accessiblecomponenthelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleExtendedComponent.hpp + include/comphelper/accessiblecontexthelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleContext.hpp + - com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp + include/comphelper/accessibleselectionhelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleSelection.hpp + include/comphelper/accessibletexthelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleText.hpp + include/comphelper/accessiblewrapper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleContext.hpp + - com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp + - com/sun/star/accessibility/XAccessibleEventListener.hpp + include/comphelper/accimplaccess.hxx: + # base class has to be a complete type + - com/sun/star/lang/XUnoTunnel.hpp + include/comphelper/attributelist.hxx: + # base class has to be a complete type + - com/sun/star/util/XCloneable.hpp + - com/sun/star/xml/sax/XAttributeList.hpp + include/comphelper/ChainablePropertySetInfo.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertySetInfo.hpp + include/comphelper/containermultiplexer.hxx: + # base class has to be a complete type + - com/sun/star/container/XContainerListener.hpp + include/comphelper/docpasswordrequest.hxx: + # base class has to be a complete type + - com/sun/star/task/XInteractionRequest.hpp + include/comphelper/enumhelper.hxx: + # base class has to be a complete type + - com/sun/star/container/XEnumeration.hpp + - com/sun/star/lang/XEventListener.hpp + include/comphelper/evtlistenerhlp.hxx: + # base class has to be a complete type + - com/sun/star/lang/XEventListener.hpp + include/comphelper/interaction.hxx: + # base class has to be a complete type + - com/sun/star/task/XInteractionAbort.hpp + - com/sun/star/task/XInteractionApprove.hpp + - com/sun/star/task/XInteractionDisapprove.hpp + - com/sun/star/task/XInteractionRequest.hpp + - com/sun/star/task/XInteractionRetry.hpp + include/comphelper/SelectionMultiplex.hxx: + # base class has to be a complete type + - com/sun/star/view/XSelectionChangeListener.hpp + include/comphelper/MasterPropertySetInfo.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertySetInfo.hpp + include/comphelper/namedvaluecollection.hxx: + # Needed for template class + - com/sun/star/beans/PropertyValue.hpp + - com/sun/star/beans/NamedValue.hpp + include/comphelper/numberedcollection.hxx: + # base class has to be a complete type + - com/sun/star/frame/XUntitledNumbers.hpp + include/comphelper/oslfile2streamwrap.hxx: + # base class has to be a complete type + - com/sun/star/io/XInputStream.hpp + - com/sun/star/io/XOutputStream.hpp + include/comphelper/propertysetinfo.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertySetInfo.hpp + include/comphelper/propmultiplex.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyChangeListener.hpp + include/comphelper/propertystatecontainer.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyState.hpp + include/comphelper/seekableinput.hxx: + # base class has to be a complete type + - com/sun/star/io/XInputStream.hpp + - com/sun/star/io/XSeekable.hpp + include/comphelper/seqstream.hxx: + # base class has to be a complete type + - com/sun/star/io/XInputStream.hpp + - com/sun/star/io/XSeekable.hpp + include/comphelper/servicedecl.hxx: + # base class has to be a complete type + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/uno/XComponentContext.hpp + include/comphelper/servicehelper.hxx: + # Needed for macro + - rtl/instance.hxx + include/comphelper/stl_types.hxx: + # Needed for std::equal + - algorithm + include/comphelper/unique_disposing_ptr.hxx: + # base class has to be a complete type + - com/sun/star/lang/XServiceInfo.hpp + include/comphelper/uno3.hxx: + # Needed for macro + - comphelper/sequence.hxx + include/comphelper/weakeventlistener.hxx: + # base class has to be a complete type + - com/sun/star/lang/XEventListener.hpp + - com/sun/star/lang/XComponent.hpp + include/basegfx/numeric/ftools.hxx: + # MSVC does not compile when this is removed + - math.h + - cmath + include/basegfx/utils/unopolypolygon.hxx: + # base class has to be a complete type + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/rendering/XBezierPolyPolygon2D.hpp + - com/sun/star/rendering/XLinePolyPolygon2D.hpp + include/o3tl/deleter.hxx: + # Needed for __COVERITY__ + - com/sun/star/uno/Exception.hpp + - sal/log.hxx + include/o3tl/lru_map.hxx: + # Needed for std::min + - algorithm + include/o3tl/make_shared.hxx: + # Needed for __COVERITY__ + - o3tl/deleter.hxx + include/o3tl/safeint.hxx: + # Needed for std::min + - algorithm + include/sot/exchange.hxx: + # Used in a macro #define + - com/sun/star/datatransfer/dnd/DNDConstants.hpp + include/tools/color.hxx: + # OSL_BIGENDIAN is being checked + - osl/endian.h + include/tools/debug.hxx: + # Used behind #ifndef + - tools/toolsdllapi.h + include/tools/diagnose_ex.h: + # Needed for macros + - com/sun/star/lang/IllegalArgumentException.hpp + - com/sun/star/uno/RuntimeException.hpp + - rtl/ustring.hxx + include/tools/fldunit.hxx: + # Needed for enum type + - sal/types.h + include/tools/long.hxx: + # Needed on _WIN64 + - sal/types.h + include/tools/svlibrary.h: + # Used behind #ifndef + - osl/module.h + include/tools/simdsupport.hxx: + # Needed for CPU intrinsics detection to work + - emmintrin.h + include/unotools/accessiblestatesethelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleStateSet.hpp + include/unotools/accessiblerelationsethelper.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleRelationSet.hpp + include/unotools/eventcfg.hxx: + # base class has to be a complete type + - com/sun/star/container/XNameReplace.hpp + - com/sun/star/document/XEventsSupplier.hpp + include/unotools/fontcfg.hxx: + # Needed for a sal_uLong enum + - tools/solar.h + include/unotools/progresshandlerwrap.hxx: + # base class has to be a complete type + - com/sun/star/ucb/XProgressHandler.hpp + include/unotools/streamwrap.hxx: + # base class has to be a complete type + - com/sun/star/io/XOutputStream.hpp + - com/sun/star/io/XStream.hpp + - com/sun/star/io/XTruncate.hpp + include/sax/fshelper.hxx: + # base class has to be a complete type + - com/sun/star/xml/sax/XFastAttributeList.hpp + include/sax/fastattribs.hxx: + # base class has to be a complete type + - com/sun/star/xml/sax/XFastAttributeList.hpp + include/sax/fastparser.hxx: + # base class has to be a complete type + - com/sun/star/lang/XInitialization.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/xml/sax/XFastParser.hpp + include/svl/numuno.hxx: + # base class has to be a complete type + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/util/XNumberFormatsSupplier.hpp + include/svl/urihelper.hxx: + # base class has to be a complete type + - tools/link.hxx + include/svl/style.hxx: + # base class has to be a complete type + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/style/XStyle.hpp + include/vcl/FilterConfigItem.hxx: + # Needed on Windows with --disable-pch + - com/sun/star/beans/PropertyValue.hpp + include/vcl/builderfactory.hxx: + # Needed for macro #define + - vcl/builder.hxx + - vcl/vclptr.hxx + include/vcl/decoview.hxx: + # Full definition needed for VclPtr + - vcl/outdev.hxx + include/vcl/devicecoordinate.hxx: + # Needed for #if configure switch + - basegfx/point/b2ipoint.hxx + include/vcl/event.hxx: + # Needed for enum type + - vcl/window.hxx + include/vcl/imap.hxx: + # Needed for implicit dtor + - vcl/imapobj.hxx + include/vcl/keycodes.hxx: + # Needed for macros + - com/sun/star/awt/Key.hpp + - com/sun/star/awt/KeyGroup.hpp + include/vcl/mtfxmldump.hxx: + # Full definition needed for o3tl::enumarray + - vcl/metaactiontypes.hxx + include/vcl/outdevstate.hxx: + # Full definition needed for boost::optional + - vcl/mapmod.hxx + - tools/color.hxx + - tools/gen.hxx + include/vcl/transfer.hxx: + # base class has to be a complete type + - com/sun/star/datatransfer/XTransferable2.hpp + - com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp + - com/sun/star/datatransfer/dnd/XDragSourceListener.hpp + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/frame/XTerminateListener.hpp + - com/sun/star/datatransfer/dnd/XDragGestureListener.hpp + - com/sun/star/datatransfer/dnd/XDropTargetListener.hpp + include/vcl/weld.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleRelationSet.hpp + - com/sun/star/accessibility/XAccessible.hpp + include/toolkit/awt/vclxaccessiblecomponent.hxx: + # base class has to be a complete type + - com/sun/star/lang/XServiceInfo.hpp + include/toolkit/awt/vclxwindow.hxx: + # base class has to be a complete type + - toolkit/awt/vclxdevice.hxx + - com/sun/star/awt/XWindow2.hpp + - com/sun/star/awt/XVclWindowPeer.hpp + - com/sun/star/awt/XLayoutConstrains.hpp + - com/sun/star/awt/XView.hpp + - com/sun/star/beans/XPropertySetInfo.hpp + - com/sun/star/accessibility/XAccessible.hpp + - com/sun/star/awt/XDockableWindow.hpp + - com/sun/star/awt/XStyleSettingsSupplier.hpp + include/toolkit/awt/vclxwindows.hxx: + # base class has to be a complete type + - com/sun/star/awt/XListBox.hpp + - com/sun/star/awt/XToggleButton.hpp + - com/sun/star/awt/XComboBox.hpp + - com/sun/star/awt/XItemListListener.hpp + include/toolkit/controls/unocontrol.hxx: + # base class has to be a complete type + - com/sun/star/awt/XControl.hpp + - com/sun/star/awt/XWindow2.hpp + - com/sun/star/awt/XView.hpp + - com/sun/star/beans/XPropertiesChangeListener.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/awt/XUnitConversion.hpp + - com/sun/star/awt/XStyleSettingsSupplier.hpp + - com/sun/star/accessibility/XAccessible.hpp + - com/sun/star/util/XModeChangeBroadcaster.hpp + include/toolkit/controls/unocontrolmodel.hxx: + # base class has to be a complete type + - com/sun/star/awt/XControlModel.hpp + - com/sun/star/lang/XComponent.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/beans/XPropertyState.hpp + - com/sun/star/io/XPersistObject.hpp + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/util/XCloneable.hpp + include/toolkit/controls/unocontrols.hxx: + # base class has to be a complete type + - com/sun/star/awt/XTextComponent.hpp + - com/sun/star/awt/XTextListener.hpp + - com/sun/star/awt/XTextLayoutConstrains.hpp + - com/sun/star/awt/XButton.hpp + - com/sun/star/awt/XToggleButton.hpp + - com/sun/star/awt/XRadioButton.hpp + - com/sun/star/awt/XCheckBox.hpp + - com/sun/star/awt/XListBox.hpp + - com/sun/star/awt/XItemList.hpp + include/toolkit/helper/macros.hxx: + # Needed for macros + - comphelper/servicehelper.hxx + - tools/diagnose_ex.h + include/xmloff/attrlist.hxx: + # base class has to be a complete type + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/util/XCloneable.hpp + - com/sun/star/xml/sax/XAttributeList.hpp + include/xmloff/unointerfacetouniqueidentifiermapper.hxx: + # base class has to be a complete type + - com/sun/star/uno/XInterface.hpp + include/xmloff/unoatrcn.hxx: + # base class has to be a complete type + - com/sun/star/container/XNameContainer.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/lang/XUnoTunnel.hpp + include/xmloff/xmlictxt.hxx: + # base class has to be a complete type + - com/sun/star/xml/sax/XFastContextHandler.hpp + include/xmloff/xmlexp.hxx: + # base class has to be a complete type + - com/sun/star/document/XFilter.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/document/XExporter.hpp + - com/sun/star/lang/XInitialization.hpp + - com/sun/star/container/XNamed.hpp + - com/sun/star/lang/XUnoTunnel.hpp + include/xmloff/xmlmetae.hxx: + # base class has to be a complete type + - com/sun/star/xml/sax/XDocumentHandler.hpp + include/xmloff/xmlimp.hxx: + # base class has to be a complete type + - com/sun/star/document/XFilter.hpp + - com/sun/star/document/XImporter.hpp + - com/sun/star/lang/XInitialization.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/xml/sax/XExtendedDocumentHandler.hpp + - com/sun/star/xml/sax/XFastDocumentHandler.hpp + - com/sun/star/xml/sax/XFastParser.hpp + include/svtools/asynclink.hxx: + # unique_ptr needs complete type + - osl/mutex.hxx + - vcl/idle.hxx + include/svtools/cliplistener.hxx: + # base class has to be a complete type + - com/sun/star/datatransfer/clipboard/XClipboardListener.hpp + include/svtools/dialogclosedlistener.hxx: + # base class has to be a complete type + - com/sun/star/ui/dialogs/XDialogClosedListener.hpp + include/svtools/genericunodialog.hxx: + # base class has to be a complete type + - com/sun/star/lang/XInitialization.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/ui/dialogs/XExecutableDialog.hpp + include/svtools/openfiledroptargetlistener.hxx: + # base class has to be a complete type + - com/sun/star/datatransfer/dnd/XDropTargetListener.hpp + include/svtools/popupmenucontrollerbase.hxx: + # base class has to be a complete type + - com/sun/star/frame/XDispatch.hpp + - com/sun/star/frame/XDispatchProvider.hpp + - com/sun/star/frame/XPopupMenuController.hpp + - com/sun/star/frame/XStatusListener.hpp + - com/sun/star/lang/XInitialization.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/svtools/popupwindowcontroller.hxx: + # base class has to be a complete type + - com/sun/star/lang/XServiceInfo.hpp + - svtools/toolboxcontroller.hxx + include/svtools/sfxecode.hxx: + # Needed for macro defines + - class ErrCode + include/svtools/statusbarcontroller.hxx: + # Don't propose hxx -> h change in URE libs + - cppuhelper/interfacecontainer.hxx + include/svtools/toolboxcontroller.hxx: + # base class has to be a complete type + - com/sun/star/frame/XStatusListener.hpp + - com/sun/star/frame/XToolbarController.hpp + - com/sun/star/util/XUpdatable.hpp + - com/sun/star/lang/XInitialization.hpp + # Complete type is needed for DispatchInfo struct + - com/sun/star/beans/PropertyValue.hpp + # Don't propose hxx -> h change in URE libs + - cppuhelper/interfacecontainer.hxx + include/svtools/unoevent.hxx: + # base class has to be a complete type + - com/sun/star/container/XNameReplace.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/framework/dispatchhelper.hxx: + # base class has to be a complete type + - com/sun/star/frame/XDispatchHelper.hpp + - com/sun/star/frame/XDispatchResultListener.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/framework/titlehelper.hxx: + # base class has to be a complete type + - com/sun/star/frame/XTitle.hpp + - com/sun/star/frame/XTitleChangeBroadcaster.hpp + - com/sun/star/frame/XFrameActionListener.hpp + - com/sun/star/document/XDocumentEventListener.hpp + # Don't propose hxx -> h change in URE libs + - cppuhelper/interfacecontainer.hxx + include/linguistic/hyphdta.hxx: + # base class has to be a complete type + - com/sun/star/linguistic2/XHyphenatedWord.hpp + - com/sun/star/linguistic2/XPossibleHyphens.hpp + include/linguistic/lngprophelp.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyChangeListener.hpp + - com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp + include/linguistic/spelldta.hxx: + # base class has to be a complete type + - com/sun/star/linguistic2/XSetSpellAlternatives.hpp + - com/sun/star/linguistic2/XSpellAlternatives.hpp + include/linguistic/misc.hxx: + # base class has to be a complete type + - com/sun/star/frame/XTerminateListener.hpp + include/cppcanvas/renderer.hxx: + # Used in boost::optional type + - basegfx/matrix/b2dhommatrix.hxx + include/basic/modsizeexceeded.hxx: + # base class has to be a complete type + - com/sun/star/task/XInteractionRequest.hpp + include/basic/sberrors.hxx: + # Needed for macro defines + - vcl/errcode.hxx + include/connectivity/BlobHelper.hxx: + # base class has to be a complete type + - com/sun/star/sdbc/XBlob.hpp + include/connectivity/CommonTools.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertySet.hpp + - com/sun/star/sdbcx/XColumnsSupplier.hpp + # Needed for macro defines + - cppuhelper/supportsservice.hxx + # Needed for HAVE_FEATURE_JAVA + - rtl/ref.hxx + include/connectivity/ConnectionWrapper.hxx: + # base class has to be a complete type + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/connectivity/conncleanup.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyChangeListener.hpp + - com/sun/star/sdbc/XRowSetListener.hpp + include/connectivity/parameters.hxx: + # base class has to be a complete type + - com/sun/star/sdb/XSingleSelectQueryComposer.hpp + include/connectivity/paramwrapper.hxx: + # base class has to be a complete type + - com/sun/star/container/XEnumerationAccess.hpp + - com/sun/star/container/XIndexAccess.hpp + include/connectivity/sdbcx/VCollection.hxx: + # base class has to be a complete type + - com/sun/star/container/XNameAccess.hpp + - com/sun/star/container/XIndexAccess.hpp + - com/sun/star/container/XEnumerationAccess.hpp + - com/sun/star/container/XContainer.hpp + - com/sun/star/sdbc/XColumnLocate.hpp + - com/sun/star/util/XRefreshable.hpp + - com/sun/star/sdbcx/XDataDescriptorFactory.hpp + - com/sun/star/sdbcx/XAppend.hpp + - com/sun/star/sdbcx/XDrop.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/beans/XPropertySet.hpp + include/connectivity/sdbcx/VCatalog.hxx: + # base class has to be a complete type + - com/sun/star/sdbcx/XTablesSupplier.hpp + - com/sun/star/sdbcx/XViewsSupplier.hpp + - com/sun/star/sdbcx/XUsersSupplier.hpp + - com/sun/star/sdbcx/XGroupsSupplier.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/connectivity/sdbcx/VColumn.hxx: + # base class has to be a complete type + - com/sun/star/container/XNamed.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/sdbcx/XDataDescriptorFactory.hpp + include/connectivity/sdbcx/VGroup.hxx: + # base class has to be a complete type + - com/sun/star/container/XNamed.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/sdbcx/XAuthorizable.hpp + - com/sun/star/sdbcx/XUsersSupplier.hpp + include/connectivity/sdbcx/VIndex.hxx: + # base class has to be a complete type + - com/sun/star/sdbcx/XDataDescriptorFactory.hpp + include/connectivity/sdbcx/VKey.hxx: + # base class has to be a complete type + - com/sun/star/sdbcx/XDataDescriptorFactory.hpp + include/connectivity/sdbcx/VTypeDef.hxx: + # base class has to be a complete type + - com/sun/star/container/XNamed.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/sdbcx/XColumnsSupplier.hpp + include/connectivity/sdbcx/VTable.hxx: + # base class has to be a complete type + - com/sun/star/container/XNamed.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/sdbcx/XAlterTable.hpp + - com/sun/star/sdbcx/XColumnsSupplier.hpp + - com/sun/star/sdbcx/XDataDescriptorFactory.hpp + - com/sun/star/sdbcx/XIndexesSupplier.hpp + - com/sun/star/sdbcx/XKeysSupplier.hpp + - com/sun/star/sdbcx/XRename.hpp + include/connectivity/sdbcx/VUser.hxx: + # base class has to be a complete type + - com/sun/star/container/XNamed.hpp + - com/sun/star/sdbcx/XGroupsSupplier.hpp + - com/sun/star/sdbcx/XUser.hpp + include/connectivity/sdbcx/VView.hxx: + # base class has to be a complete type + - com/sun/star/container/XNamed.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/sdbcx/XDataDescriptorFactory.hpp + include/drawinglayer/primitive2d/baseprimitive2d.hxx: + # base class has to be a complete type + - com/sun/star/graphic/XPrimitive2D.hpp + - com/sun/star/util/XAccounting.hpp + include/drawinglayer/primitive3d/baseprimitive3d.hxx: + # base class has to be a complete type + - com/sun/star/graphic/XPrimitive3D.hpp + include/sfx2/charwin.hxx: + # Needed for implicit dtor + - vcl/virdev.hxx + include/sfx2/dinfdlg.hxx: + # Needed for implicit dtor + - com/sun/star/document/CmisProperty.hpp + include/sfx2/docfile.hxx: + # Full type needed for template + - tools/link.hxx + include/sfx2/docstoragemodifylistener.hxx: + # base class has to be a complete type + - com/sun/star/util/XModifyListener.hpp + include/sfx2/DocumentMetadataAccess.hxx: + # base class has to be a complete type + - com/sun/star/rdf/XDocumentMetadataAccess.hpp + include/sfx2/mieclip.hxx: + # Needed for implicit dtor + - tools/stream.hxx + include/sfx2/sfxbasecontroller.hxx: + # base class has to be a complete type + - com/sun/star/frame/XController2.hpp + - com/sun/star/frame/XControllerBorder.hpp + - com/sun/star/frame/XDispatchProvider.hpp + - com/sun/star/task/XStatusIndicatorSupplier.hpp + - com/sun/star/ui/XContextMenuInterception.hpp + - com/sun/star/awt/XUserInputInterception.hpp + - com/sun/star/frame/XDispatchInformationProvider.hpp + - com/sun/star/frame/XTitle.hpp + - com/sun/star/frame/XTitleChangeBroadcaster.hpp + - com/sun/star/lang/XInitialization.hpp + include/sfx2/sfxbasemodel.hxx: + # base class has to be a complete type + - com/sun/star/container/XChild.hpp + - com/sun/star/document/XDocumentPropertiesSupplier.hpp + - com/sun/star/document/XCmisDocument.hpp + - com/sun/star/rdf/XDocumentMetadataAccess.hpp + - com/sun/star/document/XDocumentRecovery.hpp + - com/sun/star/document/XUndoManagerSupplier.hpp + - com/sun/star/document/XEventBroadcaster.hpp + - com/sun/star/document/XDocumentEventBroadcaster.hpp + - com/sun/star/lang/XEventListener.hpp + - com/sun/star/document/XEventsSupplier.hpp + - com/sun/star/document/XEmbeddedScripts.hpp + - com/sun/star/document/XScriptInvocationContext.hpp + - com/sun/star/frame/XModel2.hpp + - com/sun/star/util/XModifiable2.hpp + - com/sun/star/view/XPrintable.hpp + - com/sun/star/view/XPrintJobBroadcaster.hpp + - com/sun/star/frame/XStorable2.hpp + - com/sun/star/frame/XLoadable.hpp + - com/sun/star/script/XStarBasicAccess.hpp + - com/sun/star/document/XViewDataSupplier.hpp + - com/sun/star/util/XCloseable.hpp + - com/sun/star/datatransfer/XTransferable.hpp + - com/sun/star/document/XDocumentSubStorageSupplier.hpp + - com/sun/star/document/XStorageBasedDocument.hpp + - com/sun/star/script/provider/XScriptProviderSupplier.hpp + - com/sun/star/ui/XUIConfigurationManagerSupplier.hpp + - com/sun/star/embed/XVisualObject.hpp + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/frame/XModule.hpp + - com/sun/star/frame/XTitle.hpp + - com/sun/star/frame/XTitleChangeBroadcaster.hpp + - com/sun/star/frame/XUntitledNumbers.hpp + include/sfx2/sfxsids.hrc: + # Needed for sfxitems.sdi to build + - svl/memberid.h + # Needed for TypedWhichId defines + - svl/typedwhich.hxx + - class SvxZoomItem + - class SfxUInt16Item + - class SvxHyperlinkItem + - class SfxDocumentInfoItem + - class SvxSearchItem + include/sfx2/shell.hxx: + # Used in macro define + - class SfxModule + include/sfx2/sfxstatuslistener.hxx: + # base class has to be a complete type + - com/sun/star/frame/XStatusListener.hpp + - com/sun/star/lang/XComponent.hpp + include/sfx2/sidebar/SidebarController.hxx: + # base class has to be a complete type + - com/sun/star/ui/XContextChangeEventListener.hpp + - com/sun/star/beans/XPropertyChangeListener.hpp + - com/sun/star/ui/XSidebar.hpp + - com/sun/star/frame/XStatusListener.hpp + - com/sun/star/frame/XFrameActionListener.hpp + include/sfx2/sidebar/SidebarPanelBase.hxx: + # base class has to be a complete type + - com/sun/star/ui/XContextChangeEventListener.hpp + - com/sun/star/ui/XUIElement.hpp + - com/sun/star/ui/XToolPanel.hpp + - com/sun/star/ui/XSidebarPanel.hpp + - com/sun/star/ui/XUpdateModel.hpp + include/sfx2/sidebar/Theme.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertySet.hpp + include/sfx2/sidebar/UnoSidebar.hxx: + # base class has to be a complete type + - com/sun/star/ui/XSidebarProvider.hpp + include/sfx2/viewsh.hxx: + # Needed for macro + - class SfxViewFactory + include/editeng/AccessibleContextBase.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleContext.hpp + - com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp + - com/sun/star/accessibility/XAccessible.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/editeng/AccessibleEditableTextPara.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleComponent.hpp + - com/sun/star/accessibility/XAccessibleContext.hpp + - com/sun/star/accessibility/XAccessibleEditableText.hpp + - com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp + - com/sun/star/accessibility/XAccessible.hpp + - com/sun/star/accessibility/XAccessibleHypertext.hpp + - com/sun/star/accessibility/XAccessibleMultiLineText.hpp + - com/sun/star/accessibility/XAccessibleTextAttributes.hpp + - com/sun/star/lang/XServiceInfo.hpp + include/editeng/AccessibleStaticTextBase.hxx: + # base class has to be a complete type + - com/sun/star/accessibility/XAccessibleText.hpp + - com/sun/star/accessibility/XAccessibleTextAttributes.hpp + include/editeng/editerr.hxx: + # Needed for macro defines + - vcl/errcode.hxx + include/editeng/eeitem.hxx: + # Needed for macro defines + - svl/typedwhich.hxx + - class SfxBoolItem + - class SfxGrabBagItem + - class SfxInt16Item + - class SvxAdjustItem + - class SvxAutoKernItem + - class SvxCaseMapItem + - class SvxCharReliefItem + - class SvxCharScaleWidthItem + - class SvxColorItem + - class SvxContourItem + - class SvxCrossedOutItem + - class SvxEmphasisMarkItem + - class SvxEscapementItem + - class SvxFontHeightItem + - class SvxFontItem + - class SvxForbiddenRuleItem + - class SvxFrameDirectionItem + - class SvxHangingPunctuationItem + - class SvxKerningItem + - class SvxLanguageItem + - class SvxLineSpacingItem + - class SvxLRSpaceItem + - class SvxOverlineItem + - class SvxPostureItem + - class SvXMLAttrContainerItem + - class SvxScriptSpaceItem + - class SvxShadowedItem + - class SvxTabStopItem + - class SvxULSpaceItem + - class SvxUnderlineItem + - class SvxWeightItem + - class SvxWordLineModeItem + - class SvxBulletItem + - class SvxNumBulletItem + include/editeng/UnoForbiddenCharsTable.hxx: + # base class has to be a complete type + - com/sun/star/i18n/XForbiddenCharacters.hpp + - com/sun/star/linguistic2/XSupportedLocales.hpp + include/editeng/unonrule.hxx: + # base class has to be a complete type + - com/sun/star/container/XIndexReplace.hpp + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/lang/XUnoTunnel.hpp + - com/sun/star/ucb/XAnyCompare.hpp + - com/sun/star/util/XCloneable.hpp + include/editeng/unotext.hxx: + # Needed for macro defines + - com/sun/star/container/XIndexReplace.hpp + - com/sun/star/awt/FontSlant.hpp + - com/sun/star/awt/FontDescriptor.hpp + - com/sun/star/style/LineSpacing.hpp + - com/sun/star/style/TabStop.hpp + - editeng/eeitem.hxx + include/formula/FormulaOpCodeMapperObj.hxx: + # base class has to be a complete type + - com/sun/star/lang/XServiceInfo.hpp + - com/sun/star/sheet/XFormulaOpCodeMapper.hpp + include/formula/paramclass.hxx: + # Needed for enum type + - sal/types.h + include/formula/opcode.hxx: + # Needed for enum type + - sal/types.h + include/formula/tokenarray.hxx: + # Needed to avoid linking errors on WIN + - formula/ExternalReferenceHelper.hxx + include/svx/AccessibleControlShape.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyChangeListener.hpp + - com/sun/star/container/XContainerListener.hpp + - com/sun/star/util/XModeChangeListener.hpp + include/svx/dbaexchange.hxx: + # Needed for implicit dtor + - com/sun/star/beans/PropertyValue.hpp + include/svx/EnhancedCustomShape2d.hxx: + # Needed for implicit dtor + - com/sun/star/drawing/EnhancedCustomShapeAdjustmentValue.hpp + - com/sun/star/drawing/EnhancedCustomShapeSegment.hpp + - com/sun/star/drawing/EnhancedCustomShapeTextFrame.hpp + include/svx/fmgridif.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyChangeListener.hpp + - com/sun/star/container/XContainer.hpp + - com/sun/star/container/XEnumerationAccess.hpp + - com/sun/star/form/XBoundComponent.hpp + - com/sun/star/form/XGridControl.hpp + - com/sun/star/form/XGridPeer.hpp + - com/sun/star/form/XLoadListener.hpp + - com/sun/star/form/XResetListener.hpp + - com/sun/star/frame/XDispatchProvider.hpp + - com/sun/star/frame/XDispatchProviderInterception.hpp + - com/sun/star/frame/XStatusListener.hpp + - com/sun/star/sdbc/XRowSetListener.hpp + - com/sun/star/sdb/XRowSetSupplier.hpp + - com/sun/star/util/XModeSelector.hpp + - com/sun/star/util/XModifyBroadcaster.hpp + - com/sun/star/view/XSelectionSupplier.hpp + - toolkit/awt/vclxwindow.hxx + include/svx/fmsrcimp.hxx: + # base class has to be a complete type + - com/sun/star/beans/XPropertyChangeListener.hpp + include/svx/fmtools.hxx: + # base class has to be a complete type + - com/sun/star/lang/XEventListener.hpp + include/svx/ifaceids.hxx: + # Keep for macro define + - sfx2/shell.hxx + include/svx/measctrl.hxx: + # Needed for template class + - svx/svdobj.hxx + include/svx/svddef.hxx: + # Used in macro definition + - svl/typedwhich.hxx + include/svx/svxerr.hxx: + # Used in macro definition + - vcl/errcode.hxx + include/svx/svxids.hrc: + # Used in macro definition + - svl/typedwhich.hxx + include/svx/unopage.hxx: + # Don't propose hxx -> h change in URE libs + - cppuhelper/interfacecontainer.hxx + include/svx/unoshprp.hxx: + # Needed for macro defines + - com/sun/star/drawing/PointSequence.hpp + - com/sun/star/drawing/PointSequenceSequence.hpp + - com/sun/star/uno/Sequence.hxx + - com/sun/star/drawing/RectanglePoint.hpp + - com/sun/star/awt/XBitmap.hpp + - com/sun/star/awt/Gradient.hpp + - com/sun/star/drawing/Hatch.hpp + - com/sun/star/drawing/FillStyle.hpp + - com/sun/star/drawing/LineCap.hpp + - com/sun/star/drawing/LineDash.hpp + - com/sun/star/drawing/LineJoint.hpp + - com/sun/star/drawing/LineStyle.hpp + - com/sun/star/beans/PropertyAttribute.hpp + - com/sun/star/awt/Rectangle.hpp + - com/sun/star/drawing/TextAnimationDirection.hpp + - com/sun/star/drawing/TextAnimationKind.hpp + - com/sun/star/drawing/TextFitToSizeType.hpp + - com/sun/star/drawing/TextVerticalAdjust.hpp + - com/sun/star/drawing/TextHorizontalAdjust.hpp + - com/sun/star/drawing/ConnectorType.hpp + - com/sun/star/drawing/XShape.hpp + - com/sun/star/drawing/MeasureKind.hpp + - com/sun/star/drawing/MeasureTextHorzPos.hpp + - com/sun/star/drawing/MeasureTextVertPos.hpp + - com/sun/star/drawing/HomogenMatrix3.hpp + - com/sun/star/drawing/CircleKind.hpp + - com/sun/star/drawing/PolygonKind.hpp + - com/sun/star/drawing/PolyPolygonBezierCoords.hpp + - com/sun/star/drawing/ColorMode.hpp + - com/sun/star/drawing/HomogenMatrix.hpp + - com/sun/star/drawing/Direction3D.hpp + - com/sun/star/drawing/ProjectionMode.hpp + - com/sun/star/drawing/ShadeMode.hpp + - com/sun/star/drawing/Position3D.hpp + - com/sun/star/drawing/NormalsKind.hpp + - com/sun/star/drawing/TextureKind.hpp + - com/sun/star/drawing/TextureMode.hpp + - com/sun/star/drawing/TextureProjectionMode.hpp + - com/sun/star/drawing/PolyPolygonShape3D.hpp + - com/sun/star/text/GraphicCrop.hpp + - com/sun/star/drawing/BitmapMode.hpp + - com/sun/star/drawing/CameraGeometry.hpp + - com/sun/star/text/WritingMode.hpp + - com/sun/star/graphic/XGraphic.hpp + - com/sun/star/drawing/QRCode.hpp + - com/sun/star/text/XTextColumns.hpp + - com/sun/star/drawing/BarCode.hpp + - editeng/unoprnms.hxx + - svx/svddef.hxx + include/svx/xdef.hxx: + # Needed for macro defines + - svl/typedwhich.hxx + include/svx/svdtext.hxx: + # TODO too many replacements would be needed + - tools/weakbase.hxx + include/oox/helper/helper.hxx: + # OSL_BIGENDIAN is being checked + - osl/endian.h + include/codemaker/global.hxx: + # Don't propose hxx -> h change in URE libs + - osl/file.hxx + include/comphelper/crashzone.hxx: + # Needed for sig_atomic_t + - csignal + include/comphelper/parallelsort.hxx: + # Needed when PARALLELSORT_ENABLEPZ is defined + - chrono diff --git a/include/LibreOfficeKit/LibreOfficeKit.h b/include/LibreOfficeKit/LibreOfficeKit.h new file mode 100644 index 000000000..aff71dcc1 --- /dev/null +++ b/include/LibreOfficeKit/LibreOfficeKit.h @@ -0,0 +1,491 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKIT_H +#define INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKIT_H + +#include + +// the unstable API needs C99's bool +// TODO remove the C99 types from the API before making stable +#if defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY +# ifndef _WIN32 +# include +# endif +# include +#endif + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef struct _LibreOfficeKit LibreOfficeKit; +typedef struct _LibreOfficeKitClass LibreOfficeKitClass; + +typedef struct _LibreOfficeKitDocument LibreOfficeKitDocument; +typedef struct _LibreOfficeKitDocumentClass LibreOfficeKitDocumentClass; + +// Do we have an extended member in this struct ? +#define LIBREOFFICEKIT_HAS_MEMBER(strct,member,nSize) \ + (offsetof(strct, member) < (nSize)) + +#define LIBREOFFICEKIT_HAS(pKit,member) LIBREOFFICEKIT_HAS_MEMBER(LibreOfficeKitClass,member,(pKit)->pClass->nSize) + +struct _LibreOfficeKit +{ + LibreOfficeKitClass* pClass; +}; + +struct _LibreOfficeKitClass +{ + size_t nSize; + + void (*destroy) (LibreOfficeKit* pThis); + + LibreOfficeKitDocument* (*documentLoad) (LibreOfficeKit* pThis, + const char* pURL); + + char* (*getError) (LibreOfficeKit* pThis); + + /// @since LibreOffice 5.0 + LibreOfficeKitDocument* (*documentLoadWithOptions) (LibreOfficeKit* pThis, + const char* pURL, + const char* pOptions); + /// @since LibreOffice 5.2 + void (*freeError) (char* pFree); + + /// @since LibreOffice 6.0 + void (*registerCallback) (LibreOfficeKit* pThis, + LibreOfficeKitCallback pCallback, + void* pData); + + /** @see lok::Office::getFilterTypes(). + @since LibreOffice 6.0 + */ + char* (*getFilterTypes) (LibreOfficeKit* pThis); + + /** @see lok::Office::setOptionalFeatures(). + @since LibreOffice 6.0 + */ + void (*setOptionalFeatures)(LibreOfficeKit* pThis, unsigned long long features); + + /** @see lok::Office::setDocumentPassword(). + @since LibreOffice 6.0 + */ + void (*setDocumentPassword) (LibreOfficeKit* pThis, + char const* pURL, + char const* pPassword); + + /** @see lok::Office::getVersionInfo(). + @since LibreOffice 6.0 + */ + char* (*getVersionInfo) (LibreOfficeKit* pThis); + + /** @see lok::Office::runMacro(). + @since LibreOffice 6.0 + */ + int (*runMacro) (LibreOfficeKit *pThis, const char* pURL); + + /** @see lok::Office::signDocument(). + @since LibreOffice 6.2 + */ + bool (*signDocument) (LibreOfficeKit* pThis, + const char* pUrl, + const unsigned char* pCertificateBinary, + const int nCertificateBinarySize, + const unsigned char* pPrivateKeyBinary, + const int nPrivateKeyBinarySize); + + /// @see lok::Office::runLoop() + void (*runLoop) (LibreOfficeKit* pThis, + LibreOfficeKitPollCallback pPollCallback, + LibreOfficeKitWakeCallback pWakeCallback, + void* pData); + + /// @see lok::Office::sendDialogEvent + void (*sendDialogEvent) (LibreOfficeKit* pThis, + unsigned long long int nLOKWindowId, + const char* pArguments); + + /// @see lok::Office::setOption + void (*setOption) (LibreOfficeKit* pThis, const char* pOption, const char* pValue); +}; + +#define LIBREOFFICEKIT_DOCUMENT_HAS(pDoc,member) LIBREOFFICEKIT_HAS_MEMBER(LibreOfficeKitDocumentClass,member,(pDoc)->pClass->nSize) + +struct _LibreOfficeKitDocument +{ + LibreOfficeKitDocumentClass* pClass; +}; + +struct _LibreOfficeKitDocumentClass +{ + size_t nSize; + + void (*destroy) (LibreOfficeKitDocument* pThis); + + int (*saveAs) (LibreOfficeKitDocument* pThis, + const char* pUrl, + const char* pFormat, + const char* pFilterOptions); + + /** @see lok::Document::getDocumentType(). + @since LibreOffice 6.0 + */ + int (*getDocumentType) (LibreOfficeKitDocument* pThis); + +#if defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY + /// @see lok::Document::getParts(). + int (*getParts) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::getPartPageRectangles(). + char* (*getPartPageRectangles) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::getPart(). + int (*getPart) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::setPart(). + void (*setPart) (LibreOfficeKitDocument* pThis, + int nPart); + + /// @see lok::Document::getPartName(). + char* (*getPartName) (LibreOfficeKitDocument* pThis, + int nPart); + + /// @see lok::Document::setPartMode(). + void (*setPartMode) (LibreOfficeKitDocument* pThis, + int nMode); + + /// @see lok::Document::paintTile(). + void (*paintTile) (LibreOfficeKitDocument* pThis, + unsigned char* pBuffer, + const int nCanvasWidth, + const int nCanvasHeight, + const int nTilePosX, + const int nTilePosY, + const int nTileWidth, + const int nTileHeight); + + /// @see lok::Document::getTileMode(). + int (*getTileMode) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::getDocumentSize(). + void (*getDocumentSize) (LibreOfficeKitDocument* pThis, + long* pWidth, + long* pHeight); + + /// @see lok::Document::initializeForRendering(). + void (*initializeForRendering) (LibreOfficeKitDocument* pThis, + const char* pArguments); + + /// @see lok::Document::registerCallback(). + void (*registerCallback) (LibreOfficeKitDocument* pThis, + LibreOfficeKitCallback pCallback, + void* pData); + + /// @see lok::Document::postKeyEvent + void (*postKeyEvent) (LibreOfficeKitDocument* pThis, + int nType, + int nCharCode, + int nKeyCode); + + /// @see lok::Document::postMouseEvent + void (*postMouseEvent) (LibreOfficeKitDocument* pThis, + int nType, + int nX, + int nY, + int nCount, + int nButtons, + int nModifier); + + /// @see lok::Document::postUnoCommand + void (*postUnoCommand) (LibreOfficeKitDocument* pThis, + const char* pCommand, + const char* pArguments, + bool bNotifyWhenFinished); + + /// @see lok::Document::setTextSelection + void (*setTextSelection) (LibreOfficeKitDocument* pThis, + int nType, + int nX, + int nY); + + /// @see lok::Document::getTextSelection + char* (*getTextSelection) (LibreOfficeKitDocument* pThis, + const char* pMimeType, + char** pUsedMimeType); + + /// @see lok::Document::paste(). + bool (*paste) (LibreOfficeKitDocument* pThis, + const char* pMimeType, + const char* pData, + size_t nSize); + + /// @see lok::Document::setGraphicSelection + void (*setGraphicSelection) (LibreOfficeKitDocument* pThis, + int nType, + int nX, + int nY); + + /// @see lok::Document::resetSelection + void (*resetSelection) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::getCommandValues(). + char* (*getCommandValues) (LibreOfficeKitDocument* pThis, const char* pCommand); + + /// @see lok::Document::setClientZoom(). + void (*setClientZoom) (LibreOfficeKitDocument* pThis, + int nTilePixelWidth, + int nTilePixelHeight, + int nTileTwipWidth, + int nTileTwipHeight); + + /// @see lok::Document::setVisibleArea). + void (*setClientVisibleArea) (LibreOfficeKitDocument* pThis, int nX, int nY, int nWidth, int nHeight); + + /// @see lok::Document::createView(). + int (*createView) (LibreOfficeKitDocument* pThis); + /// @see lok::Document::destroyView(). + void (*destroyView) (LibreOfficeKitDocument* pThis, int nId); + /// @see lok::Document::setView(). + void (*setView) (LibreOfficeKitDocument* pThis, int nId); + /// @see lok::Document::getView(). + int (*getView) (LibreOfficeKitDocument* pThis); + /// @see lok::Document::getViewsCount(). + int (*getViewsCount) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::renderFont(). + unsigned char* (*renderFont) (LibreOfficeKitDocument* pThis, + const char* pFontName, + const char* pChar, + int* pFontWidth, + int* pFontHeight); + + /// @see lok::Document::getPartHash(). + char* (*getPartHash) (LibreOfficeKitDocument* pThis, + int nPart); + + /// Paints a tile from a specific part. + /// @see lok::Document::paintTile(). + void (*paintPartTile) (LibreOfficeKitDocument* pThis, + unsigned char* pBuffer, + const int nPart, + const int nCanvasWidth, + const int nCanvasHeight, + const int nTilePosX, + const int nTilePosY, + const int nTileWidth, + const int nTileHeight); + + /// @see lok::Document::getViewIds(). + bool (*getViewIds) (LibreOfficeKitDocument* pThis, + int* pArray, + size_t nSize); + + /// @see lok::Document::setOutlineState). + void (*setOutlineState) (LibreOfficeKitDocument* pThis, bool bColumn, int nLevel, int nIndex, bool bHidden); + + /// Paints window with given id to the buffer + /// @see lok::Document::paintWindow(). + void (*paintWindow) (LibreOfficeKitDocument* pThis, unsigned nWindowId, + unsigned char* pBuffer, + const int x, const int y, + const int width, const int height); + + /// @see lok::Document::postWindow(). + void (*postWindow) (LibreOfficeKitDocument* pThis, unsigned nWindowId, int nAction, const char* pData); + + /// @see lok::Document::postWindowKeyEvent(). + void (*postWindowKeyEvent) (LibreOfficeKitDocument* pThis, + unsigned nWindowId, + int nType, + int nCharCode, + int nKeyCode); + + /// @see lok::Document::postWindowMouseEvent(). + void (*postWindowMouseEvent) (LibreOfficeKitDocument* pThis, + unsigned nWindowId, + int nType, + int nX, + int nY, + int nCount, + int nButtons, + int nModifier); + + /// @see lok::Document::setViewLanguage(). + void (*setViewLanguage) (LibreOfficeKitDocument* pThis, int nId, const char* language); + + /// @see lok::Document::postWindowExtTextInputEvent + void (*postWindowExtTextInputEvent) (LibreOfficeKitDocument* pThis, + unsigned nWindowId, + int nType, + const char* pText); + + /// @see lok::Document::getPartInfo(). + char* (*getPartInfo) (LibreOfficeKitDocument* pThis, int nPart); + + /// Paints window with given id to the buffer with the give DPI scale + /// (every pixel is dpiscale-times larger). + /// @see lok::Document::paintWindow(). + void (*paintWindowDPI) (LibreOfficeKitDocument* pThis, unsigned nWindowId, + unsigned char* pBuffer, + const int x, const int y, + const int width, const int height, + const double dpiscale); + +#ifdef IOS + /// @see lok::Document::paintTileToCGContext(). + void (*paintTileToCGContext) (LibreOfficeKitDocument* pThis, + void* rCGContext, + const int nCanvasWidth, + const int nCanvasHeight, + const int nTilePosX, + const int nTilePosY, + const int nTileWidth, + const int nTileHeight); +#endif // IOS + +// CERTIFICATE AND SIGNING + + /// @see lok::Document::insertCertificate(). + bool (*insertCertificate) (LibreOfficeKitDocument* pThis, + const unsigned char* pCertificateBinary, + const int nCertificateBinarySize, + const unsigned char* pPrivateKeyBinary, + const int nPrivateKeyBinarySize); + + /// @see lok::Document::addCertificate(). + bool (*addCertificate) (LibreOfficeKitDocument* pThis, + const unsigned char* pCertificateBinary, + const int nCertificateBinarySize); + + /// @see lok::Document::getSignatureState(). + int (*getSignatureState) (LibreOfficeKitDocument* pThis); +// END CERTIFICATE AND SIGNING + + /// @see lok::Document::renderShapeSelection + size_t (*renderShapeSelection)(LibreOfficeKitDocument* pThis, char** pOutput); + + /// @see lok::Document::postWindowGestureEvent(). + void (*postWindowGestureEvent) (LibreOfficeKitDocument* pThis, + unsigned nWindowId, + const char* pType, + int nX, + int nY, + int nOffset); + + /// @see lok::Document::createViewWithOptions(). + int (*createViewWithOptions) (LibreOfficeKitDocument* pThis, const char* pOptions); + + /// @see lok::Document::selectPart(). + void (*selectPart) (LibreOfficeKitDocument* pThis, int nPart, int nSelect); + + /// @see lok::Document::moveSelectedParts(). + void (*moveSelectedParts) (LibreOfficeKitDocument* pThis, int nPosition, bool bDuplicate); + + /// Resize window with given id. + /// @see lok::Document::resizeWindow(). + void (*resizeWindow) (LibreOfficeKitDocument* pThis, unsigned nWindowId, + const int width, const int height); + + /// Pass a nullptr terminated array of mime-type strings + /// @see lok::Document::getClipboard for more details + int (*getClipboard) (LibreOfficeKitDocument* pThis, + const char **pMimeTypes, + size_t *pOutCount, + char ***pOutMimeTypes, + size_t **pOutSizes, + char ***pOutStreams); + + /// @see lok::Document::setClipboard + int (*setClipboard) (LibreOfficeKitDocument* pThis, + const size_t nInCount, + const char **pInMimeTypes, + const size_t *pInSizes, + const char **pInStreams); + + /// @see lok::Document::getSelectionType + int (*getSelectionType) (LibreOfficeKitDocument* pThis); + + /// @see lok::Document::removeTextContext + void (*removeTextContext) (LibreOfficeKitDocument* pThis, + unsigned nWindowId, + int nBefore, + int nAfter); + + /// @see lok::Document::sendDialogEvent + void (*sendDialogEvent) (LibreOfficeKitDocument* pThis, + unsigned long long int nLOKWindowId, + const char* pArguments); + + /// @see lok::Document::renderFontOrientation(). + unsigned char* (*renderFontOrientation) (LibreOfficeKitDocument* pThis, + const char* pFontName, + const char* pChar, + int* pFontWidth, + int* pFontHeight, + int pOrientation); + + /// Switches view to viewId if viewId >= 0, and paints window + /// @see lok::Document::paintWindowDPI(). + void (*paintWindowForView) (LibreOfficeKitDocument* pThis, unsigned nWindowId, + unsigned char* pBuffer, + const int x, const int y, + const int width, const int height, + const double dpiscale, + int viewId); + + /// @see lok::Document::completeFunction(). + void (*completeFunction) (LibreOfficeKitDocument* pThis, const char* pFunctionName); + + /// @see lok::Document::setWindowTextSelection + void (*setWindowTextSelection) (LibreOfficeKitDocument* pThis, + unsigned nWindowId, + bool bSwap, + int nX, + int nY); + + /// @see lok::Document::sendFormFieldEvent + void (*sendFormFieldEvent) (LibreOfficeKitDocument* pThis, + const char* pArguments); + + /// @see lok::Document::setBlockedCommandList + void (*setBlockedCommandList) (LibreOfficeKitDocument* pThis, + int nViewId, + const char* blockedCommandList); + + /// @see lok::Document::renderSearchResult + bool (*renderSearchResult) (LibreOfficeKitDocument* pThis, + const char* pSearchResult, + unsigned char** pBitmapBuffer, + int* pWidth, int* pHeight, size_t* pByteSize); + + /// @see lok::Document::sendContentControlEvent(). + void (*sendContentControlEvent)(LibreOfficeKitDocument* pThis, const char* pArguments); + + /// @see lok::Document::getSelectionTypeAndText + /// @since LibreOffice 7.4 + int (*getSelectionTypeAndText) (LibreOfficeKitDocument* pThis, + const char* pMimeType, + char** pText, + char** pUsedMimeType); + +#endif // defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY +}; + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKIT_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/LibreOfficeKit/LibreOfficeKit.hxx b/include/LibreOfficeKit/LibreOfficeKit.hxx new file mode 100644 index 000000000..6dbfbf964 --- /dev/null +++ b/include/LibreOfficeKit/LibreOfficeKit.hxx @@ -0,0 +1,1119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include + +/* + * The reasons this C++ code is not as pretty as it could be are: + * a) provide a pure C API - that's useful for some people + * b) allow ABI stability - C++ vtables are not good for that. + * c) avoid C++ types as part of the API. + */ +namespace lok +{ + +/// The lok::Document class represents one loaded document instance. +class Document +{ +private: + LibreOfficeKitDocument* mpDoc; + +public: + /// A lok::Document is typically created by the lok::Office::documentLoad() method. + Document(LibreOfficeKitDocument* pDoc) : + mpDoc(pDoc) + {} + + ~Document() + { + mpDoc->pClass->destroy(mpDoc); + } + + /** + * Stores the document's persistent data to a URL and + * continues to be a representation of the old URL. + * + * @param pUrl the location where to store the document + * @param pFormat the format to use while exporting, when omitted, then deducted from pURL's extension + * @param pFilterOptions options for the export filter, e.g. SkipImages. + * Another useful FilterOption is "TakeOwnership". It is consumed + * by the saveAs() itself, and when provided, the document identity + * changes to the provided pUrl - meaning that '.uno:ModifiedStatus' + * is triggered as with the "Save As..." in the UI. + * "TakeOwnership" mode must not be used when saving to PNG or PDF. + */ + bool saveAs(const char* pUrl, const char* pFormat = NULL, const char* pFilterOptions = NULL) + { + return mpDoc->pClass->saveAs(mpDoc, pUrl, pFormat, pFilterOptions) != 0; + } + + /// Gives access to the underlying C pointer. + LibreOfficeKitDocument *get() { return mpDoc; } + + /** + * Get document type. + * + * @since LibreOffice 6.0 + * @return an element of the LibreOfficeKitDocumentType enum. + */ + int getDocumentType() + { + return mpDoc->pClass->getDocumentType(mpDoc); + } + +#if defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY + /** + * Get number of part that the document contains. + * + * Part refers to either individual sheets in a Calc, or slides in Impress, + * and has no relevance for Writer. + */ + int getParts() + { + return mpDoc->pClass->getParts(mpDoc); + } + + /** + * Get the logical rectangle of each part in the document. + * + * A part refers to an individual page in Writer and has no relevant for + * Calc or Impress. + * + * @return a rectangle list, using the same format as + * LOK_CALLBACK_TEXT_SELECTION. + */ + char* getPartPageRectangles() + { + return mpDoc->pClass->getPartPageRectangles(mpDoc); + } + + /// Get the current part of the document. + int getPart() + { + return mpDoc->pClass->getPart(mpDoc); + } + + /// Set the current part of the document. + void setPart(int nPart) + { + mpDoc->pClass->setPart(mpDoc, nPart); + } + + /// Get the current part's name. + char* getPartName(int nPart) + { + return mpDoc->pClass->getPartName(mpDoc, nPart); + } + + /// Get the current part's hash. + char* getPartHash(int nPart) + { + return mpDoc->pClass->getPartHash(mpDoc, nPart); + } + + void setPartMode(int nMode) + { + mpDoc->pClass->setPartMode(mpDoc, nMode); + } + + /** + * Renders a subset of the document to a pre-allocated buffer. + * + * Note that the buffer size and the tile size implicitly supports + * rendering at different zoom levels, as the number of rendered pixels and + * the rendered rectangle of the document are independent. + * + * @param pBuffer pointer to the buffer, its size is determined by nCanvasWidth and nCanvasHeight. + * @param nCanvasWidth number of pixels in a row of pBuffer. + * @param nCanvasHeight number of pixels in a column of pBuffer. + * @param nTilePosX logical X position of the top left corner of the rendered rectangle, in TWIPs. + * @param nTilePosY logical Y position of the top left corner of the rendered rectangle, in TWIPs. + * @param nTileWidth logical width of the rendered rectangle, in TWIPs. + * @param nTileHeight logical height of the rendered rectangle, in TWIPs. + */ + void paintTile(unsigned char* pBuffer, + const int nCanvasWidth, + const int nCanvasHeight, + const int nTilePosX, + const int nTilePosY, + const int nTileWidth, + const int nTileHeight) + { + return mpDoc->pClass->paintTile(mpDoc, pBuffer, nCanvasWidth, nCanvasHeight, + nTilePosX, nTilePosY, nTileWidth, nTileHeight); + } + + /** + * Renders a window (dialog, popup, etc.) with give id + * + * @param nWindowId + * @param pBuffer Buffer with enough memory allocated to render any dialog + * @param x x-coordinate from where the dialog should start painting + * @param y y-coordinate from where the dialog should start painting + * @param width The width of the dialog image to be painted + * @param height The height of the dialog image to be painted + * @param dpiscale The dpi scale value used by the client. Please note + * that the x, y, width, height are supposed to be the + * values with dpiscale applied (ie. dialog covering + * 100x100 "normal" pixels with dpiscale '2' will have + * 200x200 width x height), so that it is easy to compute + * the buffer sizes etc. + */ + void paintWindow(unsigned nWindowId, + unsigned char* pBuffer, + const int x, + const int y, + const int width, + const int height, + const double dpiscale = 1.0, + const int viewId = -1) + { + return mpDoc->pClass->paintWindowForView(mpDoc, nWindowId, pBuffer, x, y, + width, height, dpiscale, viewId); + } + + /** + * Posts a command to the window (dialog, popup, etc.) with given id + * + * @param nWindowid + */ + void postWindow(unsigned nWindowId, int nAction, const char* pData = nullptr) + { + return mpDoc->pClass->postWindow(mpDoc, nWindowId, nAction, pData); + } + + /** + * Gets the tile mode: the pixel format used for the pBuffer of paintTile(). + * + * @return an element of the LibreOfficeKitTileMode enum. + */ + int getTileMode() + { + return mpDoc->pClass->getTileMode(mpDoc); + } + + /// Get the document sizes in TWIPs. + void getDocumentSize(long* pWidth, long* pHeight) + { + mpDoc->pClass->getDocumentSize(mpDoc, pWidth, pHeight); + } + + /** + * Initialize document for rendering. + * + * Sets the rendering and document parameters to default values that are + * needed to render the document correctly using tiled rendering. This + * method has to be called right after documentLoad() in case any of the + * tiled rendering methods are to be used later. + * + * Example argument string for text documents: + * + * { + * ".uno:HideWhitespace": + * { + * "type": "boolean", + * "value": "true" + * } + * } + * + * @param pArguments arguments of the rendering + */ + void initializeForRendering(const char* pArguments = NULL) + { + mpDoc->pClass->initializeForRendering(mpDoc, pArguments); + } + + /** + * Registers a callback. LOK will invoke this function when it wants to + * inform the client about events. + * + * @param pCallback the callback to invoke + * @param pData the user data, will be passed to the callback on invocation + */ + void registerCallback(LibreOfficeKitCallback pCallback, void* pData) + { + mpDoc->pClass->registerCallback(mpDoc, pCallback, pData); + } + + /** + * Posts a keyboard event to the focused frame. + * + * @param nType Event type, like press or release. + * @param nCharCode contains the Unicode character generated by this event or 0 + * @param nKeyCode contains the integer code representing the key of the event (non-zero for control keys) + */ + void postKeyEvent(int nType, int nCharCode, int nKeyCode) + { + mpDoc->pClass->postKeyEvent(mpDoc, nType, nCharCode, nKeyCode); + } + + /** + * Posts a keyboard event to the dialog + * + * @param nWindowId + * @param nType Event type, like press or release. + * @param nCharCode contains the Unicode character generated by this event or 0 + * @param nKeyCode contains the integer code representing the key of the event (non-zero for control keys) + */ + void postWindowKeyEvent(unsigned nWindowId, int nType, int nCharCode, int nKeyCode) + { + mpDoc->pClass->postWindowKeyEvent(mpDoc, nWindowId, nType, nCharCode, nKeyCode); + } + + /** + * Posts a mouse event to the document. + * + * @param nType Event type, like down, move or up. + * @param nX horizontal position in document coordinates + * @param nY vertical position in document coordinates + * @param nCount number of clicks: 1 for single click, 2 for double click + * @param nButtons: which mouse buttons: 1 for left, 2 for middle, 4 right + * @param nModifier: which keyboard modifier: (see include/vcl/vclenum.hxx for possible values) + */ + void postMouseEvent(int nType, int nX, int nY, int nCount, int nButtons, int nModifier) + { + mpDoc->pClass->postMouseEvent(mpDoc, nType, nX, nY, nCount, nButtons, nModifier); + } + + /** + * Posts a mouse event to the window with given id. + * + * @param nWindowId + * @param nType Event type, like down, move or up. + * @param nX horizontal position in document coordinates + * @param nY vertical position in document coordinates + * @param nCount number of clicks: 1 for single click, 2 for double click + * @param nButtons: which mouse buttons: 1 for left, 2 for middle, 4 right + * @param nModifier: which keyboard modifier: (see include/vcl/vclenum.hxx for possible values) + */ + void postWindowMouseEvent(unsigned nWindowId, int nType, int nX, int nY, int nCount, int nButtons, int nModifier) + { + mpDoc->pClass->postWindowMouseEvent(mpDoc, nWindowId, nType, nX, nY, nCount, nButtons, nModifier); + } + + /** + * Posts a dialog event for the window with given id + * + * @param nWindowId id of the window to notify + * @param pArguments arguments of the event. + */ + void sendDialogEvent(unsigned long long int nWindowId, const char* pArguments = NULL) + { + mpDoc->pClass->sendDialogEvent(mpDoc, nWindowId, pArguments); + } + + /** + * Posts a UNO command to the document. + * + * Example argument string: + * + * { + * "SearchItem.SearchString": + * { + * "type": "string", + * "value": "foobar" + * }, + * "SearchItem.Backward": + * { + * "type": "boolean", + * "value": "false" + * } + * } + * + * @param pCommand uno command to be posted to the document, like ".uno:Bold" + * @param pArguments arguments of the uno command. + */ + void postUnoCommand(const char* pCommand, const char* pArguments = NULL, bool bNotifyWhenFinished = false) + { + mpDoc->pClass->postUnoCommand(mpDoc, pCommand, pArguments, bNotifyWhenFinished); + } + + /** + * Sets the start or end of a text selection. + * + * @param nType @see LibreOfficeKitSetTextSelectionType + * @param nX horizontal position in document coordinates + * @param nY vertical position in document coordinates + */ + void setTextSelection(int nType, int nX, int nY) + { + mpDoc->pClass->setTextSelection(mpDoc, nType, nX, nY); + } + + /** + * Gets the currently selected text. + * + * @param pMimeType suggests the return format, for example text/plain;charset=utf-8. + * @param pUsedMimeType output parameter to inform about the determined format (suggested one or plain text). + */ + char* getTextSelection(const char* pMimeType, char** pUsedMimeType = NULL) + { + return mpDoc->pClass->getTextSelection(mpDoc, pMimeType, pUsedMimeType); + } + + /** + * Gets the type of the selected content. + * + * In most cases it is more efficient to use getSelectionTypeAndText(). + * + * @return an element of the LibreOfficeKitSelectionType enum. + */ + int getSelectionType() + { + return mpDoc->pClass->getSelectionType(mpDoc); + } + + /** + * Gets the type of the selected content and possibly its text. + * + * This function is a more efficient combination of getSelectionType() and getTextSelection(). + * It returns the same as getSelectionType(), and additionally if the return value is + * LOK_SELTYPE_TEXT then it also returns the same as getTextSelection(), otherwise + * pText and pUsedMimeType are unchanged. + * + * @param pMimeType suggests the return format, for example text/plain;charset=utf-8. + * @param pText the currently selected text + * @param pUsedMimeType output parameter to inform about the determined format (suggested one or plain text). + * @return an element of the LibreOfficeKitSelectionType enum. + * @since LibreOffice 7.4 + */ + int getSelectionTypeAndText(const char* pMimeType, char** pText, char** pUsedMimeType = NULL) + { + if (LIBREOFFICEKIT_DOCUMENT_HAS(mpDoc, getSelectionTypeAndText)) + return mpDoc->pClass->getSelectionTypeAndText(mpDoc, pMimeType, pText, pUsedMimeType); + int type = mpDoc->pClass->getSelectionType(mpDoc); + if(type == LOK_SELTYPE_TEXT && pText) + *pText = mpDoc->pClass->getTextSelection(mpDoc, pMimeType, pUsedMimeType); + return type; + } + + /** + * Gets the content on the clipboard for the current view as a series of binary streams. + * + * NB. returns a complete set of possible selection types if nullptr is passed for pMimeTypes. + * + * @param pMimeTypes passes in a nullptr terminated list of mime types to fetch + * @param pOutCount returns the size of the other @pOut arrays + * @param pOutMimeTypes returns an array of mime types + * @param pOutSizes returns the size of each pOutStream + * @param pOutStreams the content of each mime-type, of length in @pOutSizes + * + * @returns: true on success, false on error. + */ + bool getClipboard(const char **pMimeTypes, + size_t *pOutCount, + char ***pOutMimeTypes, + size_t **pOutSizes, + char ***pOutStreams) + { + return mpDoc->pClass->getClipboard(mpDoc, pMimeTypes, pOutCount, pOutMimeTypes, pOutSizes, pOutStreams); + } + + /** + * Populates the clipboard for this view with multiple types of content. + * + * @param nInCount the number of types to paste + * @param pInMimeTypes array of mime type strings + * @param pInSizes array of sizes of the data to paste + * @param pInStreams array containing the data of the various types + * + * @return if the supplied data was populated successfully. + */ + bool setClipboard(const size_t nInCount, + const char **pInMimeTypes, + const size_t *pInSizes, + const char **pInStreams) + { + return mpDoc->pClass->setClipboard(mpDoc, nInCount, pInMimeTypes, pInSizes, pInStreams); + } + + /** + * Pastes content at the current cursor position. + * + * @param pMimeType format of pData, for example text/plain;charset=utf-8. + * @param pData the actual data to be pasted. + * @return if the supplied data was pasted successfully. + */ + bool paste(const char* pMimeType, const char* pData, size_t nSize) + { + return mpDoc->pClass->paste(mpDoc, pMimeType, pData, nSize); + } + + /** + * Adjusts the graphic selection. + * + * @param nType @see LibreOfficeKitSetGraphicSelectionType + * @param nX horizontal position in document coordinates + * @param nY vertical position in document coordinates + */ + void setGraphicSelection(int nType, int nX, int nY) + { + mpDoc->pClass->setGraphicSelection(mpDoc, nType, nX, nY); + } + + /** + * Gets rid of any text or graphic selection. + */ + void resetSelection() + { + mpDoc->pClass->resetSelection(mpDoc); + } + + /** + * Returns a json mapping of the possible values for the given command + * e.g. {commandName: ".uno:StyleApply", commandValues: {"familyName1" : ["list of style names in the family1"], etc.}} + * @param pCommand a UNO command for which the possible values are requested + * @return {commandName: unoCmd, commandValues: {possible_values}} + */ + char* getCommandValues(const char* pCommand) + { + return mpDoc->pClass->getCommandValues(mpDoc, pCommand); + } + + /** + * Save the client's view so that we can compute the right zoom level + * for the mouse events. This only affects CALC. + * @param nTilePixelWidth - tile width in pixels + * @param nTilePixelHeight - tile height in pixels + * @param nTileTwipWidth - tile width in twips + * @param nTileTwipHeight - tile height in twips + */ + void setClientZoom( + int nTilePixelWidth, + int nTilePixelHeight, + int nTileTwipWidth, + int nTileTwipHeight) + { + mpDoc->pClass->setClientZoom(mpDoc, nTilePixelWidth, nTilePixelHeight, nTileTwipWidth, nTileTwipHeight); + } + + /** + * Inform core about the currently visible area of the document on the + * client, so that it can perform e.g. page down (which depends on the + * visible height) in a sane way. + * + * @param nX - top left corner horizontal position + * @param nY - top left corner vertical position + * @param nWidth - area width + * @param nHeight - area height + */ + void setClientVisibleArea(int nX, int nY, int nWidth, int nHeight) + { + mpDoc->pClass->setClientVisibleArea(mpDoc, nX, nY, nWidth, nHeight); + } + + /** + * Show/Hide a single row/column header outline for Calc documents. + * + * @param bColumn - if we are dealing with a column or row group + * @param nLevel - the level to which the group belongs + * @param nIndex - the group entry index + * @param bHidden - the new group state (collapsed/expanded) + */ + void setOutlineState(bool bColumn, int nLevel, int nIndex, bool bHidden) + { + mpDoc->pClass->setOutlineState(mpDoc, bColumn, nLevel, nIndex, bHidden); + } + + /** + * Create a new view for an existing document with + * options similar to documentLoadWithOptions. + * By default a loaded document has 1 view. + * @return the ID of the new view. + */ + int createView(const char* pOptions = nullptr) + { + if (LIBREOFFICEKIT_DOCUMENT_HAS(mpDoc, createViewWithOptions)) + return mpDoc->pClass->createViewWithOptions(mpDoc, pOptions); + else + return mpDoc->pClass->createView(mpDoc); + } + + /** + * Destroy a view of an existing document. + * @param nId a view ID, returned by createView(). + */ + void destroyView(int nId) + { + mpDoc->pClass->destroyView(mpDoc, nId); + } + + /** + * Set an existing view of an existing document as current. + * @param nId a view ID, returned by createView(). + */ + void setView(int nId) + { + mpDoc->pClass->setView(mpDoc, nId); + } + + /** + * Get the current view. + * @return a view ID, previously returned by createView(). + */ + int getView() + { + return mpDoc->pClass->getView(mpDoc); + } + + /** + * Get number of views of this document. + */ + int getViewsCount() + { + return mpDoc->pClass->getViewsCount(mpDoc); + } + + /** + * Paints a font name or character if provided to be displayed in the font list + * @param pFontName the font to be painted + */ + unsigned char* renderFont(const char *pFontName, + const char *pChar, + int *pFontWidth, + int *pFontHeight, + int pOrientation=0) + { + if (LIBREOFFICEKIT_DOCUMENT_HAS(mpDoc, renderFontOrientation)) + return mpDoc->pClass->renderFontOrientation(mpDoc, pFontName, pChar, pFontWidth, pFontHeight, pOrientation); + else + return mpDoc->pClass->renderFont(mpDoc, pFontName, pChar, pFontWidth, pFontHeight); + } + + /** + * Renders a subset of the document's part to a pre-allocated buffer. + * + * @param nPart the part number of the document of which the tile is painted. + * @see paintTile. + */ + void paintPartTile(unsigned char* pBuffer, + const int nPart, + const int nCanvasWidth, + const int nCanvasHeight, + const int nTilePosX, + const int nTilePosY, + const int nTileWidth, + const int nTileHeight) + { + return mpDoc->pClass->paintPartTile(mpDoc, pBuffer, nPart, + nCanvasWidth, nCanvasHeight, + nTilePosX, nTilePosY, + nTileWidth, nTileHeight); + } + + /** + * Returns the viewID for each existing view. Since viewIDs are not reused, + * viewIDs are not the same as the index of the view in the view array over + * time. Use getViewsCount() to know the minimal nSize that's large enough. + * + * @param pArray the array to write the viewIDs into + * @param nSize the size of pArray + * @returns true if pArray was large enough and result is written, false + * otherwise. + */ + bool getViewIds(int* pArray, + size_t nSize) + { + return mpDoc->pClass->getViewIds(mpDoc, pArray, nSize); + } + + /** + * Set the language tag of the window with the specified nId. + * + * @param nId a view ID, returned by createView(). + * @param language Bcp47 languageTag, like en-US or so. + */ + void setViewLanguage(int nId, const char* language) + { + mpDoc->pClass->setViewLanguage(mpDoc, nId, language); + } + + /** + * Post the text input from external input window, like IME, to given windowId + * + * @param nWindowId Specify the window id to post the input event to. If + * nWindow is 0, the event is posted into the document + * @param nType see LibreOfficeKitExtTextInputType + * @param pText Text for LOK_EXT_TEXTINPUT + */ + void postWindowExtTextInputEvent(unsigned nWindowId, int nType, const char* pText) + { + mpDoc->pClass->postWindowExtTextInputEvent(mpDoc, nWindowId, nType, pText); + } + +#ifdef IOS + /** + * Renders a subset of the document to a Core Graphics context. + * + * Note that the buffer size and the tile size implicitly supports + * rendering at different zoom levels, as the number of rendered pixels and + * the rendered rectangle of the document are independent. + * + * @param rCGContext the CGContextRef, cast to a void*. + * @param nCanvasHeight number of pixels in a column of pBuffer. + * @param nTilePosX logical X position of the top left corner of the rendered rectangle, in TWIPs. + * @param nTilePosY logical Y position of the top left corner of the rendered rectangle, in TWIPs. + * @param nTileWidth logical width of the rendered rectangle, in TWIPs. + * @param nTileHeight logical height of the rendered rectangle, in TWIPs. + */ + void paintTileToCGContext(void* rCGContext, + const int nCanvasWidth, + const int nCanvasHeight, + const int nTilePosX, + const int nTilePosY, + const int nTileWidth, + const int nTileHeight) + { + return mpDoc->pClass->paintTileToCGContext(mpDoc, rCGContext, nCanvasWidth, nCanvasHeight, + nTilePosX, nTilePosY, nTileWidth, nTileHeight); + } +#endif // IOS + + /** + * Insert certificate (in binary form) to the certificate store. + */ + bool insertCertificate(const unsigned char* pCertificateBinary, + const int pCertificateBinarySize, + const unsigned char* pPrivateKeyBinary, + const int nPrivateKeyBinarySize) + { + return mpDoc->pClass->insertCertificate(mpDoc, + pCertificateBinary, pCertificateBinarySize, + pPrivateKeyBinary, nPrivateKeyBinarySize); + } + + /** + * Add the certificate (in binary form) to the certificate store. + * + */ + bool addCertificate(const unsigned char* pCertificateBinary, + const int pCertificateBinarySize) + { + return mpDoc->pClass->addCertificate(mpDoc, + pCertificateBinary, pCertificateBinarySize); + } + + /** + * Verify signature of the document. + * + * Check possible values in include/sfx2/signaturestate.hxx + */ + int getSignatureState() + { + return mpDoc->pClass->getSignatureState(mpDoc); + } + + /** + * Gets an image of the selected shapes. + * @param pOutput contains the result; use free to deallocate. + * @return the size of *pOutput in bytes. + */ + size_t renderShapeSelection(char** pOutput) + { + return mpDoc->pClass->renderShapeSelection(mpDoc, pOutput); + } + + /** + * Posts a gesture event to the window with given id. + * + * @param nWindowId + * @param pType Event type, like panStart, panEnd, panUpdate. + * @param nX horizontal position in document coordinates + * @param nY vertical position in document coordinates + * @param nOffset difference value from when the gesture started to current value + */ + void postWindowGestureEvent(unsigned nWindowId, + const char* pType, + int nX, int nY, int nOffset) + { + return mpDoc->pClass->postWindowGestureEvent(mpDoc, nWindowId, pType, nX, nY, nOffset); + } + + /// Set a part's selection mode. + /// nSelect is 0 to deselect, 1 to select, and 2 to toggle. + void selectPart(int nPart, int nSelect) + { + mpDoc->pClass->selectPart(mpDoc, nPart, nSelect); + } + + /// Moves the selected pages/slides to a new position. + /// nPosition is the new position where the selection + /// should go. bDuplicate when true will copy instead of move. + void moveSelectedParts(int nPosition, bool bDuplicate) + { + mpDoc->pClass->moveSelectedParts(mpDoc, nPosition, bDuplicate); + } + + /** + * Resize a window (dialog, popup, etc.) with give id. + * + * @param nWindowId + * @param width The width of the window. + * @param height The height of the window. + */ + void resizeWindow(unsigned nWindowId, + const int width, + const int height) + { + return mpDoc->pClass->resizeWindow(mpDoc, nWindowId, width, height); + } + + /** + * For deleting many characters all at once + * + * @param nWindowId Specify the window id to post the input event to. If + * nWindow is 0, the event is posted into the document + * @param nBefore The characters to be deleted before the cursor position + * @param nAfter The characters to be deleted after the cursor position + */ + void removeTextContext(unsigned nWindowId, int nBefore, int nAfter) + { + mpDoc->pClass->removeTextContext(mpDoc, nWindowId, nBefore, nAfter); + } + + /** + * Select the Calc function to be pasted into the formula input box + * + * @param nIndex is the index of the selected function + */ + void completeFunction(const char* pFunctionName) + { + mpDoc->pClass->completeFunction(mpDoc, pFunctionName); + } + + /** + * Sets the start or end of a text selection for a dialog. + * + * @param nWindowId + * @param bSwap swap anchor and cursor position of current selection + * @param nX horizontal position in document coordinates + * @param nY vertical position in document coordinates + */ + void setWindowTextSelection(unsigned nWindowId, bool bSwap, int nX, int nY) + { + mpDoc->pClass->setWindowTextSelection(mpDoc, nWindowId, bSwap, nX, nY); + } + + /** + * Posts an event for the form field at the cursor position. + * + * @param pArguments arguments of the event. + */ + void sendFormFieldEvent(const char* pArguments) + { + mpDoc->pClass->sendFormFieldEvent(mpDoc, pArguments); + } + + void setBlockedCommandList(int nViewId, const char* blockedCommandList) + { + mpDoc->pClass->setBlockedCommandList(mpDoc, nViewId, blockedCommandList); + } + /** + * Render input search result to a bitmap buffer. + * + * @param pSearchResult payload containing the search result data + * @param pBitmapBuffer contains the bitmap; use free to deallocate. + * @param nWidth output bitmap width + * @param nHeight output bitmap height + * @param nByteSize output bitmap byte size + * @return true if successful + */ + bool renderSearchResult(const char* pSearchResult, unsigned char** pBitmapBuffer, + int* pWidth, int* pHeight, size_t* pByteSize) + { + return mpDoc->pClass->renderSearchResult(mpDoc, pSearchResult, pBitmapBuffer, pWidth, pHeight, pByteSize); + } + + /** + * Posts an event for the content control at the cursor position. + * + * @param pArguments arguments of the event. + * + * Examples: + * To select the 3rd list item of the drop-down: + * { + * "type": "drop-down", + * "selected": "2" + * } + * + * To change a picture place-holder: + * { + * "type": "picture", + * "changed": "file:///path/to/test.png" + * } + * + * To select a date of the current date content control: + * { + * "type": "date", + * "selected": "2022-05-29T00:00:00Z" + * } + */ + void sendContentControlEvent(const char* pArguments) + { + mpDoc->pClass->sendContentControlEvent(mpDoc, pArguments); + } + +#endif // defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY +}; + +/// The lok::Office class represents one started LibreOfficeKit instance. +class Office +{ +private: + LibreOfficeKit* mpThis; + +public: + /// A lok::Office is typically created by the lok_cpp_init() function. + Office(LibreOfficeKit* pThis) : + mpThis(pThis) + {} + + ~Office() + { + mpThis->pClass->destroy(mpThis); + } + + /** + * Loads a document from a URL. + * + * @param pUrl the URL of the document to load + * @param pFilterOptions options for the import filter, e.g. SkipImages. + * Another useful FilterOption is "Language=...". It is consumed + * by the documentLoad() itself, and when provided, LibreOfficeKit + * switches the language accordingly first. + * @since pFilterOptions argument added in LibreOffice 5.0 + */ + Document* documentLoad(const char* pUrl, const char* pFilterOptions = NULL) + { + LibreOfficeKitDocument* pDoc = NULL; + + if (LIBREOFFICEKIT_HAS(mpThis, documentLoadWithOptions)) + pDoc = mpThis->pClass->documentLoadWithOptions(mpThis, pUrl, pFilterOptions); + else + pDoc = mpThis->pClass->documentLoad(mpThis, pUrl); + + if (pDoc == NULL) + return NULL; + + return new Document(pDoc); + } + + /// Returns the last error as a string, the returned pointer has to be freed by the caller. + char* getError() + { + return mpThis->pClass->getError(mpThis); + } + + /** + * Frees the memory pointed to by pFree. + * + * @since LibreOffice 5.2 + */ + void freeError(char* pFree) + { + mpThis->pClass->freeError(pFree); + } + + /** + * Registers a callback. LOK will invoke this function when it wants to + * inform the client about events. + * + * @since LibreOffice 6.0 + * @param pCallback the callback to invoke + * @param pData the user data, will be passed to the callback on invocation + */ + void registerCallback(LibreOfficeKitCallback pCallback, void* pData) + { + mpThis->pClass->registerCallback(mpThis, pCallback, pData); + } + + /** + * Returns details of filter types. + * + * Example returned string: + * + * { + * "writer8": { + * "MediaType": "application/vnd.oasis.opendocument.text" + * }, + * "calc8": { + * "MediaType": "application/vnd.oasis.opendocument.spreadsheet" + * } + * } + * + * @since LibreOffice 6.0 + */ + char* getFilterTypes() + { + return mpThis->pClass->getFilterTypes(mpThis); + } + + /** + * Set bitmask of optional features supported by the client. + * + * @since LibreOffice 6.0 + * @see LibreOfficeKitOptionalFeatures + */ + void setOptionalFeatures(unsigned long long features) + { + return mpThis->pClass->setOptionalFeatures(mpThis, features); + } + + /** + * Set password required for loading or editing a document. + * + * Loading the document is blocked until the password is provided. + * + * @param pURL the URL of the document, as sent to the callback + * @param pPassword the password, nullptr indicates no password + * + * In response to LOK_CALLBACK_DOCUMENT_PASSWORD, a valid password + * will continue loading the document, an invalid password will + * result in another LOK_CALLBACK_DOCUMENT_PASSWORD request, + * and a NULL password will abort loading the document. + * + * In response to LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY, a valid + * password will continue loading the document, an invalid password will + * result in another LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY request, + * and a NULL password will continue loading the document in read-only + * mode. + * + * @since LibreOffice 6.0 + */ + void setDocumentPassword(char const* pURL, char const* pPassword) + { + mpThis->pClass->setDocumentPassword(mpThis, pURL, pPassword); + } + + /** + * Get version information of the LOKit process + * + * @since LibreOffice 6.0 + * @returns JSON string containing version information in format: + * {ProductName: <>, ProductVersion: <>, ProductExtension: <>, BuildId: <>} + * + * Eg: {"ProductName": "LibreOffice", + * "ProductVersion": "5.3", + * "ProductExtension": ".0.0.alpha0", + * "BuildId": ""} + */ + char* getVersionInfo() + { + return mpThis->pClass->getVersionInfo(mpThis); + } + + /** + * Run a macro. + * + * Same syntax as on command line is permissible (ie. the macro:// URI forms) + * + * @since LibreOffice 6.0 + * @param pURL macro url to run + */ + + bool runMacro( const char* pURL) + { + return mpThis->pClass->runMacro( mpThis, pURL ); + } + + /** + * Exports the document and signes its content. + */ + bool signDocument(const char* pURL, + const unsigned char* pCertificateBinary, const int nCertificateBinarySize, + const unsigned char* pPrivateKeyBinary, const int nPrivateKeyBinarySize) + { + return mpThis->pClass->signDocument(mpThis, pURL, + pCertificateBinary, nCertificateBinarySize, + pPrivateKeyBinary, nPrivateKeyBinarySize); + } + + /** + * Runs the main-loop in the current thread. To trigger this + * mode you need to putenv a SAL_LOK_OPTIONS containing 'unipoll'. + * The @pPollCallback is called to poll for events from the Kit client + * and the @pWakeCallback can be called by internal LibreOfficeKit threads + * to wake the caller of 'runLoop' ie. the main thread. + * + * it is expected that runLoop does not return until Kit exit. + * + * @pData is a context/closure passed to both methods. + */ + void runLoop(LibreOfficeKitPollCallback pPollCallback, + LibreOfficeKitWakeCallback pWakeCallback, + void* pData) + { + mpThis->pClass->runLoop(mpThis, pPollCallback, pWakeCallback, pData); + } + + /** + * Posts a dialog event for the window with given id + * + * @param nWindowId id of the window to notify + * @param pArguments arguments of the event. + */ + void sendDialogEvent(unsigned long long int nWindowId, const char* pArguments = NULL) + { + mpThis->pClass->sendDialogEvent(mpThis, nWindowId, pArguments); + } + + /** + * Generic function to toggle and tweak various things in the core LO + * + * The currently available option names and their allowed values are: + * + * "profilezonerecording": "start" or "stop" + * Start or stop recording profile zone trace data in the process. + * + * "sallogoverride": "" + * Override the SAL_LOG environment variable + * + * For the syntax of the string see the documentation for "Basic + * logging functionality" in LibreOffice internal API + * documentation (include/sal/log.hxx). If the logging selector + * has been set by this function to a non-empty value, that is used + * instead of the environment variable SAL_LOG. + * + * The parameter is not copied so you should pass a value that + * points to memory that will stay valid until you call setOption + * with this option name the next time. + * + * If you pass nullptr or an empty string as value, the + * environment variable SAL_LOG is again used as by default. You + * can switch back and forth as you like. + * + * "addfont": "" + * + * Adds the font at the URL given. + * + * @param pOption the option name + * @param pValue its value + */ + void setOption(const char* pOption, const char* pValue) + { + mpThis->pClass->setOption(mpThis, pOption, pValue); + } +}; + +/// Factory method to create a lok::Office instance. +inline Office* lok_cpp_init(const char* pInstallPath, const char* pUserProfileUrl = NULL) +{ + LibreOfficeKit* pThis = lok_init_2(pInstallPath, pUserProfileUrl); + if (pThis == NULL || pThis->pClass->nSize == 0) + return NULL; + return new ::lok::Office(pThis); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/LibreOfficeKit/LibreOfficeKitEnums.h b/include/LibreOfficeKit/LibreOfficeKitEnums.h new file mode 100644 index 000000000..f1b232851 --- /dev/null +++ b/include/LibreOfficeKit/LibreOfficeKitEnums.h @@ -0,0 +1,1066 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITENUMS_H +#define INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITENUMS_H + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY +typedef enum +{ + LOK_DOCTYPE_TEXT, + LOK_DOCTYPE_SPREADSHEET, + LOK_DOCTYPE_PRESENTATION, + LOK_DOCTYPE_DRAWING, + LOK_DOCTYPE_OTHER +} +LibreOfficeKitDocumentType; + +typedef enum +{ + LOK_PARTMODE_SLIDES, + LOK_PARTMODE_NOTES +} +LibreOfficeKitPartMode; + +typedef enum +{ + LOK_TILEMODE_RGBA, + LOK_TILEMODE_BGRA +} +LibreOfficeKitTileMode; + +typedef enum +{ + LOK_WINDOW_CLOSE, + LOK_WINDOW_PASTE +} +LibreOfficeKitWindowAction; + +typedef enum +{ + LOK_SELTYPE_NONE, + LOK_SELTYPE_TEXT, + LOK_SELTYPE_LARGE_TEXT, // unused (same as LOK_SELTYPE_COMPLEX) + LOK_SELTYPE_COMPLEX +} +LibreOfficeKitSelectionType; + +/** Optional features of LibreOfficeKit, in particular callbacks that block + * LibreOfficeKit until the corresponding reply is received, which would + * deadlock if the client does not support the feature. + * + * @see lok::Office::setOptionalFeatures(). + */ +typedef enum +{ + /** + * Handle LOK_CALLBACK_DOCUMENT_PASSWORD by prompting the user + * for a password. + * + * @see lok::Office::setDocumentPassword(). + */ + LOK_FEATURE_DOCUMENT_PASSWORD = (1ULL << 0), + + /** + * Handle LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY by prompting the user + * for a password. + * + * @see lok::Office::setDocumentPassword(). + */ + LOK_FEATURE_DOCUMENT_PASSWORD_TO_MODIFY = (1ULL << 1), + + /** + * Request to have the part number as an 5th value in the + * LOK_CALLBACK_INVALIDATE_TILES payload. + */ + LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK = (1ULL << 2), + + /** + * Turn off tile rendering for annotations + */ + LOK_FEATURE_NO_TILED_ANNOTATIONS = (1ULL << 3), + + /** + * Enable range based header data + */ + LOK_FEATURE_RANGE_HEADERS = (1ULL << 4), + + /** + * Request to have the active view's Id as the 1st value in the + * LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR payload. + */ + LOK_FEATURE_VIEWID_IN_VISCURSOR_INVALIDATION_CALLBACK = (1ULL << 5) +} +LibreOfficeKitOptionalFeatures; + +// This enumerates the types of callbacks emitted to a LibreOfficeKit +// object's callback function or to a LibreOfficeKitDocument object's +// callback function. No callback type will be emitted to both. It is a +// bit unfortunate that the same enum contains both kinds of +// callbacks. + +// TODO: We should really add some indication at the documentation for +// each enum value telling which type of callback it is. + +typedef enum +{ + /** + * Any tiles which are over the rectangle described in the payload are no + * longer valid. + * + * Rectangle format: "x, y, width, height", where all numbers are document + * coordinates, in twips. When all tiles are supposed to be dropped, the + * format is the "EMPTY" string. + * + * @see LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK. + */ + LOK_CALLBACK_INVALIDATE_TILES = 0, + /** + * The size and/or the position of the visible cursor changed. + * + * Old format is the same as LOK_CALLBACK_INVALIDATE_TILES. + * New format is a JSON with 3 elements the 'viewId' element represented by + * an integer value, a 'rectangle' element in the format "x, y, width, height", + * and a 'misspelledWord' element represented by an integer value: '1' when + * a misspelled word is at the cursor position, '0' when the word is + * not misspelled. + */ + LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR = 1, + /** + * The list of rectangles representing the current text selection changed. + * + * List format is "rectangle1[; rectangle2[; ...]]" (without quotes and + * brackets), where rectangleN has the same format as + * LOK_CALLBACK_INVALIDATE_TILES. When there is no selection, an empty + * string is provided. + */ + LOK_CALLBACK_TEXT_SELECTION = 2, + /** + * The position and size of the cursor rectangle at the text + * selection start. It is used to draw the selection handles. + * + * This callback must be called prior to LOK_CALLBACK_TEXT_SELECTION every + * time the selection is updated. + * + * Rectangle format is the same as LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_TEXT_SELECTION_START = 3, + /** + * The position and size of the cursor rectangle at the text + * selection end. It is used to draw the selection handles. + * + * This callback must be called prior to LOK_CALLBACK_TEXT_SELECTION every + * time the selection is updated. + * + * Rectangle format is the same as LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_TEXT_SELECTION_END = 4, + /** + * The blinking text cursor is now visible or not. + * + * Clients should assume that this is true initially and are expected to + * hide the blinking cursor at the rectangle described by + * LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR once it becomes false. Payload is + * either the "true" or the "false" string. + */ + LOK_CALLBACK_CURSOR_VISIBLE = 5, + /** + * The size and/or the position of the graphic selection changed, + * the rotation angle of the embedded graphic object, and a property list + * which can be used for informing the client about several properties. + * + * Format is "x, y, width, height, angle, { list of properties }", + * where angle is in 100th of degree, and the property list is optional. + * + * The "{ list of properties }" part is in JSON format. + * Follow some examples of the property list part: + * + * 1) when the selected object is an image inserted in Writer: + * + * { "isWriterGraphic": true } + * + * 2) when the selected object is a chart legend: + * + * { "isDraggable": true, "isResizable": true, "isRotatable": false } + * + * 3) when the selected object is a pie segment in a chart: + * + * { + * "isDraggable": true, + * "isResizable": false, + * "isRotatable": false, + * "dragInfo": { + * "dragMethod": "PieSegmentDragging", + * "initialOffset": 50, + * "dragDirection": [x, y], + * "svg": " + * "message": freeform description + * } + */ + LOK_CALLBACK_ERROR = 22, + + /** + * Context menu structure + * + * Returns the structure of context menu. Contains all the separators & + * submenus, example of the returned structure: + * + * { + * "menu": [ + * { "text": "label text1", "type": "command", "command": ".uno:Something1", "enabled": "true" }, + * { "text": "label text2", "type": "command", "command": ".uno:Something2", "enabled": "false" }, + * { "type": "separator" }, + * { "text": "label text2", "type": "menu", "menu": [ { ... }, { ... }, ... ] }, + * ... + * ] + * } + * + * The 'command' can additionally have a checkable status, like: + * + * {"text": "label text3", "type": "command", "command": ".uno:Something3", "checktype": "checkmark|radio|auto", "checked": "true|false"} + */ + LOK_CALLBACK_CONTEXT_MENU = 23, + + /** + * The size and/or the position of the view cursor changed. A view cursor + * is a cursor of another view, the current view can't change it. + * + * The payload format: + * + * { + * "viewId": "..." + * "rectangle": "..." + * } + * + * - viewId is a value returned earlier by lok::Document::createView() + * - rectangle uses the format of LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR + */ + LOK_CALLBACK_INVALIDATE_VIEW_CURSOR = 24, + + /** + * The text selection in one of the other views has changed. + * + * The payload format: + * + * { + * "viewId": "..." + * "selection": "..." + * } + * + * - viewId is a value returned earlier by lok::Document::createView() + * - selection uses the format of LOK_CALLBACK_TEXT_SELECTION. + */ + LOK_CALLBACK_TEXT_VIEW_SELECTION = 25, + + /** + * The cell cursor in one of the other views has changed. + * + * The payload format: + * + * { + * "viewId": "..." + * "rectangle": "..." + * } + * + * - viewId is a value returned earlier by lok::Document::createView() + * - rectangle uses the format of LOK_CALLBACK_CELL_CURSOR. + */ + LOK_CALLBACK_CELL_VIEW_CURSOR = 26, + + /** + * The size and/or the position of a graphic selection in one of the other + * views has changed. + * + * The payload format: + * + * { + * "viewId": "..." + * "selection": "..." + * } + * + * - viewId is a value returned earlier by lok::Document::createView() + * - selection uses the format of LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_GRAPHIC_VIEW_SELECTION = 27, + + /** + * The blinking text cursor in one of the other views is now visible or + * not. + * + * The payload format: + * + * { + * "viewId": "..." + * "visible": "..." + * } + * + * - viewId is a value returned earlier by lok::Document::createView() + * - visible uses the format of LOK_CALLBACK_CURSOR_VISIBLE. + */ + LOK_CALLBACK_VIEW_CURSOR_VISIBLE = 28, + + /** + * The size and/or the position of a lock rectangle in one of the other + * views has changed. + * + * The payload format: + * + * { + * "viewId": "..." + * "rectangle": "..." + * } + * + * - viewId is a value returned earlier by lok::Document::createView() + * - rectangle uses the format of LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_VIEW_LOCK = 29, + + /** + * The size of the change tracking table has changed. + * + * The payload example: + * { + * "redline": { + * "action": "Remove", + * "index": "1", + * "author": "Unknown Author", + * "type": "Delete", + * "comment": "", + * "description": "Delete 'abc'", + * "dateTime": "2016-08-18T12:14:00" + * } + * } + * + * The format is the same as an entry of + * lok::Document::getCommandValues('.uno:AcceptTrackedChanges'), extra + * fields: + * + * - 'action' is either 'Add' or 'Remove', depending on if this is an + * insertion into the table or a removal. + */ + LOK_CALLBACK_REDLINE_TABLE_SIZE_CHANGED = 30, + + /** + * An entry in the change tracking table has been modified. + * + * The payload example: + * { + * "redline": { + * "action": "Modify", + * "index": "1", + * "author": "Unknown Author", + * "type": "Insert", + * "comment": "", + * "description": "Insert 'abcd'", + * "dateTime": "2016-08-18T13:13:00" + * } + * } + * + * The format is the same as an entry of + * lok::Document::getCommandValues('.uno:AcceptTrackedChanges'), extra + * fields: + * + * - 'action' is 'Modify'. + */ + LOK_CALLBACK_REDLINE_TABLE_ENTRY_MODIFIED = 31, + + /** + * There is some change in comments in the document + * + * The payload example: + * { + * "comment": { + * "action": "Add", + * "id": "11", + * "parent": "4", + * "author": "Unknown Author", + * "text": "", + * "dateTime": "2016-08-18T13:13:00", + * "anchorPos": "4529, 3906", + * "textRange": "1418, 3906, 3111, 919" + * } + * } + * + * The format is the same as an entry of + * lok::Document::getCommandValues('.uno:ViewAnnotations'), extra + * fields: + * + * - 'action' can be 'Add', 'Remove' or 'Modify' depending on whether + * comment has been added, removed or modified. + */ + LOK_CALLBACK_COMMENT = 32, + + /** + * The column/row header is no more valid because of a column/row insertion + * or a similar event. Clients must query a new column/row header set. + * + * The payload says if we are invalidating a row or column header. So, + * payload values can be: "row", "column", "all". + */ + LOK_CALLBACK_INVALIDATE_HEADER = 33, + /** + * The text content of the address field in Calc. Eg: "A7" + */ + LOK_CALLBACK_CELL_ADDRESS = 34, + /** + * The key ruler related properties on change are reported by this. + * + * The payload format is: + * + * { + * "margin1": "...", + * "margin2": "...", + * "leftOffset": "...", + * "pageOffset": "...", + * "pageWidth": "...", + * "unit": "..." + * } + * + * Here all aproperties are same as described in svxruler. + */ + LOK_CALLBACK_RULER_UPDATE = 35, + /** + * Window related callbacks are emitted under this category. It includes + * external windows like dialogs, autopopups for now. + * + * The payload format is: + * + * { + * "id": "unique integer id of the dialog", + * "action": "", + * "type": "" + * "rectangle": "x, y, width, height" + * } + * + * "type" tells the type of the window the action is associated with + * - "dialog" - window is a dialog + * - "child" - window is a floating window (combo boxes, etc.) + * - "deck" - window is a docked/floating deck (i.e. the sidebar) + * - "tooltip" - window is a tooltip popup + * + * "action" can take following values: + * - "created" - window is created in the backend, client can render it now + * - "title_changed" - window's title is changed + * - "size_changed" - window's size is changed + * - "invalidate" - the area as described by "rectangle" is invalidated + * Clients must request the new area + * - "cursor_invalidate" - cursor is invalidated. New position is in "rectangle" + * - "cursor_visible" - cursor visible status is changed. Status is available + * in "visible" field + * - "close" - window is closed + * - "show" - show the window + * - "hide" - hide the window + */ + LOK_CALLBACK_WINDOW = 36, + + /** + * When for the current cell is defined a validity list we need to show + * a drop down button in the form of a marker. + * + * The payload format is: "x, y, visible" where x, y are the current + * cell cursor coordinates and visible is set to 0 or 1. + */ + LOK_CALLBACK_VALIDITY_LIST_BUTTON = 37, + + /** + * Notification that the clipboard contents have changed. + * Typically fired in response to copying to clipboard. + * + * Payload is optional. When payload is empty, Online gets string from selected text. + * Payload format is JSON. + * Example: { "mimeType": "text/plain", "content": "some content" } + */ + LOK_CALLBACK_CLIPBOARD_CHANGED = 38, + + /** + * When the (editing) context changes - like the user switches from + * editing textbox in Impress to editing a shape there. + * + * Payload is the application ID and context, delimited by space. + * Eg. com.sun.star.presentation.PresentationDocument TextObject + */ + LOK_CALLBACK_CONTEXT_CHANGED = 39, + + /** + * On-load notification of the document signature status. + */ + LOK_CALLBACK_SIGNATURE_STATUS = 40, + + /** + * Profiling tracing information single string of multiple lines + * containing and zone start/stop information + */ + LOK_CALLBACK_PROFILE_FRAME = 41, + + /** + * The position and size of the cell selection area. It is used to + * draw the selection handles for cells in Calc documents. + * + * Rectangle format is the same as LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_CELL_SELECTION_AREA = 42, + + /** + * The position and size of the cell auto fill area. It is used to + * trigger auto fill functionality if that area is hit. + * + * Rectangle format is the same as LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_CELL_AUTO_FILL_AREA = 43, + + /** + * When the cursor is in a table or a table is selected in the + * document, this sends the table's column and row border positions + * to the client. If the payload is empty (empty JSON object), then + * no table is currently selected or the cursor is not inside a table + * cell. + */ + LOK_CALLBACK_TABLE_SELECTED = 44, + + /* + * Show reference marks from payload. + * + * Example payload: + * { + * "marks": [ + * { "rectangle": "3825, 3315, 1245, 2010", "color": "0000ff", "part": "0" }, + * { "rectangle": "8925, 4335, 2520, 735", "color": "ff0000", "part": "0" }, + * ... + * ] + * } + */ + LOK_CALLBACK_REFERENCE_MARKS = 45, + + /** + * Callback related to native dialogs generated in JavaScript from + * the description. + */ + LOK_CALLBACK_JSDIALOG = 46, + + /** + * Send the list of functions whose name starts with the characters entered + * by the user in the formula input bar. + */ + LOK_CALLBACK_CALC_FUNCTION_LIST = 47, + + /** + * Sends the tab stop list for the current of the current cursor position. + */ + LOK_CALLBACK_TAB_STOP_LIST = 48, + + /** + * Sends all information for displaying form field button for a text based field. + * + * It contains the position where the frame with the button should be displayed and + * also contains all information that the popup window needs. + * + * The payload example: + * { + * "action": "show", + * "type": "drop-down", + * "textArea": "1418, 3906, 3111, 919", + * "params": { + * "items": ["January", "February", "July"], + * "selected": "2", + * "placeholder": "No items specified" + * } + * } + * + * or + * { + * "action": "hide", + * "type": "drop-down" + * } + */ + LOK_CALLBACK_FORM_FIELD_BUTTON = 49, + + /** + * This is Calc specific. Indicates that some or all of the current sheet's + * geometry data has changed. Clients must request a full or partial sheet + * geometry data set. + * + * The payload specifies what part of the sheet geometry data has changed. + * The payload format is: + * 'all|rows|columns [sizes [hidden [filtered [groups]]]]' + * + * For example, the payload 'rows sizes groups' indicates that the row heights + * and row-groups data have changed. + */ + LOK_CALLBACK_INVALIDATE_SHEET_GEOMETRY = 50, + + /** + * When for the current cell is defined an input help text. + * + * The payload format is JSON: { "title": "title text", "content": "content text" } + */ + LOK_CALLBACK_VALIDITY_INPUT_HELP = 51, + + /** + * This is currently Calc only. Indicates the document background + * color in the payload as a RGB hex string (RRGGBB). + */ + LOK_CALLBACK_DOCUMENT_BACKGROUND_COLOR = 52, + + /** + * When a user tries to use command which is restricted for that user + */ + LOK_COMMAND_BLOCKED = 53, + + /** + * The position of the cell cursor jumped to. + * + * Payload format: "x, y, width, height, column, row", where the first + * 4 numbers are document coordinates, in twips, and the last 2 are table + * coordinates starting from 0. + * When the cursor is not shown the payload format is the "EMPTY" string. + * + * Rectangle format is the same as LOK_CALLBACK_INVALIDATE_TILES. + */ + LOK_CALLBACK_SC_FOLLOW_JUMP = 54, + + /** + * Sends all information for displaying metadata for a text based content control. + * + * Examples: + * Entered a rich text content control: + * { + * "action": "show", + * "rectangles": "1418, 1694, 720, 551; 10291, 1418, 1099, 275" + * } + * + * Left a rich text content control: + * { + * "action": "hide" + * } + * + * Entered a dropdown content control: + * { + * "action": "show", + * "rectangles": "...", + * "items": ["red", "green", "blue"] + * } + * + * Clicked on a picture content control's placeholder: + * { + * "action": "change-picture" + * } + * + * Entered a date content control: + * { + * "action": "show", + * "rectangles": "...", + * "date": "true" + * } + */ + LOK_CALLBACK_CONTENT_CONTROL = 55, + + /** + * This is Calc specific. The payload contains print ranges of all + * sheets in the document. + * + * Payload example: + * { + * "printranges" : [ + * { + * "sheet": 0, + * "ranges": [ + * [0, 0, 4, 5], + * [5, 100, 8, 150] + * ] + * }, + * { + * "sheet": 3, + * "ranges": [ + * [1, 0, 6, 10], + * [3, 200, 6, 230] + * ] + * } + * ] + * } + * + * The format of the inner "ranges" array for each sheet is + * [, , , ] + */ + LOK_CALLBACK_PRINT_RANGES = 56, +} +LibreOfficeKitCallbackType; + +typedef enum +{ + /// A key on the keyboard is pressed. + LOK_KEYEVENT_KEYINPUT, + /// A key on the keyboard is released. + LOK_KEYEVENT_KEYUP +} +LibreOfficeKitKeyEventType; + +typedef enum +{ + /// cf. SalEvent::ExtTextInput + LOK_EXT_TEXTINPUT, + /// cf. SalEvent::ExtTextInputPos + LOK_EXT_TEXTINPUT_POS, + /// cf. SalEvent::EndExtTextInput + LOK_EXT_TEXTINPUT_END +} +LibreOfficeKitExtTextInputType; + +/// Returns the string representation of a LibreOfficeKitCallbackType enumeration element. +static inline const char* lokCallbackTypeToString(int nType) +{ + switch (static_cast(nType)) + { + case LOK_CALLBACK_INVALIDATE_TILES: + return "LOK_CALLBACK_INVALIDATE_TILES"; + case LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR: + return "LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR"; + case LOK_CALLBACK_TEXT_SELECTION: + return "LOK_CALLBACK_TEXT_SELECTION"; + case LOK_CALLBACK_TEXT_SELECTION_START: + return "LOK_CALLBACK_TEXT_SELECTION_START"; + case LOK_CALLBACK_TEXT_SELECTION_END: + return "LOK_CALLBACK_TEXT_SELECTION_END"; + case LOK_CALLBACK_CURSOR_VISIBLE: + return "LOK_CALLBACK_CURSOR_VISIBLE"; + case LOK_CALLBACK_VIEW_CURSOR_VISIBLE: + return "LOK_CALLBACK_VIEW_CURSOR_VISIBLE"; + case LOK_CALLBACK_GRAPHIC_SELECTION: + return "LOK_CALLBACK_GRAPHIC_SELECTION"; + case LOK_CALLBACK_GRAPHIC_VIEW_SELECTION: + return "LOK_CALLBACK_GRAPHIC_VIEW_SELECTION"; + case LOK_CALLBACK_CELL_CURSOR: + return "LOK_CALLBACK_CELL_CURSOR"; + case LOK_CALLBACK_HYPERLINK_CLICKED: + return "LOK_CALLBACK_HYPERLINK_CLICKED"; + case LOK_CALLBACK_MOUSE_POINTER: + return "LOK_CALLBACK_MOUSE_POINTER"; + case LOK_CALLBACK_STATE_CHANGED: + return "LOK_CALLBACK_STATE_CHANGED"; + case LOK_CALLBACK_STATUS_INDICATOR_START: + return "LOK_CALLBACK_STATUS_INDICATOR_START"; + case LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE: + return "LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE"; + case LOK_CALLBACK_STATUS_INDICATOR_FINISH: + return "LOK_CALLBACK_STATUS_INDICATOR_FINISH"; + case LOK_CALLBACK_SEARCH_NOT_FOUND: + return "LOK_CALLBACK_SEARCH_NOT_FOUND"; + case LOK_CALLBACK_DOCUMENT_SIZE_CHANGED: + return "LOK_CALLBACK_DOCUMENT_SIZE_CHANGED"; + case LOK_CALLBACK_SET_PART: + return "LOK_CALLBACK_SET_PART"; + case LOK_CALLBACK_SEARCH_RESULT_SELECTION: + return "LOK_CALLBACK_SEARCH_RESULT_SELECTION"; + case LOK_CALLBACK_DOCUMENT_PASSWORD: + return "LOK_CALLBACK_DOCUMENT_PASSWORD"; + case LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY: + return "LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY"; + case LOK_CALLBACK_CONTEXT_MENU: + return "LOK_CALLBACK_CONTEXT_MENU"; + case LOK_CALLBACK_INVALIDATE_VIEW_CURSOR: + return "LOK_CALLBACK_INVALIDATE_VIEW_CURSOR"; + case LOK_CALLBACK_TEXT_VIEW_SELECTION: + return "LOK_CALLBACK_TEXT_VIEW_SELECTION"; + case LOK_CALLBACK_CELL_VIEW_CURSOR: + return "LOK_CALLBACK_CELL_VIEW_CURSOR"; + case LOK_CALLBACK_CELL_ADDRESS: + return "LOK_CALLBACK_CELL_ADDRESS"; + case LOK_CALLBACK_CELL_FORMULA: + return "LOK_CALLBACK_CELL_FORMULA"; + case LOK_CALLBACK_UNO_COMMAND_RESULT: + return "LOK_CALLBACK_UNO_COMMAND_RESULT"; + case LOK_CALLBACK_ERROR: + return "LOK_CALLBACK_ERROR"; + case LOK_CALLBACK_VIEW_LOCK: + return "LOK_CALLBACK_VIEW_LOCK"; + case LOK_CALLBACK_REDLINE_TABLE_SIZE_CHANGED: + return "LOK_CALLBACK_REDLINE_TABLE_SIZE_CHANGED"; + case LOK_CALLBACK_REDLINE_TABLE_ENTRY_MODIFIED: + return "LOK_CALLBACK_REDLINE_TABLE_ENTRY_MODIFIED"; + case LOK_CALLBACK_INVALIDATE_HEADER: + return "LOK_CALLBACK_INVALIDATE_HEADER"; + case LOK_CALLBACK_COMMENT: + return "LOK_CALLBACK_COMMENT"; + case LOK_CALLBACK_RULER_UPDATE: + return "LOK_CALLBACK_RULER_UPDATE"; + case LOK_CALLBACK_WINDOW: + return "LOK_CALLBACK_WINDOW"; + case LOK_CALLBACK_VALIDITY_LIST_BUTTON: + return "LOK_CALLBACK_VALIDITY_LIST_BUTTON"; + case LOK_CALLBACK_VALIDITY_INPUT_HELP: + return "LOK_CALLBACK_VALIDITY_INPUT_HELP"; + case LOK_CALLBACK_CLIPBOARD_CHANGED: + return "LOK_CALLBACK_CLIPBOARD_CHANGED"; + case LOK_CALLBACK_CONTEXT_CHANGED: + return "LOK_CALLBACK_CONTEXT_CHANGED"; + case LOK_CALLBACK_SIGNATURE_STATUS: + return "LOK_CALLBACK_SIGNATURE_STATUS"; + case LOK_CALLBACK_PROFILE_FRAME: + return "LOK_CALLBACK_PROFILE_FRAME"; + case LOK_CALLBACK_CELL_SELECTION_AREA: + return "LOK_CALLBACK_CELL_SELECTION_AREA"; + case LOK_CALLBACK_CELL_AUTO_FILL_AREA: + return "LOK_CALLBACK_CELL_AUTO_FILL_AREA"; + case LOK_CALLBACK_TABLE_SELECTED: + return "LOK_CALLBACK_TABLE_SELECTED"; + case LOK_CALLBACK_REFERENCE_MARKS: + return "LOK_CALLBACK_REFERENCE_MARKS"; + case LOK_CALLBACK_JSDIALOG: + return "LOK_CALLBACK_JSDIALOG"; + case LOK_CALLBACK_CALC_FUNCTION_LIST: + return "LOK_CALLBACK_CALC_FUNCTION_LIST"; + case LOK_CALLBACK_TAB_STOP_LIST: + return "LOK_CALLBACK_TAB_STOP_LIST"; + case LOK_CALLBACK_FORM_FIELD_BUTTON: + return "LOK_CALLBACK_FORM_FIELD_BUTTON"; + case LOK_CALLBACK_INVALIDATE_SHEET_GEOMETRY: + return "LOK_CALLBACK_INVALIDATE_SHEET_GEOMETRY"; + case LOK_CALLBACK_DOCUMENT_BACKGROUND_COLOR: + return "LOK_CALLBACK_DOCUMENT_BACKGROUND_COLOR"; + case LOK_COMMAND_BLOCKED: + return "LOK_COMMAND_BLOCKED"; + case LOK_CALLBACK_SC_FOLLOW_JUMP: + return "LOK_CALLBACK_SC_FOLLOW_JUMP"; + case LOK_CALLBACK_CONTENT_CONTROL: + return "LOK_CALLBACK_CONTENT_CONTROL"; + case LOK_CALLBACK_PRINT_RANGES: + return "LOK_CALLBACK_PRINT_RANGES"; + } + + assert(!"Unknown LibreOfficeKitCallbackType type."); + return nullptr; +} + +typedef enum +{ + /// A mouse button has been pressed down. + LOK_MOUSEEVENT_MOUSEBUTTONDOWN, + /// A mouse button has been let go. + LOK_MOUSEEVENT_MOUSEBUTTONUP, + /// The mouse has moved while a button is pressed. + LOK_MOUSEEVENT_MOUSEMOVE +} +LibreOfficeKitMouseEventType; + +typedef enum +{ + /// The start of selection is to be adjusted. + LOK_SETTEXTSELECTION_START, + /// The end of selection is to be adjusted. + LOK_SETTEXTSELECTION_END, + /// Both the start and the end of selection is to be adjusted. + LOK_SETTEXTSELECTION_RESET +} +LibreOfficeKitSetTextSelectionType; + +typedef enum +{ + /** + * A move or a resize action starts. It is assumed that there is a valid + * graphic selection (see LOK_CALLBACK_GRAPHIC_SELECTION) and the supplied + * coordinates are the ones the user tapped on. + * + * The type of the action is move by default, unless the coordinates are + * the position of a handle (see below), in which case it's a resize. + * + * There are 8 handles for a graphic selection: + * - top-left, top-center, top-right + * - middle-left, middle-right + * - bottom-left, bottom-center, bottom-right + */ + LOK_SETGRAPHICSELECTION_START, + /** + * A move or resize action stops. It is assumed that this is always used + * only after a LOK_SETTEXTSELECTION_START. The supplied coordinates are + * the ones where the user released the screen. + */ + LOK_SETGRAPHICSELECTION_END +} +LibreOfficeKitSetGraphicSelectionType; + +#endif // defined LOK_USE_UNSTABLE_API || defined LIBO_INTERNAL_ONLY + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITENUMS_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/LibreOfficeKit/LibreOfficeKitGtk.h b/include/LibreOfficeKit/LibreOfficeKitGtk.h new file mode 100644 index 000000000..83a2a1f75 --- /dev/null +++ b/include/LibreOfficeKit/LibreOfficeKitGtk.h @@ -0,0 +1,381 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITGTK_H +#define INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITGTK_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define LOK_TYPE_DOC_VIEW (lok_doc_view_get_type()) +#define LOK_DOC_VIEW(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), LOK_TYPE_DOC_VIEW, LOKDocView)) +#define LOK_IS_DOC_VIEW(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), LOK_TYPE_DOC_VIEW)) +#define LOK_DOC_VIEW_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), LOK_TYPE_DOC_VIEW, LOKDocViewClass)) +#define LOK_IS_DOC_VIEW_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), LOK_TYPE_DOC_VIEW)) +#define LOK_DOC_VIEW_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), LOK_TYPE_DOC_VIEW, LOKDocViewClass)) + +typedef struct _LOKDocView LOKDocView; +typedef struct _LOKDocViewClass LOKDocViewClass; +typedef struct _LOKDocViewPrivate LOKDocViewPrivate; + +struct _LOKDocView +{ + GtkDrawingArea aDrawingArea; +}; + +struct _LOKDocViewClass +{ + GtkDrawingAreaClass parent_class; +}; + +GType lok_doc_view_get_type (void) G_GNUC_CONST; + +/** + * lok_doc_view_new: + * @pPath: (nullable) (allow-none): LibreOffice install path. Pass null to set it to default + * path which in most cases would be $libdir/libreoffice/program + * @cancellable: The cancellable object that you can use to cancel this + * operation. + * @error: The error that will be set if the object fails to initialize. + * + * Returns: (transfer none): The #LOKDocView widget instance. + */ +GtkWidget* lok_doc_view_new (const gchar* pPath, + GCancellable *cancellable, + GError **error); + +/** + * lok_doc_view_new_from_user_profile: + * @pPath: (nullable) (allow-none): LibreOffice install path. Pass null to set it to default + * path which in most cases would be $libdir/libreoffice/program + * @pUserProfile: (nullable) (allow-none): User profile URL. Must be either a file URL or a + * special vnd.sun.star.pathname URL. Pass non-null to be able to use this + * widget and LibreOffice itself in parallel. + * @cancellable: The cancellable object that you can use to cancel this + * operation. + * @error: The error that will be set if the object fails to initialize. + * + * Returns: (transfer none): The #LOKDocView widget instance. + */ +GtkWidget* lok_doc_view_new_from_user_profile (const gchar* pPath, + const gchar* pUserProfile, + GCancellable *cancellable, + GError **error); + +/** + * lok_doc_view_new_from_widget: + * @pDocView: The #LOKDocView instance + * @pRenderingArguments: (nullable) (allow-none): lok::Document::initializeForRendering() arguments. + * + * Returns: (transfer none): The #LOKDocView widget instance. + */ +GtkWidget* lok_doc_view_new_from_widget (LOKDocView* pDocView, + const gchar* pRenderingArguments); + +/** + * lok_doc_view_open_document: + * @pDocView: The #LOKDocView instance + * @pPath: (transfer full): The path of the document that #LOKDocView widget should try to open + * @pRenderingArguments: (nullable) (allow-none): lok::Document::initializeForRendering() arguments. + * @cancellable: + * @callback: + * @userdata: + */ +void lok_doc_view_open_document (LOKDocView* pDocView, + const gchar* pPath, + const gchar* pRenderingArguments, + GCancellable* cancellable, + GAsyncReadyCallback callback, + gpointer userdata); + +/** + * lok_doc_view_open_document_finish: + * @pDocView: The #LOKDocView instance + * @res: + * @error: + * + * Returns: %TRUE if the document is loaded successfully, %FALSE otherwise + */ +gboolean lok_doc_view_open_document_finish (LOKDocView* pDocView, + GAsyncResult* res, + GError** error); + +/** + * lok_doc_view_get_document: + * @pDocView: The #LOKDocView instance + * + * Gets the document the viewer displays. + * + * Returns: The #LibreOfficeKitDocument instance the widget is currently showing + */ +LibreOfficeKitDocument* lok_doc_view_get_document (LOKDocView* pDocView); + +/** + * lok_doc_view_set_zoom: + * @pDocView: The #LOKDocView instance + * @fZoom: The new zoom level that pDocView must set it into. + * + * Sets the new zoom level for the widget. Does nothing if fZoom is equal to + * existing zoom level. Values outside the range [0.25, 5.0] are clamped into + * the nearest allowed value in the interval. + */ +void lok_doc_view_set_zoom (LOKDocView* pDocView, + float fZoom); +/** + * lok_doc_view_set_visible_area: + * @pDocView: The #LOKDocView instance + * @pVisibleArea: The new visible area of pDocView in twips. + * + * Sets the new visible area of the widget. This helps e.g. the page down key + * to jump the correct length, which depends on the amount of visible height of + * the document. + */ +void lok_doc_view_set_visible_area (LOKDocView* pDocView, + GdkRectangle* pVisibleArea); + +/** + * lok_doc_view_get_zoom: + * @pDocView: The #LOKDocView instance + * + * Returns: The current zoom factor value in float for pDocView + */ +gfloat lok_doc_view_get_zoom (LOKDocView* pDocView); + +/** + * lok_doc_view_get_parts: + * @pDocView: The #LOKDocView instance + * + * Returns: Part refers to either individual sheets in a Calc, or slides in Impress, + * and has no relevance for Writer. Returns -1 if no document is set currently. + */ +gint lok_doc_view_get_parts (LOKDocView* pDocView); + +/** + * lok_doc_view_get_part: + * @pDocView: The #LOKDocView instance + * + * Returns: Current part number of the document. Returns -1 if no document is set currently. + */ +gint lok_doc_view_get_part (LOKDocView* pDocView); + +/** + * lok_doc_view_set_part: + * @pDocView: The #LOKDocView instance + * @nPart: + */ +void lok_doc_view_set_part (LOKDocView* pDocView, + int nPart); + +/** + * lok_doc_view_get_part_name: + * @pDocView: The #LOKDocView instance + * @nPart: + * + * Returns: Get current part name of loaded document. Returns null if no + * document is set, or document has been destroyed using lok_doc_view_destroy_document. + */ +gchar* lok_doc_view_get_part_name (LOKDocView* pDocView, + int nPart); + +/** + * lok_doc_view_set_partmode: + * @pDocView: The #LOKDocView instance + * @nPartMode: + */ +void lok_doc_view_set_partmode (LOKDocView* pDocView, + int nPartMode); + +/** + * lok_doc_view_reset_view: + * @pDocView: The #LOKDocView instance + */ +void lok_doc_view_reset_view (LOKDocView* pDocView); + +/** + * lok_doc_view_set_edit: + * @pDocView: The #LOKDocView instance + * @bEdit: %TRUE if the pDocView should go in edit mode, %FALSE otherwise + * + * Sets if the viewer is actually an editor or not. + */ +void lok_doc_view_set_edit (LOKDocView* pDocView, + gboolean bEdit); + +/** + * lok_doc_view_get_edit: + * @pDocView: The #LOKDocView instance + * + * Gets if the viewer is actually an editor or not. + * + * Returns: %TRUE if the given pDocView is in edit mode. + */ +gboolean lok_doc_view_get_edit (LOKDocView* pDocView); + +/** + * lok_doc_view_post_command: + * @pDocView: the #LOKDocView instance + * @pCommand: the command to issue to LO core + * @pArguments: the arguments to the given command + * @bNotifyWhenFinished: normally false, but it may be useful for eg. .uno:Save + * + * Posts the .uno: command to the LibreOfficeKit. + */ +void lok_doc_view_post_command (LOKDocView* pDocView, + const gchar* pCommand, + const gchar* pArguments, + gboolean bNotifyWhenFinished); + +/** + * lok_doc_view_get_command_values: + * @pDocView: the #LOKDocView instance + * @pCommand: the command to issue to LO core + * + * Get a json mapping of the possible values for the given command. + * In the form of: {commandName: unoCmd, commandValues: {possible_values}} + * + * Returns: A json mapping of the possible values for the given command + */ +gchar * lok_doc_view_get_command_values (LOKDocView* pDocView, + const gchar* pCommand); + +/** + * lok_doc_view_find_next: + * @pDocView: The #LOKDocView instance + * @pText: text to search for + * @bHighlightAll: Whether all the matches should be highlighted or not + * + * Highlights the next matching text in the view. `search-not-found` signal will + * be emitted when no search is found + */ +void lok_doc_view_find_next (LOKDocView* pDocView, + const gchar* pText, + gboolean bHighlightAll); + +/** + * lok_doc_view_find_prev: + * @pDocView: The #LOKDocView instance + * @pText: text to search for + * @bHighlightAll: Whether all the matches should be highlighted or not + * + * Highlights the previous matching text in the view. `search-not-found` signal + * will be emitted when no search is found + */ +void lok_doc_view_find_prev (LOKDocView* pDocView, + const gchar* pText, + gboolean bHighlightAll); + +/** + * lok_doc_view_highlight_all: + * @pDocView: The #LOKDocView instance + * @pText: text to search for + * + * Highlights all matching texts in the view. `search-not-found` signal + * will be emitted when no search is found + */ +void lok_doc_view_highlight_all (LOKDocView* pDocView, + const gchar* pText); + +/** + * lok_doc_view_copy_selection: + * @pDocView: The #LOKDocView instance + * @pMimeType: suggests the return format, for example text/plain;charset=utf-8 + * @pUsedMimeType: (out): output parameter to inform about the determined format + * (suggested or plain text). + * + * Returns: Selected text. The caller must free the returned buffer after + * use. Returns null if no document is set. + */ +gchar* lok_doc_view_copy_selection (LOKDocView* pDocView, + const gchar* pMimeType, + gchar** pUsedMimeType); + +/** + * lok_doc_view_paste: + * @pDocView: The #LOKDocView instance + * @pMimeType: format of pData, for example text/plain;charset=utf-8 + * @pData: the data to be pasted + * @nSize: length of data to be pasted + * + * Pastes the content at the current cursor position + * + * Returns: if pData was pasted successfully. + */ +gboolean lok_doc_view_paste (LOKDocView* pDocView, + const gchar* pMimeType, + const gchar* pData, + gsize nSize); + +/** + * lok_doc_view_set_document_password: + * @pDocView: The #LOKDocView instance + * @pURL: the URL of the document to set password for, as sent with signal `password-required` + * @pPassword: (nullable) (allow-none): the password, NULL for no password + * + * Set the password for password protected documents + */ +void lok_doc_view_set_document_password (LOKDocView* pDocView, + const gchar* pURL, + const gchar* pPassword); + +/** + * lok_doc_view_get_version_info: + * @pDocView: The #LOKDocView instance + * + * Get version information of the LOKit process + * + * Returns: JSON string containing version information in format: + * {ProductName: <>, ProductVersion: <>, ProductExtension: <>, BuildId: <>} + * + * Eg: {"ProductName": "LibreOffice", + * "ProductVersion": "5.3", + * "ProductExtension": ".0.0.alpha0", + * "BuildId": ""} + */ +gchar* lok_doc_view_get_version_info (LOKDocView* pDocView); + +/** + * lok_doc_view_pixel_to_twip: + * @pDocView: The #LOKDocView instance + * @fInput: The value in pixels to convert to twips + * + * Converts the value in pixels to twips according to zoom level. + * + * Returns: The corresponding value in twips + */ +gfloat lok_doc_view_pixel_to_twip (LOKDocView* pDocView, + float fInput); + +/** + * lok_doc_view_twip_to_pixel: + * @pDocView: The #LOKDocView instance + * @fInput: The value in twips to convert to pixels + * + * Converts the value in twips to pixels according to zoom level. + * + * Returns: The corresponding value in pixels + */ +gfloat lok_doc_view_twip_to_pixel (LOKDocView* pDocView, + float fInput); + +/** + * lok_doc_view_send_content_control_event: + * @pDocView: The #LOKDocView instance + * @pArguments: (nullable) (allow-none): see lok::Document::sendContentControlEvent() for the details. + */ +void lok_doc_view_send_content_control_event(LOKDocView* pDocView, const gchar* pArguments); + +G_END_DECLS + +#endif // INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITGTK_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/LibreOfficeKit/LibreOfficeKitInit.h b/include/LibreOfficeKit/LibreOfficeKitInit.h new file mode 100644 index 000000000..5bbb722b5 --- /dev/null +++ b/include/LibreOfficeKit/LibreOfficeKitInit.h @@ -0,0 +1,364 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITINIT_H +#define INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITINIT_H + +#include + +#if defined __GNUC__ || defined __clang__ +# define LOK_TOLERATE_UNUSED __attribute__((used)) +#else +# define LOK_TOLERATE_UNUSED +#endif + +#if defined(__linux__) || defined (__FreeBSD__) || defined(_AIX) ||\ + defined(_WIN32) || defined(__APPLE__) || defined (__NetBSD__) ||\ + defined (__sun) || defined(__OpenBSD__) + +#include +#include +#include +#include + +#ifndef _WIN32 + + #include + + #ifdef _AIX + # include + #endif + #ifdef __APPLE__ + #define TARGET_LIB "lib" "sofficeapp" ".dylib" + #define TARGET_MERGED_LIB "lib" "mergedlo" ".dylib" + #else + #define TARGET_LIB "lib" "sofficeapp" ".so" + #define TARGET_MERGED_LIB "lib" "mergedlo" ".so" + #endif + #define SEPARATOR '/' + +#else + + #if !defined WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #define TARGET_LIB "sofficeapp" ".dll" + #define TARGET_MERGED_LIB "mergedlo" ".dll" + #define SEPARATOR '\\' + #define UNOPATH "\\..\\URE\\bin" + +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifndef _WIN32 + +#if !defined(IOS) + static void *lok_loadlib(const char *pFN) + { + return dlopen(pFN, RTLD_LAZY +#if defined LOK_LOADLIB_GLOBAL + | RTLD_GLOBAL +#endif + ); + } + + static char *lok_dlerror(void) + { + return dlerror(); + } + + // This function must be called to release memory allocated by lok_dlerror() + static void lok_dlerror_free(char *pErrMessage) + { + (void)pErrMessage; + // Do nothing for return of dlerror() + } + + static void extendUnoPath(const char *pPath) + { + (void)pPath; + } + + static void *lok_dlsym(void *Hnd, const char *pName) + { + return dlsym(Hnd, pName); + } + + static int lok_dlclose(void *Hnd) + { + return dlclose(Hnd); + } +#endif // IOS + + +#else + static void *lok_loadlib(const char *pFN) + { + return (void *) LoadLibraryA(pFN); + } + + static char *lok_dlerror(void) + { + LPSTR buf = NULL; + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, GetLastError(), 0, reinterpret_cast(&buf), 0, NULL); + return buf; + } + + // This function must be called to release memory allocated by lok_dlerror() + static void lok_dlerror_free(char *pErrMessage) + { + HeapFree(GetProcessHeap(), 0, pErrMessage); + } + + static void *lok_dlsym(void *Hnd, const char *pName) + { + return reinterpret_cast(GetProcAddress((HINSTANCE) Hnd, pName)); + } + + static int lok_dlclose(void *Hnd) + { + return FreeLibrary((HINSTANCE) Hnd); + } + + static void extendUnoPath(const char *pPath) + { + char *sNewPath = NULL, *sEnvPath = NULL; + size_t size_sEnvPath = 0, buffer_size = 0; + DWORD cChars; + + if (!pPath) + return; + + cChars = GetEnvironmentVariableA("PATH", sEnvPath, 0); + if (cChars > 0) + { + sEnvPath = (char *) malloc(cChars); + cChars = GetEnvironmentVariableA("PATH", sEnvPath, cChars); + //If PATH is not set then it is no error + if (cChars == 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) + { + free(sEnvPath); + return; + } + } + //prepare the new PATH. Add the Ure/bin directory at the front. + //note also adding ';' + if(sEnvPath) + size_sEnvPath = strlen(sEnvPath); + buffer_size = size_sEnvPath + 2*strlen(pPath) + strlen(UNOPATH) + 4; + sNewPath = (char *) malloc(buffer_size); + sNewPath[0] = L'\0'; + strcat_s(sNewPath, buffer_size, pPath); // program to PATH + strcat_s(sNewPath, buffer_size, ";"); + strcat_s(sNewPath, buffer_size, UNOPATH); // UNO to PATH + if (size_sEnvPath > 0) + { + strcat_s(sNewPath, buffer_size, ";"); + strcat_s(sNewPath, buffer_size, sEnvPath); + } + + SetEnvironmentVariableA("PATH", sNewPath); + + free(sNewPath); + free(sEnvPath); + } +#endif + +#if !defined(IOS) +static void *lok_dlopen( const char *install_path, char ** _imp_lib ) +{ + char *imp_lib; + void *dlhandle; + + size_t partial_length, imp_lib_size; + struct stat dir_st; + + *_imp_lib = NULL; + + if (!install_path) + return NULL; + + if (stat(install_path, &dir_st) != 0) + { + fprintf(stderr, "installation path \"%s\" does not exist\n", install_path); + return NULL; + } + + // allocate large enough buffer + partial_length = strlen(install_path); + imp_lib_size = partial_length + sizeof(TARGET_LIB) + sizeof(TARGET_MERGED_LIB) + 2; + imp_lib = (char *) malloc(imp_lib_size); + if (!imp_lib) + { + fprintf( stderr, "failed to open library : not enough memory\n"); + return NULL; + } + + memcpy(imp_lib, install_path, partial_length); + + extendUnoPath(install_path); + + imp_lib[partial_length++] = SEPARATOR; + strncpy(imp_lib + partial_length, TARGET_LIB, imp_lib_size - partial_length); + + dlhandle = lok_loadlib(imp_lib); + if (!dlhandle) + { + // If TARGET_LIB exists, and likely is a real library (not a + // small one-line text stub as in the --enable-mergedlib + // case), but dlopen failed for some reason, don't try + // TARGET_MERGED_LIB. + struct stat st; + if (stat(imp_lib, &st) == 0 && st.st_size > 100) + { + char *pErrMessage = lok_dlerror(); + fprintf(stderr, "failed to open library '%s': %s\n", + imp_lib, pErrMessage); + lok_dlerror_free(pErrMessage); + free(imp_lib); + return NULL; + } + + strncpy(imp_lib + partial_length, TARGET_MERGED_LIB, imp_lib_size - partial_length); + + dlhandle = lok_loadlib(imp_lib); + if (!dlhandle) + { + char *pErrMessage = lok_dlerror(); + fprintf(stderr, "failed to open library '%s': %s\n", + imp_lib, pErrMessage); + lok_dlerror_free(pErrMessage); + free(imp_lib); + return NULL; + } + } + *_imp_lib = imp_lib; + return dlhandle; +} +#endif + +typedef LibreOfficeKit *(LokHookFunction)( const char *install_path); + +typedef LibreOfficeKit *(LokHookFunction2)( const char *install_path, const char *user_profile_url ); + +typedef int (LokHookPreInit) ( const char *install_path, const char *user_profile_url ); + +typedef int (LokHookPreInit2) ( const char *install_path, const char *user_profile_url, LibreOfficeKit** kit); + +#if defined(IOS) || defined(ANDROID) +LibreOfficeKit *libreofficekit_hook_2(const char* install_path, const char* user_profile_path); +#endif + +static LibreOfficeKit *lok_init_2( const char *install_path, const char *user_profile_url ) +{ +#if !defined(IOS) && !defined(ANDROID) + void *dlhandle; + char *imp_lib; + LokHookFunction *pSym; + LokHookFunction2 *pSym2; + + dlhandle = lok_dlopen(install_path, &imp_lib); + if (!dlhandle) + return NULL; + + pSym2 = (LokHookFunction2 *) lok_dlsym(dlhandle, "libreofficekit_hook_2"); + if (!pSym2) + { + if (user_profile_url != NULL) + { + fprintf( stderr, "the LibreOffice version in '%s' does not support passing a user profile to the hook function\n", + imp_lib ); + lok_dlclose( dlhandle ); + free( imp_lib ); + return NULL; + } + pSym = (LokHookFunction *) lok_dlsym( dlhandle, "libreofficekit_hook" ); + if (!pSym) + { + fprintf( stderr, "failed to find hook in library '%s'\n", imp_lib ); + lok_dlclose( dlhandle ); + free( imp_lib ); + return NULL; + } + free( imp_lib ); + // dlhandle is "leaked" + // coverity[leaked_storage] - on purpose + return pSym( install_path ); + } + + if (user_profile_url != NULL && user_profile_url[0] == '/') + { + // It should be either a file: URL or a vnd.sun.star.pathname: URL. + fprintf( stderr, "second parameter to lok_init_2 '%s' should be a URL, not a pathname\n", user_profile_url ); + lok_dlclose( dlhandle ); + free( imp_lib ); + return NULL; + } + + free( imp_lib ); + // dlhandle is "leaked" + // coverity[leaked_storage] - on purpose + return pSym2( install_path, user_profile_url ); +#else + return libreofficekit_hook_2( install_path, user_profile_url ); +#endif +} + +static LOK_TOLERATE_UNUSED +LibreOfficeKit *lok_init( const char *install_path ) +{ + return lok_init_2( install_path, NULL ); +} + +#if !defined(IOS) +static LOK_TOLERATE_UNUSED +int lok_preinit( const char *install_path, const char *user_profile_url ) +{ + void *dlhandle; + char *imp_lib; + LokHookPreInit *pSym; + + dlhandle = lok_dlopen(install_path, &imp_lib); + if (!dlhandle) + return -1; + + pSym = (LokHookPreInit *) lok_dlsym(dlhandle, "lok_preinit"); + if (!pSym) + { + fprintf( stderr, "failed to find pre-init hook in library '%s'\n", imp_lib ); + lok_dlclose( dlhandle ); + free( imp_lib ); + return -1; + } + + free( imp_lib ); + + // dlhandle is "leaked" + // coverity[leaked_storage] - on purpose + return pSym( install_path, user_profile_url ); +} +#endif + +#undef SEPARATOR // It is used at least in enum class MenuItemType + +#ifdef __cplusplus +} +#endif + +#endif // defined(__linux__) || defined (__FreeBSD__) || defined(_AIX) || defined(_WIN32) || defined(__APPLE__) + +#endif // INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKITINIT_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/LibreOfficeKit/LibreOfficeKitTypes.h b/include/LibreOfficeKit/LibreOfficeKitTypes.h new file mode 100644 index 000000000..8513ef754 --- /dev/null +++ b/include/LibreOfficeKit/LibreOfficeKitTypes.h @@ -0,0 +1,34 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKIT_TYPES_H +#define INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKIT_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** @see lok::Office::registerCallback(). + @since LibreOffice 6.0 + */ +typedef void (*LibreOfficeKitCallback)(int nType, const char* pPayload, void* pData); + +/** @see lok::Office::runLoop(). + @since LibreOffice 6.3 + */ +typedef int (*LibreOfficeKitPollCallback)(void* pData, int timeoutUs); +typedef void (*LibreOfficeKitWakeCallback)(void* pData); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_LIBREOFFICEKIT_LIBREOFFICEKIT_TYPES_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/android/compatibility.hxx b/include/android/compatibility.hxx new file mode 100644 index 000000000..bddb1b8f1 --- /dev/null +++ b/include/android/compatibility.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#if defined(ARM) +#include +#include +#include + +namespace std +{ +inline double fmax(double x, double y) { return ::fmax(x, y); } + +template T round(T x) { return ::round(x); } + +template T trunc(T x) { return ::trunc(x); } + +template T lround(T x) { return ::lround(x); } + +template std::string to_string(const T& rNumber) +{ + std::ostringstream aStream; + aStream << rNumber; + return aStream.str(); +} +} +#endif diff --git a/include/animations/animationnodehelper.hxx b/include/animations/animationnodehelper.hxx new file mode 100644 index 000000000..eee41cd28 --- /dev/null +++ b/include/animations/animationnodehelper.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_ANIMATIONS_ANIMATIONNODEHELPER_HXX +#define INCLUDED_ANIMATIONS_ANIMATIONNODEHELPER_HXX + +#include +#include +#include +#include + +#include + +/* Declaration and definition of AnimationNode helper */ + +namespace anim +{ + // TODO(Q1): this could possibly be implemented with a somewhat + // more lightweight template, by having the actual worker receive + // only a function pointer, and a thin templated wrapper around + // that which converts member functions into that. + + /** pushes the given node to the given vector and recursively calls itself for each child node. + */ + inline void create_deep_vector( const css::uno::Reference< css::animations::XAnimationNode >& xNode, + std::vector< css::uno::Reference< css::animations::XAnimationNode > >& rVector ) + { + rVector.push_back( xNode ); + + try + { + // get an XEnumerationAccess to the children + css::uno::Reference< css::container::XEnumerationAccess > + xEnumerationAccess( xNode, css::uno::UNO_QUERY ); + + if( xEnumerationAccess.is() ) + { + css::uno::Reference< css::container::XEnumeration > + xEnumeration = xEnumerationAccess->createEnumeration(); + + if( xEnumeration.is() ) + { + while( xEnumeration->hasMoreElements() ) + { + css::uno::Reference< css::animations::XAnimationNode > + xChildNode( xEnumeration->nextElement(), + css::uno::UNO_QUERY_THROW ); + + create_deep_vector( xChildNode, rVector ); + } + } + } + } + catch( css::uno::Exception& ) + { + } + } +} + +#endif /* INCLUDED_ANIMATIONS_ANIMATIONNODEHELPER_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/apple_remote/RemoteControl.h b/include/apple_remote/RemoteControl.h new file mode 100644 index 000000000..2d9c189b8 --- /dev/null +++ b/include/apple_remote/RemoteControl.h @@ -0,0 +1,117 @@ +/* -*- Mode: ObjC; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/***************************************************************************** + * RemoteControl.h + * RemoteControlWrapper + * + * Created by Martin Kahr on 11.03.06 under a MIT-style license. + * Copyright (c) 2006 martinkahr.com. All rights reserved. + * + * Code modified and adapted to OpenOffice.org + * by Eric Bachard on 11.08.2008 under the same License + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + *****************************************************************************/ + +#include + +#import + +#include + +// notification names that are being used to signal that an application wants to +// have access to the remote control device or if the application has finished +// using the remote control device +extern NSString* REQUEST_FOR_REMOTE_CONTROL_NOTIFICATION; +extern NSString* FINISHED_USING_REMOTE_CONTROL_NOTIFICATION; + +// keys used in user objects for distributed notifications +extern NSString* kRemoteControlDeviceName; +extern NSString* kApplicationIdentifier; +extern NSString* kTargetApplicationIdentifier; + +// we have a 6 bit offset to make a hold event out of a normal event +#define EVENT_TO_HOLD_EVENT_OFFSET 6 + +@class RemoteControl; + +typedef enum { + // normal events + kRemoteButtonPlus =1<<1, + kRemoteButtonMinus =1<<2, + kRemoteButtonMenu =1<<3, + kRemoteButtonPlay =1<<4, + kRemoteButtonRight =1<<5, + kRemoteButtonLeft =1<<6, + + // hold events + kRemoteButtonPlus_Hold =1<<7, + kRemoteButtonMinus_Hold =1<<8, + kRemoteButtonMenu_Hold =1<<9, + kRemoteButtonPlay_Hold =1<<10, + kRemoteButtonRight_Hold =1<<11, + kRemoteButtonLeft_Hold =1<<12, + + // special events (not supported by all devices) + kRemoteControl_Switched =1<<13, + + // New values for the "metallic" Remote (2009 model) + kMetallicRemote2009ButtonPlay =1<<14, + kMetallicRemote2009ButtonMiddlePlay =1<<15 + +} RemoteControlEventIdentifier; + +@interface NSObject(RemoteControlDelegate) + +- (void) sendRemoteButtonEvent: (RemoteControlEventIdentifier) event pressedDown: (BOOL) pressedDown remoteControl: (RemoteControl*) remoteControl; + +@end + +/* + Base Interface for Remote Control devices +*/ +SAL_DLLPUBLIC_EXPORT @interface RemoteControl : NSObject { + id delegate; +} + +// returns nil if the remote control device is not available +- (id) initWithDelegate: (id) remoteControlDelegate; + +- (void) setListeningToRemote: (BOOL) value; +- (BOOL) isListeningToRemote; + +- (BOOL) isOpenInExclusiveMode; +- (void) setOpenInExclusiveMode: (BOOL) value; + +- (void) startListening: (id) sender; +- (void) stopListening: (id) sender; + +// is this remote control sending the given event? +- (BOOL) sendsEventForButtonIdentifier: (RemoteControlEventIdentifier) identifier; + +// sending of notifications between applications ++ (void) sendFinishedNotificationForAppIdentifier: (NSString*) identifier; ++ (void) sendRequestForRemoteControlNotification; + +// name of the device ++ (const char*) remoteControlDeviceName; + +@end + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/apple_remote/RemoteMainController.h b/include/apple_remote/RemoteMainController.h new file mode 100644 index 000000000..3d1951d31 --- /dev/null +++ b/include/apple_remote/RemoteMainController.h @@ -0,0 +1,57 @@ +/* -*- Mode: ObjC; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/***************************************************************************** + * RemoteMainController.h + * + * + * Created by Martin Kahr on 11.03.06 under a MIT-style license. + * Copyright (c) 2006 martinkahr.com. All rights reserved. + * + * Code modified and adapted to OpenOffice.org + * by Eric Bachard on 11.08.2008 under the same License + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + *****************************************************************************/ + +#include + +#import + +#include + +#define AppleRemoteControlEvent 15 + +@class RemoteControl; +@class MultiClickRemoteBehavior; + +//static void sendTheEvent( unichar, int ); + +SAL_DLLPUBLIC_EXPORT @interface AppleRemoteMainController : NSObject +{ +@public // else remoteControl is not reachable from GetSalData()->mpMainController + RemoteControl* remoteControl; +@private + MultiClickRemoteBehavior* remoteControlBehavior; +} +- (RemoteControl*)remoteControl; +- (MultiClickRemoteBehavior*)remoteBehavior; + +@end + + /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/avmedia/MediaControlBase.hxx b/include/avmedia/MediaControlBase.hxx new file mode 100644 index 000000000..1379a4364 --- /dev/null +++ b/include/avmedia/MediaControlBase.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_AVMEDIA_MEDIACONTROLBASE_HXX +#define INCLUDED_AVMEDIA_MEDIACONTROLBASE_HXX + +#include +#include + +#include + +namespace avmedia { class MediaItem; } + +#define AVMEDIA_TIME_RANGE 2048 + +#define AVMEDIA_ZOOMLEVEL_50 0 +#define AVMEDIA_ZOOMLEVEL_100 1 +#define AVMEDIA_ZOOMLEVEL_200 2 +#define AVMEDIA_ZOOMLEVEL_FIT 3 +#define AVMEDIA_ZOOMLEVEL_SCALED 4 +#define AVMEDIA_ZOOMLEVEL_INVALID 65535 + +namespace avmedia { + +enum class MediaControlStyle +{ + SingleLine = 0, + MultiLine = 1 +}; + +class UNLESS_MERGELIBS(AVMEDIA_DLLPUBLIC) MediaControlBase +{ +public: + MediaControlBase(); + virtual ~MediaControlBase(){}; + +protected: + std::unique_ptr mxPlayToolBox; + std::unique_ptr mxTimeSlider; + std::unique_ptr mxMuteToolBox; + std::unique_ptr mxVolumeSlider; + std::unique_ptr mxZoomListBox; + std::unique_ptr mxTimeEdit; + bool mbCurrentlySettingZoom; + + virtual void InitializeWidgets(); + virtual void UpdateToolBoxes(const MediaItem& rMediaItem); + void UpdateVolumeSlider( MediaItem const & aMediaItem ); + void UpdateTimeSlider( MediaItem const & aMediaItem ); + void UpdateTimeField( MediaItem const & aMediaItem, double fTime ); + void UpdatePlayState(const MediaItem& rMediaItem); + void SelectPlayToolBoxItem( MediaItem& aExecItem, MediaItem const & aItem, std::string_view rId); + void disposeWidgets(); +}; + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/avmedia/avmediadllapi.h b/include/avmedia/avmediadllapi.h new file mode 100644 index 000000000..abe4fb48c --- /dev/null +++ b/include/avmedia/avmediadllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_AVMEDIA_AVMEDIADLLAPI_H +#define INCLUDED_AVMEDIA_AVMEDIADLLAPI_H + +#include + +#if defined(AVMEDIA_DLLIMPLEMENTATION) +#define AVMEDIA_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define AVMEDIA_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define AVMEDIA_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_AVMEDIA_AVMEDIADLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/avmedia/mediaitem.hxx b/include/avmedia/mediaitem.hxx new file mode 100644 index 000000000..bbb5e06e4 --- /dev/null +++ b/include/avmedia/mediaitem.hxx @@ -0,0 +1,169 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_AVMEDIA_MEDIAITEM_HXX +#define INCLUDED_AVMEDIA_MEDIAITEM_HXX + +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::io { class XStream; } +namespace com::sun::star::text { struct GraphicCrop; } +class Graphic; + +enum class AVMediaSetMask +{ + NONE = 0x000, + STATE = 0x001, + DURATION = 0x002, + TIME = 0x004, + LOOP = 0x008, + MUTE = 0x010, + VOLUMEDB = 0x020, + ZOOM = 0x040, + URL = 0x080, + MIME_TYPE = 0x100, + GRAPHIC = 0x200, + CROP = 0x400, + ALL = 0x7ff, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + + +namespace avmedia +{ + + +enum class MediaState +{ + Stop, Play, Pause +}; + + +class AVMEDIA_DLLPUBLIC MediaItem final : public SfxPoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit MediaItem( sal_uInt16 i_nWhich = 0, + AVMediaSetMask nMaskSet = AVMediaSetMask::NONE ); + MediaItem( const MediaItem& rMediaItem ); + virtual ~MediaItem() override; + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual MediaItem* Clone( SfxItemPool* pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreUnit, + MapUnit ePresUnit, + OUString& rText, + const IntlWrapper& rIntl ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + bool merge(const MediaItem& rMediaItem); + + AVMediaSetMask getMaskSet() const; + + bool setState(MediaState eState); + MediaState getState() const; + + bool setDuration(double fDuration); + double getDuration() const; + + bool setTime(double fTime); + double getTime() const; + + bool setLoop(bool bLoop); + bool isLoop() const; + + bool setMute(bool bMute); + bool isMute() const; + + bool setVolumeDB(sal_Int16 nDB); + sal_Int16 getVolumeDB() const; + + bool setZoom(css::media::ZoomLevel eZoom); + ::css::media::ZoomLevel getZoom() const; + + bool setURL(const OUString& rURL, + const OUString& rTempURL, + const OUString& rReferer); + const OUString& getURL() const; + + bool setMimeType(const OUString& rMimeType); + OUString getMimeType() const; + bool setGraphic(const Graphic& rGraphic); + const Graphic & getGraphic() const; + bool setCrop(const css::text::GraphicCrop& rCrop); + const css::text::GraphicCrop& getCrop() const; + const OUString& getTempURL() const; + + const OUString& getReferer() const; + +private: + + struct Impl; + std::unique_ptr m_pImpl; +}; + +typedef ::avmedia::MediaItem avmedia_MediaItem; + +bool AVMEDIA_DLLPUBLIC EmbedMedia( + const ::css::uno::Reference< ::css::frame::XModel>& xModel, + const OUString& rSourceURL, + OUString & o_rEmbeddedURL, + ::css::uno::Reference<::css::io::XInputStream> const& xInputStream = + ::css::uno::Reference<::css::io::XInputStream>()); + +bool AVMEDIA_DLLPUBLIC CreateMediaTempFile( + ::css::uno::Reference<::css::io::XInputStream> const& xInStream, + OUString& o_rTempFileURL, + std::u16string_view rDesiredExtension); + +OUString GetFilename(OUString const& rSourceURL); + +::css::uno::Reference< ::css::io::XStream> CreateStream( + const ::css::uno::Reference< ::css::embed::XStorage>& xStorage, const OUString& rFilename); + +struct AVMEDIA_DLLPUBLIC MediaTempFile +{ + OUString const m_TempFileURL; + MediaTempFile(OUString aURL) + : m_TempFileURL(std::move(aURL)) + {} + ~MediaTempFile(); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/avmedia/mediaplayer.hxx b/include/avmedia/mediaplayer.hxx new file mode 100644 index 000000000..52ecd942e --- /dev/null +++ b/include/avmedia/mediaplayer.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_AVMEDIA_MEDIAPLAYER_HXX +#define INCLUDED_AVMEDIA_MEDIAPLAYER_HXX + +#include +#include +#include +#include + +namespace avmedia +{ + +class AVMEDIA_DLLPUBLIC MediaPlayer final : public SfxChildWindow +{ +public: + MediaPlayer( vcl::Window*, sal_uInt16, SfxBindings*, SfxChildWinInfo* ); + virtual ~MediaPlayer() override; + + SFX_DECL_CHILDWINDOW_WITHID( MediaPlayer ); +}; + +class MediaWindow; + +class AVMEDIA_DLLPUBLIC MediaFloater final : public SfxDockingWindow +{ +public: + + MediaFloater( SfxBindings* pBindings, SfxChildWindow* pCW, vcl::Window* pParent ); + virtual ~MediaFloater() override; + virtual void dispose() override; + + void setURL( const OUString& rURL, const OUString& rReferer, bool bPlayImmediately ); + + void dispatchCurrentURL(); + +private: + + virtual void Resize() override; + virtual void ToggleFloatingMode() override; + + std::unique_ptr mpMediaWindow; +}; + +inline MediaFloater * getMediaFloater() { + SfxViewFrame * cur = SfxViewFrame::Current(); + if (cur != nullptr) { + SfxChildWindow * win = cur->GetChildWindow( + MediaPlayer::GetChildWindowId()); + if (win != nullptr) { + return static_cast(win->GetWindow()); + } + } + return nullptr; +} + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/avmedia/mediatoolbox.hxx b/include/avmedia/mediatoolbox.hxx new file mode 100644 index 000000000..434d202ca --- /dev/null +++ b/include/avmedia/mediatoolbox.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_AVMEDIA_MEDIATOOLBOX_HXX +#define INCLUDED_AVMEDIA_MEDIATOOLBOX_HXX + +#include +#include + +namespace avmedia +{ + +class MediaItem; + +class AVMEDIA_DLLPUBLIC MediaToolBoxControl final : public SfxToolBoxControl +{ + friend class MediaToolBoxControl_Impl; + +public: + + SFX_DECL_TOOLBOX_CONTROL(); + + MediaToolBoxControl( sal_uInt16 nSlotId, ToolBoxItemId nId, ToolBox& rTbX ); + virtual ~MediaToolBoxControl() override; + + virtual void StateChangedAtToolBoxControl( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState ) override; + virtual VclPtr CreateItemWindow( vcl::Window* pParent ) override; + +private: + + AVMEDIA_DLLPRIVATE void implUpdateMediaControl(); + AVMEDIA_DLLPRIVATE void implExecuteMediaControl( const MediaItem& rItem ); +}; + +} + +#endif // INCLUDED_AVMEDIA_MEDIATOOLBOX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/avmedia/mediawindow.hxx b/include/avmedia/mediawindow.hxx new file mode 100644 index 000000000..e8515d77f --- /dev/null +++ b/include/avmedia/mediawindow.hxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_AVMEDIA_MEDIAWINDOW_HXX +#define INCLUDED_AVMEDIA_MEDIAWINDOW_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME -1.0 + +namespace com::sun::star::frame { class XDispatchProvider; } +namespace com::sun::star::graphic { class XGraphic; } +namespace com::sun::star::media { + class XPlayer; + class XPlayerNotifier; +} + +namespace vcl { class Window; } +namespace weld { class Window; } +class KeyEvent; +class MouseEvent; +class CommandEvent; +struct AcceptDropEvent; +struct ExecuteDropEvent; +enum class PointerStyle; + +namespace avmedia +{ + typedef ::std::vector< ::std::pair< OUString, OUString > > FilterNameVector; + + class MediaItem; + + namespace priv { class MediaWindowImpl; } + + typedef cppu::WeakComponentImplHelper PlayerListener_BASE; + + class AVMEDIA_DLLPUBLIC PlayerListener final : public cppu::BaseMutex, public PlayerListener_BASE + { + private: + css::uno::Reference m_xNotifier; + std::function&)> m_aFn; + + using WeakComponentImplHelperBase::disposing; + public: + PlayerListener(std::function&)> fn); + virtual void SAL_CALL dispose() override; + virtual ~PlayerListener() override; + + virtual void SAL_CALL preferredPlayerWindowSizeAvailable(const css::lang::EventObject& rSource) override; + virtual void SAL_CALL disposing(const css::lang::EventObject& rSource) override; + + void startListening(const css::uno::Reference& rNotifier); + void stopListening(); + + void callPlayerWindowSizeAvailable(const css::uno::Reference& rPlayer) { m_aFn(rPlayer); } + }; + + class AVMEDIA_DLLPUBLIC MediaWindow + { + public: + MediaWindow( vcl::Window* parent, bool bInternalMediaControl ); + virtual ~MediaWindow(); + + void setURL( const OUString& rURL, const OUString& rReferer ); + const OUString& getURL() const; + + bool isValid() const; + Size getPreferredSize() const; + + vcl::Window* getWindow() const; + + void setPosSize( const tools::Rectangle& rNewRect ); + + void setPointer( PointerStyle aPointer ); + + bool start(); + + void updateMediaItem( MediaItem& rItem ) const; + void executeMediaItem( const MediaItem& rItem ); + + void show(); + void hide(); + bool isVisible() const; + + public: + + virtual void MouseMove( const MouseEvent& rMEvt ); + virtual void MouseButtonDown( const MouseEvent& rMEvt ); + virtual void MouseButtonUp( const MouseEvent& rMEvt ); + + virtual void KeyInput( const KeyEvent& rKEvt ); + virtual void KeyUp( const KeyEvent& rKEvt ); + + virtual void Command( const CommandEvent& rCEvt ); + + virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); + virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); + + virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel ); + + public: + + static FilterNameVector getMediaFilters(); + /// @param o_pbLink if not 0, this is an "insert" dialog: display link + /// checkbox and store its state in *o_pbLink + static bool executeMediaURLDialog(weld::Window* pParent, OUString& rURL, bool *const o_pbLink); + static void executeFormatErrorBox(weld::Window* pParent); + static bool isMediaURL(std::u16string_view rURL, const OUString& rReferer, bool bDeep = false, + rtl::Reference xPreferredPixelSizeListener = nullptr); + + static css::uno::Reference< css::media::XPlayer > createPlayer( const OUString& rURL, const OUString& rReferer, const OUString* pMimeType = nullptr ); + + static css::uno::Reference + grabFrame(const css::uno::Reference& rPlayer, + const css::uno::Reference& rGraphic = nullptr); + + static css::uno::Reference< css::graphic::XGraphic > grabFrame(const OUString& rURL, const OUString& rReferer, + const OUString& sMimeType, rtl::Reference xPreferredPixelSizeListener); + + static void dispatchInsertAVMedia(const css::uno::Reference&, + const css::awt::Size& rSize, const OUString& rURL, bool bLink); + + private: + MediaWindow(const MediaWindow&) = delete; + MediaWindow& operator =( const MediaWindow& ) = delete; + + VclPtr mpImpl; + }; + +} + +#endif // INCLUDED_AVMEDIA_MEDIAWINDOW_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/DrawCommands.hxx b/include/basegfx/DrawCommands.hxx new file mode 100644 index 000000000..14d3ad245 --- /dev/null +++ b/include/basegfx/DrawCommands.hxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_BASEGFX_DRAWCOMMANDS_H +#define INCLUDED_BASEGFX_DRAWCOMMANDS_H + +#include +#include +#include + +#include +#include +#include +#include + +namespace gfx +{ +class DrawBase; + +class DrawCommand +{ +public: + std::vector> maChildren; +}; + +enum class DrawCommandType +{ + Root, + Rectangle, + Path +}; + +enum class GradientType +{ + Linear +}; + +class GradientStop +{ +public: + basegfx::BColor maColor; + float mfOffset; + float mfOpacity; +}; + +class GradientInfo +{ +public: + GradientType meType; + + std::vector maGradientStops; + + GradientInfo(GradientType eType) + : meType(eType) + { + } +}; + +class LinearGradientInfo : public GradientInfo +{ +public: + LinearGradientInfo() + : GradientInfo(GradientType::Linear) + , x1(0.0) + , y1(0.0) + , x2(0.0) + , y2(0.0) + { + } + + double x1; + double y1; + double x2; + double y2; + + basegfx::B2DHomMatrix maMatrix; +}; + +class DrawBase : public DrawCommand +{ +private: + DrawCommandType meType; + +public: + DrawBase(DrawCommandType eType) + : meType(eType) + { + } + + DrawCommandType getType() const { return meType; } +}; + +class DrawRoot : public DrawBase +{ +public: + basegfx::B2DRange maRectangle; + + DrawRoot() + : DrawBase(DrawCommandType::Root) + { + } +}; + +class DrawRectangle : public DrawBase +{ +public: + basegfx::B2DRange maRectangle; + double mnRx; + double mnRy; + + double mnStrokeWidth; + double mnOpacity; + std::shared_ptr mpFillColor; + std::shared_ptr mpStrokeColor; + std::shared_ptr mpFillGradient; + + DrawRectangle(basegfx::B2DRange const& rRectangle) + : DrawBase(DrawCommandType::Rectangle) + , maRectangle(rRectangle) + , mnRx(1.0) + , mnRy(1.0) + , mnStrokeWidth(1.0) + , mnOpacity(1.0) + { + } +}; + +class DrawPath : public DrawBase +{ +public: + basegfx::B2DPolyPolygon maPolyPolygon; + + double mnStrokeWidth; + double mnOpacity; + std::shared_ptr mpFillColor; + std::shared_ptr mpStrokeColor; + std::shared_ptr mpFillGradient; + + DrawPath(basegfx::B2DPolyPolygon aPolyPolygon) + : DrawBase(DrawCommandType::Path) + , maPolyPolygon(std::move(aPolyPolygon)) + , mnStrokeWidth(1.0) + , mnOpacity(1.0) + { + } +}; + +} // end namespace gfx + +#endif // INCLUDED_BASEGFX_DRAWCOMMANDS_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/basegfxdllapi.h b/include/basegfx/basegfxdllapi.h new file mode 100644 index 000000000..b1ef1709b --- /dev/null +++ b/include/basegfx/basegfxdllapi.h @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASEGFX_BASEGFXDLLAPI_H +#define INCLUDED_BASEGFX_BASEGFXDLLAPI_H + +#include + +#if defined BASEGFX_STATICLIBRARY + +#define BASEGFX_DLLPUBLIC +#define BASEGFX_DLLPRIVATE + +#else /*BASEGFX_STATICLIBRARY*/ + +#if defined BASEGFX_DLLIMPLEMENTATION +#define BASEGFX_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define BASEGFX_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define BASEGFX_DLLPRIVATE SAL_DLLPRIVATE + +#endif /*BASEGFX_STATICLIBRARY*/ + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/color/bcolor.hxx b/include/basegfx/color/bcolor.hxx new file mode 100644 index 000000000..d8788b1cf --- /dev/null +++ b/include/basegfx/color/bcolor.hxx @@ -0,0 +1,185 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +#include +#include + +namespace basegfx +{ + /** Base Color class with three double values + + This class derives all operators and common handling for + a 3D data class from B3DTuple. All necessary extensions + which are special for colors will be added here. + + @see B3DTuple + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColor : public B3DTuple + { + public: + /** Create a Color with red, green and blue components from [0.0 to 1.0] + + The color is initialized to (0.0, 0.0, 0.0) + */ + BColor() + {} + + /** Create a 3D Color + + @param fRed + @param fGreen + @param fBlue + These parameters are used to initialize the red, green and blue intensities of the color + */ + BColor(double fRed, double fGreen, double fBlue) + : B3DTuple(fRed, fGreen, fBlue) + {} + + /** Create a 3D Color + + @param fLuminosity + The parameter is used to initialize the red, green and blue intensities of the color + */ + explicit BColor(double fLuminosity) + : B3DTuple(fLuminosity, fLuminosity, fLuminosity) + {} + + /** constructor with tuple to allow copy-constructing + from B3DTuple-based classes + */ + BColor(const ::basegfx::B3DTuple& rTuple) + : B3DTuple(rTuple) + {} + + // data access read + double getRed() const { return mfX; } + double getGreen() const { return mfY; } + double getBlue() const { return mfZ; } + + // data access write + void setRed(double fNew) { mfX = fNew; } + void setGreen(double fNew) { mfY = fNew; } + void setBlue(double fNew) { mfZ = fNew; } + + /** *=operator to allow usage from BColor, too + */ + BColor& operator*=( const BColor& rPnt ) + { + mfX *= rPnt.mfX; + mfY *= rPnt.mfY; + mfZ *= rPnt.mfZ; + return *this; + } + + /** *=operator to allow usage from BColor, too + */ + BColor& operator*=(double t) + { + mfX *= t; + mfY *= t; + mfZ *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B3DTuple calculations + */ + BColor& operator=( const ::basegfx::B3DTuple& rVec ) + { + mfX = rVec.getX(); + mfY = rVec.getY(); + mfZ = rVec.getZ(); + return *this; + } + + // luminance + double luminance() const + { + const double fRedWeight(77.0 / 256.0); // 0.30 + const double fGreenWeight(151.0 / 256.0); // 0.59 + const double fBlueWeight(28.0 / 256.0); // 0.11 + + return (mfX * fRedWeight + mfY * fGreenWeight + mfZ * fBlueWeight); + } + + // distances in color space + double getDistanceRed(const BColor& rColor) const { return (getRed() > rColor.getRed() ? getRed() - rColor.getRed() : rColor.getRed() - getRed()); } + double getDistanceGreen(const BColor& rColor) const { return (getGreen() > rColor.getGreen() ? getGreen() - rColor.getGreen() : rColor.getGreen() - getGreen()); } + double getDistanceBlue(const BColor& rColor) const { return (getBlue() > rColor.getBlue() ? getBlue() - rColor.getBlue() : rColor.getBlue() - getBlue()); } + + double getDistance(const BColor& rColor) const + { + const double fDistR(getDistanceRed(rColor)); + const double fDistG(getDistanceGreen(rColor)); + const double fDistB(getDistanceBlue(rColor)); + + return sqrt(fDistR * fDistR + fDistG * fDistG + fDistB * fDistB); + } + + double getMaximumDistance(const BColor& rColor) const + { + const double fDistR(getDistanceRed(rColor)); + const double fDistG(getDistanceGreen(rColor)); + const double fDistB(getDistanceBlue(rColor)); + + double fRetval(std::max(fDistR, fDistG)); + return std::max(fRetval, fDistB); + } + + // clamp color to [0.0..1.0] values in all three intensity components + BColor& clamp() + { + mfX = std::clamp(mfX, 0.0, 1.0); + mfY = std::clamp(mfY, 0.0, 1.0); + mfZ = std::clamp(mfZ, 0.0, 1.0); + return *this; + } + + void invert() + { + mfX = 1.0 - mfX; + mfY = 1.0 - mfY; + mfZ = 1.0 - mfZ; + } + + static const BColor& getEmptyBColor() + { + return static_cast( ::basegfx::B3DTuple::getEmptyTuple() ); + } + + }; + + template + std::basic_ostream & operator <<( + std::basic_ostream & stream, BColor const & color) + { + return stream + << '[' << color.getRed() << ", " << color.getGreen() << ", " + << color.getBlue() << ']'; + } +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/color/bcolormodifier.hxx b/include/basegfx/color/bcolormodifier.hxx new file mode 100644 index 000000000..b39849ed7 --- /dev/null +++ b/include/basegfx/color/bcolormodifier.hxx @@ -0,0 +1,336 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +#include + +#include +#include + +namespace basegfx +{ + /** base class to define color modifications + + The basic idea is to have instances of color modifiers where each + of these can be asked to get a modified version of a color. This + can be as easy as to return a fixed color, but may also do any + other computation based on the given source color and the local + algorithm to apply. + + This base implementation defines the abstract base class. Every + derivation offers another color blending effect, when needed with + parameters for that blending defined as members. + + As long as aw080 is not applied, an operator== is needed to implement + the operator== of the primitive based on this instances. + + For the exact definitions of the color blending applied refer to the + implementation of the method getModifiedColor + + BColorModifier is not copyable (no copy constructor, no assignment + operator); local values cannot be changed after construction. The + instances are cheap and the idea is to create them on demand. To + be able to reuse these as much as possible, a define for a + std::shared_ptr named BColorModifierSharedPtr exists below. + All usages should handle instances of BColorModifier encapsulated + into these shared pointers. + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColorModifier + { + private: + BColorModifier(const BColorModifier&) = delete; + BColorModifier& operator=(const BColorModifier&) = delete; + protected: + // no one is allowed to incarnate the abstract base class + // except derivations + BColorModifier() {} + + public: + // no one should directly destroy it; all incarnations should be + // handled in a std::shared_ptr of type BColorModifierSharedPtr + virtual ~BColorModifier(); + + // compare operator + virtual bool operator==(const BColorModifier& rCompare) const = 0; + bool operator!=(const BColorModifier& rCompare) const + { + return !(operator==(rCompare)); + } + + // compute modified color + virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const = 0; + }; + + /** convert color to gray + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColorModifier_gray final : public BColorModifier + { + public: + BColorModifier_gray() + { + } + + virtual ~BColorModifier_gray() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** invert color + + returns a color where red green and blue are inverted using 1.0 - n + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColorModifier_invert final : public BColorModifier + { + public: + BColorModifier_invert() + { + } + + virtual ~BColorModifier_invert() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** convert to alpha based on luminance + + returns a color where red green and blue are first weighted and added + to build a luminance value which is then inverted and used for red, + green and blue. The weights are r * 0.2125 + g * 0.7154 + b * 0.0721. + This derivation is used for the svg importer and does exactly what SVG + defines for this needed case. + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColorModifier_luminance_to_alpha final : public BColorModifier + { + public: + BColorModifier_luminance_to_alpha() + { + } + + virtual ~BColorModifier_luminance_to_alpha() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** replace color + + does not use the source color at all, but always returns the + given color, replacing everything. Useful e.g. for unified shadow + creation + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColorModifier_replace final : public BColorModifier + { + private: + ::basegfx::BColor maBColor; + + public: + BColorModifier_replace(const ::basegfx::BColor& rBColor) + : maBColor(rBColor) + { + } + + virtual ~BColorModifier_replace() override; + + // data access + const ::basegfx::BColor& getBColor() const { return maBColor; } + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** interpolate color + + returns an interpolated color mixed by the given value (f) in the range + [0.0 .. 1.0] and the given color (col) as follows: + + col * (1 - f) + aSourceColor * f + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC BColorModifier_interpolate final : public BColorModifier + { + private: + ::basegfx::BColor maBColor; + double mfValue; + + public: + BColorModifier_interpolate(const ::basegfx::BColor& rBColor, double fValue) + : maBColor(rBColor), + mfValue(fValue) + { + } + + virtual ~BColorModifier_interpolate() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** convert color to black and white + + returns black when the luminance of the given color is less than + the given threshold value in the range [0.0 .. 1.0], else white + */ + class SAL_WARN_UNUSED UNLESS_MERGELIBS(BASEGFX_DLLPUBLIC) BColorModifier_black_and_white final : public BColorModifier + { + private: + double mfValue; + + public: + BColorModifier_black_and_white(double fValue) + : mfValue(fValue) + { + } + + virtual ~BColorModifier_black_and_white() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** gamma correction + + Input is a gamma correction value in the range ]0.0 .. 10.0]; the + color values get corrected using + + col(r,g,b) = clamp(pow(col(r,g,b), 1.0 / gamma), 0.0, 1.0) + */ + class SAL_WARN_UNUSED UNLESS_MERGELIBS(BASEGFX_DLLPUBLIC) BColorModifier_gamma final : public BColorModifier + { + private: + double mfValue; + double mfInvValue; + + bool mbUseIt : 1; + + public: + BColorModifier_gamma(double fValue); + + virtual ~BColorModifier_gamma() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /** Red, Green, Blue, Luminance and Contrast correction + + Input are percent values from [-1.0 .. 1-0] which correspond to -100% to 100% + correction of Red, Green, Blue, Luminance or Contrast. 0.0 means no change of + the corresponding channel. All these are combined (but can be used single) to + - be able to cover a bigger change range utilizing the combination + - allow execution by a small, common, precalculated table + */ + class SAL_WARN_UNUSED UNLESS_MERGELIBS(BASEGFX_DLLPUBLIC) BColorModifier_RGBLuminanceContrast final : public BColorModifier + { + private: + double mfRed; + double mfGreen; + double mfBlue; + double mfLuminance; + double mfContrast; + + double mfContrastOff; + double mfRedOff; + double mfGreenOff; + double mfBlueOff; + + bool mbUseIt : 1; + + public: + BColorModifier_RGBLuminanceContrast(double fRed, double fGreen, double fBlue, double fLuminance, double fContrast); + + virtual ~BColorModifier_RGBLuminanceContrast() override; + + // compare operator + SAL_DLLPRIVATE virtual bool operator==(const BColorModifier& rCompare) const override; + + // compute modified color + SAL_DLLPRIVATE virtual ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& aSourceColor) const override; + }; + + /// typedef to allow working with shared instances of BColorModifier + /// for the whole mechanism + typedef std::shared_ptr< BColorModifier > BColorModifierSharedPtr; + + /** Class to hold a stack of BColorModifierSharedPtrs and to get the modified color with + applying all existing entry changes as defined in the stack. Instances of BColorModifier + can be pushed and popped to change the stack. + + All references to BColorModifier members use shared pointers, thus instances of + BColorModifierStack can be copied by the default mechanisms if needed. + */ + class BASEGFX_DLLPUBLIC BColorModifierStack final + { + ::std::vector< BColorModifierSharedPtr > maBColorModifiers; + + public: + sal_uInt32 count() const + { + return maBColorModifiers.size(); + } + + const BColorModifierSharedPtr& getBColorModifier(sal_uInt32 nIndex) const + { + OSL_ENSURE(nIndex < count(), "BColorModifierStack: Access out of range (!)"); + return maBColorModifiers[nIndex]; + } + + // get the color in its modified form by applying all existing BColorModifiers, + // from back to front (the newest first) + ::basegfx::BColor getModifiedColor(const ::basegfx::BColor& rSource) const; + + void push(const BColorModifierSharedPtr& rNew) + { + maBColorModifiers.push_back(rNew); + } + + void pop() + { + maBColorModifiers.pop_back(); + } + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/color/bcolortools.hxx b/include/basegfx/color/bcolortools.hxx new file mode 100644 index 000000000..8af2b7c94 --- /dev/null +++ b/include/basegfx/color/bcolortools.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace basegfx +{ +class BColor; +} + +namespace basegfx::utils +{ +/// Transform from RGB to HSL +BASEGFX_DLLPUBLIC BColor rgb2hsl(const BColor& rRGBColor); +/// Transform from HSL to RGB +BASEGFX_DLLPUBLIC BColor hsl2rgb(const BColor& rHSLColor); + +/// Transform from RGB to HSV +BASEGFX_DLLPUBLIC BColor rgb2hsv(const BColor& rRGBColor); +/// Transform from HSV to RGB +BASEGFX_DLLPUBLIC BColor hsv2rgb(const BColor& rHSVColor); + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/curve/b2dbeziertools.hxx b/include/basegfx/curve/b2dbeziertools.hxx new file mode 100644 index 000000000..b9c91fac0 --- /dev/null +++ b/include/basegfx/curve/b2dbeziertools.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + + +// predefines + +namespace basegfx +{ + class B2DCubicBezier; +} + + +namespace basegfx +{ + class BASEGFX_DLLPUBLIC B2DCubicBezierHelper + { + private: + ::std::vector< double > maLengthArray; + sal_uInt32 mnEdgeCount; + + public: + explicit B2DCubicBezierHelper(const B2DCubicBezier& rBase, sal_uInt32 nDivisions = 9); + + double getLength() const { if(!maLengthArray.empty()) return maLengthArray[maLengthArray.size() - 1]; else return 0.0; } + double distanceToRelative(double fDistance) const; + }; +} // end of namespace basegfx + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/curve/b2dcubicbezier.hxx b/include/basegfx/curve/b2dcubicbezier.hxx new file mode 100644 index 000000000..4d8d9406e --- /dev/null +++ b/include/basegfx/curve/b2dcubicbezier.hxx @@ -0,0 +1,198 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ + class B2DPolygon; +} + +namespace basegfx +{ + class BASEGFX_DLLPUBLIC B2DCubicBezier + { + private: + B2DPoint maStartPoint; + B2DPoint maEndPoint; + B2DPoint maControlPointA; + B2DPoint maControlPointB; + + public: + B2DCubicBezier(); + B2DCubicBezier(const B2DCubicBezier& rBezier); + B2DCubicBezier(const B2DPoint& rStart, const B2DPoint& rControlPointA, const B2DPoint& rControlPointB, const B2DPoint& rEnd); + + // assignment operator + B2DCubicBezier& operator=(const B2DCubicBezier& rBezier); + + // compare operators + bool operator==(const B2DCubicBezier& rBezier) const; + bool operator!=(const B2DCubicBezier& rBezier) const; + bool equal(const B2DCubicBezier& rBezier) const; + + // test if vectors are used + bool isBezier() const; + + // test if contained bezier is trivial and reset vectors accordingly + void testAndSolveTrivialBezier(); + + /** get length of edge + + This method handles beziers and simple edges. For + beziers, the deviation describes the maximum allowed + deviation from the real edge length. The default + allows a deviation of 1% from the correct length. + + For beziers, there is no direct way to get the length, + thus this method may subdivide the bezier edge and may + not be cheap. + + @param fDeviation + The maximal allowed deviation between correct length + and bezier edge length + + @return + The length of the edge + */ + double getLength(double fDeviation = 0.01) const; + + // get distance between start and end point + SAL_DLLPRIVATE double getEdgeLength() const; + + // get length of control polygon + SAL_DLLPRIVATE double getControlPolygonLength() const; + + // data interface + const B2DPoint& getStartPoint() const { return maStartPoint; } + void setStartPoint(const B2DPoint& rValue) { maStartPoint = rValue; } + + const B2DPoint& getEndPoint() const { return maEndPoint; } + void setEndPoint(const B2DPoint& rValue) { maEndPoint = rValue; } + + const B2DPoint& getControlPointA() const { return maControlPointA; } + void setControlPointA(const B2DPoint& rValue) { maControlPointA = rValue; } + + const B2DPoint& getControlPointB() const { return maControlPointB; } + void setControlPointB(const B2DPoint& rValue) { maControlPointB = rValue; } + + /** get the tangent in point t + + This method handles all the exceptions, e.g. when control point + A is equal to start point and/or control point B is equal to end + point + + @param t + The bezier index in the range [0.0 .. 1.0]. It will be truncated. + + @return + The tangent vector in point t + */ + B2DVector getTangent(double t) const; + + /** adaptive subdivide by angle criteria + no start point is added, but all necessary created edges + and the end point + #i37443# allow the criteria to get unsharp in recursions + */ + SAL_DLLPRIVATE void adaptiveSubdivideByAngle(B2DPolygon& rTarget, double fAngleBound) const; + + /** #i37443# adaptive subdivide by nCount subdivisions + no start point is added, but all necessary created edges + and the end point + */ + SAL_DLLPRIVATE void adaptiveSubdivideByCount(B2DPolygon& rTarget, sal_uInt32 nCount) const; + + /** Subdivide cubic bezier segment. + + This function adaptively subdivides the bezier + segment into as much straight line segments as necessary, + such that the maximal orthogonal distance from any of the + segments to the true curve is less than the given error + value. + No start point is added, but all necessary created edges + and the end point + + @param rPoly + Output polygon. The subdivided bezier segment is added to + this polygon via B2DPolygon::append(). + + @param rCurve + The cubic bezier curve to subdivide + + @param fDistanceBound + Bound on the maximal distance of the approximation to the + true curve. + */ + void adaptiveSubdivideByDistance(B2DPolygon& rTarget, double fDistanceBound) const; + + // get point at given relative position + B2DPoint interpolatePoint(double t) const; + + // calculate the smallest distance from given point to this cubic bezier segment + // and return the value. The relative position on the segment is returned in rCut. + SAL_DLLPRIVATE double getSmallestDistancePointToBezierSegment(const B2DPoint& rTestPoint, double& rCut) const; + + // do a split at position t and fill both resulting segments + void split(double t, B2DCubicBezier* pBezierA, B2DCubicBezier* pBezierB) const; + + // extract snippet from fStart to fEnd from this bezier + SAL_DLLPRIVATE B2DCubicBezier snippet(double fStart, double fEnd) const; + + // get range including control points + B2DRange getRange() const; + + /** Get the minimum extremum position t + + @param rfResult + Will be changed and might possibly be set to a found split value, which should be in the + range [0.0 .. 1.0]. It will be the smallest current extremum; there may be more + + @return + Returns true if there was at least one extremum found + */ + SAL_DLLPRIVATE bool getMinimumExtremumPosition(double& rfResult) const; + + /** Get all extremum pos of this segment + + This method will calculate all extremum positions of the segment + and add them to rResults if they are in the range ]0.0 .. 1.0[ + + @param rResults + The vector of doubles where the results will be added. Evtl. + existing contents will be removed since an empty vector is a + necessary result to express that there are no extreme positions + anymore. Since there is an upper maximum of 4 values, it makes + sense to use reserve(4) at the vector as preparation. + */ + SAL_DLLPRIVATE void getAllExtremumPositions(::std::vector< double >& rResults) const; + + /// apply transformation given in matrix form + void transform(const basegfx::B2DHomMatrix& rMatrix); + + /// fround content + SAL_DLLPRIVATE void fround(); + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/matrix/b2dhommatrix.hxx b/include/basegfx/matrix/b2dhommatrix.hxx new file mode 100644 index 000000000..d7fa5b442 --- /dev/null +++ b/include/basegfx/matrix/b2dhommatrix.hxx @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + +#include +#include +#include + +namespace basegfx +{ + class B2DTuple; + class Impl2DHomMatrix; + + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B2DHomMatrix + { + public: + typedef o3tl::cow_wrapper< Impl2DHomMatrix > ImplType; + + private: + ImplType mpImpl; + + public: + B2DHomMatrix(); + B2DHomMatrix(const B2DHomMatrix& rMat); + B2DHomMatrix(B2DHomMatrix&& rMat); + ~B2DHomMatrix(); + + /** Convenience creator for declaration of the matrix that is commonly + used by web standards (SVG, CSS, HTML). + + Values a,b,c,d,e,f represent the following values in the matrix: + [a,c,e] [a,c,e] + [b,d,f] or [b,d,f] + [0,0,1] + + */ + static B2DHomMatrix abcdef(double da, double db, double dc, double dd, double de, double df) + { + return B2DHomMatrix(da, dc, de, db, dd, df); + } + + // Convenience accessor for value at 0,0 position in the matrix + double a() const { return get(0,0); } + // Convenience accessor for value at 1,0 position in the matrix + double b() const { return get(1,0); } + // Convenience accessor for value at 0,1 position in the matrix + double c() const { return get(0,1); } + // Convenience accessor for value at 1,1 position in the matrix + double d() const { return get(1,1); } + // Convenience accessor for value at 0,2 position in the matrix + double e() const { return get(0,2); } + // Convenience accessor for value at 1,2 position in the matrix + double f() const { return get(1,2); } + + /** constructor to allow setting all needed values for a 3x2 matrix at once. The + parameter f_0x1 e.g. is the same as using set(0, 1, f) + */ + B2DHomMatrix(double f_0x0, double f_0x1, double f_0x2, double f_1x0, double f_1x1, double f_1x2); + + double get(sal_uInt16 nRow, sal_uInt16 nColumn) const; + void set(sal_uInt16 nRow, sal_uInt16 nColumn, double fValue); + + /** allow setting all needed values for a 3x2 matrix in one call. The + parameter f_0x1 e.g. is the same as using set(0, 1, f) + */ + void set3x2(double f_0x0, double f_0x1, double f_0x2, double f_1x0, double f_1x1, double f_1x2); + + // test if last line is default to see if last line needs to be + // involved in calculations + bool isLastLineDefault() const; + + // reset to a standard matrix + bool isIdentity() const; + void identity(); + + bool isInvertible() const; + bool invert(); + + void rotate(double fRadiant); + + void translate(double fX, double fY); + void translate(const B2DTuple& rTuple); + + void scale(double fX, double fY); + void scale(const B2DTuple& rTuple); + + // Shearing-Matrices + void shearX(double fSx); + void shearY(double fSy); + + B2DHomMatrix& operator+=(const B2DHomMatrix& rMat); + B2DHomMatrix& operator-=(const B2DHomMatrix& rMat); + + bool operator==(const B2DHomMatrix& rMat) const; + bool operator!=(const B2DHomMatrix& rMat) const; + + B2DHomMatrix& operator*=(double fValue); + B2DHomMatrix& operator/=(double fValue); + + // matrix multiplication from the left to the local + B2DHomMatrix& operator*=(const B2DHomMatrix& rMat); + + // assignment operator + B2DHomMatrix& operator=(const B2DHomMatrix& rMat); + B2DHomMatrix& operator=(B2DHomMatrix&& rMat); + + // Help routine to decompose given homogen 3x3 matrix to components. A correction of + // the components is done to avoid inaccuracies. + bool decompose(B2DTuple& rScale, B2DTuple& rTranslate, double& rRotate, double& rShearX) const; + }; + + inline B2DHomMatrix operator*(const B2DHomMatrix& rMatA, const B2DHomMatrix& rMatB) + { + B2DHomMatrix aMul(rMatB); + aMul *= rMatA; + return aMul; + } + + template + std::basic_ostream & operator <<( + std::basic_ostream & stream, B2DHomMatrix const & matrix) + { + return stream + << '[' << matrix.get(0, 0) << ' ' << matrix.get(0, 1) << ' ' + << matrix.get(0, 2) << "; " << matrix.get(1, 0) << ' ' + << matrix.get(1, 1) << ' ' << matrix.get(1, 2) << "; " + << matrix.get(2, 0) << ' ' << matrix.get(2, 1) << ' ' + << matrix.get(2, 2) << ']'; + } +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/matrix/b2dhommatrixtools.hxx b/include/basegfx/matrix/b2dhommatrixtools.hxx new file mode 100644 index 000000000..9b81f33d2 --- /dev/null +++ b/include/basegfx/matrix/b2dhommatrixtools.hxx @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace basegfx { class B2DRange; } + +namespace basegfx::utils +{ + /** If the rotation angle is an approximate multiple of pi/2, + force fSin/fCos to -1/0/1, to maintain orthogonality (which + might also be advantageous for the other cases, but: for + multiples of pi/2, the exact values _can_ be attained. It + would be largely unintuitive, if a 180 degrees rotation + would introduce slight roundoff errors, instead of exactly + mirroring the coordinate system) + */ + void createSinCosOrthogonal(double& o_rSin, double& rCos, double fRadiant); + + /** Tooling methods for on-the-fly matrix generation e.g. for inline + multiplications + */ + BASEGFX_DLLPUBLIC B2DHomMatrix createScaleB2DHomMatrix(double fScaleX, double fScaleY); + BASEGFX_DLLPUBLIC B2DHomMatrix createShearXB2DHomMatrix(double fShearX); + BASEGFX_DLLPUBLIC B2DHomMatrix createShearYB2DHomMatrix(double fShearY); + BASEGFX_DLLPUBLIC B2DHomMatrix createRotateB2DHomMatrix(double fRadiant); + BASEGFX_DLLPUBLIC B2DHomMatrix createTranslateB2DHomMatrix(double fTranslateX, double fTranslateY); + + /// inline versions for parameters as tuples + inline B2DHomMatrix createScaleB2DHomMatrix(const B2DTuple& rScale) + { + return createScaleB2DHomMatrix(rScale.getX(), rScale.getY()); + } + + inline B2DHomMatrix createTranslateB2DHomMatrix(const B2DTuple& rTranslate) + { + return createTranslateB2DHomMatrix(rTranslate.getX(), rTranslate.getY()); + } + + /** Tooling methods for faster completely combined matrix creation + when scale, shearX, rotation and translation needs to be done in + exactly that order. It's faster since it directly calculates + each matrix value based on a symbolic calculation of the three + matrix multiplications. + Inline versions for parameters as tuples added, too. + */ + BASEGFX_DLLPUBLIC B2DHomMatrix createScaleShearXRotateTranslateB2DHomMatrix( + double fScaleX, double fScaleY, + double fShearX, + double fRadiant, + double fTranslateX, double fTranslateY); + inline B2DHomMatrix createScaleShearXRotateTranslateB2DHomMatrix( + const B2DTuple& rScale, + double fShearX, + double fRadiant, + const B2DTuple& rTranslate) + { + return createScaleShearXRotateTranslateB2DHomMatrix( + rScale.getX(), rScale.getY(), + fShearX, + fRadiant, + rTranslate.getX(), rTranslate.getY()); + } + + BASEGFX_DLLPUBLIC B2DHomMatrix createShearXRotateTranslateB2DHomMatrix( + double fShearX, + double fRadiant, + double fTranslateX, double fTranslateY); + inline B2DHomMatrix createShearXRotateTranslateB2DHomMatrix( + double fShearX, + double fRadiant, + const B2DTuple& rTranslate) + { + return createShearXRotateTranslateB2DHomMatrix( + fShearX, + fRadiant, + rTranslate.getX(), rTranslate.getY()); + } + + BASEGFX_DLLPUBLIC B2DHomMatrix createScaleTranslateB2DHomMatrix( + double fScaleX, double fScaleY, + double fTranslateX, double fTranslateY); + inline B2DHomMatrix createScaleTranslateB2DHomMatrix( + const B2DTuple& rScale, + const B2DTuple& rTranslate) + { + return createScaleTranslateB2DHomMatrix( + rScale.getX(), rScale.getY(), + rTranslate.getX(), rTranslate.getY()); + } + + /// special for the often used case of rotation around a point + BASEGFX_DLLPUBLIC B2DHomMatrix createRotateAroundPoint( + double fPointX, double fPointY, + double fRadiant); + inline B2DHomMatrix createRotateAroundPoint( + const B2DTuple& rPoint, + double fRadiant) + { + return createRotateAroundPoint( + rPoint.getX(), rPoint.getY(), + fRadiant); + } + + /// special for creating a mapping for a Range rotated around it's center + /// while keeping AspectRatio unchanged and staying inside the given Range + /// by optimally using the available space (no overlap or outside allowed) + B2DHomMatrix createRotateAroundCenterKeepAspectRatioStayInsideRange( + const basegfx::B2DRange& rTargetRange, + double fRotate); + + /// special for the case to map from source range to target range + BASEGFX_DLLPUBLIC B2DHomMatrix createSourceRangeTargetRangeTransform( + const B2DRange& rSourceRange, + const B2DRange& rTargetRange); + + /// create based on given CoordinateSystem which is defined by origin and x/yaxis + BASEGFX_DLLPUBLIC B2DHomMatrix createCoordinateSystemTransform( + const B2DPoint& rOrigin, + const B2DVector& rX, + const B2DVector& rY); + + /// get column vector from B2dHomMatrix, e.g. to extract coordinate system origin and x/yaxis + BASEGFX_DLLPUBLIC B2DTuple getColumn(const B2DHomMatrix& rMatrix, sal_uInt16 nCol); + + + class BASEGFX_DLLPUBLIC B2DHomMatrixBufferedDecompose + { + private: + B2DVector maScale; + B2DVector maTranslate; + double mfRotate; + double mfShearX; + + public: + B2DHomMatrixBufferedDecompose(const B2DHomMatrix& rB2DHomMatrix = B2DHomMatrix()) + : mfRotate(0.0), + mfShearX(0.0) + { + rB2DHomMatrix.decompose(maScale, maTranslate, mfRotate, mfShearX); + } + + // data access + B2DHomMatrix getB2DHomMatrix() const + { + return createScaleShearXRotateTranslateB2DHomMatrix( + maScale, mfShearX, mfRotate, maTranslate); + } + + const B2DVector& getScale() const { return maScale; } + const B2DVector& getTranslate() const { return maTranslate; } + double getRotate() const { return mfRotate; } + double getShearX() const { return mfShearX; } + }; + + class BASEGFX_DLLPUBLIC B2DHomMatrixBufferedOnDemandDecompose + { + private: + B2DHomMatrix maB2DHomMatrix; + B2DVector maScale; + B2DVector maTranslate; + double mfRotate; + double mfShearX; + + bool mbDecomposed : 1; + + void impCheckDecompose() + { + if(!mbDecomposed) + { + maB2DHomMatrix.decompose(maScale, maTranslate, mfRotate, mfShearX); + mbDecomposed = true; + } + } + + public: + B2DHomMatrixBufferedOnDemandDecompose(B2DHomMatrix aB2DHomMatrix = B2DHomMatrix()) + : maB2DHomMatrix(std::move(aB2DHomMatrix)), + mfRotate(0.0), + mfShearX(0.0), + mbDecomposed(false) + { + } + + // data access + const B2DHomMatrix& getB2DHomMatrix() const { return maB2DHomMatrix; } + const B2DVector& getScale() const { const_cast< B2DHomMatrixBufferedOnDemandDecompose* >(this)->impCheckDecompose(); return maScale; } + const B2DVector& getTranslate() const { const_cast< B2DHomMatrixBufferedOnDemandDecompose* >(this)->impCheckDecompose(); return maTranslate; } + double getRotate() const { const_cast< B2DHomMatrixBufferedOnDemandDecompose* >(this)->impCheckDecompose(); return mfRotate; } + double getShearX() const { const_cast< B2DHomMatrixBufferedOnDemandDecompose* >(this)->impCheckDecompose(); return mfShearX; } + }; +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/matrix/b3dhommatrix.hxx b/include/basegfx/matrix/b3dhommatrix.hxx new file mode 100644 index 000000000..29603f88e --- /dev/null +++ b/include/basegfx/matrix/b3dhommatrix.hxx @@ -0,0 +1,127 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace basegfx +{ + class B3DTuple; + class Impl3DHomMatrix; + + class BASEGFX_DLLPUBLIC B3DHomMatrix + { + public: + typedef o3tl::cow_wrapper< Impl3DHomMatrix, o3tl::ThreadSafeRefCountingPolicy > ImplType; + + private: + ImplType mpImpl; + + public: + B3DHomMatrix(); + B3DHomMatrix(const B3DHomMatrix& rMat); + B3DHomMatrix(B3DHomMatrix&& rMat); + ~B3DHomMatrix(); + + double get(sal_uInt16 nRow, sal_uInt16 nColumn) const; + void set(sal_uInt16 nRow, sal_uInt16 nColumn, double fValue); + + // test if last line is default to see if last line needs to be + // involved in calculations + bool isLastLineDefault() const; + + bool isIdentity() const; + /// Reset to the identity matrix + void identity(); + + /// Invert the matrix (if possible) + void invert(); + + /// Calc the matrix determinant + double determinant() const; + + /// Rotation + void rotate(double fAngleX,double fAngleY,double fAngleZ); + void rotate(const B3DTuple& rRotation); + + /// Translation + void translate(double fX, double fY, double fZ); + void translate(const B3DTuple& rTranslation); + + /// Scaling + void scale(double fX, double fY, double fZ); + void scale(const B3DTuple& rScale); + + // Shearing-Matrices + void shearXY(double fSx, double fSy); + void shearXZ(double fSx, double fSz); + + // Projection matrices, used for converting between eye and + // clip coordinates + void frustum(double fLeft = -1.0, double fRight = 1.0, + double fBottom = -1.0, double fTop = 1.0, + double fNear = 0.001, double fFar = 1.0); + + void ortho(double fLeft = -1.0, double fRight = 1.0, + double fBottom = -1.0, double fTop = 1.0, + double fNear = 0.0, double fFar = 1.0); + + // build orientation matrix + void orientation( + const B3DPoint& rVRP = B3DPoint(0.0,0.0,1.0), + B3DVector aVPN = B3DVector(0.0,0.0,1.0), + B3DVector aVUV = B3DVector(0.0,1.0,0.0)); + + // addition, subtraction + B3DHomMatrix& operator+=(const B3DHomMatrix& rMat); + B3DHomMatrix& operator-=(const B3DHomMatrix& rMat); + + // comparison + bool operator==(const B3DHomMatrix& rMat) const; + bool operator!=(const B3DHomMatrix& rMat) const; + + // multiplication, division by constant value + B3DHomMatrix& operator*=(double fValue); + B3DHomMatrix& operator/=(double fValue); + + // matrix multiplication (from the left) + B3DHomMatrix& operator*=(const B3DHomMatrix& rMat); + + // assignment operator + B3DHomMatrix& operator=(const B3DHomMatrix& rMat); + B3DHomMatrix& operator=(B3DHomMatrix&& rMat); + + // decomposition + void decompose(B3DTuple& rScale, B3DTuple& rTranslate, B3DTuple& rRotate, B3DTuple& rShear) const; + }; + + inline B3DHomMatrix operator*(const B3DHomMatrix& rMatA, const B3DHomMatrix& rMatB) + { + B3DHomMatrix aMul(rMatB); + aMul *= rMatA; + return aMul; + } +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/matrix/b3dhommatrixtools.hxx b/include/basegfx/matrix/b3dhommatrixtools.hxx new file mode 100644 index 000000000..6b65d2460 --- /dev/null +++ b/include/basegfx/matrix/b3dhommatrixtools.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace com::sun::star::drawing +{ +struct HomogenMatrix; +} + +namespace basegfx::utils +{ +/* tooling methods for converting API matrices (drawing::HomogenMatrix) to + B3DHomMatrix. drawing::HomogenMatrix4 is not used by OOo + */ +BASEGFX_DLLPUBLIC B3DHomMatrix +UnoHomogenMatrixToB3DHomMatrix(const com::sun::star::drawing::HomogenMatrix& rMatrixIn); + +BASEGFX_DLLPUBLIC void +B3DHomMatrixToUnoHomogenMatrix(const B3DHomMatrix& rMatrixIn, + com::sun::star::drawing::HomogenMatrix& rMatrixOut); + +} // end of namespace basegfx::tools + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/numeric/ftools.hxx b/include/basegfx/numeric/ftools.hxx new file mode 100644 index 000000000..14deaa059 --- /dev/null +++ b/include/basegfx/numeric/ftools.hxx @@ -0,0 +1,209 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + + +// fTools defines + +namespace basegfx +{ + /** Round double to nearest integer + + @return the nearest integer + */ + inline sal_Int32 fround( double fVal ) + { + if (fVal >= std::numeric_limits::max() - .5) + return std::numeric_limits::max(); + else if (fVal <= std::numeric_limits::min() + .5) + return std::numeric_limits::min(); + return fVal > 0.0 ? static_cast( fVal + .5 ) : static_cast( fVal - .5 ); + } + + /** Round double to nearest integer + + @return the nearest 64 bit integer + */ + inline sal_Int64 fround64( double fVal ) + { + return fVal > 0.0 ? static_cast( fVal + .5 ) : -static_cast( -fVal + .5 ); + } + + /** Prune a small epsilon range around zero. + + Use this method e.g. for calculating scale values. There, it + is usually advisable not to set a scaling to 0.0, because that + yields singular transformation matrices. + + @param fVal + An arbitrary, but finite and valid number + + @return either fVal, or a small value slightly above (when + fVal>0) or below (when fVal<0) zero. + */ + inline double pruneScaleValue( double fVal ) + { + if(fVal < 0.0) + return std::min(fVal, -0.00001); + else + return std::max(fVal, 0.00001); + } + + /** Convert value from degrees to radians + */ + template constexpr double deg2rad( double v ) + { + // divide first, to get exact values for v being a multiple of + // 90 degrees + return v / (90.0 * DegMultiple) * M_PI_2; + } + + /** Convert value radians to degrees + */ + template constexpr double rad2deg( double v ) + { + // divide first, to get exact values for v being a multiple of + // pi/2 + return v / M_PI_2 * (90.0 * DegMultiple); + } + + /** Snap v to nearest multiple of fStep, from negative and + positive side. + + Examples: + + snapToNearestMultiple(-0.1, 0.5) = 0.0 + snapToNearestMultiple(0.1, 0.5) = 0.0 + snapToNearestMultiple(0.25, 0.5) = 0.0 + snapToNearestMultiple(0.26, 0.5) = 0.5 + */ + BASEGFX_DLLPUBLIC double snapToNearestMultiple(double v, const double fStep); + + /** Snap v to the range [0.0 .. fWidth] using modulo + */ + double snapToZeroRange(double v, double fWidth); + + /** Snap v to the range [fLow .. fHigh] using modulo + */ + double snapToRange(double v, double fLow, double fHigh); + + /** return fValue with the sign of fSignCarrier, thus evtl. changed + */ + inline double copySign(double fValue, double fSignCarrier) + { +#ifdef _WIN32 + return _copysign(fValue, fSignCarrier); +#else + return copysign(fValue, fSignCarrier); +#endif + } + + /** RotateFlyFrame3: Normalize to range defined by [0.0 ... fRange[, independent + if v is positive or negative. + + Examples: + + normalizeToRange(0.5, -1.0) = 0.0 + normalizeToRange(0.5, 0.0) = 0.0 + normalizeToRange(0.5, 1.0) = 0.5 + normalizeToRange(-0.5, 1.0) = 0.5 + normalizeToRange(-0.3, 1.0) = 0.7 + normalizeToRange(-0.7, 1.0) = 0.3 + normalizeToRange(3.5, 1.0) = 0.5 + normalizeToRange(3.3, 1.0) = 0.3 + normalizeToRange(3.7, 1.0) = 0.7 + normalizeToRange(-3.5, 1.0) = 0.5 + normalizeToRange(-3.3, 1.0) = 0.7 + normalizeToRange(-3.7, 1.0) = 0.3 + */ + BASEGFX_DLLPUBLIC double normalizeToRange(double v, const double fRange); + + namespace fTools + { + /// Get threshold value for equalZero and friends + inline double getSmallValue() { return 0.000000001f; } + + /// Compare against small value + template , int> = 0> + inline bool equalZero(const T& rfVal) + { + return (fabs(rfVal) <= getSmallValue()); + } + + /// Compare against given small value + template , int> = 0> + inline bool equalZero(const T& rfVal, const T& rfSmallValue) + { + return (fabs(rfVal) <= rfSmallValue); + } + + template , int> = 0> + inline bool equal(T const& rfValA, T const& rfValB) + { + // changed to approxEqual usage for better numerical correctness + return rtl_math_approxEqual(rfValA, rfValB); + } + + template , int> = 0> + inline bool equal(const T& rfValA, const T& rfValB, const T& rfSmallValue) + { + return (fabs(rfValA - rfValB) <= rfSmallValue); + } + + template , int> = 0> + inline bool less(const T& rfValA, const T& rfValB) + { + return (rfValA < rfValB && !equal(rfValA, rfValB)); + } + + template , int> = 0> + inline bool lessOrEqual(const T& rfValA, const T& rfValB) + { + return (rfValA < rfValB || equal(rfValA, rfValB)); + } + + template , int> = 0> + inline bool more(const T& rfValA, const T& rfValB) + { + return (rfValA > rfValB && !equal(rfValA, rfValB)); + } + + template , int> = 0> + inline bool moreOrEqual(const T& rfValA, const T& rfValB) + { + return (rfValA > rfValB || equal(rfValA, rfValB)); + } + + template , int> = 0> + inline bool betweenOrEqualEither(const T& rfValA, const T& rfValB, const T& rfValC) + { + return (rfValA > rfValB && rfValA < rfValC) || equal(rfValA, rfValB) || equal(rfValA, rfValC); + } + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/pixel/bpixel.hxx b/include/basegfx/pixel/bpixel.hxx new file mode 100644 index 000000000..50209ec2c --- /dev/null +++ b/include/basegfx/pixel/bpixel.hxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ + class BPixel final + { + union + { + struct + { + unsigned mnR : 8; // red intensity + unsigned mnG : 8; // green intensity + unsigned mnB : 8; // blue intensity + unsigned mnA : 8; // opacity, 0 == full transparence + } maRGBA; + + struct + { + unsigned mnValue : 32; // all values + } maCombinedRGBA; + } maPixelUnion; + + public: + BPixel() + { + maPixelUnion.maCombinedRGBA.mnValue = 0; + } + + // use explicit here to make sure everyone knows what he is doing. Values range from + // 0..255 integer here. + explicit BPixel(sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue, sal_uInt8 nAlpha) + { + maPixelUnion.maRGBA.mnR = nRed; + maPixelUnion.maRGBA.mnG = nGreen; + maPixelUnion.maRGBA.mnB = nBlue; + maPixelUnion.maRGBA.mnA = nAlpha; + } + + // constructor from BColor which uses double precision color, so change it + // to local integer format. It will also be clamped here. + BPixel(const BColor& rColor, sal_uInt8 nAlpha) + { + maPixelUnion.maRGBA.mnR = sal_uInt8((rColor.getRed() * 255.0) + 0.5); + maPixelUnion.maRGBA.mnG = sal_uInt8((rColor.getGreen() * 255.0) + 0.5); + maPixelUnion.maRGBA.mnB = sal_uInt8((rColor.getBlue() * 255.0) + 0.5); + maPixelUnion.maRGBA.mnA = nAlpha; + } + + // data access read + sal_uInt8 getRed() const { return maPixelUnion.maRGBA.mnR; } + sal_uInt8 getGreen() const { return maPixelUnion.maRGBA.mnG; } + sal_uInt8 getBlue() const { return maPixelUnion.maRGBA.mnB; } + sal_uInt8 getAlpha() const { return maPixelUnion.maRGBA.mnA; } + + // data access write + void setRed(sal_uInt8 nNew) { maPixelUnion.maRGBA.mnR = nNew; } + void setGreen(sal_uInt8 nNew) { maPixelUnion.maRGBA.mnG = nNew; } + void setBlue(sal_uInt8 nNew) { maPixelUnion.maRGBA.mnB = nNew; } + void setAlpha(sal_uInt8 nNew) { maPixelUnion.maRGBA.mnA = nNew; } + + // comparators + bool operator==( const BPixel& rPixel ) const + { + return (rPixel.maPixelUnion.maCombinedRGBA.mnValue == maPixelUnion.maCombinedRGBA.mnValue); + } + + bool operator!=( const BPixel& rPixel ) const + { + return (rPixel.maPixelUnion.maCombinedRGBA.mnValue != maPixelUnion.maCombinedRGBA.mnValue); + } + }; + + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/point/b2dpoint.hxx b/include/basegfx/point/b2dpoint.hxx new file mode 100644 index 000000000..d2f77aa49 --- /dev/null +++ b/include/basegfx/point/b2dpoint.hxx @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace basegfx +{ + class B2DHomMatrix; + + /** Base Point class with two double values + + This class derives all operators and common handling for + a 2D data class from B2DTuple. All necessary extensions + which are special for points will be added here. + + @see B2DTuple + */ + class SAL_WARN_UNUSED B2DPoint : public ::basegfx::B2DTuple + { + public: + /** Create a 2D Point + + The point is initialized to (0.0, 0.0) + */ + B2DPoint() + {} + + /** Create a 2D Point + + @param fX + This parameter is used to initialize the X-coordinate + of the 2D Point. + + @param fY + This parameter is used to initialize the Y-coordinate + of the 2D Point. + */ + B2DPoint(double fX, double fY) + : B2DTuple(fX, fY) + {} + + /** Create a copy of a 2D Point + + @param rPoint + The 2D Point which will be copied. + */ + explicit B2DPoint(const ::basegfx::B2IPoint& rPoint) + : B2DTuple(rPoint) + {} + + /** constructor with tuple to allow copy-constructing + from B2DTuple-based classes + */ + B2DPoint(const ::basegfx::B2DTuple& rTuple) + : B2DTuple(rTuple) + {} + + /** *=operator to allow usage from B2DPoint, too + */ + B2DPoint& operator*=( const B2DPoint& rPnt ) + { + mfX *= rPnt.mfX; + mfY *= rPnt.mfY; + return *this; + } + + /** *=operator to allow usage from B2DPoint, too + */ + B2DPoint& operator*=(double t) + { + mfX *= t; + mfY *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B2DTuple calculations + */ + BASEGFX_DLLPUBLIC B2DPoint& operator=( const ::basegfx::B2DTuple& rPoint ); + + /** Transform point by given transformation matrix. + + The translational components of the matrix are, in + contrast to B2DVector, applied. + */ + BASEGFX_DLLPUBLIC B2DPoint& operator*=( const ::basegfx::B2DHomMatrix& rMat ); + + static const B2DPoint& getEmptyPoint() + { + return static_cast( ::basegfx::B2DTuple::getEmptyTuple() ); + } + }; + + // external operators + + /** Transform B2DPoint by given transformation matrix. + + Since this is a Point, translational components of the + matrix are used. + */ + BASEGFX_DLLPUBLIC B2DPoint operator*( const B2DHomMatrix& rMat, const B2DPoint& rPoint ); + + template< typename charT, typename traits > + inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const B2DPoint& point ) + { + return stream << "(" << point.getX() << "," << point.getY() << ")"; + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/point/b2ipoint.hxx b/include/basegfx/point/b2ipoint.hxx new file mode 100644 index 000000000..9357e9f0f --- /dev/null +++ b/include/basegfx/point/b2ipoint.hxx @@ -0,0 +1,99 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace basegfx +{ + class B2DHomMatrix; + + /** Base Point class with two sal_Int32 values + + This class derives all operators and common handling for + a 2D data class from B2ITuple. All necessary extensions + which are special for points will be added here. + + @see B2ITuple + */ + class SAL_WARN_UNUSED B2IPoint : public ::basegfx::B2ITuple + { + public: + /** Create a 2D Point + + The point is initialized to (0, 0) + */ + B2IPoint() + {} + + /** Create a 2D Point + + @param nX + This parameter is used to initialize the X-coordinate + of the 2D Point. + + @param nY + This parameter is used to initialize the Y-coordinate + of the 2D Point. + */ + B2IPoint(sal_Int32 nX, sal_Int32 nY) + : B2ITuple(nX, nY) + {} + + /** constructor with tuple to allow copy-constructing + from B2ITuple-based classes + */ + B2IPoint(const ::basegfx::B2ITuple& rTuple) + : B2ITuple(rTuple) + {} + + /** *=operator to allow usage from B2IPoint, too + */ + B2IPoint& operator*=( const B2IPoint& rPnt ) + { + mnX *= rPnt.mnX; + mnY *= rPnt.mnY; + return *this; + } + + /** *=operator to allow usage from B2IPoint, too + */ + B2IPoint& operator*=(sal_Int32 t) + { + mnX *= t; + mnY *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B2ITuple calculations + */ + B2IPoint& operator=( const ::basegfx::B2ITuple& rPoint ); + + /** Transform point by given transformation matrix. + + The translational components of the matrix are, in + contrast to B2DVector, applied. + */ + B2IPoint& operator*=( const ::basegfx::B2DHomMatrix& rMat ); + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/point/b3dpoint.hxx b/include/basegfx/point/b3dpoint.hxx new file mode 100644 index 000000000..e424f0a4c --- /dev/null +++ b/include/basegfx/point/b3dpoint.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ + class B3DHomMatrix; + + /** Base Point class with three double values + + This class derives all operators and common handling for + a 3D data class from B3DTuple. All necessary extensions + which are special for points will be added here. + + @see B3DTuple + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B3DPoint : public ::basegfx::B3DTuple + { + public: + /** Create a 3D Point + + The point is initialized to (0.0, 0.0, 0.0) + */ + B3DPoint() + {} + + /** Create a 3D Point + + @param fX + This parameter is used to initialize the X-coordinate + of the 3D Point. + + @param fY + This parameter is used to initialize the Y-coordinate + of the 3D Point. + + @param fZ + This parameter is used to initialize the Z-coordinate + of the 3D Point. + */ + B3DPoint(double fX, double fY, double fZ) + : B3DTuple(fX, fY, fZ) + {} + + /** constructor with tuple to allow copy-constructing + from B3DTuple-based classes + */ + B3DPoint(const ::basegfx::B3DTuple& rTuple) + : B3DTuple(rTuple) + {} + + /** *=operator to allow usage from B3DPoint, too + */ + B3DPoint& operator*=( const B3DPoint& rPnt ) + { + mfX *= rPnt.mfX; + mfY *= rPnt.mfY; + mfZ *= rPnt.mfZ; + return *this; + } + + /** *=operator to allow usage from B3DPoint, too + */ + B3DPoint& operator*=(double t) + { + mfX *= t; + mfY *= t; + mfZ *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B3DTuple calculations + */ + B3DPoint& operator=( const ::basegfx::B3DTuple& rVec ) + { + mfX = rVec.getX(); + mfY = rVec.getY(); + mfZ = rVec.getZ(); + return *this; + } + + /** Transform point by given transformation matrix. + + The translational components of the matrix are, in + contrast to B3DVector, applied. + */ + B3DPoint& operator*=( const ::basegfx::B3DHomMatrix& rMat ); + }; + + // external operators + + + /** Transform B3DPoint by given transformation matrix. + + Since this is a Point, translational components of the + matrix are used. + */ + BASEGFX_DLLPUBLIC B3DPoint operator*( const B3DHomMatrix& rMat, const B3DPoint& rPoint ); + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/WaveLine.hxx b/include/basegfx/polygon/WaveLine.hxx new file mode 100644 index 000000000..b839c7519 --- /dev/null +++ b/include/basegfx/polygon/WaveLine.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ +// Creates a polygon of a wave line in the input rectangle. +// +// The polygon is created with points at the center of the rectangle, +// and the quadratic control points at the upper and lower side. See +// the diagram below. +// +// *----Q---------------Q------------* +// | | +// |P-------P-------P-------P-------P| +// | | +// *------------Q---------------Q----* +// +// P is the point +// Q is the quadratic bezier control point +// +BASEGFX_DLLPUBLIC B2DPolygon createWaveLinePolygon(basegfx::B2DRectangle const& rRectangle); + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dlinegeometry.hxx b/include/basegfx/polygon/b2dlinegeometry.hxx new file mode 100644 index 000000000..e12dd7498 --- /dev/null +++ b/include/basegfx/polygon/b2dlinegeometry.hxx @@ -0,0 +1,147 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace basegfx::utils +{ + /** Create line start/end geometry element, mostly arrows and things like that. + + @param rCandidate + The polygon which needs to get that line ends and needs to have two points + at least. + + @param rArrow + The line start/end geometry. It is assumed that the tip is pointing + upwards. Result will be rotated and scaled to fit. + + @param bStart + describes if creation is for start or end of candidate. + + @param fWidth + defines the size of the element, it's describing the target width in X + of the arrow. + + @param fDockingPosition needs to be in [0.0 ..1.0] range, where 0.0 means + that the tip of the arrow will be aligned with the polygon start, 1.0 means + the bottom. The default of 0.5 describes a centered arrow. + + @param pConsumedLength + Using this parameter it is possible to get back how much from the candidate + geometry is overlapped by the created element (consumed). + + @param fCandidateLength + This should contain the length of rCandidate to allow work without + again calculating the length (which may be expensive with beziers). If 0.0 is + given, the length is calculated on demand. + + @param fShift + When it is necessary to count with the thickness of the line, it + makes sense to move the start position slightly - so define the shift. + + @return + The Line start and end polygon, correctly rotated and scaled + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon createAreaGeometryForLineStartEnd( + const B2DPolygon& rCandidate, + const B2DPolyPolygon& rArrow, + bool bStart, + double fWidth, + double fCandidateLength, // 0.0 -> calculate self + double fDockingPosition, // 0->top, 1->bottom + double* pConsumedLength = nullptr, + double fShift = 0.0); + + /** create filled polygon geometry for lines with a line width + + This method will create bezier based, fillable polygons which + will resample the curve if it was extended for the given half + line width. It will remove extrema positions from contained + bezier segments and get as close as possible and defined by + the given parameters to the ideal result. + + It will check edges for trivial bezier to avoid unnecessary + bezier polygons. Care is taken to produce the in-between + polygon points (the ones original on the source polygon) since + it has showed that without those, the raster converters leave + non-filled gaps. + + @param rCandidate + The source polygon defining the hairline polygon path + + @param fHalfLineWidth + The width of the line to one side + + @param eJoin + The LineJoin if the edges meeting in a point do not have a C1 + or C2 continuity + + @param eCap + The kind of cap, which is added to the line. + + @param fMaxAllowedAngle + Allows to hand over the maximum allowed angle between an edge and + it's control vectors. The smaller, the more subdivisions will be + needed to create the filled geometry. Allowed range is cropped to + [M_PI_2 .. 0.01 * M_PI_2]. + + @param fMaxPartOfEdge + Allows to influence from with relative length of a control vector + compared to its edge a split is forced. The smaller, the more + subdivisions will be needed to create the filled geometry. Allowed + range is cropped to [1.0 .. 0.01] + + @param fMiterMinimumAngle + The minimum wanted angle between two edges when edge rounding + is using miter. When an edge is smaller than this (tighter) + the usual fallback to bevel is used. Allowed range is cropped + to [M_PI .. 0.01 * M_PI]. + + Commit 51b5b93092d6231615de470c62494c24e54828a1 needs + revert, we need the triangulation for X11 fat line drawing + + @param pTriangles + If given, the method will additionally add the created geometry as + B2DTriangle's + + @return + The tools::PolyPolygon containing the geometry of the extended line by + it's line width. Contains bezier segments and edge roundings as + needed and defined. + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon createAreaGeometry( + const B2DPolygon& rCandidate, + double fHalfLineWidth, + B2DLineJoin eJoin, + css::drawing::LineCap eCap, + double fMaxAllowedAngle = basegfx::deg2rad(12.5), + double fMaxPartOfEdge = 0.4, + double fMiterMinimumAngle = basegfx::deg2rad(15.0), + basegfx::triangulator::B2DTriangleVector* pTriangles = nullptr); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolygon.hxx b/include/basegfx/polygon/b2dpolygon.hxx new file mode 100644 index 000000000..c5a862773 --- /dev/null +++ b/include/basegfx/polygon/b2dpolygon.hxx @@ -0,0 +1,279 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +class ImplB2DPolygon; + +namespace basegfx +{ + class B2DPoint; + class B2DRange; + class B2DHomMatrix; + class B2DCubicBezier; + class SystemDependentData; + class SystemDependentDataManager; + typedef std::shared_ptr SystemDependentData_SharedPtr; +} + +namespace basegfx +{ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B2DPolygon + { + public: + typedef o3tl::cow_wrapper< ImplB2DPolygon > ImplType; + + private: + // internal data. + ImplType mpPolygon; + + public: + /// diverse constructors + B2DPolygon(); + B2DPolygon(const B2DPolygon& rPolygon); + B2DPolygon(B2DPolygon&& rPolygon); + B2DPolygon(const B2DPolygon& rPolygon, sal_uInt32 nIndex, sal_uInt32 nCount); + B2DPolygon(std::initializer_list rPoints); + + ~B2DPolygon(); + + /// assignment operator + B2DPolygon& operator=(const B2DPolygon& rPolygon); + B2DPolygon& operator=(B2DPolygon&& rPolygon); + + /// unshare this polygon with all internally shared instances + void makeUnique(); + + /// compare operators + bool operator==(const B2DPolygon& rPolygon) const; + bool operator!=(const B2DPolygon& rPolygon) const; + + /// member count + sal_uInt32 count() const; + + /// Coordinate interface + basegfx::B2DPoint const & getB2DPoint(sal_uInt32 nIndex) const; + void setB2DPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue); + + /// Coordinate insert/append + void insert(sal_uInt32 nIndex, const basegfx::B2DPoint& rPoint, sal_uInt32 nCount = 1); + void append(const basegfx::B2DPoint& rPoint, sal_uInt32 nCount); + void append(const basegfx::B2DPoint& rPoint); + void reserve(sal_uInt32 nCount); + + /// Basic ControlPoint interface + basegfx::B2DPoint getPrevControlPoint(sal_uInt32 nIndex) const; + basegfx::B2DPoint getNextControlPoint(sal_uInt32 nIndex) const; + void setPrevControlPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue); + void setNextControlPoint(sal_uInt32 nIndex, const basegfx::B2DPoint& rValue); + void setControlPoints(sal_uInt32 nIndex, const basegfx::B2DPoint& rPrev, const basegfx::B2DPoint& rNext); + + /// ControlPoint resets + void resetPrevControlPoint(sal_uInt32 nIndex); + void resetNextControlPoint(sal_uInt32 nIndex); + void resetControlPoints(); + + /// Bezier segment append with control points. The current last polygon point is implicitly taken as start point. + void appendBezierSegment(const basegfx::B2DPoint& rNextControlPoint, + const basegfx::B2DPoint& rPrevControlPoint, + const basegfx::B2DPoint& rPoint); + + /// This is a shortcut to append a quadratic bezier segment. The current last polygon point is implicitly taken as start point. + /// Note that the quadratic bezier control points will be converted to cubic bezier with 2 control points. + void appendQuadraticBezierSegment(const basegfx::B2DPoint& rQuadControlPoint, + const basegfx::B2DPoint& rPoint); + + /// ControlPoint checks + bool areControlPointsUsed() const; + bool isPrevControlPointUsed(sal_uInt32 nIndex) const; + bool isNextControlPointUsed(sal_uInt32 nIndex) const; + B2VectorContinuity getContinuityInPoint(sal_uInt32 nIndex) const; + + /** bezier segment access + + This method also works when it is no bezier segment at all and will fill + the given B2DCubicBezier as needed. + In any case, the given B2DCubicBezier will be filled, if necessary with + the single start point (if no valid edge exists). + + @param nIndex + Index of the addressed edge's start point + + @param rTarget + The B2DCubicBezier to be filled. It's data WILL be changed. + */ + void getBezierSegment(sal_uInt32 nIndex, B2DCubicBezier& rTarget) const; + + /** Default adaptive subdivision access + + This method will return a default adaptive subdivision of the polygon. + If the polygon does not contain any bezier curve segments, it will + just return itself. + + The subdivision is created on first request and buffered, so when using + this subdivision You have the guarantee for fast accesses for multiple + usages. It is intended for tooling usage for tasks which would be hard + to accomplish on bezier segments (e.g. isInEpsilonRange). + + The current default subdivision uses adaptiveSubdivideByCount with 9 + subdivisions which gives 10 edges and 11 points per segment and is + usually pretty usable for processing purposes. There is no parameter + passing here ATM but it may be changed on demand. If needed, a TYPE + and PARAMETER (both defaulted) may be added to allow for switching + between the different kinds of subdivisioned and passing them one + parameter. + + The lifetime of the buffered subdivision is based on polygon changes. + When changing the polygon, it will be flushed. It is buffered at the + refcounted implementation class, so it will survive copy by value and + combinations in PolyPolygons. + + @return + The default (and buffered) subdivision of this polygon. It may + be this polygon itself when it has no bezier segments. It is guaranteed + to have no more bezier segments + */ + B2DPolygon const & getDefaultAdaptiveSubdivision() const; + + /** Get the B2DRange (Rectangle dimensions) of this B2DPolygon + + A polygon may have up to three ranges: + + (a) the range of the polygon points + (b) the range of the polygon points and control points + (c) the outer range of the subdivided bezier curve + + Ranges (a) and (c) are produced by tools::getRange(); resp. this + getB2DRange(). tools::getRangeWithControlPoints handles case (b). + + To get range (c) a simple solution would be to subdivide the polygon + and use getRange() on it. Since subdivision is expensive and decreases + the polygon quality, i added this new method. It will use a + methodology suggested by HDU. First, it gets the range (a). + Then it iterates over the bezier segments and for each it + first tests if the outer range of the bezier segment is already + contained in the result range. + + The subdivision itself uses getAllExtremumPositions() to only + calculate extremum points and to expand the result accordingly. + Thus it calculates maximal four extremum points on the bezier + segment, no split is used at all. + + @return + The outer range of the bezier curve/polygon + */ + B2DRange const & getB2DRange() const; + + /** append other 2D polygons + + The default (nIndex ==0 && nCount == 0) will append + the whole rPoly + + @param rPoly + The source polygon + + @param nIndex + The index to the first point of rPoly to append + + @param nCount + The number of points to append from rPoly, starting + from nIndex. If zero, as much as possible is appended + */ + void append(const B2DPolygon& rPoly, sal_uInt32 nIndex = 0, sal_uInt32 nCount = 0); + + /// remove points + void remove(sal_uInt32 nIndex, sal_uInt32 nCount = 1); + + /// clear all points + void clear(); + + /// closed state interface + bool isClosed() const; + void setClosed(bool bNew); + + /// flip polygon direction + void flip(); + + /// test if Polygon has double points + bool hasDoublePoints() const; + + /// remove double points, at the begin/end and follow-ups, too + void removeDoublePoints(); + + /// apply transformation given in matrix form + void transform(const basegfx::B2DHomMatrix& rMatrix); + + // exclusive management op's for SystemDependentData at B2DPolygon + template + std::shared_ptr getSystemDependentData() const + { + return std::static_pointer_cast(getSystemDependantDataInternal(typeid(T).hash_code())); + } + + template + std::shared_ptr addOrReplaceSystemDependentData(SystemDependentDataManager& manager, Args&&... args) const + { + std::shared_ptr r = std::make_shared(manager, std::forward(args)...); + + // tdf#129845 only add to buffer if a relevant buffer time is estimated + if(r->calculateCombinedHoldCyclesInSeconds() > 0) + { + basegfx::SystemDependentData_SharedPtr r2(r); + addOrReplaceSystemDependentDataInternal(r2); + } + + return r; + } + + private: + void addOrReplaceSystemDependentDataInternal(SystemDependentData_SharedPtr& rData) const; + SystemDependentData_SharedPtr getSystemDependantDataInternal(size_t hash_code) const; + }; + + // typedef for a vector of B2DPolygons + typedef ::std::vector< B2DPolygon > B2DPolygonVector; + + template< typename charT, typename traits > + inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const B2DPolygon& poly ) + { + stream << "<" << poly.count() << ":"; + for (sal_uInt32 i = 0; i < poly.count(); i++) + { + if (i > 0) + stream << "--"; + stream << poly.getB2DPoint(i); + } + stream << ">"; + + return stream; + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolygonclipper.hxx b/include/basegfx/polygon/b2dpolygonclipper.hxx new file mode 100644 index 000000000..a6a2ce9d2 --- /dev/null +++ b/include/basegfx/polygon/b2dpolygonclipper.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ + class B2DRange; +} + +namespace basegfx::utils +{ + // This method clips the given tools::PolyPolygon against a horizontal or vertical axis (parallel to X or Y axis). The axis is + // defined by bParallelToXAxis (true -> it's parallel to the X-Axis of the coordinate system, else to the Y-Axis) and the + // fValueOnOtherAxis (gives the translation to the coordinate system axis). For example, when You want to define + // a clip axis parallel to X.Axis and 100 above it, use bParallelToXAxis = true and fValueOnOtherAxis = 100. + // The value bAboveAxis defines on which side the return value will be (true -> above X, right of Y). + // The switch bStroke decides if the polygon is interpreted as area (false) or strokes (true). + B2DPolyPolygon clipPolyPolygonOnParallelAxis(const B2DPolyPolygon& rCandidate, bool bParallelToXAxis, bool bAboveAxis, double fValueOnOtherAxis, bool bStroke); + BASEGFX_DLLPUBLIC B2DPolyPolygon clipPolygonOnParallelAxis(const B2DPolygon& rCandidate, bool bParallelToXAxis, bool bAboveAxis, double fValueOnOtherAxis, bool bStroke); + + // Clip the given tools::PolyPolygon against the given range. bInside defines if the result will contain the + // parts which are contained in the range or vice versa. + // The switch bStroke decides if the polygon is interpreted as area (false) or strokes (true). + BASEGFX_DLLPUBLIC B2DPolyPolygon clipPolyPolygonOnRange(const B2DPolyPolygon& rCandidate, const B2DRange& rRange, bool bInside, bool bStroke); + BASEGFX_DLLPUBLIC B2DPolyPolygon clipPolygonOnRange(const B2DPolygon& rCandidate, const B2DRange& rRange, bool bInside, bool bStroke); + + // Clip given tools::PolyPolygon against given clipping polygon. + // The switch bStroke decides if the polygon is interpreted as area (false) or strokes (true). + // With stroke polygons, You get all line snippets inside rCip. + // With filled polygons, You get all tools::PolyPolygon parts which were inside rClip. + // The switch bInside decides if the parts inside the clip polygon or outside shall be created. + // The clip polygon is always assumed closed, even when it's isClosed() is false. + BASEGFX_DLLPUBLIC B2DPolyPolygon clipPolyPolygonOnPolyPolygon(const B2DPolyPolygon& rCandidate, const B2DPolyPolygon& rClip, + bool bInside, bool bStroke, size_t *pPointLimit = nullptr); + BASEGFX_DLLPUBLIC B2DPolyPolygon clipPolygonOnPolyPolygon(const B2DPolygon& rCandidate, const B2DPolyPolygon& rClip, bool bInside, bool bStroke); + + // clip the given polygon against the given range. the resulting polygon will always contain + // the inside parts which will always be interpreted as areas. the incoming polygon is expected + // to be a simple triangle list. the result is also a simple triangle list. + BASEGFX_DLLPUBLIC B2DPolygon clipTriangleListOnRange( const B2DPolygon& rCandidate, const B2DRange& rRange ); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolygoncutandtouch.hxx b/include/basegfx/polygon/b2dpolygoncutandtouch.hxx new file mode 100644 index 000000000..600ad1c5c --- /dev/null +++ b/include/basegfx/polygon/b2dpolygoncutandtouch.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx::utils +{ + +// look for self-intersections and self-touches (points on an edge) in given polygon and add +// extra points there. Result will have no touches or intersections on an edge, only on points +B2DPolygon addPointsAtCutsAndTouches(const B2DPolygon& rCandidate, size_t* pPointLimit = nullptr); + +// look for polypolygon-intersections and polypolygon-touches (point of poly A on an edge of poly B) in given tools::PolyPolygon and add +// extra points there. Result will have no touches or intersections between contained polygons on an edge, only on points. For +// convenience, the correction for self-intersections for each member polygon will be used, too. +B2DPolyPolygon addPointsAtCutsAndTouches(const B2DPolyPolygon& rCandidate, size_t* pPointLimit = nullptr); + +// look for intersections of rCandidate with the edge from rStart to rEnd and add extra points there. +// Points are only added in the range of the edge, not on the endless vector. +B2DPolygon addPointsAtCuts(const B2DPolygon& rCandidate, const B2DPoint& rStart, const B2DPoint& rEnd); + +// look for intersections of rCandidate with the mask Polygon and add extra points there. +// The mask polygon is assumed to be closed, even when it's not explicitly. +B2DPolygon addPointsAtCuts(const B2DPolygon& rCandidate, const B2DPolyPolygon& rMask); + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolygontools.hxx b/include/basegfx/polygon/b2dpolygontools.hxx new file mode 100644 index 000000000..8f3ef342f --- /dev/null +++ b/include/basegfx/polygon/b2dpolygontools.hxx @@ -0,0 +1,529 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace basegfx { class B2DPolyPolygon; } + +// Definitions for the cut flags used from the findCut methods +enum class CutFlagValue +{ + NONE = 0x0000, + LINE = 0x0001, + START1 = 0x0002, + START2 = 0x0004, + END1 = 0x0008, + END2 = 0x0010, + ALL = LINE|START1|START2|END1|END2, + DEFAULT = LINE|START2|END2, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace basegfx +{ + class B2DPolygon; + class B2DRange; +} + +namespace basegfx::utils +{ + // B2DPolygon tools + + // open/close with point add/remove and control point corrections + BASEGFX_DLLPUBLIC void openWithGeometryChange(B2DPolygon& rCandidate); + BASEGFX_DLLPUBLIC void closeWithGeometryChange(B2DPolygon& rCandidate); + + /** Check if given polygon is closed. + + This is kind of a 'classic' method to support old polygon + definitions. Those old polygon definitions define the + closed state of the polygon using identical start and + endpoints. This method corrects this (removes double + start/end points) and sets the Closed()-state of the + polygon correctly. + */ + BASEGFX_DLLPUBLIC void checkClosed(B2DPolygon& rCandidate); + + // Get successor and predecessor indices. Returning the same index means there + // is none. Same for successor. + BASEGFX_DLLPUBLIC sal_uInt32 getIndexOfPredecessor(sal_uInt32 nIndex, const B2DPolygon& rCandidate); + BASEGFX_DLLPUBLIC sal_uInt32 getIndexOfSuccessor(sal_uInt32 nIndex, const B2DPolygon& rCandidate); + + // Get orientation of Polygon + BASEGFX_DLLPUBLIC B2VectorOrientation getOrientation(const B2DPolygon& rCandidate); + + // isInside tests for B2dPoint and other B2dPolygon. On border is not inside as long as + // not true is given in bWithBorder flag. + BASEGFX_DLLPUBLIC bool isInside(const B2DPolygon& rCandidate, const B2DPoint& rPoint, bool bWithBorder = false); + BASEGFX_DLLPUBLIC bool isInside(const B2DPolygon& rCandidate, const B2DPolygon& rPolygon, bool bWithBorder = false); + + /** Get the range of a polygon + + This method creates the outer range of the subdivided bezier curve. + For detailed discussion see B2DPolygon::getB2DRange() + + @param rCandidate + The B2DPolygon possibly containing bezier segments + + @return + The outer range of the bezier curve + */ + BASEGFX_DLLPUBLIC B2DRange getRange(const B2DPolygon& rCandidate); + + // get signed area of polygon + BASEGFX_DLLPUBLIC double getSignedArea(const B2DPolygon& rCandidate); + + // get area of polygon + BASEGFX_DLLPUBLIC double getArea(const B2DPolygon& rCandidate); + + /** get length of polygon edge from point nIndex to nIndex + 1 */ + BASEGFX_DLLPUBLIC double getEdgeLength(const B2DPolygon& rCandidate, sal_uInt32 nIndex); + + /** get length of polygon */ + BASEGFX_DLLPUBLIC double getLength(const B2DPolygon& rCandidate); + + // get position on polygon for absolute given distance. If + // length is given, it is assumed the correct polygon length, if 0.0 it is calculated + // using getLength(...) + BASEGFX_DLLPUBLIC B2DPoint getPositionAbsolute(const B2DPolygon& rCandidate, double fDistance, double fLength = 0.0); + + // get position on polygon for relative given distance in range [0.0 .. 1.0]. If + // length is given, it is assumed the correct polygon length, if 0.0 it is calculated + // using getLength(...) + BASEGFX_DLLPUBLIC B2DPoint getPositionRelative(const B2DPolygon& rCandidate, double fDistance, double fLength = 0.0); + + // get a snippet from given polygon for absolute distances. The polygon is assumed + // to be opened (not closed). fFrom and fTo need to be in range [0.0 .. fLength], where + // fTo >= fFrom. If length is given, it is assumed the correct polygon length, + // if 0.0 it is calculated using getLength(...) + BASEGFX_DLLPUBLIC B2DPolygon getSnippetAbsolute(const B2DPolygon& rCandidate, double fFrom, double fTo, double fLength = 0.0); + + // Continuity check for point with given index + BASEGFX_DLLPUBLIC B2VectorContinuity getContinuityInPoint(const B2DPolygon& rCandidate, sal_uInt32 nIndex); + + // Subdivide all contained curves. Use distanceBound value if given. + BASEGFX_DLLPUBLIC B2DPolygon adaptiveSubdivideByDistance(const B2DPolygon& rCandidate, double fDistanceBound); + + // Subdivide all contained curves. Use angleBound value if given. + BASEGFX_DLLPUBLIC B2DPolygon adaptiveSubdivideByAngle(const B2DPolygon& rCandidate, double fAngleBound = 0.0); + + // This version works with two points and vectors to define the + // edges for the cut test. + BASEGFX_DLLPUBLIC CutFlagValue findCut( + const B2DPoint& rEdge1Start, const B2DVector& rEdge1Delta, + const B2DPoint& rEdge2Start, const B2DVector& rEdge2Delta, + CutFlagValue aCutFlags = CutFlagValue::DEFAULT, + double* pCut1 = nullptr, double* pCut2 = nullptr); + + // test if point is on the given edge in range ]0.0..1.0[ without + // the start/end points. If so, return true and put the parameter + // value in pCut (if provided) + BASEGFX_DLLPUBLIC bool isPointOnEdge( + const B2DPoint& rPoint, + const B2DPoint& rEdgeStart, + const B2DVector& rEdgeDelta, + double* pCut = nullptr); + + /** Apply given LineDashing to given polygon + + This method is used to cut down line polygons to the needed + pieces when a dashing needs to be applied. + It is now capable of keeping contained bezier segments. + It is also capable of delivering line and non-line portions + depending on what target polygons You provide. This is useful + e.g. for dashed lines with two colors. + If the last and the first snippet in one of the results have + a common start/end ppoint, they will be merged to achieve as + view as needed result line snippets. This is also relevant for + further processing the results. + + @param rCandidate + The polygon based on which the snippets will be created. + + @param rDotDashArray + The line pattern given as array of length values + + @param pLineTarget + The target for line snippets, e.g. the first entry will be + a line segment with length rDotDashArray[0]. The given + polygon will be emptied as preparation. + + @param pGapTarget + The target for gap snippets, e.g. the first entry will be + a line segment with length rDotDashArray[1]. The given + polygon will be emptied as preparation. + + @param fFullDashDotLen + The summed-up length of the rDotDashArray. If zero, it will + be calculated internally. + + There is now a 2nd version that allows to provide callback + functions that get called when a snippet of a line/gap is + produced and needs to be added. This allows to use it like + a 'pipeline'. When using this (e.g. the 1st version uses + this internally to guarantee the same algorithm is used) + it is not needed to accumulate a potentially huge number + of polygons in the result-polyPolygons, but e.g. consume + them directly in the caller. Example is rendering a + dashed line but without creating the potentially huge amount + of polygons. + The 2nd version will also merge first/last line/gap snippets + if the input polygon is closed and the start/end-points match + accordingly - at the cost that this will be delivered last. + */ + BASEGFX_DLLPUBLIC void applyLineDashing( + const B2DPolygon& rCandidate, + const std::vector& rDotDashArray, + std::function aLineTargetCallback, + std::function aGapTargetCallback = std::function(), + double fDotDashLength = 0.0); + BASEGFX_DLLPUBLIC void applyLineDashing( + const B2DPolygon& rCandidate, + const ::std::vector& rDotDashArray, + B2DPolyPolygon* pLineTarget, + B2DPolyPolygon* pGapTarget = nullptr, + double fDotDashLength = 0.0); + + // test if point is inside epsilon-range around an edge defined + // by the two given points. Can be used for HitTesting. The epsilon-range + // is defined to be the rectangle centered to the given edge, using height + // 2 x fDistance, and the circle around both points with radius fDistance. + BASEGFX_DLLPUBLIC bool isInEpsilonRange(const B2DPoint& rEdgeStart, const B2DPoint& rEdgeEnd, const B2DPoint& rTestPosition, double fDistance); + + // test if point is inside epsilon-range around the given Polygon. Can be used + // for HitTesting. The epsilon-range is defined to be the rectangle centered + // to the given edge, using height 2 x fDistance, and the circle around both points + // with radius fDistance. + BASEGFX_DLLPUBLIC bool isInEpsilonRange(const B2DPolygon& rCandidate, const B2DPoint& rTestPosition, double fDistance); + + /** Create a polygon from a rectangle. + + @param rRect + The rectangle which describes the polygon size + + @param fRadiusX + @param fRadiusY + Radius of the edge rounding, relative to the rectangle size. 0.0 means no + rounding, 1.0 will lead to an ellipse + */ + BASEGFX_DLLPUBLIC B2DPolygon createPolygonFromRect( const B2DRectangle& rRect, double fRadiusX, double fRadiusY ); + + /** Create a polygon from a rectangle. + */ + BASEGFX_DLLPUBLIC B2DPolygon createPolygonFromRect( const B2DRectangle& rRect ); + + /** Create the unit polygon + */ + BASEGFX_DLLPUBLIC B2DPolygon const & createUnitPolygon(); + + /** Create a circle polygon with given radius. + + This method creates a circle approximation consisting of + 12 cubic bezier segments, which approximate the given + circle with an error of less than 0.5 percent. + + @param rCenter + Center point of the circle + + @param fRadius + Radius of the circle + */ + BASEGFX_DLLPUBLIC B2DPolygon createPolygonFromCircle( const B2DPoint& rCenter, double fRadius ); + + /// create half circle centered on (0,0) from [0 .. M_PI] + B2DPolygon const & createHalfUnitCircle(); + + /** create a polygon which describes the unit circle and close it + + @param nStartQuadrant + To be able to rebuild the old behaviour where the circles started at bottom, + this parameter is used. Default is 0 which is the first quadrant and the + polygon's start point will be the rightmost one. When using e.g. 1, the + first created quadrant will start at the YMax-position (with Y down on screens, + this is the lowest one). This is needed since when lines are dashed, toe old + geometry started at bottom point, else it would look different. + */ + BASEGFX_DLLPUBLIC B2DPolygon const & createPolygonFromUnitCircle(sal_uInt32 nStartQuadrant = 0); + + /** Create an ellipse polygon with given radii. + + This method creates an ellipse approximation consisting of + 12 cubic bezier segments, which approximate the given + ellipse with an error of less than 0.5 percent. + + @param rCenter + Center point of the circle + + @param fRadiusX + Radius of the ellipse in X direction + + @param fRadiusY + Radius of the ellipse in Y direction + + @param nStartQuadrant + With Y down on screens, 0 = 3 o'clock, 1 = 6 o'clock, 2 = 9 o'clock, 3 = 12 o'clock + */ + BASEGFX_DLLPUBLIC B2DPolygon createPolygonFromEllipse( const B2DPoint& rCenter, double fRadiusX, double fRadiusY, sal_uInt32 nStartQuadrant = 0); + + /** Create a unit ellipse polygon with the given angles, from start to end + */ + BASEGFX_DLLPUBLIC B2DPolygon createPolygonFromEllipseSegment( const B2DPoint& rCenter, double fRadiusX, double fRadiusY, double fStart, double fEnd ); + + BASEGFX_DLLPUBLIC B2DPolygon createPolygonFromUnitEllipseSegment( double fStart, double fEnd ); + + /** Predicate whether a given polygon is a rectangle. + + @param rPoly + Polygon to check + + @return true, if the polygon describes a rectangle + (polygon is closed, and the points are either cw or ccw + enumerations of a rectangle's vertices). Note that + intermediate points and duplicate points are ignored. + */ + BASEGFX_DLLPUBLIC bool isRectangle( const B2DPolygon& rPoly ); + + // create 3d polygon from given 2d polygon. The given fZCoordinate is used to expand the + // third coordinate. + BASEGFX_DLLPUBLIC B3DPolygon createB3DPolygonFromB2DPolygon(const B2DPolygon& rCandidate, double fZCoordinate = 0.0); + + // create 2d tools::PolyPolygon from given 3d PolyPolygon. All coordinates are transformed using the given + // matrix and the resulting x,y is used to form the new polygon. + BASEGFX_DLLPUBLIC B2DPolygon createB2DPolygonFromB3DPolygon(const B3DPolygon& rCandidate, const B3DHomMatrix& rMat); + + // calculate the smallest distance to given edge and return. The relative position on the edge is returned in Cut. + // That position is in the range [0.0 .. 1.0] and the returned distance is adapted accordingly to the start or end + // point of the edge + BASEGFX_DLLPUBLIC double getSmallestDistancePointToEdge(const B2DPoint& rPointA, const B2DPoint& rPointB, const B2DPoint& rTestPoint, double& rCut); + + // for each contained edge calculate the smallest distance. Return the index to the smallest + // edge in rEdgeIndex. The relative position on the edge is returned in rCut. + // If nothing was found (e.g. empty input plygon), DBL_MAX is returned. + BASEGFX_DLLPUBLIC double getSmallestDistancePointToPolygon(const B2DPolygon& rCandidate, const B2DPoint& rTestPoint, sal_uInt32& rEdgeIndex, double& rCut); + + // distort single point. rOriginal describes the original range, where the given points describe the distorted corresponding points. + BASEGFX_DLLPUBLIC B2DPoint distort(const B2DPoint& rCandidate, const B2DRange& rOriginal, const B2DPoint& rTopLeft, const B2DPoint& rTopRight, const B2DPoint& rBottomLeft, const B2DPoint& rBottomRight); + + // distort polygon. rOriginal describes the original range, where the given points describe the distorted corresponding points. + BASEGFX_DLLPUBLIC B2DPolygon distort(const B2DPolygon& rCandidate, const B2DRange& rOriginal, const B2DPoint& rTopLeft, const B2DPoint& rTopRight, const B2DPoint& rBottomLeft, const B2DPoint& rBottomRight); + + // expand all segments (which are not yet) to curve segments. This is done with setting the control + // vectors on the 1/3 resp. 2/3 distances on each segment. + BASEGFX_DLLPUBLIC B2DPolygon expandToCurve(const B2DPolygon& rCandidate); + + // expand given segment to curve segment. This is done with setting the control + // vectors on the 1/3 resp. 2/3 distances. The return value describes if a change took place. + BASEGFX_DLLPUBLIC bool expandToCurveInPoint(B2DPolygon& rCandidate, sal_uInt32 nIndex); + + // set continuity for given index. If not a curve, nothing will change. Non-curve points are not changed, too. + // The return value describes if a change took place. + BASEGFX_DLLPUBLIC bool setContinuityInPoint(B2DPolygon& rCandidate, sal_uInt32 nIndex, B2VectorContinuity eContinuity); + + // test if polygon contains neutral points. A neutral point is one whose orientation is neutral + // e.g. positioned on the edge of its predecessor and successor + BASEGFX_DLLPUBLIC bool hasNeutralPoints(const B2DPolygon& rCandidate); + + // remove neutral points. A neutral point is one whose orientation is neutral + // e.g. positioned on the edge of its predecessor and successor + BASEGFX_DLLPUBLIC B2DPolygon removeNeutralPoints(const B2DPolygon& rCandidate); + + // tests if polygon is convex + BASEGFX_DLLPUBLIC bool isConvex(const B2DPolygon& rCandidate); + + // calculates the orientation at edge nIndex + BASEGFX_DLLPUBLIC B2VectorOrientation getOrientationForIndex(const B2DPolygon& rCandidate, sal_uInt32 nIndex); + + // calculates if given point is on given line, taking care of the numerical epsilon + BASEGFX_DLLPUBLIC bool isPointOnLine(const B2DPoint& rStart, const B2DPoint& rEnd, const B2DPoint& rCandidate, bool bWithPoints); + + // calculates if given point is on given polygon, taking care of the numerical epsilon. Uses + // isPointOnLine internally + BASEGFX_DLLPUBLIC bool isPointOnPolygon(const B2DPolygon& rCandidate, const B2DPoint& rPoint, bool bWithPoints = true); + + // test if candidate is inside triangle + BASEGFX_DLLPUBLIC bool isPointInTriangle(const B2DPoint& rA, const B2DPoint& rB, const B2DPoint& rC, const B2DPoint& rCandidate, bool bWithBorder); + + // test if candidateA and candidateB are on the same side of the given line + bool arePointsOnSameSideOfLine(const B2DPoint& rStart, const B2DPoint& rEnd, const B2DPoint& rCandidateA, const B2DPoint& rCandidateB, bool bWithLine); + + // add triangles for given rCandidate to rTarget. For each triangle, 3 points will be added to rCandidate. + // All triangles will go from the start point of rCandidate to two consecutive points, building (rCandidate.count() - 2) + // triangles. + void addTriangleFan( + const B2DPolygon& rCandidate, + triangulator::B2DTriangleVector& rTarget); + + // grow for polygon. Move all geometry in each point in the direction of the normal in that point + // with the given amount. Value may be negative. + BASEGFX_DLLPUBLIC B2DPolygon growInNormalDirection(const B2DPolygon& rCandidate, double fValue); + + // force all sub-polygons to a point count of nSegments + BASEGFX_DLLPUBLIC B2DPolygon reSegmentPolygon(const B2DPolygon& rCandidate, sal_uInt32 nSegments); + + // create polygon state at t from 0.0 to 1.0 between the two polygons. Both polygons must have the same + // organisation, e.g. same amount of points + BASEGFX_DLLPUBLIC B2DPolygon interpolate(const B2DPolygon& rOld1, const B2DPolygon& rOld2, double t); + + // #i76891# Try to remove existing curve segments if they are simply edges + BASEGFX_DLLPUBLIC B2DPolygon simplifyCurveSegments(const B2DPolygon& rCandidate); + + // makes the given indexed point the new polygon start point. To do that, the points in the + // polygon will be rotated. This is only valid for closed polygons, for non-closed ones + // an assertion will be triggered + BASEGFX_DLLPUBLIC B2DPolygon makeStartPoint(const B2DPolygon& rCandidate, sal_uInt32 nIndexOfNewStatPoint); + + /** create edges of given length along given B2DPolygon + + @param rCandidate + The polygon to move along. Points at the given polygon are created, starting + at position fStart and stopping at less or equal to fEnd. The closed state is + preserved. + The polygon is subdivided if curve segments are included. That subdivision is the base + for the newly created points. + If the source is closed, the indirectly existing last edge may NOT have the + given length. + If the source is open, all edges will have the given length. You may use the last + point of the original when You want to add the last edge Yourself. + + @param fLength + The length of the created edges. If less or equal zero, an empty polygon is returned. + + @param fStart + The start distance for the first to be generated point. Use 0.0 to get the + original start point. Negative values are truncated to 0.0. + + @param fEnd + The maximum distance for the last point. No more points behind this distance will be created. + Use 0.0 to process the whole polygon. Negative values are truncated to 0.0. It also + needs to be more or equal to fStart, else it is truncated to fStart. + + @return + The newly created polygon + */ + B2DPolygon createEdgesOfGivenLength(const B2DPolygon& rCandidate, double fLength, double fStart = 0.0, double fEnd = 0.0); + + /** Create Waveline along given polygon + The implementation is based on createEdgesOfGivenLength and creates a curve + segment with the given dimensions for each created line segment. The polygon + is treated as if opened (closed state will be ignored) and only for whole + edges a curve segment will be created (no rest handling) + + @param rCandidate + The polygon along which the waveline will be created + + @param fWaveWidth + The length of a single waveline curve segment + + @param fgWaveHeight + The height of the waveline (amplitude) + */ + BASEGFX_DLLPUBLIC B2DPolygon createWaveline(const B2DPolygon& rCandidate, double fWaveWidth, double fWaveHeight); + + /** 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 + */ + BASEGFX_DLLPUBLIC B2DPolygon snapPointsOfHorizontalOrVerticalEdges(const B2DPolygon& rCandidate); + + /// get the tangent with which the given point is entered seen from the previous + /// polygon path data. Take into account all stuff like closed state, zero-length edges and others. + BASEGFX_DLLPUBLIC B2DVector getTangentEnteringPoint(const B2DPolygon& rCandidate, sal_uInt32 nIndex); + + /// get the tangent with which the given point is left seen from the following + /// polygon path data. Take into account all stuff like closed state, zero-length edges and others. + BASEGFX_DLLPUBLIC B2DVector getTangentLeavingPoint(const B2DPolygon& rCandidate, sal_uInt32 nIndex); + + /// converters for css::drawing::PointSequence + BASEGFX_DLLPUBLIC B2DPolygon UnoPointSequenceToB2DPolygon( + const css::drawing::PointSequence& rPointSequenceSource); + BASEGFX_DLLPUBLIC void B2DPolygonToUnoPointSequence( + const B2DPolygon& rPolygon, + css::drawing::PointSequence& rPointSequenceRetval); + + /* converters for css::drawing::PointSequence and + css::drawing::FlagSequence to B2DPolygon (curved polygons) + */ + B2DPolygon UnoPolygonBezierCoordsToB2DPolygon( + const css::drawing::PointSequence& rPointSequenceSource, + const css::drawing::FlagSequence& rFlagSequenceSource); + void B2DPolygonToUnoPolygonBezierCoords( + const B2DPolygon& rPolyPolygon, + css::drawing::PointSequence& rPointSequenceRetval, + css::drawing::FlagSequence& rFlagSequenceRetval); + + /** Read poly-polygon from SVG. + + This function imports a poly-polygon from an SVG points + attribute (a plain list of coordinate pairs). + + @param o_rPoly + The output polygon. Note that svg:points can only define a + single polygon + + @param rSvgPointsAttribute + A valid SVG points attribute string + + @return true, if the string was successfully parsed + */ + BASEGFX_DLLPUBLIC bool importFromSvgPoints( B2DPolygon& o_rPoly, + std::u16string_view rSvgPointsAttribute ); + + /** Write poly-polygon to SVG. + + This function imports a non-bezier polygon to SVG points + (a plain list of coordinate pairs). + + @param rPoly + The polygon to export + + @param rSvgPointsAttribute + A valid SVG points attribute string + + @return true, if the string was successfully parsed + */ + BASEGFX_DLLPUBLIC OUString exportToSvgPoints( const B2DPolygon& rPoly ); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolygontriangulator.hxx b/include/basegfx/polygon/b2dpolygontriangulator.hxx new file mode 100644 index 000000000..1fb2c9d54 --- /dev/null +++ b/include/basegfx/polygon/b2dpolygontriangulator.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +#include + +namespace basegfx { class B2DPolyPolygon; } + +namespace basegfx::triangulator +{ + // Simple B2D-based triangle. Main reason is to + // keep the data types separated (before a B2DPolygon + // was used with the convention that three points in + // a row define a triangle) + class BASEGFX_DLLPUBLIC B2DTriangle + { + // positions + basegfx::B2DPoint maA; + basegfx::B2DPoint maB; + basegfx::B2DPoint maC; + + public: + B2DTriangle( + const basegfx::B2DPoint& rA, + const basegfx::B2DPoint& rB, + const basegfx::B2DPoint& rC) + : maA(rA), + maB(rB), + maC(rC) + { + } + + // get positions + const basegfx::B2DPoint& getA() const { return maA; } + const basegfx::B2DPoint& getB() const { return maB; } + const basegfx::B2DPoint& getC() const { return maC; } + }; + + // typedef for a vector of B2DTriangle + typedef ::std::vector< B2DTriangle > B2DTriangleVector; + + // triangulate given polygon + BASEGFX_DLLPUBLIC B2DTriangleVector triangulate(const ::basegfx::B2DPolygon& rCandidate); + + // triangulate given PolyPolygon + BASEGFX_DLLPUBLIC B2DTriangleVector triangulate(const ::basegfx::B2DPolyPolygon& rCandidate); + +} // end of namespace basegfx::triangulator + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolypolygon.hxx b/include/basegfx/polygon/b2dpolypolygon.hxx new file mode 100644 index 000000000..f1420edef --- /dev/null +++ b/include/basegfx/polygon/b2dpolypolygon.hxx @@ -0,0 +1,170 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace basegfx +{ + class B2DHomMatrix; + class ImplB2DPolyPolygon; + + class BASEGFX_DLLPUBLIC B2DPolyPolygon + { + private: + o3tl::cow_wrapper mpPolyPolygon; + + public: + B2DPolyPolygon(); + B2DPolyPolygon(const B2DPolyPolygon& rPolyPolygon); + B2DPolyPolygon(B2DPolyPolygon&& rPolyPolygon); + explicit B2DPolyPolygon(const B2DPolygon& rPolygon); + ~B2DPolyPolygon(); + + // assignment operator + B2DPolyPolygon& operator=(const B2DPolyPolygon& rPolyPolygon); + B2DPolyPolygon& operator=(B2DPolyPolygon&& rPolyPolygon); + + /// unshare this poly-polygon (and all included polygons) with all internally shared instances + void makeUnique(); + + // compare operators + bool operator==(const B2DPolyPolygon& rPolyPolygon) const; + bool operator!=(const B2DPolyPolygon& rPolyPolygon) const; + + // polygon interface + sal_uInt32 count() const; + + B2DPolygon const & getB2DPolygon(sal_uInt32 nIndex) const; + void setB2DPolygon(sal_uInt32 nIndex, const B2DPolygon& rPolygon); + + // test for curve + bool areControlPointsUsed() const; + + // insert/append single polygon + void insert(sal_uInt32 nIndex, const B2DPolygon& rPolygon, sal_uInt32 nCount = 1); + void append(const B2DPolygon& rPolygon, sal_uInt32 nCount = 1); + + /** Default adaptive subdivision access + + For details refer to B2DPolygon::getDefaultAdaptiveSubdivision() + + @return + The default subdivision of this polygon + */ + B2DPolyPolygon getDefaultAdaptiveSubdivision() const; + + /** Get the B2DRange (Rectangle dimensions) of this B2DPolyPolygon + + For details refer to B2DPolygon::getB2DRange() + + @return + The outer range of the bezier curve/polygon + */ + B2DRange getB2DRange() const; + + // insert/append multiple polygons + void insert(sal_uInt32 nIndex, const B2DPolyPolygon& rPolyPolygon); + void append(const B2DPolyPolygon& rPolyPolygon); + + // remove + void remove(sal_uInt32 nIndex, sal_uInt32 nCount = 1); + + // reset to empty state + void clear(); + + // closed state + bool isClosed() const; + void setClosed(bool bNew); + + // flip polygon direction + void flip(); + + // test if tools::PolyPolygon has double points + bool hasDoublePoints() const; + + // remove double points, at the begin/end and follow-ups, too + void removeDoublePoints(); + + // apply transformation given in matrix form to the polygon + void transform(const basegfx::B2DHomMatrix& rMatrix); + + // polygon iterators (same iterator validity conditions as for vector) + const B2DPolygon* begin() const; + const B2DPolygon* end() const; + B2DPolygon* begin(); + B2DPolygon* end(); + + // exclusive management op's for SystemDependentData at B2DPolygon + template + std::shared_ptr getSystemDependentData() const + { + return std::static_pointer_cast(getSystemDependantDataInternal(typeid(T).hash_code())); + } + + template + std::shared_ptr addOrReplaceSystemDependentData(SystemDependentDataManager& manager, Args&&... args) const + { + std::shared_ptr r = std::make_shared(manager, std::forward(args)...); + + // tdf#129845 only add to buffer if a relevant buffer time is estimated + if(r->calculateCombinedHoldCyclesInSeconds() > 0) + { + basegfx::SystemDependentData_SharedPtr r2(r); + addOrReplaceSystemDependentDataInternal(r2); + } + + return r; + } + + private: + void addOrReplaceSystemDependentDataInternal(SystemDependentData_SharedPtr& rData) const; + SystemDependentData_SharedPtr getSystemDependantDataInternal(size_t hash_code) const; + }; + + // typedef for a vector of B2DPolyPolygons + typedef ::std::vector< B2DPolyPolygon > B2DPolyPolygonVector; + + template< typename charT, typename traits > + inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const B2DPolyPolygon& poly ) + { + stream << "[" << poly.count() << ":"; + for (sal_uInt32 i = 0; i < poly.count(); i++) + { + if (i > 0) + stream << ","; + stream << poly.getB2DPolygon(i); + } + stream << "]"; + + return stream; + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolypolygoncutter.hxx b/include/basegfx/polygon/b2dpolypolygoncutter.hxx new file mode 100644 index 000000000..55dd29cf8 --- /dev/null +++ b/include/basegfx/polygon/b2dpolypolygoncutter.hxx @@ -0,0 +1,144 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + + +namespace basegfx::utils +{ + /** Solve all crossovers (aka self-intersections) in a polyPolygon. + + This re-layouts all contained polygons so that the result + will contain only non-cutting polygons. For that reason, + points will be added at crossover and touch points and the + single Polygons may be re-combined. The orientations of + the contained polygons in not changed but used as + topological information. Self crossovers of the contained + sub-polygons are implicitly handled, but to not lose the + topological information, it may be necessary to remove + self-intersections of the contained sub-polygons in a + preparing step and to explicitly correct their + orientations. + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon solveCrossovers(const B2DPolyPolygon& rCandidate, + size_t* pPointLimit = nullptr); + + /** Solve all crossovers (aka self-intersections) in a Polygon + + Same as above, but for single polygons. Result will be + free of self-intersections. When result contains multiple + polygons, it may be necessary to rearrange their + orientations since holes may have been created (possibly use + correctOrientations). + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon solveCrossovers(const B2DPolygon& rCandidate); + + /** Strip neutral polygons from PolyPolygon. + + Neutral polygons are ones who's orientation is neutral, so + normally they have no volume -> just closed paths. A + polygon with the same positive and negative oriented + volume is also neutral, so this may not be wanted. It is + safe to call with self-intersection-free polygons, though + (that's where it's mostly used). + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon stripNeutralPolygons(const B2DPolyPolygon& rCandidate); + + /** Remove unnecessary/non-displayed polygons. + + Works only correct with self-intersection-free + polygons. For each polygon, the depth for the PolyPolygon + is calculated. The orientation is used to identify holes. + Start value for holes is -1, for polygons it's zero. Ech + time a polygon is contained in another one, it's depth is + increased when inside a polygon, decreased when inside a + hole. The result is a depth which e.g. is -1 for holes + outside everything, 1 for a polygon covered by another + polygon and zero for e.g. holes in a polygon or polygons + outside everything else. In the 2nd step, all polygons + with depth other than zero are removed. If bKeepAboveZero + is used, all polygons < 1 are removed. The bKeepAboveZero + mode is useful for clipping, e.g. just append one polygon + to another and use this mode -> only parts where two + polygons overlapped will be kept. In combination with + correct orientation of the input orientations and the + SolveCrossover calls this can be combined for logical + polygon operations or polygon clipping. + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon stripDispensablePolygons(const B2DPolyPolygon& rCandidate, bool bKeepAboveZero = false); + + /** Emulate nonzero winding rule filling. + + Geometrically convert PolyPolygons which are proposed to + use nonzero fill rule to a representation where evenodd + paint will give the same result. To do this all + intersections and self-intersections get solved (the + polygons will be rearranged if needed). Then all polygons + which are inside another one with the same orientation get + deleted + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon createNonzeroConform(const B2DPolyPolygon& rCandidate); + + // For convenience: the four basic operations OR, XOR, AND and DIFF for + // two PolyPolygons. These are combinations of the above methods. To not be forced + // to do evtl. already done preparations twice, You have to do the operations Yourself. + + // A source preparation consists of preparing it to be seen as XOR-Rule PolyPolygon, + // so it is freed of intersections, self-intersections and the orientations are corrected. + // Important is that it will define the same areas as before, but is intersection-free. + // As an example think about a single polygon looping in itself and having holes. To + // topologically correctly handle this, it is necessary to remove all intersections and + // to correct the orientations. The orientation of the isolated holes e.g. will be negative. + // Topologically it is necessary to prepare each polygon which is seen as entity. It is + // not sufficient just to concatenate them and prepare the result, this may be topologically + // different since the simple concatenation will be seen as XOR. To work correctly, You + // may need to OR those polygons. + + /// prep for ops - solve self-intersections and intersections, remove neutral parts and check orientations. + BASEGFX_DLLPUBLIC B2DPolyPolygon prepareForPolygonOperation(const B2DPolygon& rCandidate); + /// prep for ops - solve self-intersections and intersections, remove neutral parts and check orientations. + BASEGFX_DLLPUBLIC B2DPolyPolygon prepareForPolygonOperation(const B2DPolyPolygon& rCandidate); + + /// OR: Return all areas where CandidateA or CandidateB exist + BASEGFX_DLLPUBLIC B2DPolyPolygon solvePolygonOperationOr(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB); + + /// XOR: Return all areas where CandidateA or CandidateB exist, but not both + BASEGFX_DLLPUBLIC B2DPolyPolygon solvePolygonOperationXor(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB); + + /// AND: Return all areas where CandidateA and CandidateB exist + BASEGFX_DLLPUBLIC B2DPolyPolygon solvePolygonOperationAnd(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB); + + /// DIFF: Return all areas where CandidateA is not covered by CandidateB (cut B out of A) + BASEGFX_DLLPUBLIC B2DPolyPolygon solvePolygonOperationDiff(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB); + + /** merge all single PolyPolygons to a single, OR-ed PolyPolygon + + @param rInput + The source PolyPolygons + + @return A single tools::PolyPolygon containing the Or-merged result + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon mergeToSinglePolyPolygon(const B2DPolyPolygonVector& rInput); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dpolypolygontools.hxx b/include/basegfx/polygon/b2dpolypolygontools.hxx new file mode 100644 index 000000000..d253531f6 --- /dev/null +++ b/include/basegfx/polygon/b2dpolypolygontools.hxx @@ -0,0 +1,297 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::drawing { struct PolyPolygonBezierCoords; } + +namespace basegfx +{ + class B2DPolyPolygon; + class B2DRange; +} + +namespace basegfx::utils +{ + // B2DPolyPolygon tools + + // Check and evtl. correct orientations of all contained Polygons so that + // the orientations of contained polygons will variate to express areas and + // holes + BASEGFX_DLLPUBLIC B2DPolyPolygon correctOrientations(const B2DPolyPolygon& rCandidate); + + // make sure polygon with index 0L is not a hole. This may evtl. change the + // sequence of polygons, but allows to use polygon with index 0L to + // get the correct normal for the whole polyPolygon + BASEGFX_DLLPUBLIC B2DPolyPolygon correctOutmostPolygon(const B2DPolyPolygon& rCandidate); + + // Subdivide all contained curves. Use distanceBound value if given. + BASEGFX_DLLPUBLIC B2DPolyPolygon adaptiveSubdivideByDistance(const B2DPolyPolygon& rCandidate, double fDistanceBound); + + // Subdivide all contained curves. Use distanceBound value if given. Else, a convenient one + // is created. + BASEGFX_DLLPUBLIC B2DPolyPolygon adaptiveSubdivideByAngle(const B2DPolyPolygon& rCandidate, double fAngleBound = 0.0); + + // isInside test for B2dPoint. On border is not inside as long as not true is given + // in bWithBorder flag. It is assumed that the orientations of the given polygon are correct. + BASEGFX_DLLPUBLIC bool isInside(const B2DPolyPolygon& rCandidate, const B2DPoint& rPoint, bool bWithBorder = false); + + /** Get the range of a polyPolygon + + For detailed description look at getRange(const B2DPolygon&). + This method just expands by the range of every sub-Polygon. + + @param rCandidate + The B2DPolyPolygon possibly containing bezier segments + + @return + The outer range of the polygon + */ + BASEGFX_DLLPUBLIC B2DRange getRange(const B2DPolyPolygon& rCandidate); + + // get signed area of polygon + BASEGFX_DLLPUBLIC double getSignedArea(const B2DPolyPolygon& rCandidate); + + // get area of polygon + BASEGFX_DLLPUBLIC double getArea(const B2DPolyPolygon& rCandidate); + + /** Apply given LineDashing to given polyPolygon + + For a description see applyLineDashing in b2dpolygontoos.hxx + */ + BASEGFX_DLLPUBLIC void applyLineDashing( + const B2DPolyPolygon& rCandidate, + const ::std::vector& rDotDashArray, + B2DPolyPolygon* pLineTarget, + double fFullDashDotLen = 0.0); + + // test if point is inside epsilon-range around the given PolyPolygon. Can be used + // for HitTesting. The epsilon-range is defined to be the tube around the PolyPolygon + // with distance fDistance and rounded edges (start and end point). + BASEGFX_DLLPUBLIC bool isInEpsilonRange(const B2DPolyPolygon& rCandidate, const B2DPoint& rTestPosition, double fDistance); + + /** Helper class to transport PointIndices to a PolyPolygon, + with an operator< for convenient sorting in a std::set usage + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC PointIndex + { + private: + sal_uInt32 mnPolygonIndex; + sal_uInt32 mnPointIndex; + + public: + PointIndex(sal_uInt32 nPolygonIndex, sal_uInt32 nPointIndex) + : mnPolygonIndex(nPolygonIndex), + mnPointIndex(nPointIndex) + {} + + sal_uInt32 getPolygonIndex() const { return mnPolygonIndex; } + sal_uInt32 getPointIndex() const { return mnPointIndex; } + bool operator<(const PointIndex& rComp) const; + }; + + /** the PointIndexSet itself; it allows to define a 'selection'of + points in a tools::PolyPolygon by giving the polygon and point index. + Adding points double makes no sense, hence the std::set + */ + typedef o3tl::sorted_vector< PointIndex > PointIndexSet; + + /** Read poly-polygon from SVG. + + This function imports a poly-polygon from an SVG-D + attribute. + + @param o_rPolyPoly + The output poly-polygon + + @param rSvgDAttribute + A valid SVG-D attribute string + + @param bHandleRelativeNextPointCompatible + If set to true, the old error that after a relative 'z' command + the current point was not reset to the first point of the current + polygon is kept; this is needed to read odf files. + If false, pure svg is used; this is needed for svg import. + + @param pHelpPointIndexSet + If given, all points created in the target PolyPolygon + which are only helper points are added here using their + point indices; this are currently points created from + import of the 'a' and 'A' svg:d statements which create + bezier curve info as representation and maybe points + which are no 'real' svg:d points, but helper points. It + is necessary to identify these e.g. when markers need to + be created in the svg import + + @return true, if the string was successfully parsed + */ + BASEGFX_DLLPUBLIC bool importFromSvgD( + B2DPolyPolygon& o_rPolyPoly, + std::u16string_view rSvgDAttribute, + bool bHandleRelativeNextPointCompatible, + PointIndexSet* pHelpPointIndexSet); + + // grow for polyPolygon. Move all geometry in each point in the direction of the normal in that point + // with the given amount. Value may be negative. + BASEGFX_DLLPUBLIC B2DPolyPolygon growInNormalDirection(const B2DPolyPolygon& rCandidate, double fValue); + + // force all sub-polygons to a point count of nSegments + BASEGFX_DLLPUBLIC B2DPolyPolygon reSegmentPolyPolygon(const B2DPolyPolygon& rCandidate, sal_uInt32 nSegments); + + // create polygon state at t from 0.0 to 1.0 between the two polygons. Both polygons must have the same + // organisation, e.g. same amount of polygons + BASEGFX_DLLPUBLIC B2DPolyPolygon interpolate(const B2DPolyPolygon& rOld1, const B2DPolyPolygon& rOld2, double t); + + // create 3d tools::PolyPolygon from given 2d PolyPolygon. The given fZCoordinate is used to expand the + // third coordinate. + BASEGFX_DLLPUBLIC B3DPolyPolygon createB3DPolyPolygonFromB2DPolyPolygon(const B2DPolyPolygon& rCandidate, double fZCoordinate = 0.0); + + // create 2d tools::PolyPolygon from given 3d PolyPolygon. All coordinates are transformed using the given + // matrix and the resulting x,y is used to form the new polygon. + BASEGFX_DLLPUBLIC B2DPolyPolygon createB2DPolyPolygonFromB3DPolyPolygon(const B3DPolyPolygon& rCandidate, const B3DHomMatrix& rMat); + + // for each contained edge in each contained polygon calculate the smallest distance. Return the index to the smallest + // edge in rEdgeIndex and the index to the polygon in rPolygonIndex. The relative position on the edge is returned in rCut. + // If nothing was found (e.g. empty input plygon), DBL_MAX is returned. + BASEGFX_DLLPUBLIC double getSmallestDistancePointToPolyPolygon(const B2DPolyPolygon& rCandidate, const B2DPoint& rTestPoint, sal_uInt32& rPolygonIndex, sal_uInt32& rEdgeIndex, double& rCut); + + // distort PolyPolygon. rOriginal describes the original range, where the given points describe the distorted + // corresponding points. + BASEGFX_DLLPUBLIC B2DPolyPolygon distort(const B2DPolyPolygon& rCandidate, const B2DRange& rOriginal, const B2DPoint& rTopLeft, const B2DPoint& rTopRight, const B2DPoint& rBottomLeft, const B2DPoint& rBottomRight); + + // expand all segments (which are not yet) to curve segments. This is done with setting the control + // vectors on the 1/3 resp. 2/3 distances on each segment. + BASEGFX_DLLPUBLIC B2DPolyPolygon expandToCurve(const B2DPolyPolygon& rCandidate); + + /** Predicate whether a given poly-polygon is a rectangle. + + @param rPoly + tools::PolyPolygon to check + + @return true, if the poly-polygon describes a rectangle + (contains exactly one polygon, polygon is closed, and the + points are either cw or ccw enumerations of a rectangle's + vertices). Note that intermediate points and duplicate + points are ignored. + */ + BASEGFX_DLLPUBLIC bool isRectangle( const B2DPolyPolygon& rPoly ); + + /** Export poly-polygon to SVG. + + This function exports a poly-polygon into an SVG-D + statement. Currently, output of relative point sequences + is not yet supported (might cause slightly larger output) + + @param rPolyPoly + The poly-polygon to export + + @param bUseRelativeCoordinates + When true, all coordinate values are exported as relative + to the current position. This tends to save some space, + since fewer digits needs to be written. + + @param bDetectQuadraticBeziers + When true, the export tries to detect cubic bezier + segments in the input polygon, which can be represented by + quadratic bezier segments. Note that the generated string + causes versions prior to OOo2.0 to crash. + + @param bHandleRelativeNextPointCompatible + If set to true, the old error that after a relative 'z' command + the current point was not reset to the first point of the current + polygon is kept; this is needed to read odf files. + If false, pure svg is used; this is needed for svg import. + + @param bOOXMLMotionPath + If set to true, export string format that is acceptable for + for animation motion path for PowerPoint: always space delimited, + never neglect command char, always end with E, and do not export + H or V. + + @return the generated SVG-D statement (the XML d attribute + value alone, without any "" or "d="...") + */ + BASEGFX_DLLPUBLIC OUString exportToSvgD( + const B2DPolyPolygon& rPolyPoly, + bool bUseRelativeCoordinates, + bool bDetectQuadraticBeziers, + bool bHandleRelativeNextPointCompatible, + bool bOOXMLMotionPath = false); + + // #i76891# Try to remove existing curve segments if they are simply edges + BASEGFX_DLLPUBLIC B2DPolyPolygon simplifyCurveSegments(const B2DPolyPolygon& rCandidate); + + /** Creates polypolygon for seven-segment display number + + This function takes an integer number between 0 and 9 and + convert it into the well-known seven-segment display + number (like most digital clocks show their numbers). The + digit will exactly fit the unit rectangle. The polypolygon + will be a line polygon, i.e. if you need the segment parts + to have width, use createAreaGeometry() on the result. + + @param cNumber + Number from '0' to '9' as ASCII char, or '-', 'E' and '.' + to convert to 7 segment code + + @param bLitSegments + When true, return a polygon containing the segments that + are 'lit' for the given number. Return un-lit segments + otherwise. + */ + B2DPolyPolygon createSevenSegmentPolyPolygon(char cNumber, bool bLitSegments); + + /** 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 + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon snapPointsOfHorizontalOrVerticalEdges(const B2DPolyPolygon& rCandidate); + + /// converters for css::drawing::PointSequence + BASEGFX_DLLPUBLIC B2DPolyPolygon UnoPointSequenceSequenceToB2DPolyPolygon( + const css::drawing::PointSequenceSequence& rPointSequenceSequenceSource); + BASEGFX_DLLPUBLIC void B2DPolyPolygonToUnoPointSequenceSequence( + const B2DPolyPolygon& rPolyPolygon, + css::drawing::PointSequenceSequence& rPointSequenceSequenceRetval); + + /// converters for css::drawing::PolyPolygonBezierCoords (curved polygons) + BASEGFX_DLLPUBLIC B2DPolyPolygon UnoPolyPolygonBezierCoordsToB2DPolyPolygon( + const css::drawing::PolyPolygonBezierCoords& rPolyPolygonBezierCoordsSource); + BASEGFX_DLLPUBLIC void B2DPolyPolygonToUnoPolyPolygonBezierCoords( + const B2DPolyPolygon& rPolyPolygon, + css::drawing::PolyPolygonBezierCoords& rPolyPolygonBezierCoordsRetval); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b2dtrapezoid.hxx b/include/basegfx/polygon/b2dtrapezoid.hxx new file mode 100644 index 000000000..aeed7148e --- /dev/null +++ b/include/basegfx/polygon/b2dtrapezoid.hxx @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + + +namespace basegfx { class B2DPolyPolygon; } +namespace basegfx { class B2DPoint; } + +namespace basegfx +{ + // class to hold a single trapezoid + class UNLESS_MERGELIBS(BASEGFX_DLLPUBLIC) B2DTrapezoid + { + private: + // Geometry data. YValues are down-oriented, this means bottom should + // be bigger than top to be below it. The constructor implementation + // guarantees: + + // - mfBottomY >= mfTopY + // - mfTopXRight >= mfTopXLeft + // - mfBottomXRight >= mfBottomXLeft + double mfTopXLeft; + double mfTopXRight; + double mfTopY; + double mfBottomXLeft; + double mfBottomXRight; + double mfBottomY; + + public: + // constructor + B2DTrapezoid( + const double& rfTopXLeft, + const double& rfTopXRight, + const double& rfTopY, + const double& rfBottomXLeft, + const double& rfBottomXRight, + const double& rfBottomY); + + // data read access + const double& getTopXLeft() const { return mfTopXLeft; } + const double& getTopXRight() const { return mfTopXRight; } + const double& getTopY() const { return mfTopY; } + const double& getBottomXLeft() const { return mfBottomXLeft; } + const double& getBottomXRight() const { return mfBottomXRight; } + const double& getBottomY() const { return mfBottomY; } + + // convenience method to get content as Polygon + B2DPolygon getB2DPolygon() const; + }; + + typedef ::std::vector< B2DTrapezoid > B2DTrapezoidVector; + +} // end of namespace basegfx + + +namespace basegfx::utils +{ + // convert SourcePolyPolygon to trapezoids. The trapezoids will be appended to + // ro_Result. ro_Result will not be cleared. If SourcePolyPolygon contains curves, + // it's default AdaptiveSubdivision will be used. + // CAUTION: Trapezoids are orientation-dependent in the sense that the upper and lower + // lines have to be parallel to the X-Axis, thus this subdivision is NOT simply usable + // for primitive decompositions. To use it, the shear and rotate parts of the + // involved transformations HAVE to be taken into account. + BASEGFX_DLLPUBLIC void trapezoidSubdivide( + B2DTrapezoidVector& ro_Result, + const B2DPolyPolygon& rSourcePolyPolygon); + + // directly create trapezoids from given edge. Depending on the given geometry, + // none up to three trapezoids will be created + void createLineTrapezoidFromEdge( + B2DTrapezoidVector& ro_Result, + const B2DPoint& rPointA, + const B2DPoint& rPointB, + double fLineWidth); + + // create trapezoids for all edges of the given polygon. The closed state of + // the polygon is taken into account. If curves are contained, the default + // AdaptiveSubdivision will be used. + void createLineTrapezoidFromB2DPolygon( + B2DTrapezoidVector& ro_Result, + const B2DPolygon& rPolygon, + double fLineWidth); +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b3dpolygon.hxx b/include/basegfx/polygon/b3dpolygon.hxx new file mode 100644 index 000000000..ea9ea2fde --- /dev/null +++ b/include/basegfx/polygon/b3dpolygon.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +class ImplB3DPolygon; + +namespace basegfx +{ + class B3DPoint; + class B3DHomMatrix; + class B3DVector; + class B2DPoint; + class B2DHomMatrix; + class BColor; +} + +namespace basegfx +{ + class BASEGFX_DLLPUBLIC B3DPolygon + { + public: + typedef o3tl::cow_wrapper< ImplB3DPolygon, o3tl::ThreadSafeRefCountingPolicy > ImplType; + + private: + // internal data. + ImplType mpPolygon; + + public: + B3DPolygon(); + B3DPolygon(const B3DPolygon& rPolygon); + B3DPolygon(B3DPolygon&& rPolygon); + ~B3DPolygon(); + + // assignment operator + B3DPolygon& operator=(const B3DPolygon& rPolygon); + B3DPolygon& operator=(B3DPolygon&& rPolygon); + + // compare operators + bool operator==(const B3DPolygon& rPolygon) const; + bool operator!=(const B3DPolygon& rPolygon) const; + + // member count + sal_uInt32 count() const; + + // Coordinate interface + B3DPoint const & getB3DPoint(sal_uInt32 nIndex) const; + void setB3DPoint(sal_uInt32 nIndex, const B3DPoint& rValue); + + // Coordinate append + void append(const B3DPoint& rPoint, sal_uInt32 nCount = 1); + + // BColor interface + BColor const & getBColor(sal_uInt32 nIndex) const; + void setBColor(sal_uInt32 nIndex, const BColor& rValue); + bool areBColorsUsed() const; + void clearBColors(); + + // Normals interface + B3DVector const & getNormal() const; // plane normal + B3DVector const & getNormal(sal_uInt32 nIndex) const; // normal in each point + void setNormal(sal_uInt32 nIndex, const B3DVector& rValue); + void transformNormals(const B3DHomMatrix& rMatrix); + bool areNormalsUsed() const; + void clearNormals(); + + // TextureCoordinate interface + B2DPoint const & getTextureCoordinate(sal_uInt32 nIndex) const; + void setTextureCoordinate(sal_uInt32 nIndex, const B2DPoint& rValue); + void transformTextureCoordinates(const B2DHomMatrix& rMatrix); + bool areTextureCoordinatesUsed() const; + void clearTextureCoordinates(); + + // append other 2D polygons + void append(const B3DPolygon& rPoly, sal_uInt32 nIndex = 0, sal_uInt32 nCount = 0); + + // remove + void remove(sal_uInt32 nIndex, sal_uInt32 nCount = 1); + + // clear all points + void clear(); + + // closed state + bool isClosed() const; + void setClosed(bool bNew); + + // flip polygon direction + void flip(); + + // test if Polygon has double points + bool hasDoublePoints() const; + + // remove double points, at the begin/end and follow-ups, too + void removeDoublePoints(); + + // apply transformation given in matrix form to the polygon + void transform(const B3DHomMatrix& rMatrix); + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b3dpolygontools.hxx b/include/basegfx/polygon/b3dpolygontools.hxx new file mode 100644 index 000000000..2bdddbc33 --- /dev/null +++ b/include/basegfx/polygon/b3dpolygontools.hxx @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include +#include +#include + +namespace basegfx +{ + class B3DPolyPolygon; + class B3DPolygon; + class B3DRange; +} + +namespace basegfx::utils +{ + // B3DPolygon tools + + /** Check if given polygon is closed. This is kind of a + 'classic' method to support old polygon definitions. + Those old polygon definitions define the closed state + of the polygon using identical start and endpoints. This + method corrects this (removes double start/end points) + and sets the Closed()-state of the polygon correctly. + */ + BASEGFX_DLLPUBLIC void checkClosed(B3DPolygon& rCandidate); + + // Get successor and predecessor indices. Returning the same index means there + // is none. Same for successor. + BASEGFX_DLLPUBLIC sal_uInt32 getIndexOfSuccessor(sal_uInt32 nIndex, const B3DPolygon& rCandidate); + + // get size of polygon. Control vectors are included in that ranges. + BASEGFX_DLLPUBLIC B3DRange getRange(const B3DPolygon& rCandidate); + + // get length of polygon + BASEGFX_DLLPUBLIC double getLength(const B3DPolygon& rCandidate); + + /** Apply given LineDashing to given polygon + + For a description see applyLineDashing in b2dpolygontoos.hxx + Also 2nd version with callbacks, see comments in 2D version + */ + void applyLineDashing( + const B3DPolygon& rCandidate, + const std::vector& rDotDashArray, + std::function aLineTargetCallback, + double fDotDashLength = 0.0); + BASEGFX_DLLPUBLIC void applyLineDashing( + const B3DPolygon& rCandidate, + const ::std::vector& rDotDashArray, + B3DPolyPolygon* pLineTarget, + double fDotDashLength = 0.0); + + /** Create/replace normals for given 3d geometry with default normals from given center to outside. + rCandidate: the 3d geometry to change + rCenter: the center of the 3d geometry + */ + B3DPolygon applyDefaultNormalsSphere( const B3DPolygon& rCandidate, const B3DPoint& rCenter); + + /** invert normals for given 3d geometry. + */ + BASEGFX_DLLPUBLIC B3DPolygon invertNormals( const B3DPolygon& rCandidate); + + /** Create/replace texture coordinates for given 3d geometry with parallel projected one + rRange: the full range of the 3d geometry + If bChangeX, x texture coordinate will be recalculated. + If bChangeY, y texture coordinate will be recalculated. + */ + B3DPolygon applyDefaultTextureCoordinatesParallel( const B3DPolygon& rCandidate, const B3DRange& rRange, bool bChangeX, bool bChangeY); + + /** Create/replace texture coordinates for given 3d geometry with spherical one + rCenter: the centre of the used 3d geometry + If bChangeX, x texture coordinate will be recalculated. + If bChangeY, y texture coordinate will be recalculated. + */ + B3DPolygon applyDefaultTextureCoordinatesSphere( const B3DPolygon& rCandidate, const B3DPoint& rCenter, bool bChangeX, bool bChangeY); + + // isInside tests for B3DPoint. On border is not inside as long as not true is given in bWithBorder flag. + BASEGFX_DLLPUBLIC bool isInside(const B3DPolygon& rCandidate, const B3DPoint& rPoint, bool bWithBorder); + + // calculates if given point is on given line, taking care of the numerical epsilon + BASEGFX_DLLPUBLIC bool isPointOnLine(const B3DPoint& rStart, const B3DPoint& rEnd, const B3DPoint& rCandidate, bool bWithPoints); + + // calculates if given point is on given polygon, taking care of the numerical epsilon. Uses + // isPointOnLine internally + BASEGFX_DLLPUBLIC bool isPointOnPolygon(const B3DPolygon& rCandidate, const B3DPoint& rPoint); + + // helper to get a fCut position between a plane (given with normal and a point) + // and a line given by start and end point + BASEGFX_DLLPUBLIC bool getCutBetweenLineAndPlane(const B3DVector& rPlaneNormal, const B3DPoint& rPlanePoint, const B3DPoint& rEdgeStart, const B3DPoint& rEdgeEnd, double& fCut); + + /** 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 + */ + BASEGFX_DLLPUBLIC B3DPolygon snapPointsOfHorizontalOrVerticalEdges(const B3DPolygon& rCandidate); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b3dpolypolygon.hxx b/include/basegfx/polygon/b3dpolypolygon.hxx new file mode 100644 index 000000000..14a062c08 --- /dev/null +++ b/include/basegfx/polygon/b3dpolypolygon.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +class ImplB3DPolyPolygon; + +namespace basegfx +{ + class B3DPolygon; + class B3DHomMatrix; + class B2DHomMatrix; +} + +namespace basegfx +{ + class BASEGFX_DLLPUBLIC B3DPolyPolygon + { + public: + typedef o3tl::cow_wrapper< ImplB3DPolyPolygon, o3tl::ThreadSafeRefCountingPolicy > ImplType; + + private: + ImplType mpPolyPolygon; + + public: + B3DPolyPolygon(); + B3DPolyPolygon(const B3DPolyPolygon& rPolyPolygon); + B3DPolyPolygon(B3DPolyPolygon&& rPolygon); + explicit B3DPolyPolygon(const B3DPolygon& rPolygon); + ~B3DPolyPolygon(); + + // assignment operator + B3DPolyPolygon& operator=(const B3DPolyPolygon& rPolyPolygon); + B3DPolyPolygon& operator=(B3DPolyPolygon&& rPolyPolygon); + + // compare operators + bool operator==(const B3DPolyPolygon& rPolyPolygon) const; + bool operator!=(const B3DPolyPolygon& rPolyPolygon) const; + + // polygon interface + sal_uInt32 count() const; + + // B3DPolygon interface + B3DPolygon const & getB3DPolygon(sal_uInt32 nIndex) const; + void setB3DPolygon(sal_uInt32 nIndex, const B3DPolygon& rPolygon); + + // BColor interface + bool areBColorsUsed() const; + void clearBColors(); + + // Normals interface + void transformNormals(const B3DHomMatrix& rMatrix); + bool areNormalsUsed() const; + void clearNormals(); + + // TextureCoordinate interface + void transformTextureCoordinates(const B2DHomMatrix& rMatrix); + bool areTextureCoordinatesUsed() const; + void clearTextureCoordinates(); + + // append single polygon + void append(const B3DPolygon& rPolygon, sal_uInt32 nCount = 1); + + // append multiple polygons + void append(const B3DPolyPolygon& rPolyPolygon); + + // remove + void remove(sal_uInt32 nIndex, sal_uInt32 nCount = 1); + + // reset to empty state + void clear(); + + // flip polygon direction + void flip(); + + // test if tools::PolyPolygon has double points + bool hasDoublePoints() const; + + // remove double points, at the begin/end and follow-ups, too + void removeDoublePoints(); + + // apply transformation given in matrix form to the polygon + void transform(const basegfx::B3DHomMatrix& rMatrix); + + // polygon iterators (same iterator validity conditions as for vector) + const B3DPolygon* begin() const; + const B3DPolygon* end() const; + B3DPolygon* begin(); + B3DPolygon* end(); + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/polygon/b3dpolypolygontools.hxx b/include/basegfx/polygon/b3dpolypolygontools.hxx new file mode 100644 index 000000000..d201696dc --- /dev/null +++ b/include/basegfx/polygon/b3dpolypolygontools.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace com::sun::star::drawing { struct PolyPolygonShape3D; } + +namespace basegfx +{ + class B3DPolyPolygon; + class B3DRange; +} + +namespace basegfx::utils +{ + // B3DPolyPolygon tools + + // get size of PolyPolygon. Control vectors are included in that ranges. + BASEGFX_DLLPUBLIC B3DRange getRange(const B3DPolyPolygon& rCandidate); + + /** Create a unit 3D line polyPolygon which defines a cube. + */ + B3DPolyPolygon const & createUnitCubePolyPolygon(); + + /** Create a unit 3D fill polyPolygon which defines a cube. + */ + B3DPolyPolygon const & createUnitCubeFillPolyPolygon(); + + /** Create a 3D line polyPolygon from a B3DRange which defines a cube. + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon createCubePolyPolygonFromB3DRange( const B3DRange& rRange); + + /** Create a 3D fill polyPolygon from a B3DRange which defines a cube. + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon createCubeFillPolyPolygonFromB3DRange( const B3DRange& rRange); + + /** Create a unit 3D line polyPolygon which defines a sphere with the given count of hor and ver segments. + Result will be centered at (0.0, 0.0, 0.0) and sized [-1.0 .. 1.0] in all dimensions. + If nHorSeg == 0 and/or nVerSeg == 0, a default will be calculated to have a step at least each 15 degrees. + With VerStart, VerStop and hor range in cartesian may be specified to create a partial sphere only. + */ + B3DPolyPolygon createUnitSpherePolyPolygon( + sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, + double fVerStart = M_PI_2, double fVerStop = -M_PI_2, + double fHorStart = 0.0, double fHorStop = 2 * M_PI); + + /** Create a 3D line polyPolygon from a B3DRange which defines a sphere with the given count of hor and ver segments. + If nHorSeg == 0 and/or nVerSeg == 0, a default will be calculated to have a step at least each 15 degrees. + With VerStart, VerStop and hor range in cartesian may be specified to create a partial sphere only. + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon createSpherePolyPolygonFromB3DRange( + const B3DRange& rRange, + sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, + double fVerStart = M_PI_2, double fVerStop = -M_PI_2, + double fHorStart = 0.0, double fHorStop = 2 * M_PI); + + /** same as createUnitSpherePolyPolygon, but creates filled polygons (closed and oriented) + There is one extra, the bool bNormals defines if normals will be set, default is false + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon createUnitSphereFillPolyPolygon( + sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, + bool bNormals = false, + double fVerStart = M_PI_2, double fVerStop = -M_PI_2, + double fHorStart = 0.0, double fHorStop = 2 * M_PI); + + /** same as createSpherePolyPolygonFromB3DRange, but creates filled polygons (closed and oriented) + There is one extra, the bool bNormals defines if normals will be set, default is false + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon createSphereFillPolyPolygonFromB3DRange( + const B3DRange& rRange, + sal_uInt32 nHorSeg, sal_uInt32 nVerSeg, + bool bNormals = false, + double fVerStart = M_PI_2, double fVerStop = -M_PI_2, + double fHorStart = 0.0, double fHorStop = 2 * M_PI); + + /** Create/replace normals for given 3d geometry with default normals from given center to outside. + rCandidate: the 3d geometry to change + rCenter: the center of the 3d geometry + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon applyDefaultNormalsSphere( const B3DPolyPolygon& rCandidate, const B3DPoint& rCenter); + + /** invert normals for given 3d geometry. + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon invertNormals( const B3DPolyPolygon& rCandidate); + + /** Create/replace texture coordinates for given 3d geometry with parallel projected one + rRange: the full range of the 3d geometry + If bChangeX, x texture coordinate will be recalculated. + If bChangeY, y texture coordinate will be recalculated. + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon applyDefaultTextureCoordinatesParallel( const B3DPolyPolygon& rCandidate, const B3DRange& rRange, bool bChangeX = true, bool bChangeY = true); + + /** Create/replace texture coordinates for given 3d geometry with spherical one + rCenter: the centre of the used 3d geometry + If bChangeX, x texture coordinate will be recalculated. + If bChangeY, y texture coordinate will be recalculated. + */ + BASEGFX_DLLPUBLIC B3DPolyPolygon applyDefaultTextureCoordinatesSphere( const B3DPolyPolygon& rCandidate, const B3DPoint& rCenter, bool bChangeX = true, bool bChangeY = true); + + // isInside test for B3DPoint. On border is not inside. + // It is assumed that the orientations of the given polygon are correct. + BASEGFX_DLLPUBLIC bool isInside(const B3DPolyPolygon& rCandidate, const B3DPoint& rPoint); + + /// converters for css::drawing::PolyPolygonShape3D + BASEGFX_DLLPUBLIC B3DPolyPolygon UnoPolyPolygonShape3DToB3DPolyPolygon( + const css::drawing::PolyPolygonShape3D& rPolyPolygonShape3DSource); + BASEGFX_DLLPUBLIC void B3DPolyPolygonToUnoPolyPolygonShape3D( + const B3DPolyPolygon& rPolyPolygonSource, + css::drawing::PolyPolygonShape3D& rPolyPolygonShape3DRetval); + +} // end of namespace basegfx::utils + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/Range2D.hxx b/include/basegfx/range/Range2D.hxx new file mode 100644 index 000000000..664887529 --- /dev/null +++ b/include/basegfx/range/Range2D.hxx @@ -0,0 +1,178 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ +template class Range2D +{ +protected: + basegfx::BasicRange maRangeX; + basegfx::BasicRange maRangeY; + +public: + typedef TYPE ValueType; + typedef TRAITS TraitsType; + + Range2D() = default; + + /// Create degenerate interval consisting of a single point + explicit Range2D(const Tuple2D& rTuple) + : maRangeX(rTuple.getX()) + , maRangeY(rTuple.getY()) + { + } + + /// Create proper interval between the two given points + Range2D(const Tuple2D& rTuple1, const Tuple2D& rTuple2) + : maRangeX(rTuple1.getX()) + , maRangeY(rTuple1.getY()) + { + expand(rTuple2); + } + + /// Create proper interval between the two given pairs + Range2D(TYPE x1, TYPE y1, TYPE x2, TYPE y2) + : maRangeX(x1) + , maRangeY(y1) + { + maRangeX.expand(x2); + maRangeY.expand(y2); + } + + /** Check if the interval set is empty + + @return false, if no value is in this set - having a + single point included will already return true. + */ + bool isEmpty() const { return maRangeX.isEmpty() || maRangeY.isEmpty(); } + + /// reset the object to empty state again, clearing all values + void reset() + { + maRangeX.reset(); + maRangeY.reset(); + } + + bool operator==(const Range2D& rRange) const + { + return maRangeX == rRange.maRangeX && maRangeY == rRange.maRangeY; + } + + bool operator!=(const Range2D& rRange) const + { + return maRangeX != rRange.maRangeX || maRangeY != rRange.maRangeY; + } + + bool equal(const Range2D& rRange) const + { + return maRangeX.equal(rRange.maRangeX) && maRangeY.equal(rRange.maRangeY); + } + + /// get lower bound of the set. returns arbitrary values for empty sets. + TYPE getMinX() const { return maRangeX.getMinimum(); } + + /// get lower bound of the set. returns arbitrary values for empty sets. + TYPE getMinY() const { return maRangeY.getMinimum(); } + + /// get upper bound of the set. returns arbitrary values for empty sets. + TYPE getMaxX() const { return maRangeX.getMaximum(); } + + /// get upper bound of the set. returns arbitrary values for empty sets. + TYPE getMaxY() const { return maRangeY.getMaximum(); } + + /// return difference between upper and lower X value. returns 0 for empty sets. + TYPE getWidth() const { return maRangeX.getRange(); } + + /// return difference between upper and lower Y value. returns 0 for empty sets. + TYPE getHeight() const { return maRangeY.getRange(); } + + /// return center X value of set. returns 0 for empty sets. + double getCenterX() const { return maRangeX.getCenter(); } + + /// return center Y value of set. returns 0 for empty sets. + double getCenterY() const { return maRangeY.getCenter(); } + + /// yields true if given point is contained in set + bool isInside(const Tuple2D& rTuple) const + { + return maRangeX.isInside(rTuple.getX()) && maRangeY.isInside(rTuple.getY()); + } + + /// yields true if rRange is inside, or equal to set + bool isInside(const Range2D& rRange) const + { + return maRangeX.isInside(rRange.maRangeX) && maRangeY.isInside(rRange.maRangeY); + } + + /// yields true if rRange at least partly inside set + bool overlaps(const Range2D& rRange) const + { + return maRangeX.overlaps(rRange.maRangeX) && maRangeY.overlaps(rRange.maRangeY); + } + + /// yields true if overlaps(rRange) does, and the overlap is larger than infinitesimal + bool overlapsMore(const Range2D& rRange) const + { + return maRangeX.overlapsMore(rRange.maRangeX) && maRangeY.overlapsMore(rRange.maRangeY); + } + + /// add point to the set, expanding as necessary + void expand(const Tuple2D& rTuple) + { + maRangeX.expand(rTuple.getX()); + maRangeY.expand(rTuple.getY()); + } + + /// add rRange to the set, expanding as necessary + void expand(const Range2D& rRange) + { + maRangeX.expand(rRange.maRangeX); + maRangeY.expand(rRange.maRangeY); + } + + /// calc set intersection + void intersect(const Range2D& rRange) + { + maRangeX.intersect(rRange.maRangeX); + maRangeY.intersect(rRange.maRangeY); + } + + /// grow set by fValue on all sides + void grow(TYPE fValue) + { + maRangeX.grow(fValue); + maRangeY.grow(fValue); + } + + /// clamp value on range + Tuple2D clamp(const Tuple2D& rTuple) const + { + return Tuple2D(maRangeX.clamp(rTuple.getX()), maRangeY.clamp(rTuple.getY())); + } +}; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b1drange.hxx b/include/basegfx/range/b1drange.hxx new file mode 100644 index 000000000..0db585558 --- /dev/null +++ b/include/basegfx/range/b1drange.hxx @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + + +namespace basegfx +{ + + /** A one-dimensional interval over doubles + + This is a set of real numbers, bounded by a lower and an upper + value. All inbetween values are included in the set (see also + http://en.wikipedia.org/wiki/Interval_%28mathematics%29). + + The set is closed, i.e. the upper and the lower bound are + included (if you're used to the notation - we're talking about + [a,b] here, compared to half-open [a,b) or open intervals + (a,b)). + + That means, isInside(val) will return true also for values of + val=a or val=b. + */ + class B1DRange + { + ::basegfx::BasicRange< double, DoubleTraits > maRange; + + public: + B1DRange() {} + + /// Create degenerate interval consisting of a single double number + explicit B1DRange(double fStartValue) + : maRange(fStartValue) + { + } + + /// Create proper interval between the two given double values + B1DRange(double fStartValue1, double fStartValue2) + : maRange(fStartValue1) + { + expand(fStartValue2); + } + + /** Check if the interval set is empty + + @return false, if no value is in this set - having a + single value included will already return true. + */ + bool isEmpty() const + { + return maRange.isEmpty(); + } + + bool operator==( const B1DRange& rRange ) const + { + return (maRange == rRange.maRange); + } + + bool operator!=( const B1DRange& rRange ) const + { + return (maRange != rRange.maRange); + } + + /// get lower bound of the set. returns arbitrary values for empty sets. + double getMinimum() const + { + return maRange.getMinimum(); + } + + /// get upper bound of the set. returns arbitrary values for empty sets. + double getMaximum() const + { + return maRange.getMaximum(); + } + + /// return difference between upper and lower value. returns 0 for empty sets. + double getRange() const + { + return maRange.getRange(); + } + + /// return middle of upper and lower value. returns 0 for empty sets. + double getCenter() const + { + return maRange.getCenter(); + } + + /// yields true if value is contained in set + bool isInside(double fValue) const + { + return maRange.isInside(fValue); + } + + /// yields true if rRange at least partly inside set + bool overlaps(const B1DRange& rRange) const + { + return maRange.overlaps(rRange.maRange); + } + + /// yields true if overlaps(rRange) does, and the overlap is larger than infinitesimal + bool overlapsMore(const B1DRange& rRange) const + { + return maRange.overlapsMore(rRange.maRange); + } + + /// add fValue to the set, expanding as necessary + void expand(double fValue) + { + maRange.expand(fValue); + } + + /// add rRange to the set, expanding as necessary + void expand(const B1DRange& rRange) + { + maRange.expand(rRange.maRange); + } + + /// calc set intersection + void intersect(const B1DRange& rRange) + { + maRange.intersect(rRange.maRange); + } + + /// clamp value on range + double clamp(double fValue) const + { + return maRange.clamp(fValue); + } + }; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2dconnectedranges.hxx b/include/basegfx/range/b2dconnectedranges.hxx new file mode 100644 index 000000000..0dc7a4c24 --- /dev/null +++ b/include/basegfx/range/b2dconnectedranges.hxx @@ -0,0 +1,239 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + + +namespace basegfx +{ + /** Calculate connected ranges from input ranges. + + This template constructs a list of connected ranges from the + given input ranges. That is, the output will contain a set of + ranges, itself containing a number of input ranges, which will + be mutually non-intersecting. + + Example: + + ------------------- + | -------| + | | || + | --- | || + | | | -------| -------- + | | +--------- | | | + | --+ | | | | + | | | | -------- + | ---------- | + ------------------- + class B2DConnectedRanges + { + public: + /// Type of the basic entity (rect + user data) + typedef ::std::pair< B2DRange, UserData > ComponentType; + typedef ::std::list< ComponentType > ComponentListType; + + /// List of (intersecting) components, plus overall bounds + struct ConnectedComponents + { + ComponentListType maComponentList; + B2DRange maTotalBounds; + }; + + typedef ::std::list< ConnectedComponents > ConnectedComponentsType; + + + /// Create the range calculator + B2DConnectedRanges() : + maDisjunctAggregatesList() + { + } + + /** Add an additional range. + + This method integrates a new range into the connected + ranges lists. The method has a worst-case time complexity + of O(n^2), with n denoting the number of already added + ranges (typically, for well-behaved input, it is O(n) + though). + */ + void addRange( const B2DRange& rRange, + const UserData& rUserData ) + { + // check whether fast path is possible: if new range is + // outside accumulated total range, can add it as a + // separate component right away. + const bool bNotOutsideEverything( + maTotalBounds.overlaps( rRange ) ); + + // update own global bounds range + maTotalBounds.expand( rRange ); + + // assemble anything intersecting with rRange into + // this new connected component + ConnectedComponents aNewConnectedComponent; + + // as at least rRange will be a member of + // aNewConnectedComponent (will be added below), can + // preset the overall bounds here. + aNewConnectedComponent.maTotalBounds = rRange; + + + // STAGE 1: Search for intersecting maDisjunctAggregatesList entries + + + // if rRange is empty, it will intersect with no + // maDisjunctAggregatesList member. Thus, we can safe us + // the check. + // if rRange is outside all other rectangle, skip here, + // too + if( bNotOutsideEverything && + !rRange.isEmpty() ) + { + typename ConnectedComponentsType::iterator aCurrAggregate; + typename ConnectedComponentsType::iterator aLastAggregate; + + // flag, determining whether we touched one or more of + // the maDisjunctAggregatesList entries. _If_ we did, + // we have to repeat the intersection process, because + // these changes might have generated new + // intersections. + bool bSomeAggregatesChanged; + + // loop, until bSomeAggregatesChanged stays false + do + { + // only continue loop if 'intersects' branch below was hit + bSomeAggregatesChanged = false; + + // iterate over all current members of maDisjunctAggregatesList + for( aCurrAggregate=maDisjunctAggregatesList.begin(), + aLastAggregate=maDisjunctAggregatesList.end(); + aCurrAggregate != aLastAggregate; ) + { + // first check if current component's bounds + // are empty. This ensures that distinct empty + // components are not merged into one + // aggregate. As a matter of fact, they have + // no position and size. + + if( !aCurrAggregate->maTotalBounds.isEmpty() && + aCurrAggregate->maTotalBounds.overlaps( + aNewConnectedComponent.maTotalBounds ) ) + { + // union the intersecting + // maDisjunctAggregatesList element into + // aNewConnectedComponent + + // calc union bounding box + aNewConnectedComponent.maTotalBounds.expand( aCurrAggregate->maTotalBounds ); + + // extract all aCurrAggregate components + // to aNewConnectedComponent + aNewConnectedComponent.maComponentList.splice( + aNewConnectedComponent.maComponentList.end(), + aCurrAggregate->maComponentList ); + + // remove and delete aCurrAggregate entry + // from list (we've gutted it's content + // above). list::erase() will update our + // iterator with the predecessor here. + aCurrAggregate = maDisjunctAggregatesList.erase( aCurrAggregate ); + + // at least one aggregate changed, need to rescan everything + bSomeAggregatesChanged = true; + } + else + { + ++aCurrAggregate; + } + } + } + while( bSomeAggregatesChanged ); + } + + + // STAGE 2: Add newly generated connected component list element + + + // add new component to the end of the component list + aNewConnectedComponent.maComponentList.push_back( + ComponentType( rRange, rUserData ) ); + + // do some consistency checks (aka post conditions) + OSL_ENSURE( !aNewConnectedComponent.maComponentList.empty(), + "B2DConnectedRanges::addRange(): empty aggregate list" ); + OSL_ENSURE( !aNewConnectedComponent.maTotalBounds.isEmpty() || + aNewConnectedComponent.maComponentList.size() == 1, + "B2DConnectedRanges::addRange(): empty ranges must be solitary"); + + // add aNewConnectedComponent as a new entry to + // maDisjunctAggregatesList + maDisjunctAggregatesList.push_back( aNewConnectedComponent ); + } + + /** Apply a functor to each of the disjunct component + aggregates. + + @param aFunctor + Functor to apply. Must provide an operator( const ConnectedComponents& ). + + @return a copy of the functor, as applied to all aggregates. + */ + template< typename UnaryFunctor > UnaryFunctor forEachAggregate( UnaryFunctor aFunctor ) const + { + return ::std::for_each( maDisjunctAggregatesList.begin(), + maDisjunctAggregatesList.end(), + aFunctor ); + } + + private: + B2DConnectedRanges(const B2DConnectedRanges&) = delete; + B2DConnectedRanges& operator=( const B2DConnectedRanges& ) = delete; + + /** Current list of disjunct sets of connected components + + Each entry corresponds to one of the top-level rectangles + in the drawing above. + */ + ConnectedComponentsType maDisjunctAggregatesList; + + /** Global bound rect over all added ranges. + */ + B2DRange maTotalBounds; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2dpolyrange.hxx b/include/basegfx/range/b2dpolyrange.hxx new file mode 100644 index 000000000..9a366956c --- /dev/null +++ b/include/basegfx/range/b2dpolyrange.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace basegfx +{ + class B2DRange; + class B2DPolyPolygon; + class B2DHomMatrix; + class ImplB2DPolyRange; + + /** Multiple ranges in one object. + + This class combines multiple ranges in one object, providing a + total, enclosing range for it. + + You can use this class e.g. when updating views containing + rectangular objects. Add each modified object to a + B2DMultiRange, then test each viewable object against + intersection with the multi range. + + Similar in spirit to the poly-polygon vs. polygon relationship. + + Note that comparable to polygons, a poly-range can also + contain 'holes' - this is encoded via polygon orientation at + the poly-polygon, and via explicit flags for the poly-range. + */ + class BASEGFX_DLLPUBLIC B2DPolyRange + { + public: + typedef std::tuple ElementType; + + B2DPolyRange(); + ~B2DPolyRange(); + + /** Create a multi range with exactly one containing range + */ + B2DPolyRange( const B2DPolyRange& ); + B2DPolyRange& operator=( const B2DPolyRange& ); + + bool operator==(const B2DPolyRange&) const; + bool operator!=(const B2DPolyRange&) const; + + /// Number of included ranges + sal_uInt32 count() const; + + ElementType getElement(sal_uInt32 nIndex) const; + + // insert/append a single range + void appendElement(const B2DRange& rRange, B2VectorOrientation eOrient); + + void clear(); + + /** Test whether given range overlaps one or more of the + included ranges. Does *not* use overall range, but checks + individually. + */ + bool overlaps( const B2DRange& rRange ) const; + + /** Request a poly-polygon with solved cross-overs + */ + B2DPolyPolygon solveCrossovers() const; + + void transform(const B2DHomMatrix& rTranslate); + + private: + o3tl::cow_wrapper< ImplB2DPolyRange > mpImpl; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2drange.hxx b/include/basegfx/range/b2drange.hxx new file mode 100644 index 000000000..3fce8df1a --- /dev/null +++ b/include/basegfx/range/b2drange.hxx @@ -0,0 +1,175 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace basegfx +{ + class B2IRange; + class B2DHomMatrix; + + /** A two-dimensional interval over doubles + + This is a set of real numbers, bounded by a lower and an upper + pair. All inbetween values are included in the set (see also + http://en.wikipedia.org/wiki/Interval_%28mathematics%29). + + The set is closed, i.e. the upper and the lower bound are + included (if you're used to the notation - we're talking about + [a,b] here, compared to half-open [a,b) or open intervals + (a,b)). + + That means, isInside(val) will return true also for values of + val=a or val=b. + + @see B1DRange + */ + class SAL_WARN_UNUSED B2DRange : public Range2D + { + public: + B2DRange() + : Range2D() + {} + + /// Create degenerate interval consisting of a single point + explicit B2DRange(const Tuple2D& rTuple) + : Range2D(rTuple) + { + } + + /// Create proper interval between the two given points + B2DRange(const Tuple2D& rTuple1, + const Tuple2D& rTuple2) + : Range2D(rTuple1, rTuple2) + { + } + + B2DRange(ValueType x1, ValueType y1, ValueType x2, ValueType y2) + : Range2D(x1, y1, x2, y2) + {} + + BASEGFX_DLLPUBLIC explicit B2DRange(const B2IRange& rRange); + + /// get lower bound of the set. returns arbitrary values for empty sets. + B2DPoint getMinimum() const + { + return B2DPoint( + maRangeX.getMinimum(), + maRangeY.getMinimum() + ); + } + + /// get upper bound of the set. returns arbitrary values for empty sets. + B2DPoint getMaximum() const + { + return B2DPoint( + maRangeX.getMaximum(), + maRangeY.getMaximum() + ); + } + + /// return difference between upper and lower point. returns (0,0) for empty sets. + B2DVector getRange() const + { + return B2DVector( + maRangeX.getRange(), + maRangeY.getRange() + ); + } + + /// return center point of set. returns (0,0) for empty sets. + B2DPoint getCenter() const + { + return B2DPoint( + maRangeX.getCenter(), + maRangeY.getCenter() + ); + } + + /** Transform Range by given transformation matrix. */ + BASEGFX_DLLPUBLIC void transform(const B2DHomMatrix& rMatrix); + + /** Transform Range by given transformation matrix. + + This operation transforms the Range by transforming all four possible + extrema points (corners) of the given range and building a new one. + This means that the range will grow evtl. when a shear and/or rotation + is part of the transformation. + */ + BASEGFX_DLLPUBLIC B2DRange& operator*=( const ::basegfx::B2DHomMatrix& rMat ); + + /** Get a range filled with (0.0, 0.0, 1.0, 1.0) */ + static const B2DRange& getUnitB2DRange(); + }; + + /** Transform B2DRange by given transformation matrix (see operator*=()) + */ + B2DRange operator*( const B2DHomMatrix& rMat, const B2DRange& rB2DRange ); + + /** Round double to nearest integer for 2D range + + @return the nearest integer for this range + */ + BASEGFX_DLLPUBLIC B2IRange fround(const B2DRange& rRange); + + /** Compute the set difference of the two given ranges + + This method calculates the symmetric difference (aka XOR) + between the two given ranges, and returning the resulting + ranges. Thus, the result will contain all areas where one, but + not both ranges lie. + + @param o_rResult + Result vector. The up to four difference ranges are returned + within this vector + + @param rFirst + The first range + + @param rSecond + The second range + + @return the input vector + */ + BASEGFX_DLLPUBLIC std::vector& computeSetDifference( + std::vector& o_rResult, + const B2DRange& rFirst, + const B2DRange& rSecond); + + /** Write to char stream */ + template + inline std::basic_ostream& operator<<( + std::basic_ostream& stream, const B2DRange& range) + { + return stream << range.getWidth() << "x" << range.getHeight() << "@" << range.getMinimum(); + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2drangeclipper.hxx b/include/basegfx/range/b2drangeclipper.hxx new file mode 100644 index 000000000..6ea0a3f0e --- /dev/null +++ b/include/basegfx/range/b2drangeclipper.hxx @@ -0,0 +1,39 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx::utils +{ + /** Extract poly-polygon w/o self-intersections from poly-range + + Similar to the solveCrossovers(const B2DPolyPolygon&) + method, this one calculates a self-intersection-free + poly-polygon with the same topology, and encoding + inside/outsidedness via polygon orientation and layering. + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon solveCrossovers(const std::vector& rRanges, + const std::vector& rOrientations); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2drectangle.hxx b/include/basegfx/range/b2drectangle.hxx new file mode 100644 index 000000000..ad8744b5d --- /dev/null +++ b/include/basegfx/range/b2drectangle.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace basegfx +{ +// syntactic sugar: a B2DRange exactly models a Rectangle, thus, +// for interface clarity, we provide an alias name + +/// Alias name for interface clarity (not everybody is aware of the identity) +typedef B2DRange B2DRectangle; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2ibox.hxx b/include/basegfx/range/b2ibox.hxx new file mode 100644 index 000000000..2be733b93 --- /dev/null +++ b/include/basegfx/range/b2ibox.hxx @@ -0,0 +1,190 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace basegfx +{ + /** A two-dimensional interval over integers + + This is most easily depicted as a set of integers, bounded by + a lower and an upper value - but excluding the upper + value. All inbetween values are included in the set (see also + http://en.wikipedia.org/wiki/Interval_%28mathematics%29). + + The set is half-open, i.e. the lower bound is included, the + upper bound not (if you're used to the notation - we're + talking about [a,b) here, compared to closed [a,b] or fully + open intervals (a,b)). + + If you don't need a half-open interval, check B2IRange. + + That means, isInside(val) will return true also for values of + val=a, but not for val=b. + + Alternatively, consider this a rectangle, where the rightmost + pixel column and the bottommost pixel row are excluded - this + is much like polygon filling. As a result, filling a given + rectangle with basebmp::BitmapDevice::fillPolyPolygon(), will + affect exactly the same set of pixel as isInside() would + return true for. + + @see B2IRange + */ + class B2IBox + { + public: + typedef sal_Int32 ValueType; + typedef Int32Traits TraitsType; + + B2IBox() {} + + /// Create degenerate interval that's still empty + explicit B2IBox(const B2ITuple& rTuple) + : maRangeX(rTuple.getX()), + maRangeY(rTuple.getY()) + { + } + + /// Create proper interval between the two given points + B2IBox(sal_Int32 x1, + sal_Int32 y1, + sal_Int32 x2, + sal_Int32 y2) : + maRangeX(x1), + maRangeY(y1) + { + maRangeX.expand(x2); + maRangeY.expand(y2); + } + + /// Create proper interval between the two given points + B2IBox(const B2ITuple& rTuple1, + const B2ITuple& rTuple2) : + maRangeX(rTuple1.getX()), + maRangeY(rTuple1.getY()) + { + expand( rTuple2 ); + } + + /** Check if the interval set is empty + + @return false, if no value is in this set - having a + single value included will still return false. + */ + bool isEmpty() const + { + return maRangeX.isEmpty() || maRangeY.isEmpty(); + } + + bool operator==( const B2IBox& rBox ) const + { + return (maRangeX == rBox.maRangeX + && maRangeY == rBox.maRangeY); + } + + bool operator!=( const B2IBox& rBox ) const + { + return (maRangeX != rBox.maRangeX + || maRangeY != rBox.maRangeY); + } + + /// get lower bound of the set. returns arbitrary values for empty sets. + sal_Int32 getMinX() const + { + return maRangeX.getMinimum(); + } + + /// get lower bound of the set. returns arbitrary values for empty sets. + sal_Int32 getMinY() const + { + return maRangeY.getMinimum(); + } + + /// get upper bound of the set. returns arbitrary values for empty sets. + sal_Int32 getMaxX() const + { + return maRangeX.getMaximum(); + } + + /// get upper bound of the set. returns arbitrary values for empty sets. + sal_Int32 getMaxY() const + { + return maRangeY.getMaximum(); + } + + /// return difference between upper and lower X value. returns 0 for empty sets. + sal_Int64 getWidth() const + { + return maRangeX.getRange(); + } + + /// return difference between upper and lower Y value. returns 0 for empty sets. + sal_Int64 getHeight() const + { + return maRangeY.getRange(); + } + + /// yields true if point is contained in set + bool isInside(const B2ITuple& rTuple) const + { + return ( + maRangeX.isInside(rTuple.getX()) + && maRangeY.isInside(rTuple.getY()) + ); + } + + /// add point to the set, expanding as necessary + void expand(const B2ITuple& rTuple) + { + maRangeX.expand(rTuple.getX()); + maRangeY.expand(rTuple.getY()); + } + + /// calc set intersection + void intersect(const B2IBox& rBox) + { + maRangeX.intersect(rBox.maRangeX); + maRangeY.intersect(rBox.maRangeY); + } + + private: + BasicBox maRangeX; + BasicBox maRangeY; + }; + +} // end of namespace basegfx + +template< typename charT, typename traits > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const basegfx::B2IBox& box ) +{ + if (box.isEmpty()) + return stream << "EMPTY"; + else + return stream << box.getWidth() << 'x' << box.getHeight() + << "@(" << box.getMinX() << "," << box.getMinY() << ")"; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2irange.hxx b/include/basegfx/range/b2irange.hxx new file mode 100644 index 000000000..f1a0b0aae --- /dev/null +++ b/include/basegfx/range/b2irange.hxx @@ -0,0 +1,141 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace basegfx +{ + /** A two-dimensional interval over integers + + This is a set of real numbers, bounded by a lower and an upper + pair. All inbetween values are included in the set (see also + http://en.wikipedia.org/wiki/Interval_%28mathematics%29). + + Probably you rather want B2IBox for integers. + + The set is closed, i.e. the upper and the lower bound are + included (if you're used to the notation - we're talking about + [a,b] here, compared to half-open [a,b) or open intervals + (a,b)). + + That means, isInside(val) will return true also for values of + val=a or val=b. + + @see B2IBox + */ + class B2IRange : public Range2D + { + public: + B2IRange() + : Range2D() + {} + + /// Create degenerate interval consisting of a single point + explicit B2IRange(const Tuple2D& rTuple) + : Range2D(rTuple) + { + } + + /// Create proper interval between the two given points + B2IRange(const Tuple2D& rTuple1, + const Tuple2D& rTuple2) + : Range2D(rTuple1, rTuple2) + { + } + + B2IRange(ValueType x1, ValueType y1, ValueType x2, ValueType y2) + : Range2D(x1, y1, x2, y2) + {} + + /// get lower bound of the set. returns arbitrary values for empty sets. + B2IPoint getMinimum() const + { + return B2IPoint( + maRangeX.getMinimum(), + maRangeY.getMinimum() + ); + } + + /// get upper bound of the set. returns arbitrary values for empty sets. + B2IPoint getMaximum() const + { + return B2IPoint( + maRangeX.getMaximum(), + maRangeY.getMaximum() + ); + } + + /// return difference between upper and lower point. returns (0,0) for empty sets. + B2I64Tuple getRange() const + { + return B2I64Tuple( + maRangeX.getRange(), + maRangeY.getRange() + ); + } + }; + + /** Compute the set difference of the two given ranges + + This method calculates the symmetric difference (aka XOR) + between the two given ranges, and returning the resulting + ranges. Thus, the result will contain all areas where one, but + not both ranges lie. + + @param o_rResult + Result vector. The up to four difference ranges are returned + within this vector + + @param rFirst + The first range + + @param rSecond + The second range + + @return the input vector + */ + BASEGFX_DLLPUBLIC std::vector& computeSetDifference( + std::vector& o_rResult, + const B2IRange& rFirst, + const B2IRange& rSecond); + + /** Write to char stream */ + template + inline std::basic_ostream& operator<<( + std::basic_ostream& stream, const B2IRange& range) + { + if (range.isEmpty()) + return stream << "EMPTY"; + else + return stream << range.getWidth() << 'x' << range.getHeight() << "@" << range.getMinimum(); + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b2irectangle.hxx b/include/basegfx/range/b2irectangle.hxx new file mode 100644 index 000000000..6356fa6cf --- /dev/null +++ b/include/basegfx/range/b2irectangle.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace basegfx +{ +// syntactic sugar: a B2IRange exactly models a Rectangle, thus, +// for interface clarity, we provide an alias name + +/// Alias name for interface clarity (not everybody is aware of the identity) +typedef B2IRange B2IRectangle; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/b3drange.hxx b/include/basegfx/range/b3drange.hxx new file mode 100644 index 000000000..338c4f54a --- /dev/null +++ b/include/basegfx/range/b3drange.hxx @@ -0,0 +1,227 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace basegfx +{ + class B3DHomMatrix; + + class SAL_WARN_UNUSED B3DRange + { + typedef ::basegfx::BasicRange< double, DoubleTraits > MyBasicRange; + + MyBasicRange maRangeX; + MyBasicRange maRangeY; + MyBasicRange maRangeZ; + + public: + B3DRange() {} + + explicit B3DRange(const B3DTuple& rTuple) + : maRangeX(rTuple.getX()), + maRangeY(rTuple.getY()), + maRangeZ(rTuple.getZ()) + { + } + + B3DRange(double x1, + double y1, + double z1, + double x2, + double y2, + double z2) + : maRangeX(x1), + maRangeY(y1), + maRangeZ(z1) + { + maRangeX.expand(x2); + maRangeY.expand(y2); + maRangeZ.expand(z2); + } + + B3DRange(const B3DTuple& rTuple1, + const B3DTuple& rTuple2) + : maRangeX(rTuple1.getX()), + maRangeY(rTuple1.getY()), + maRangeZ(rTuple1.getZ()) + { + expand(rTuple2); + } + + bool isEmpty() const + { + return ( + maRangeX.isEmpty() + || maRangeY.isEmpty() + || maRangeZ.isEmpty() + ); + } + + void reset() + { + maRangeX.reset(); + maRangeY.reset(); + maRangeZ.reset(); + } + + bool operator==( const B3DRange& rRange ) const + { + return (maRangeX == rRange.maRangeX + && maRangeY == rRange.maRangeY + && maRangeZ == rRange.maRangeZ); + } + + bool operator!=( const B3DRange& rRange ) const + { + return (maRangeX != rRange.maRangeX + || maRangeY != rRange.maRangeY + || maRangeZ != rRange.maRangeZ); + } + + double getMinX() const + { + return maRangeX.getMinimum(); + } + + double getMinY() const + { + return maRangeY.getMinimum(); + } + + double getMinZ() const + { + return maRangeZ.getMinimum(); + } + + double getMaxX() const + { + return maRangeX.getMaximum(); + } + + double getMaxY() const + { + return maRangeY.getMaximum(); + } + + double getMaxZ() const + { + return maRangeZ.getMaximum(); + } + + double getWidth() const + { + return maRangeX.getRange(); + } + + double getHeight() const + { + return maRangeY.getRange(); + } + + double getDepth() const + { + return maRangeZ.getRange(); + } + + B3DVector getRange() const + { + return B3DVector( + maRangeX.getRange(), + maRangeY.getRange(), + maRangeZ.getRange() + ); + } + + B3DPoint getCenter() const + { + return B3DPoint( + maRangeX.getCenter(), + maRangeY.getCenter(), + maRangeZ.getCenter() + ); + } + + bool overlaps(const B3DRange& rRange) const + { + return ( + maRangeX.overlaps(rRange.maRangeX) + && maRangeY.overlaps(rRange.maRangeY) + && maRangeZ.overlaps(rRange.maRangeZ) + ); + } + + void expand(const B3DTuple& rTuple) + { + maRangeX.expand(rTuple.getX()); + maRangeY.expand(rTuple.getY()); + maRangeZ.expand(rTuple.getZ()); + } + + void expand(const B3DRange& rRange) + { + maRangeX.expand(rRange.maRangeX); + maRangeY.expand(rRange.maRangeY); + maRangeZ.expand(rRange.maRangeZ); + } + + void grow(double fValue) + { + maRangeX.grow(fValue); + maRangeY.grow(fValue); + maRangeZ.grow(fValue); + } + + /// clamp value on range + B3DTuple clamp(const B3DTuple& rTuple) const + { + return B3DTuple( + maRangeX.clamp(rTuple.getX()), + maRangeY.clamp(rTuple.getY()), + maRangeZ.clamp(rTuple.getZ())); + } + + BASEGFX_DLLPUBLIC void transform(const B3DHomMatrix& rMatrix); + + /** Transform Range by given transformation matrix. + + This operation transforms the Range by transforming all eight possible + extrema points (corners) of the given range and building a new one. + This means that the range will grow evtl. when a shear and/or rotation + is part of the transformation. + */ + B3DRange& operator*=( const ::basegfx::B3DHomMatrix& rMat ); + + /** Get a range filled with (0.0, 0.0, 0.0, 1.0, 1.0, 1.0) */ + static const B3DRange& getUnitB3DRange(); + }; + + /** Transform B3DRange by given transformation matrix (see operator*=()) + */ + B3DRange operator*( const B3DHomMatrix& rMat, const B3DRange& rB2DRange ); + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/basicbox.hxx b/include/basegfx/range/basicbox.hxx new file mode 100644 index 000000000..123d2b1b3 --- /dev/null +++ b/include/basegfx/range/basicbox.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + + +namespace basegfx +{ + /** Explicitly different from BasicRange, handling the inside predicates + differently. + + This is modelled after how polygon fill algorithms set pixel - + typically excluding rightmost and bottommost ones. + */ + class BasicBox : public BasicRange< sal_Int32, Int32Traits > + { + typedef BasicRange< sal_Int32, Int32Traits > Base; + public: + BasicBox() {} + + explicit BasicBox( sal_Int32 nValue ) : + Base( nValue ) + { + } + + bool isEmpty() const + { + return mnMinimum >= mnMaximum; + } + + using Base::isInside; + + bool isInside(sal_Int32 nValue) const + { + if(isEmpty()) + { + return false; + } + else + { + return (nValue >= mnMinimum) && (nValue < mnMaximum); + } + } + + using Base::overlaps; + }; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/range/basicrange.hxx b/include/basegfx/range/basicrange.hxx new file mode 100644 index 000000000..53134cd9e --- /dev/null +++ b/include/basegfx/range/basicrange.hxx @@ -0,0 +1,313 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + + +namespace basegfx +{ + template< typename T, typename Traits > class BasicRange + { + protected: + T mnMinimum; + T mnMaximum; + + public: + typedef T ValueType; + typedef Traits TraitsType; + + BasicRange() : + mnMinimum(Traits::maxVal()), + mnMaximum(Traits::minVal()) + { + } + + explicit BasicRange( T nValue ) : + mnMinimum(nValue), + mnMaximum(nValue) + { + } + + void reset() + { + mnMinimum = Traits::maxVal(); + mnMaximum = Traits::minVal(); + } + + bool isEmpty() const + { + return Traits::maxVal() == mnMinimum; + } + + T getMinimum() const { return mnMinimum; } + T getMaximum() const { return mnMaximum; } + + double getCenter() const + { + if(isEmpty()) + { + return 0.0; + } + else + { + return ((mnMaximum + mnMinimum) / 2.0); + } + } + + bool isInside(T nValue) const + { + if(isEmpty()) + { + return false; + } + else + { + return (nValue >= mnMinimum) && (nValue <= mnMaximum); + } + } + + bool isInside(const BasicRange& rRange) const + { + if(isEmpty()) + { + return false; + } + else + { + if(rRange.isEmpty()) + { + return false; + } + else + { + return (rRange.mnMinimum >= mnMinimum) && (rRange.mnMaximum <= mnMaximum); + } + } + } + + bool overlaps(const BasicRange& rRange) const + { + if(isEmpty()) + { + return false; + } + else + { + if(rRange.isEmpty()) + { + return false; + } + else + { + return (rRange.mnMaximum >= mnMinimum) && (rRange.mnMinimum <= mnMaximum); + } + } + } + + bool overlapsMore(const BasicRange& rRange) const + { + if(isEmpty() || rRange.isEmpty()) + return false; + // returns true if the overlap is more than just a touching at the limits + return ((rRange.mnMaximum > mnMinimum) && (rRange.mnMinimum < mnMaximum)); + } + + bool operator==( const BasicRange& rRange ) const + { + return (mnMinimum == rRange.mnMinimum && mnMaximum == rRange.mnMaximum); + } + + bool operator!=( const BasicRange& rRange ) const + { + return (mnMinimum != rRange.mnMinimum || mnMaximum != rRange.mnMaximum); + } + + bool equal(const BasicRange& rRange) const + { + return ( + fTools::equal(mnMinimum, rRange.mnMinimum) && + fTools::equal(mnMaximum, rRange.mnMaximum)); + } + + void expand(T nValue) + { + if(isEmpty()) + { + mnMinimum = mnMaximum = nValue; + } + else + { +// Silence over-eager warning emitted at least by GCC 4.9.2 in certain +// instantiations: +#if defined __GNUC__ && !defined __clang__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-overflow" +#endif + if(nValue < mnMinimum) +#if defined __GNUC__ && !defined __clang__ +#pragma GCC diagnostic pop +#endif + { + mnMinimum = nValue; + } + + if(nValue > mnMaximum) + { + mnMaximum = nValue; + } + } + } + + void expand(const BasicRange& rRange) + { + if(isEmpty()) + { + mnMinimum = rRange.mnMinimum; + mnMaximum = rRange.mnMaximum; + } + else + { + if(!rRange.isEmpty()) + { + if(rRange.mnMinimum < mnMinimum) + { + mnMinimum = rRange.mnMinimum; + } + + if(rRange.mnMaximum > mnMaximum) + { + mnMaximum = rRange.mnMaximum; + } + } + } + } + + void intersect(const BasicRange& rRange) + { + // here, overlaps also tests all isEmpty() conditions already. + if( !overlaps( rRange ) ) + { + reset(); + } + else + { + if(rRange.mnMinimum > mnMinimum) + { + mnMinimum = rRange.mnMinimum; + } + + if(rRange.mnMaximum < mnMaximum) + { + mnMaximum = rRange.mnMaximum; + } + } + } + + void grow(T nValue) + { + if(isEmpty()) + return; + + bool bLessThanZero(nValue < 0); + + if(nValue > 0 || bLessThanZero) + { + mnMinimum -= nValue; + mnMaximum += nValue; + + if(bLessThanZero) + { + // test if range did collapse + if(mnMinimum > mnMaximum) + { + // if yes, collapse to center + mnMinimum = mnMaximum = (mnMinimum + mnMaximum) / 2; + } + } + } + } + + T clamp(T nValue) const + { + if(isEmpty()) + { + return nValue; + } + else + { + if(nValue < mnMinimum) + { + return mnMinimum; + } + + if(nValue > mnMaximum) + { + return mnMaximum; + } + + return nValue; + } + } + +#if defined _MSC_VER && defined(_M_ARM64) +#pragma warning(push) +#pragma warning(disable: 4723) /* ignore: warning for C4723 on windows arm64 build */ +#endif + typename Traits::DifferenceType getRange() const + { + if(isEmpty()) + { + return Traits::neutral(); + } + else + { + return (mnMaximum - mnMinimum); + } + } +#if defined _MSC_VER && defined(_M_ARM64) +#pragma warning( pop ) +#endif + }; + + // some pre-fabricated traits + struct DoubleTraits + { + static constexpr double minVal() { return DBL_MIN; }; + static constexpr double maxVal() { return DBL_MAX; }; + static constexpr double neutral() { return 0.0; }; + + typedef double DifferenceType; + }; + + struct Int32Traits + { + static constexpr sal_Int32 minVal() { return SAL_MIN_INT32; }; + static constexpr sal_Int32 maxVal() { return SAL_MAX_INT32; }; + static constexpr sal_Int32 neutral() { return 0; }; + + typedef sal_Int64 DifferenceType; + }; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/raster/bzpixelraster.hxx b/include/basegfx/raster/bzpixelraster.hxx new file mode 100644 index 000000000..52ebc3c6e --- /dev/null +++ b/include/basegfx/raster/bzpixelraster.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace basegfx +{ + class BZPixelRaster + { + private: + BZPixelRaster(const BZPixelRaster&) = delete; + BZPixelRaster& operator=(const BZPixelRaster&) = delete; + + sal_uInt32 mnWidth; + sal_uInt32 mnHeight; + sal_uInt32 mnCount; + std::unique_ptr mpContent; + std::unique_ptr mpZBuffer; + + public: + // constructor/destructor + BZPixelRaster(sal_uInt32 nWidth, sal_uInt32 nHeight) + : mnWidth(nWidth), + mnHeight(nHeight), + mnCount(nWidth * nHeight), + mpContent(new BPixel[mnCount]), + mpZBuffer(new sal_uInt16[mnCount]) + { + memset(mpZBuffer.get(), 0, sizeof(sal_uInt16) * mnCount); + } + + // coordinate calcs between X/Y and span + sal_uInt32 getIndexFromXY(sal_uInt32 nX, sal_uInt32 nY) const { return (nX + (nY * mnWidth)); } + + // data access read + sal_uInt32 getWidth() const { return mnWidth; } + sal_uInt32 getHeight() const { return mnHeight; } + + // data access read only + const BPixel& getBPixel(sal_uInt32 nIndex) const + { + assert(nIndex < mnCount && "Access out of range"); + return mpContent[nIndex]; + } + + // data access read/write + BPixel& getBPixel(sal_uInt32 nIndex) + { + assert(nIndex < mnCount && "Access out of range"); + return mpContent[nIndex]; + } + + // data access read only + const sal_uInt16& getZ(sal_uInt32 nIndex) const + { + assert(nIndex < mnCount && "Access out of range"); + return mpZBuffer[nIndex]; + } + + // data access read/write + sal_uInt16& getZ(sal_uInt32 nIndex) + { + assert(nIndex < mnCount && "Access out of range"); + return mpZBuffer[nIndex]; + } + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/raster/rasterconvert3d.hxx b/include/basegfx/raster/rasterconvert3d.hxx new file mode 100644 index 000000000..83f753e31 --- /dev/null +++ b/include/basegfx/raster/rasterconvert3d.hxx @@ -0,0 +1,421 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace basegfx +{ + class B3DPolygon; + class B3DPolyPolygon; +} + +// interpolators for double precision + +namespace basegfx +{ + class ip_single + { + private: + double mfVal; + double mfInc; + + public: + ip_single() + : mfVal(0.0), + mfInc(0.0) + {} + + ip_single(double fVal, double fInc) + : mfVal(fVal), + mfInc(fInc) + {} + + double getVal() const { return mfVal; } + double getInc() const { return mfInc; } + + void increment(double fStep) { mfVal += fStep * mfInc; } + }; + + class ip_double + { + private: + ip_single maX; + ip_single maY; + + public: + ip_double() + {} + + ip_double(double fXVal, double fXInc, double fYVal, double fYInc) + : maX(fXVal, fXInc), + maY(fYVal, fYInc) + {} + + const ip_single& getX() const { return maX; } + const ip_single& getY() const { return maY; } + + void increment(double fStep) { maX.increment(fStep); maY.increment(fStep); } + }; + + class ip_triple + { + private: + ip_single maX; + ip_single maY; + ip_single maZ; + + public: + ip_triple() + {} + + ip_triple(double fXVal, double fXInc, double fYVal, double fYInc, double fZVal, double fZInc) + : maX(fXVal, fXInc), + maY(fYVal, fYInc), + maZ(fZVal, fZInc) + {} + + const ip_single& getX() const { return maX; } + const ip_single& getY() const { return maY; } + const ip_single& getZ() const { return maZ; } + + void increment(double fStep) { maX.increment(fStep); maY.increment(fStep); maZ.increment(fStep); } + }; + + // InterpolatorProvider3D to have a common source for allocating interpolators + // which may then be addressed using the index to the vectors + + #define SCANLINE_EMPTY_INDEX (0xffffffff) + + class InterpolatorProvider3D + { + private: + ::std::vector< ip_triple > maColorInterpolators; + ::std::vector< ip_triple > maNormalInterpolators; + ::std::vector< ip_double > maTextureInterpolators; + ::std::vector< ip_triple > maInverseTextureInterpolators; + + protected: + sal_uInt32 addColorInterpolator(const BColor& rA, const BColor& rB, double fInvYDelta) + { + double aDeltaRed(rB.getRed() - rA.getRed()); + + if(fTools::equalZero(aDeltaRed)) + { + aDeltaRed = 0.0; + } + else + { + aDeltaRed *= fInvYDelta; + } + + double aDeltaGreen(rB.getGreen() - rA.getGreen()); + + if(fTools::equalZero(aDeltaGreen)) + { + aDeltaGreen = 0.0; + } + else + { + aDeltaGreen *= fInvYDelta; + } + + double aDeltaBlue(rB.getBlue() - rA.getBlue()); + + if(fTools::equalZero(aDeltaBlue)) + { + aDeltaBlue = 0.0; + } + else + { + aDeltaBlue *= fInvYDelta; + } + + maColorInterpolators.push_back( + ip_triple( + rA.getRed(), aDeltaRed, + rA.getGreen(), aDeltaGreen, + rA.getBlue(), aDeltaBlue)); + + return (maColorInterpolators.size() - 1); + } + + sal_uInt32 addNormalInterpolator(const B3DVector& rA, const B3DVector& rB, double fInvYDelta) + { + double aDeltaX(rB.getX() - rA.getX()); + + if(fTools::equalZero(aDeltaX)) + { + aDeltaX = 0.0; + } + else + { + aDeltaX *= fInvYDelta; + } + + double aDeltaY(rB.getY() - rA.getY()); + + if(fTools::equalZero(aDeltaY)) + { + aDeltaY = 0.0; + } + else + { + aDeltaY *= fInvYDelta; + } + + double aDeltaZ(rB.getZ() - rA.getZ()); + + if(fTools::equalZero(aDeltaZ)) + { + aDeltaZ = 0.0; + } + else + { + aDeltaZ *= fInvYDelta; + } + + maNormalInterpolators.push_back( + ip_triple( + rA.getX(), aDeltaX, + rA.getY(), aDeltaY, + rA.getZ(), aDeltaZ)); + + return (maNormalInterpolators.size() - 1); + } + + sal_uInt32 addTextureInterpolator(const B2DPoint& rA, const B2DPoint& rB, double fInvYDelta) + { + double aDeltaX(rB.getX() - rA.getX()); + + if(fTools::equalZero(aDeltaX)) + { + aDeltaX = 0.0; + } + else + { + aDeltaX *= fInvYDelta; + } + + double aDeltaY(rB.getY() - rA.getY()); + + if(fTools::equalZero(aDeltaY)) + { + aDeltaY = 0.0; + } + else + { + aDeltaY *= fInvYDelta; + } + + maTextureInterpolators.push_back( + ip_double( + rA.getX(), aDeltaX, + rA.getY(), aDeltaY)); + + return (maTextureInterpolators.size() - 1); + } + + sal_uInt32 addInverseTextureInterpolator(const B2DPoint& rA, const B2DPoint& rB, double fZEyeA, double fZEyeB, double fInvYDelta) + { + double fZDelta(fZEyeB - fZEyeA); + const double fInvZEyeA(fTools::equalZero(fZEyeA) ? fZEyeA : 1.0 / fZEyeA); + double fInvZEyeB(fInvZEyeA); + + if(fTools::equalZero(fZDelta)) + { + fZDelta = 0.0; + } + else + { + fInvZEyeB = fTools::equalZero(fZEyeB) ? fZEyeB : 1.0 / fZEyeB; + fZDelta = (fInvZEyeB - fInvZEyeA) * fInvYDelta; + } + + const B2DPoint aInvA(rA * fInvZEyeA); + const B2DPoint aInvB(rB * fInvZEyeB); + const double aDeltaX((aInvB.getX() - aInvA.getX()) * fInvYDelta); + const double aDeltaY((aInvB.getY() - aInvA.getY()) * fInvYDelta); + + maInverseTextureInterpolators.push_back( + ip_triple( + aInvA.getX(), aDeltaX, + aInvA.getY(), aDeltaY, + fInvZEyeA, fZDelta)); + + return (maInverseTextureInterpolators.size() - 1); + } + + void reset() + { + maColorInterpolators.clear(); + maNormalInterpolators.clear(); + maTextureInterpolators.clear(); + maInverseTextureInterpolators.clear(); + } + + public: + InterpolatorProvider3D() {} + + ::std::vector< ip_triple >& getColorInterpolators() { return maColorInterpolators; } + ::std::vector< ip_triple >& getNormalInterpolators() { return maNormalInterpolators; } + ::std::vector< ip_double >& getTextureInterpolators() { return maTextureInterpolators; } + ::std::vector< ip_triple >& getInverseTextureInterpolators() { return maInverseTextureInterpolators; } + }; + + // RasterConversionLineEntry3D for Rasterconversion of 3D PolyPolygons + + class RasterConversionLineEntry3D + { + private: + ip_single maX; + ip_single maZ; + sal_Int32 mnY; + sal_uInt32 mnCount; + + sal_uInt32 mnColorIndex; + sal_uInt32 mnNormalIndex; + sal_uInt32 mnTextureIndex; + sal_uInt32 mnInverseTextureIndex; + + public: + RasterConversionLineEntry3D(const double& rfX, const double& rfDeltaX, const double& rfZ, const double& rfDeltaZ, sal_Int32 nY, sal_uInt32 nCount) + : maX(rfX, rfDeltaX), + maZ(rfZ, rfDeltaZ), + mnY(nY), + mnCount(nCount), + mnColorIndex(SCANLINE_EMPTY_INDEX), + mnNormalIndex(SCANLINE_EMPTY_INDEX), + mnTextureIndex(SCANLINE_EMPTY_INDEX), + mnInverseTextureIndex(SCANLINE_EMPTY_INDEX) + {} + + void setColorIndex(sal_uInt32 nIndex) { mnColorIndex = nIndex; } + void setNormalIndex(sal_uInt32 nIndex) { mnNormalIndex = nIndex; } + void setTextureIndex(sal_uInt32 nIndex) { mnTextureIndex = nIndex; } + void setInverseTextureIndex(sal_uInt32 nIndex) { mnInverseTextureIndex = nIndex; } + + bool operator<(const RasterConversionLineEntry3D& rComp) const + { + if(mnY == rComp.mnY) + { + return maX.getVal() < rComp.maX.getVal(); + } + + return mnY < rComp.mnY; + } + + bool decrementRasterConversionLineEntry3D(sal_uInt32 nStep) + { + if(nStep >= mnCount) + { + return false; + } + else + { + mnCount -= nStep; + return true; + } + } + + void incrementRasterConversionLineEntry3D(sal_uInt32 nStep, InterpolatorProvider3D& rProvider) + { + const double fStep(static_cast(nStep)); + maX.increment(fStep); + maZ.increment(fStep); + mnY += nStep; + + if(SCANLINE_EMPTY_INDEX != mnColorIndex) + { + rProvider.getColorInterpolators()[mnColorIndex].increment(fStep); + } + + if(SCANLINE_EMPTY_INDEX != mnNormalIndex) + { + rProvider.getNormalInterpolators()[mnNormalIndex].increment(fStep); + } + + if(SCANLINE_EMPTY_INDEX != mnTextureIndex) + { + rProvider.getTextureInterpolators()[mnTextureIndex].increment(fStep); + } + + if(SCANLINE_EMPTY_INDEX != mnInverseTextureIndex) + { + rProvider.getInverseTextureInterpolators()[mnInverseTextureIndex].increment(fStep); + } + } + + // data read access + const ip_single& getX() const { return maX; } + sal_Int32 getY() const { return mnY; } + const ip_single& getZ() const { return maZ; } + sal_uInt32 getColorIndex() const { return mnColorIndex; } + sal_uInt32 getNormalIndex() const { return mnNormalIndex; } + sal_uInt32 getTextureIndex() const { return mnTextureIndex; } + sal_uInt32 getInverseTextureIndex() const { return mnInverseTextureIndex; } + }; + + // the basic RasterConverter itself. Only one method needs to be overridden. The + // class itself is pure virtual + + class UNLESS_MERGELIBS(BASEGFX_DLLPUBLIC) RasterConverter3D : public InterpolatorProvider3D + { + private: + // the line entries for an area conversion run + ::std::vector< RasterConversionLineEntry3D > maLineEntries; + + struct lineComparator + { + bool operator()(const RasterConversionLineEntry3D* pA, const RasterConversionLineEntry3D* pB) + { + OSL_ENSURE(pA && pB, "lineComparator: empty pointer (!)"); + return pA->getX().getVal() < pB->getX().getVal(); + } + }; + + SAL_DLLPRIVATE void addArea(const B3DPolygon& rFill, const B3DHomMatrix* pViewToEye); + SAL_DLLPRIVATE void addArea(const B3DPolyPolygon& rFill, const B3DHomMatrix* pViewToEye); + SAL_DLLPRIVATE void addEdge(const B3DPolygon& rFill, sal_uInt32 a, sal_uInt32 b, const B3DHomMatrix* pViewToEye); + + SAL_DLLPRIVATE void rasterconvertB3DArea(sal_Int32 nStartLine, sal_Int32 nStopLine); + SAL_DLLPRIVATE void rasterconvertB3DEdge(const B3DPolygon& rLine, sal_uInt32 nA, sal_uInt32 nB, sal_Int32 nStartLine, sal_Int32 nStopLine, sal_uInt16 nLineWidth); + + virtual void processLineSpan(const RasterConversionLineEntry3D& rA, const RasterConversionLineEntry3D& rB, sal_Int32 nLine, sal_uInt32 nSpanCount) = 0; + + public: + RasterConverter3D(); + virtual ~RasterConverter3D(); + + void rasterconvertB3DPolyPolygon(const B3DPolyPolygon& rFill, const B3DHomMatrix* pViewToEye, sal_Int32 nStartLine, sal_Int32 nStopLine); + void rasterconvertB3DPolygon(const B3DPolygon& rLine, sal_Int32 nStartLine, sal_Int32 nStopLine, sal_uInt16 nLineWidth); + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/Tuple2D.hxx b/include/basegfx/tuple/Tuple2D.hxx new file mode 100644 index 000000000..44d546df6 --- /dev/null +++ b/include/basegfx/tuple/Tuple2D.hxx @@ -0,0 +1,157 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include + +namespace basegfx +{ +template class Tuple2D +{ +protected: + union { + // temporary alias mnX with mfX and mnY with mfY + struct + { + TYPE mnX; + TYPE mnY; + }; + struct + { + TYPE mfX; + TYPE mfY; + }; + }; + +public: + /** Create a 2D Tuple + + @param nX + This parameter is used to initialize the X-coordinate + of the 2D Tuple. + + @param nY + This parameter is used to initialize the Y-coordinate + of the 2D Tuple. + */ + Tuple2D(TYPE x, TYPE y) + : mnX(x) + , mnY(y) + { + } + + double get(Axis2D eAxis) { return eAxis == Axis2D::X ? getX() : getY(); } + + void set(Axis2D eAxis, TYPE fValue) + { + if (eAxis == Axis2D::X) + setX(fValue); + else + setY(fValue); + } + + /// Get X-Coordinate of 2D Tuple + TYPE getX() const { return mnX; } + + /// Get Y-Coordinate of 2D Tuple + TYPE getY() const { return mnY; } + + /// Set X-Coordinate of 2D Tuple + void setX(TYPE fX) { mnX = fX; } + + /// Set Y-Coordinate of 2D Tuple + void setY(TYPE fY) { mnY = fY; } + + /// Adjust X-Coordinate of 2D Tuple + void adjustX(TYPE fX) { mnX += fX; } + + /// Adjust Y-Coordinate of 2D Tuple + void adjustY(TYPE fY) { mnY += fY; } + + // comparators with tolerance + + template , int> = 0> + bool equal(const Tuple2D& rTup) const + { + return mfX == rTup.mfX && mfY == rTup.mfY; + } + + template , int> = 0> + bool equal(const Tuple2D& rTup) const + { + return this == &rTup || (fTools::equal(mfX, rTup.mfX) && fTools::equal(mfY, rTup.mfY)); + } + + template , int> = 0> + bool equalZero() const + { + return mnX == 0 && mnY == 0; + } + + template , int> = 0> + bool equalZero() const + { + return fTools::equalZero(mfX) && fTools::equalZero(mfY); + } + + // operator overrides + + Tuple2D& operator+=(const Tuple2D& rTup) + { + mfX += rTup.mfX; + mfY += rTup.mfY; + return *this; + } + + Tuple2D& operator-=(const Tuple2D& rTup) + { + mfX -= rTup.mfX; + mfY -= rTup.mfY; + return *this; + } + + Tuple2D& operator/=(const Tuple2D& rTup) + { + mfX /= rTup.mfX; + mfY /= rTup.mfY; + return *this; + } + + Tuple2D& operator*=(const Tuple2D& rTup) + { + mfX *= rTup.mfX; + mfY *= rTup.mfY; + return *this; + } + + Tuple2D& operator*=(TYPE t) + { + mfX *= t; + mfY *= t; + return *this; + } + + Tuple2D& operator/=(TYPE t) + { + mfX /= t; + mfY /= t; + return *this; + } + + bool operator==(const Tuple2D& rTup) const { return mfX == rTup.mfX && mfY == rTup.mfY; } + + bool operator!=(const Tuple2D& rTup) const { return !(*this == rTup); } +}; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/Tuple3D.hxx b/include/basegfx/tuple/Tuple3D.hxx new file mode 100644 index 000000000..967516663 --- /dev/null +++ b/include/basegfx/tuple/Tuple3D.hxx @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +namespace basegfx +{ +template class Tuple3D +{ +protected: + union { + // temporary alias mnX with mfX, mnY with mfY and mnZ with mfZ + struct + { + TYPE mnX; + TYPE mnY; + TYPE mnZ; + }; + struct + { + TYPE mfX; + TYPE mfY; + TYPE mfZ; + }; + }; + +public: + /** Create a 3D Tuple + + @param x + This parameter is used to initialize the X-coordinate + of the 3D Tuple. + + @param y + This parameter is used to initialize the Y-coordinate + of the 3D Tuple. + + @param z + This parameter is used to initialize the Z-coordinate + of the 3D Tuple. + */ + Tuple3D(TYPE x, TYPE y, TYPE z) + : mnX(x) + , mnY(y) + , mnZ(z) + { + } + + /// Get X-Coordinate of 3D Tuple + TYPE getX() const { return mnX; } + + /// Get Y-Coordinate of 3D Tuple + TYPE getY() const { return mnY; } + + /// Get Z-Coordinate of 3D Tuple + TYPE getZ() const { return mnZ; } + + /// Set X-Coordinate of 3D Tuple + void setX(TYPE fX) { mnX = fX; } + + /// Set Y-Coordinate of 3D Tuple + void setY(TYPE fY) { mnY = fY; } + + /// Set Z-Coordinate of 3D Tuple + void setZ(TYPE fZ) { mnZ = fZ; } + + // operators + + Tuple3D& operator+=(const Tuple3D& rTup) + { + mfX += rTup.mfX; + mfY += rTup.mfY; + mfZ += rTup.mfZ; + return *this; + } + + Tuple3D& operator-=(const Tuple3D& rTup) + { + mfX -= rTup.mfX; + mfY -= rTup.mfY; + mfZ -= rTup.mfZ; + return *this; + } + + Tuple3D& operator/=(const Tuple3D& rTup) + { + mfX /= rTup.mfX; + mfY /= rTup.mfY; + mfZ /= rTup.mfZ; + return *this; + } + + Tuple3D& operator*=(const Tuple3D& rTup) + { + mfX *= rTup.mfX; + mfY *= rTup.mfY; + mfZ *= rTup.mfZ; + return *this; + } + + Tuple3D& operator*=(TYPE t) + { + mfX *= t; + mfY *= t; + mfZ *= t; + return *this; + } + + Tuple3D& operator/=(TYPE t) + { + mfX /= t; + mfY /= t; + mfZ /= t; + return *this; + } + + bool operator==(const Tuple3D& rTup) const + { + return mfX == rTup.mfX && mfY == rTup.mfY && mfZ == rTup.mfZ; + } + + bool operator!=(const Tuple3D& rTup) const { return !operator==(rTup); } +}; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/b2dtuple.hxx b/include/basegfx/tuple/b2dtuple.hxx new file mode 100644 index 000000000..c47b7b898 --- /dev/null +++ b/include/basegfx/tuple/b2dtuple.hxx @@ -0,0 +1,177 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ + class B2ITuple; + + /** Base class for all Points/Vectors with two double values + + This class provides all methods common to Point + and Vector classes which are derived from here. + + @derive Use this class to implement Points or Vectors + which are based on two double values + */ + class SAL_WARN_UNUSED B2DTuple : public Tuple2D + { + public: + + /** Create a 2D Tuple + + The tuple is initialized to (0.0, 0.0) + */ + B2DTuple() + : Tuple2D(0.0, 0.0) + {} + + /** Create a 2D Tuple + + @param fX + This parameter is used to initialize the X-coordinate + of the 2D Tuple. + + @param fY + This parameter is used to initialize the Y-coordinate + of the 2D Tuple. + */ + B2DTuple(double fX, double fY) + : Tuple2D(fX, fY) + {} + + /** Create a copy of a 2D integer Tuple + + @param rTup + The 2D Tuple which will be copied. + */ + BASEGFX_DLLPUBLIC explicit B2DTuple(const B2ITuple& rTup); + + // operators + + B2DTuple operator-(void) const + { + return B2DTuple(-mfX, -mfY); + } + + BASEGFX_DLLPUBLIC static const B2DTuple& getEmptyTuple(); + }; + + // external operators + + + inline B2DTuple absolute(const B2DTuple& rTup) + { + B2DTuple aAbs( + fabs(rTup.getX()), + fabs(rTup.getY())); + return aAbs; + } + + inline B2DTuple interpolate(const B2DTuple& rOld1, const B2DTuple& rOld2, double t) + { + if(rOld1 == rOld2) + { + return rOld1; + } + else if(0.0 >= t) + { + return rOld1; + } + else if(1.0 <= t) + { + return rOld2; + } + else + { + return B2DTuple( + ((rOld2.getX() - rOld1.getX()) * t) + rOld1.getX(), + ((rOld2.getY() - rOld1.getY()) * t) + rOld1.getY()); + } + } + + inline B2DTuple average(const B2DTuple& rOld1, const B2DTuple& rOld2) + { + return B2DTuple( + rtl_math_approxEqual(rOld1.getX(), rOld2.getX()) ? rOld1.getX() : (rOld1.getX() + rOld2.getX()) * 0.5, + rtl_math_approxEqual(rOld1.getY(), rOld2.getY()) ? rOld1.getY() : (rOld1.getY() + rOld2.getY()) * 0.5); + } + + inline B2DTuple operator+(const B2DTuple& rTupA, const B2DTuple& rTupB) + { + B2DTuple aSum(rTupA); + aSum += rTupB; + return aSum; + } + + inline B2DTuple operator-(const B2DTuple& rTupA, const B2DTuple& rTupB) + { + B2DTuple aSub(rTupA); + aSub -= rTupB; + return aSub; + } + + inline B2DTuple operator/(const B2DTuple& rTupA, const B2DTuple& rTupB) + { + B2DTuple aDiv(rTupA); + aDiv /= rTupB; + return aDiv; + } + + inline B2DTuple operator*(const B2DTuple& rTupA, const B2DTuple& rTupB) + { + B2DTuple aMul(rTupA); + aMul *= rTupB; + return aMul; + } + + inline B2DTuple operator*(const B2DTuple& rTup, double t) + { + B2DTuple aNew(rTup); + aNew *= t; + return aNew; + } + + inline B2DTuple operator*(double t, const B2DTuple& rTup) + { + B2DTuple aNew(rTup); + aNew *= t; + return aNew; + } + + inline B2DTuple operator/(const B2DTuple& rTup, double t) + { + B2DTuple aNew(rTup); + aNew /= t; + return aNew; + } + + /** Round double to nearest integer for 2D tuple + + @return the nearest integer for this tuple + */ + BASEGFX_DLLPUBLIC B2ITuple fround(const B2DTuple& rTup); +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/b2i64tuple.hxx b/include/basegfx/tuple/b2i64tuple.hxx new file mode 100644 index 000000000..70838572f --- /dev/null +++ b/include/basegfx/tuple/b2i64tuple.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ + /** Base class for all Points/Vectors with two sal_Int64 values + + This class provides all methods common to Point + and Vector classes which are derived from here. + + @derive Use this class to implement Points or Vectors + which are based on two sal_Int64 values + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B2I64Tuple : public Tuple2D + { + public: + /** Create a 2D Tuple + + The tuple is initialized to (0, 0) + */ + B2I64Tuple() + : Tuple2D(0, 0) + {} + + /** Create a 2D Tuple + + @param nX + This parameter is used to initialize the X-coordinate + of the 2D Tuple. + + @param nY + This parameter is used to initialize the Y-coordinate + of the 2D Tuple. + */ + B2I64Tuple(sal_Int64 nX, sal_Int64 nY) + : Tuple2D(nX, nY) + {} + + /** Create a copy of a 2D Tuple + + @param rTup + The 2D Tuple which will be copied. + */ + B2I64Tuple(const B2I64Tuple& rTup) + : Tuple2D(rTup.mnX, rTup.mnY) + {} + + // operators + + B2I64Tuple operator-(void) const + { + return B2I64Tuple(-mnX, -mnY); + } + + B2I64Tuple& operator=( const B2I64Tuple& rTup ) + { + mnX = rTup.mnX; + mnY = rTup.mnY; + return *this; + } + }; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/b2ituple.hxx b/include/basegfx/tuple/b2ituple.hxx new file mode 100644 index 000000000..e3f195596 --- /dev/null +++ b/include/basegfx/tuple/b2ituple.hxx @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ + /** Base class for all Points/Vectors with two sal_Int32 values + + This class provides all methods common to Point + and Vector classes which are derived from here. + + @derive Use this class to implement Points or Vectors + which are based on two sal_Int32 values + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B2ITuple : public Tuple2D + { + public: + /** Create a 2D Tuple + + The tuple is initialized to (0, 0) + */ + B2ITuple() + : Tuple2D(0, 0) + {} + + /** Create a 2D Tuple + + @param nX + This parameter is used to initialize the X-coordinate + of the 2D Tuple. + + @param nY + This parameter is used to initialize the Y-coordinate + of the 2D Tuple. + */ + B2ITuple(sal_Int32 nX, sal_Int32 nY) + : Tuple2D(nX, nY) + {} + + // operators + + B2ITuple operator-(void) const + { + return B2ITuple(-mnX, -mnY); + } + }; + + // external operators + + + inline B2ITuple operator+(const B2ITuple& rTupA, const B2ITuple& rTupB) + { + B2ITuple aSum(rTupA); + aSum += rTupB; + return aSum; + } + + inline B2ITuple operator-(const B2ITuple& rTupA, const B2ITuple& rTupB) + { + B2ITuple aSub(rTupA); + aSub -= rTupB; + return aSub; + } + + inline B2ITuple operator*(sal_Int32 t, const B2ITuple& rTup) + { + B2ITuple aNew(rTup); + aNew *= t; + return aNew; + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/b3dtuple.hxx b/include/basegfx/tuple/b3dtuple.hxx new file mode 100644 index 000000000..7ac6a774b --- /dev/null +++ b/include/basegfx/tuple/b3dtuple.hxx @@ -0,0 +1,237 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace basegfx +{ + class B3ITuple; + + /** Base class for all Points/Vectors with three double values + + This class provides all methods common to Point + and Vector classes which are derived from here. + + @derive Use this class to implement Points or Vectors + which are based on three double values + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B3DTuple : public Tuple3D + { + public: + /** Create a 3D Tuple + + The tuple is initialized to (0.0, 0.0, 0.0) + */ + B3DTuple() + : Tuple3D(0.0, 0.0, 0.0) + {} + + /** Create a 3D Tuple + + @param fX + This parameter is used to initialize the X-coordinate + of the 3D Tuple. + + @param fY + This parameter is used to initialize the Y-coordinate + of the 3D Tuple. + + @param fZ + This parameter is used to initialize the Z-coordinate + of the 3D Tuple. + */ + B3DTuple(double fX, double fY, double fZ) + : Tuple3D(fX, fY, fZ) + {} + + /// Array-access to 3D Tuple + const double& operator[] (int nPos) const + { + // Here, normally two if(...)'s should be used. In the assumption that + // both double members can be accessed as an array a shortcut is used here. + // if(0 == nPos) return mfX; if(1 == nPos) return mfY; return mfZ; + return *((&mfX) + nPos); + } + + /// Array-access to 3D Tuple + double& operator[] (int nPos) + { + // Here, normally two if(...)'s should be used. In the assumption that + // both double members can be accessed as an array a shortcut is used here. + // if(0 == nPos) return mfX; if(1 == nPos) return mfY; return mfZ; + return *((&mfX) + nPos); + } + + // comparators with tolerance + + + bool equalZero() const + { + return (this == &getEmptyTuple() || + (::basegfx::fTools::equalZero(mfX) + && ::basegfx::fTools::equalZero(mfY) + && ::basegfx::fTools::equalZero(mfZ))); + } + + bool equal(const B3DTuple& rTup) const + { + return ( + this == &rTup || + (::basegfx::fTools::equal(mfX, rTup.mfX) && + ::basegfx::fTools::equal(mfY, rTup.mfY) && + ::basegfx::fTools::equal(mfZ, rTup.mfZ))); + } + + // operators + + B3DTuple operator-(void) const + { + return B3DTuple(-mfX, -mfY, -mfZ); + } + + bool operator==(const B3DTuple& rTup) const + { + return mfX == rTup.mfX && mfY == rTup.mfY && mfZ == rTup.mfZ; + } + + bool operator!=(const B3DTuple& rTup) const { return !operator==(rTup); } + + void correctValues(const double fCompareValue = 0.0) + { + if(0.0 == fCompareValue) + { + if(::basegfx::fTools::equalZero(mfX)) + { + mfX = 0.0; + } + + if(::basegfx::fTools::equalZero(mfY)) + { + mfY = 0.0; + } + + if(::basegfx::fTools::equalZero(mfZ)) + { + mfZ = 0.0; + } + } + else + { + if(::basegfx::fTools::equal(mfX, fCompareValue)) + { + mfX = fCompareValue; + } + + if(::basegfx::fTools::equal(mfY, fCompareValue)) + { + mfY = fCompareValue; + } + + if(::basegfx::fTools::equal(mfZ, fCompareValue)) + { + mfZ = fCompareValue; + } + } + } + + static const B3DTuple& getEmptyTuple(); + }; + + // external operators + + + inline B3DTuple interpolate(const B3DTuple& rOld1, const B3DTuple& rOld2, double t) + { + if(rOld1 == rOld2) + { + return rOld1; + } + else if(0.0 >= t) + { + return rOld1; + } + else if(1.0 <= t) + { + return rOld2; + } + else + { + return B3DTuple( + ((rOld2.getX() - rOld1.getX()) * t) + rOld1.getX(), + ((rOld2.getY() - rOld1.getY()) * t) + rOld1.getY(), + ((rOld2.getZ() - rOld1.getZ()) * t) + rOld1.getZ()); + } + } + + inline B3DTuple average(const B3DTuple& rOld1, const B3DTuple& rOld2) + { + return B3DTuple( + rtl_math_approxEqual(rOld1.getX(), rOld2.getX()) ? rOld1.getX() : (rOld1.getX() + rOld2.getX()) * 0.5, + rtl_math_approxEqual(rOld1.getY(), rOld2.getY()) ? rOld1.getY() : (rOld1.getY() + rOld2.getY()) * 0.5, + rtl_math_approxEqual(rOld1.getZ(), rOld2.getZ()) ? rOld1.getZ() : (rOld1.getZ() + rOld2.getZ()) * 0.5); + } + + inline B3DTuple operator+(const B3DTuple& rTupA, const B3DTuple& rTupB) + { + B3DTuple aSum(rTupA); + aSum += rTupB; + return aSum; + } + + inline B3DTuple operator-(const B3DTuple& rTupA, const B3DTuple& rTupB) + { + B3DTuple aSub(rTupA); + aSub -= rTupB; + return aSub; + } + + inline B3DTuple operator*(const B3DTuple& rTupA, const B3DTuple& rTupB) + { + B3DTuple aMul(rTupA); + aMul *= rTupB; + return aMul; + } + + inline B3DTuple operator*(const B3DTuple& rTup, double t) + { + B3DTuple aNew(rTup); + aNew *= t; + return aNew; + } + + inline B3DTuple operator/(const B3DTuple& rTup, double t) + { + B3DTuple aNew(rTup); + aNew /= t; + return aNew; + } + + /** Round double to nearest integer for 3D tuple + + @return the nearest integer for this tuple + */ + BASEGFX_DLLPUBLIC B3ITuple fround(const B3DTuple& rTup); +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/tuple/b3ituple.hxx b/include/basegfx/tuple/b3ituple.hxx new file mode 100644 index 000000000..72c9fa814 --- /dev/null +++ b/include/basegfx/tuple/b3ituple.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace basegfx +{ + /** Base class for all Points/Vectors with three sal_Int32 values + + This class provides all methods common to Point + and Vector classes which are derived from here. + + @derive Use this class to implement Points or Vectors + which are based on three sal_Int32 values + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B3ITuple : public Tuple3D + { + public: + /** Create a 3D Tuple + + The tuple is initialized to (0, 0, 0) + */ + B3ITuple() + : Tuple3D(0, 0, 0) + {} + + /** Create a 3D Tuple + + @param nX + This parameter is used to initialize the X-coordinate + of the 3D Tuple. + + @param nY + This parameter is used to initialize the Y-coordinate + of the 3D Tuple. + + @param nZ + This parameter is used to initialize the Z-coordinate + of the 3D Tuple. + */ + B3ITuple(sal_Int32 nX, sal_Int32 nY, sal_Int32 nZ) + : Tuple3D(nX, nY, nZ) + {} + + /// Array-access to 3D Tuple + const sal_Int32& operator[] (int nPos) const + { + // Here, normally two if(...)'s should be used. In the assumption that + // both sal_Int32 members can be accessed as an array a shortcut is used here. + // if(0 == nPos) return mnX; if(1 == nPos) return mnY; return mnZ; + return *((&mnX) + nPos); + } + + /// Array-access to 3D Tuple + sal_Int32& operator[] (int nPos) + { + // Here, normally two if(...)'s should be used. In the assumption that + // both sal_Int32 members can be accessed as an array a shortcut is used here. + // if(0 == nPos) return mnX; if(1 == nPos) return mnY; return mnZ; + return *((&mnX) + nPos); + } + + // operators + + B3ITuple operator-(void) const + { + return B3ITuple(-mnX, -mnY, -mnZ); + } + }; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/b2dclipstate.hxx b/include/basegfx/utils/b2dclipstate.hxx new file mode 100644 index 000000000..f4d9d9e7d --- /dev/null +++ b/include/basegfx/utils/b2dclipstate.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + + +namespace basegfx +{ + class B2DRange; + class B2DPolyPolygon; + class B2DHomMatrix; +} + +namespace basegfx::utils +{ + class ImplB2DClipState; + + /** This class provides an optimized, symbolic clip state for graphical output + + Having a current 'clip' state is a common attribute of + almost all graphic output APIs, most of which internally + represent it via a list of rectangular bands. In contrast, + this implementation purely uses symbolic clips, but in a + quite efficient manner, deferring actual evaluation until + a clip representation is requested, and using faster code + paths for common special cases (like all-rectangle clips) + */ + class BASEGFX_DLLPUBLIC B2DClipState + { + public: + typedef o3tl::cow_wrapper< ImplB2DClipState > ImplType; + + private: + ImplType mpImpl; + + public: + /// Init clip, in 'cleared' state - everything is visible + B2DClipState(); + ~B2DClipState(); + B2DClipState( const B2DClipState& ); + B2DClipState( B2DClipState&& ); + explicit B2DClipState( const B2DPolyPolygon& ); + B2DClipState& operator=( const B2DClipState& ); + B2DClipState& operator=( B2DClipState&& ); + + /// Set clip to 'null' - nothing is visible + void makeNull(); + + /// returns true when clip is 'cleared' - everything is visible + bool isCleared() const; + + bool operator==(const B2DClipState&) const; + bool operator!=(const B2DClipState&) const; + + void unionRange(const B2DRange& ); + void unionPolyPolygon(const B2DPolyPolygon& ); + + void intersectRange(const B2DRange& ); + void intersectPolyPolygon(const B2DPolyPolygon& ); + + void subtractRange(const B2DRange& ); + void subtractPolyPolygon(const B2DPolyPolygon& ); + + void xorRange(const B2DRange& ); + void xorPolyPolygon(const B2DPolyPolygon& ); + + void transform(const B2DHomMatrix& ); + + B2DPolyPolygon const & getClipPoly() const; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/canvastools.hxx b/include/basegfx/utils/canvastools.hxx new file mode 100644 index 000000000..9b2f44dd3 --- /dev/null +++ b/include/basegfx/utils/canvastools.hxx @@ -0,0 +1,165 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + + +namespace com::sun::star::geometry +{ + struct AffineMatrix2D; + struct AffineMatrix3D; + struct RealPoint2D; + struct RealSize2D; + struct RealRectangle2D; + struct RealRectangle3D; + struct IntegerSize2D; + struct IntegerRectangle2D; + struct RealBezierSegment2D; +} + +namespace com::sun::star::rendering +{ + class XGraphicDevice; + class XPolyPolygon2D; +} + +namespace com::sun::star::awt +{ + struct Rectangle; +} + +namespace basegfx +{ + class B2DHomMatrix; + class B3DHomMatrix; + class B2DVector; + class B2DPoint; + class B2DRange; + class B3DRange; + class B2IVector; + class B2IRange; + class B2DPolygon; + class B2DPolyPolygon; +} + +namespace basegfx::unotools +{ + // Polygon conversions + + + BASEGFX_DLLPUBLIC css::uno::Reference< css::rendering::XPolyPolygon2D > + xPolyPolygonFromB2DPolygon( const css::uno::Reference< css::rendering::XGraphicDevice >& xGraphicDevice, + const ::basegfx::B2DPolygon& rPoly ); + + BASEGFX_DLLPUBLIC css::uno::Reference< css::rendering::XPolyPolygon2D > + xPolyPolygonFromB2DPolyPolygon( const css::uno::Reference< css::rendering::XGraphicDevice >& xGraphicDevice, + const ::basegfx::B2DPolyPolygon& rPolyPoly ); + + + css::uno::Sequence< + css::uno::Sequence< css::geometry::RealBezierSegment2D > > + bezierSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ); + + css::uno::Sequence< + css::uno::Sequence< css::geometry::RealPoint2D > > + pointSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ); + + ::basegfx::B2DPolygon polygonFromPoint2DSequence( + const css::uno::Sequence< css::geometry::RealPoint2D >& rPoints ); + + BASEGFX_DLLPUBLIC ::basegfx::B2DPolyPolygon polyPolygonFromPoint2DSequenceSequence( + const css::uno::Sequence< css::uno::Sequence< css::geometry::RealPoint2D > >& rPoints ); + + ::basegfx::B2DPolygon polygonFromBezier2DSequence( + const css::uno::Sequence< css::geometry::RealBezierSegment2D >& rPoints ); + + BASEGFX_DLLPUBLIC ::basegfx::B2DPolyPolygon polyPolygonFromBezier2DSequenceSequence( + const css::uno::Sequence< css::uno::Sequence< css::geometry::RealBezierSegment2D > >& rPoints ); + + BASEGFX_DLLPUBLIC ::basegfx::B2DPolyPolygon b2DPolyPolygonFromXPolyPolygon2D( + const css::uno::Reference< css::rendering::XPolyPolygon2D >& rPoly ); + + // Matrix conversions + + + BASEGFX_DLLPUBLIC css::geometry::AffineMatrix2D& + affineMatrixFromHomMatrix( css::geometry::AffineMatrix2D& matrix, + const ::basegfx::B2DHomMatrix& transform); + + css::geometry::AffineMatrix3D& affineMatrixFromHomMatrix3D( + css::geometry::AffineMatrix3D& matrix, + const ::basegfx::B3DHomMatrix& transform); + + BASEGFX_DLLPUBLIC ::basegfx::B2DHomMatrix& + homMatrixFromAffineMatrix( ::basegfx::B2DHomMatrix& transform, + const css::geometry::AffineMatrix2D& matrix ); + + BASEGFX_DLLPUBLIC ::basegfx::B3DHomMatrix homMatrixFromAffineMatrix3D( const css::geometry::AffineMatrix3D& matrix ); + + // Geometry conversions + + + BASEGFX_DLLPUBLIC css::geometry::RealSize2D size2DFromB2DSize( const ::basegfx::B2DVector& ); + BASEGFX_DLLPUBLIC css::geometry::RealPoint2D point2DFromB2DPoint( const ::basegfx::B2DPoint& ); + BASEGFX_DLLPUBLIC css::geometry::RealRectangle2D rectangle2DFromB2DRectangle( const ::basegfx::B2DRange& ); + BASEGFX_DLLPUBLIC css::geometry::RealRectangle3D rectangle3DFromB3DRectangle( const ::basegfx::B3DRange& ); + + BASEGFX_DLLPUBLIC ::basegfx::B2DPoint b2DPointFromRealPoint2D( const css::geometry::RealPoint2D& ); + BASEGFX_DLLPUBLIC ::basegfx::B2DRange b2DRectangleFromRealRectangle2D( const css::geometry::RealRectangle2D& ); + ::basegfx::B3DRange b3DRectangleFromRealRectangle3D( const css::geometry::RealRectangle3D& ); + + BASEGFX_DLLPUBLIC css::geometry::IntegerSize2D integerSize2DFromB2ISize( const ::basegfx::B2IVector& ); + + BASEGFX_DLLPUBLIC ::basegfx::B2IVector b2ISizeFromIntegerSize2D( const css::geometry::IntegerSize2D& ); + BASEGFX_DLLPUBLIC ::basegfx::B2IRange b2IRectangleFromIntegerRectangle2D( const css::geometry::IntegerRectangle2D& ); + + BASEGFX_DLLPUBLIC ::basegfx::B2IRange b2IRectangleFromAwtRectangle( const css::awt::Rectangle& ); + + // Geometry comparisons + + + /** Return smalltest integer range, which completely contains + given floating point range. + + @param rRange + Input range. Values must be within the representable + bounds of sal_Int32 + + @return the closest integer range, which completely + contains rRange. + */ + BASEGFX_DLLPUBLIC ::basegfx::B2IRange b2ISurroundingRangeFromB2DRange( const ::basegfx::B2DRange& rRange ); + + /** Return smalltest B2DRange with integer values, which + completely contains given floating point range. + + @param rRange + Input range. + + @return the closest B2DRange with integer coordinates, + which completely contains rRange. + */ + BASEGFX_DLLPUBLIC ::basegfx::B2DRange b2DSurroundingIntegerRangeFromB2DRange( const ::basegfx::B2DRange& rRange ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/common.hxx b/include/basegfx/utils/common.hxx new file mode 100644 index 000000000..1c11a8bf2 --- /dev/null +++ b/include/basegfx/utils/common.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +namespace basegfx +{ +// The axis or dimension in a 2D coordinate system +enum class Axis2D +{ + X, + Y +}; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/gradienttools.hxx b/include/basegfx/utils/gradienttools.hxx new file mode 100644 index 000000000..03892122b --- /dev/null +++ b/include/basegfx/utils/gradienttools.hxx @@ -0,0 +1,399 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace basegfx { class B2DRange; } + +namespace basegfx +{ + /** Gradient definition as used in ODF 1.2 + + This struct collects all data necessary for rendering ODF + 1.2-compatible gradients. Use the createXXXODFGradientInfo() + methods below for initializing from ODF attributes. + */ + class UNLESS_MERGELIBS(BASEGFX_DLLPUBLIC) ODFGradientInfo + { + private: + /** transformation mapping from [0,1]^2 texture coordinate + space to [0,1]^2 shape coordinate space + */ + B2DHomMatrix maTextureTransform; + + /** transformation mapping from [0,1]^2 shape coordinate space + to [0,1]^2 texture coordinate space. This is the + transformation commonly used to create gradients from a + scanline rasterizer (put shape u/v coordinates into it, get + texture s/t coordinates out of it) + */ + B2DHomMatrix maBackTextureTransform; + + /** Aspect ratio of the gradient. Only used in drawinglayer + for generating nested gradient polygons currently. Already + catered for in the transformations above. + */ + double mfAspectRatio; + + /** Requested gradient steps to render. See the + implementations of the getXXXGradientAlpha() methods below, + the semantic differs slightly for the different gradient + types. + */ + sal_uInt32 mnSteps; + + public: + ODFGradientInfo() + : mfAspectRatio(1.0), + mnSteps(0) + { + } + + ODFGradientInfo( + B2DHomMatrix aTextureTransform, + double fAspectRatio, + sal_uInt32 nSteps) + : maTextureTransform(std::move(aTextureTransform)), + mfAspectRatio(fAspectRatio), + mnSteps(nSteps) + { + } + + ODFGradientInfo(const ODFGradientInfo& rODFGradientInfo) + : maTextureTransform(rODFGradientInfo.getTextureTransform()), + maBackTextureTransform(rODFGradientInfo.maBackTextureTransform), + mfAspectRatio(rODFGradientInfo.getAspectRatio()), + mnSteps(rODFGradientInfo.getSteps()) + { + } + + ODFGradientInfo& operator=(const ODFGradientInfo& rODFGradientInfo) + { + maTextureTransform = rODFGradientInfo.getTextureTransform(); + maBackTextureTransform = rODFGradientInfo.maBackTextureTransform; + mfAspectRatio = rODFGradientInfo.getAspectRatio(); + mnSteps = rODFGradientInfo.getSteps(); + + return *this; + } + + // compare operator + bool operator==(const ODFGradientInfo& rGeoTexSvx) const; + + const B2DHomMatrix& getTextureTransform() const { return maTextureTransform; } + const B2DHomMatrix& getBackTextureTransform() const; + double getAspectRatio() const { return mfAspectRatio; } + sal_uInt32 getSteps() const { return mnSteps; } + + void setTextureTransform(const B2DHomMatrix& rNew) + { + maTextureTransform = rNew; + maBackTextureTransform.identity(); + } + }; + + namespace utils + { + /** Create matrix for ODF's linear gradient definition + + Note that odf linear gradients are varying in y direction. + + @param o_rGradientInfo + Receives the calculated texture transformation matrix (for + use with standard [0,1]x[0,1] texture coordinates) + + @param rTargetArea + Output area, needed for aspect ratio calculations and + texture transformation + + @param nSteps + Number of gradient steps (from ODF) + + @param fBorder + Width of gradient border (from ODF) + + @param fAngle + Gradient angle (from ODF) + */ + BASEGFX_DLLPUBLIC ODFGradientInfo createLinearODFGradientInfo( + const B2DRange& rTargetArea, + sal_uInt32 nSteps, + double fBorder, + double fAngle); + + + /** Calculate linear gradient blend value + + This method generates you the lerp alpha value for + blending linearly between gradient start and end color, + according to the formula (startCol*(1.0-alpha) + endCol*alpha) + + @param rUV + Current uv coordinate. Values outside [0,1] will be + clamped. Assumes gradient color varies along the y axis. + + @param rGradInfo + Gradient info, for transformation and number of steps + */ + BASEGFX_DLLPUBLIC double getLinearGradientAlpha(const B2DPoint& rUV, + const ODFGradientInfo& rGradInfo); + + /** Create matrix for ODF's axial gradient definition + + Note that odf axial gradients are varying in y + direction. Note further that you can map the axial + gradient to a linear gradient (in case you want or need to + avoid an extra gradient renderer), by using + createLinearODFGradientInfo() instead, shifting the + resulting texture transformation by 0.5 to the top and + appending the same stop colors again, but mirrored. + + @param o_rGradientInfo + Receives the calculated texture transformation matrix (for + use with standard [0,1]x[0,1] texture coordinates) + + @param rTargetArea + Output area, needed for aspect ratio calculations and + texture transformation + + @param nSteps + Number of gradient steps (from ODF) + + @param fBorder + Width of gradient border (from ODF) + + @param fAngle + Gradient angle (from ODF) + */ + BASEGFX_DLLPUBLIC ODFGradientInfo createAxialODFGradientInfo( + const B2DRange& rTargetArea, + sal_uInt32 nSteps, + double fBorder, + double fAngle); + + + /** Calculate axial gradient blend value + + This method generates you the lerp alpha value for + blending linearly between gradient start and end color, + according to the formula (startCol*(1.0-alpha) + endCol*alpha) + + @param rUV + Current uv coordinate. Values outside [0,1] will be + clamped. Assumes gradient color varies along the y axis. + + @param rGradInfo + Gradient info, for transformation and number of steps + */ + BASEGFX_DLLPUBLIC double getAxialGradientAlpha(const B2DPoint& rUV, + const ODFGradientInfo& rGradInfo); + + /** Create matrix for ODF's radial gradient definition + + @param o_rGradientInfo + Receives the calculated texture transformation matrix (for + use with standard [0,1]x[0,1] texture coordinates) + + @param rTargetArea + Output area, needed for aspect ratio calculations and + texture transformation + + @param rOffset + Gradient offset value (from ODF) + + @param nSteps + Number of gradient steps (from ODF) + + @param fBorder + Width of gradient border (from ODF) + + @param fAngle + Gradient angle (from ODF) + */ + BASEGFX_DLLPUBLIC ODFGradientInfo createRadialODFGradientInfo( + const B2DRange& rTargetArea, + const B2DVector& rOffset, + sal_uInt32 nSteps, + double fBorder); + + + /** Calculate radial gradient blend value + + This method generates you the lerp alpha value for + blending linearly between gradient start and end color, + according to the formula (startCol*(1.0-alpha) + endCol*alpha) + + @param rUV + Current uv coordinate. Values outside [0,1] will be + clamped. + + @param rGradInfo + Gradient info, for transformation and number of steps + */ + BASEGFX_DLLPUBLIC double getRadialGradientAlpha(const B2DPoint& rUV, + const ODFGradientInfo& rGradInfo); + + /** Create matrix for ODF's elliptical gradient definition + + @param o_rGradientInfo + Receives the calculated texture transformation matrix (for + use with standard [0,1]x[0,1] texture coordinates) + + @param rTargetArea + Output area, needed for aspect ratio calculations and + texture transformation + + @param rOffset + Gradient offset value (from ODF) + + @param nSteps + Number of gradient steps (from ODF) + + @param fBorder + Width of gradient border (from ODF) + + @param fAngle + Gradient angle (from ODF) + */ + BASEGFX_DLLPUBLIC ODFGradientInfo createEllipticalODFGradientInfo( + const B2DRange& rTargetArea, + const B2DVector& rOffset, + sal_uInt32 nSteps, + double fBorder, + double fAngle); + + + /** Calculate elliptical gradient blend value + + This method generates you the lerp alpha value for + blending linearly between gradient start and end color, + according to the formula (startCol*(1.0-alpha) + endCol*alpha) + + @param rUV + Current uv coordinate. Values outside [0,1] will be + clamped. + + @param rGradInfo + Gradient info, for transformation and number of steps + */ + BASEGFX_DLLPUBLIC double getEllipticalGradientAlpha(const B2DPoint& rUV, + const ODFGradientInfo& rGradInfo); + + /** Create matrix for ODF's square gradient definition + + @param o_rGradientInfo + Receives the calculated texture transformation matrix (for + use with standard [0,1]x[0,1] texture coordinates) + + @param rTargetArea + Output area, needed for aspect ratio calculations and + texture transformation + + @param rOffset + Gradient offset value (from ODF) + + @param nSteps + Number of gradient steps (from ODF) + + @param fBorder + Width of gradient border (from ODF) + + @param fAngle + Gradient angle (from ODF) + */ + BASEGFX_DLLPUBLIC ODFGradientInfo createSquareODFGradientInfo( + const B2DRange& rTargetArea, + const B2DVector& rOffset, + sal_uInt32 nSteps, + double fBorder, + double fAngle); + + + /** Calculate square gradient blend value + + This method generates you the lerp alpha value for + blending linearly between gradient start and end color, + according to the formula (startCol*(1.0-alpha) + endCol*alpha) + + @param rUV + Current uv coordinate. Values outside [0,1] will be + clamped. + + @param rGradInfo + Gradient info, for transformation and number of steps + */ + BASEGFX_DLLPUBLIC double getSquareGradientAlpha(const B2DPoint& rUV, + const ODFGradientInfo& rGradInfo); + + /** Create matrix for ODF's rectangular gradient definition + + @param o_rGradientInfo + Receives the calculated texture transformation matrix (for + use with standard [0,1]x[0,1] texture coordinates) + + @param rTargetArea + Output area, needed for aspect ratio calculations and + texture transformation + + @param rOffset + Gradient offset value (from ODF) + + @param nSteps + Number of gradient steps (from ODF) + + @param fBorder + Width of gradient border (from ODF) + + @param fAngle + Gradient angle (from ODF) + */ + BASEGFX_DLLPUBLIC ODFGradientInfo createRectangularODFGradientInfo( + const B2DRange& rTargetArea, + const B2DVector& rOffset, + sal_uInt32 nSteps, + double fBorder, + double fAngle); + + + /** Calculate rectangular gradient blend value + + This method generates you the lerp alpha value for + blending linearly between gradient start and end color, + according to the formula (startCol*(1.0-alpha) + endCol*alpha) + + @param rUV + Current uv coordinate. Values outside [0,1] will be + clamped. + + @param rGradInfo + Gradient info, for transformation and number of steps + */ + BASEGFX_DLLPUBLIC double getRectangularGradientAlpha(const B2DPoint& rUV, + const ODFGradientInfo& rGradInfo); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/keystoplerp.hxx b/include/basegfx/utils/keystoplerp.hxx new file mode 100644 index 000000000..f8a821e7a --- /dev/null +++ b/include/basegfx/utils/keystoplerp.hxx @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace com::sun::star::uno { + template class Sequence; +} + +namespace basegfx::utils +{ + /** Lerp in a vector of key stops + + This class holds a key stop vector and provides the + functionality to lerp inside it. Useful e.g. for + multi-stop gradients, or the SMIL key time activity. + + For those, given a global [0,1] lerp alpha, one need to + find the suitable bucket index from key stop vector, and + then calculate the relative alpha between the two buckets + found. + */ + class BASEGFX_DLLPUBLIC KeyStopLerp + { + public: + typedef std::pair ResultType; + + /** Create lerper with given vector of stops + + @param rKeyStops + + Vector of stops, must contain at least two elements + (though preferably more, otherwise you probably don't + need key stop lerping in the first place). All + elements must be of monotonically increasing value. + */ + explicit KeyStopLerp( std::vector&& rKeyStops ); + + /** Create lerper with given sequence of stops + + @param rKeyStops + + Sequence of stops, must contain at least two elements + (though preferably more, otherwise you probably don't + need key stop lerping in the first place). All + elements must be of monotonically increasing value. + */ + explicit KeyStopLerp( const css::uno::Sequence& rKeyStops ); + + /** Find two nearest bucket index & interpolate + + @param fAlpha + Find bucket index i, with keyStops[i] < fAlpha <= + keyStops[i+1]. Return new alpha value in [0,1), + proportional to fAlpha's position between keyStops[i] + and keyStops[i+1] + */ + ResultType lerp(double fAlpha) const; + + private: + std::vector maKeyStops; + mutable std::ptrdiff_t mnLastIndex; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/lerp.hxx b/include/basegfx/utils/lerp.hxx new file mode 100644 index 000000000..e02b3b0fa --- /dev/null +++ b/include/basegfx/utils/lerp.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +namespace basegfx::utils +{ + /** Generic linear interpolator + + @tpl ValueType + Must have operator+ and operator* defined, and should + have value semantics. + + @param t + As usual, t must be in the [0,1] range + */ + template< typename ValueType > ValueType lerp( const ValueType& rFrom, + const ValueType& rTo, + double t ) + { + // This is only to suppress a double->int warning. All other + // types should be okay here. + return static_cast( (1.0-t)*rFrom + t*rTo ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/rectcliptools.hxx b/include/basegfx/utils/rectcliptools.hxx new file mode 100644 index 000000000..af6be75bf --- /dev/null +++ b/include/basegfx/utils/rectcliptools.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + + +namespace basegfx::utils +{ + namespace RectClipFlags + { + const sal_uInt32 LEFT = sal_Int32(0x01); + const sal_uInt32 RIGHT = sal_Int32(0x02); + const sal_uInt32 TOP = sal_Int32(0x04); + const sal_uInt32 BOTTOM = sal_Int32(0x08); + } + + /** Calc clip mask for Cohen-Sutherland rectangle clip + + This function returns a clip mask used for the + Cohen-Sutherland rectangle clip method, where one or more + of the lower four bits are set, if the given point is + outside one or more of the four half planes defining the + rectangle (see RectClipFlags for possible values) + */ + template< class Point, class Rect > inline + sal_uInt32 getCohenSutherlandClipFlags( const Point& rP, + const Rect& rR ) + { + // maxY | minY | maxX | minX + sal_uInt32 clip; + clip = (rP.getX() < rR.getMinX()) << 0; + clip |= (rP.getX() > rR.getMaxX()) << 1; + clip |= (rP.getY() < rR.getMinY()) << 2; + clip |= (rP.getY() > rR.getMaxY()) << 3; + return clip; + } + + /// Cohen-Sutherland mask calculation - overload for boxes. + template< class Point > inline + sal_uInt32 getCohenSutherlandClipFlags( const Point& rP, + const B2IBox& rB ) + { + // maxY | minY | maxX | minX + sal_uInt32 clip; + clip = (rP.getX() < rB.getMinX()) << 0; + clip |= (rP.getX() >= rB.getMaxX()) << 1; + clip |= (rP.getY() < rB.getMinY()) << 2; + clip |= (rP.getY() >= rB.getMaxY()) << 3; + return clip; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/systemdependentdata.hxx b/include/basegfx/utils/systemdependentdata.hxx new file mode 100644 index 000000000..6778fa967 --- /dev/null +++ b/include/basegfx/utils/systemdependentdata.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include +#include + +namespace basegfx +{ + class SystemDependentData; + typedef std::shared_ptr SystemDependentData_SharedPtr; + typedef std::weak_ptr SystemDependentData_WeakPtr; + + class BASEGFX_DLLPUBLIC SystemDependentDataManager + { + private: + // noncopyable + SystemDependentDataManager(const SystemDependentDataManager&) = delete; + SystemDependentDataManager& operator=(const SystemDependentDataManager&) = delete; + + public: + SystemDependentDataManager(); + virtual ~SystemDependentDataManager(); + + // call from (and with) SystemDependentData objects when start/end/touch + // usage is needed + virtual void startUsage(basegfx::SystemDependentData_SharedPtr& rData) = 0; + virtual void endUsage(basegfx::SystemDependentData_SharedPtr& rData) = 0; + virtual void touchUsage(basegfx::SystemDependentData_SharedPtr& rData) = 0; + + // flush all buffered data (e.g. cleanup/shutdown) + virtual void flushAll() = 0; + }; + + class BASEGFX_DLLPUBLIC SystemDependentData + { + private: + // noncopyable + SystemDependentData(const SystemDependentData&) = delete; + SystemDependentData& operator=(const SystemDependentData&) = delete; + + // reference to a SystemDependentDataManager, probably + // a single, globally used one, but not necessarily + SystemDependentDataManager& mrSystemDependentDataManager; + + // Buffered CalculatedCycles, result of estimations using + // getHoldCyclesInSeconds and estimateUsageInBytes, executed + // using getHoldCyclesInSeconds. StartValue is 0 to detect + // not-yet-calculated state + sal_uInt32 mnCalculatedCycles; + + public: + SystemDependentData( + SystemDependentDataManager& rSystemDependentDataManager); + + // CAUTION! It is VERY important to keep this base class + // virtual, else typeid(class).hash_code() from derived classes + // will NOT work what is ESSENTIAL for the SystemDependentData + // mechanism to work properly. So DO NOT REMOVE virtual here, please. + virtual ~SystemDependentData(); + + // allow access to call startUsage/endUsage/touchUsage + // using getSystemDependentDataManager() + SystemDependentDataManager& getSystemDependentDataManager() { return mrSystemDependentDataManager; } + + // Calculate HoldCyclesInSeconds based on using + // getHoldCyclesInSeconds and estimateUsageInBytes, the + // result is created once on-demand and buffered in + // mnCalculatedCycles + sal_uInt32 calculateCombinedHoldCyclesInSeconds() const; + + // Size estimation of the entry in bytes - does not have to + // be used, but should be. Default returns zero what + // means there is no size estimation available. Override to + // offer useful data if you want to have better caching. + virtual sal_Int64 estimateUsageInBytes() const; + }; + + class BASEGFX_DLLPUBLIC SystemDependentDataHolder + { + private: + // Possibility to hold System-Dependent B2DPolygon-Representations + std::map< size_t, SystemDependentData_WeakPtr > maSystemDependentReferences; + + // noncopyable + SystemDependentDataHolder(const SystemDependentDataHolder&) = delete; + SystemDependentDataHolder& operator=(const SystemDependentDataHolder&) = delete; + + public: + SystemDependentDataHolder(); + virtual ~SystemDependentDataHolder(); + + void addOrReplaceSystemDependentData(SystemDependentData_SharedPtr& rData); + SystemDependentData_SharedPtr getSystemDependentData(size_t hash_code) const; + }; +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/tools.hxx b/include/basegfx/utils/tools.hxx new file mode 100644 index 000000000..f8fc61999 --- /dev/null +++ b/include/basegfx/utils/tools.hxx @@ -0,0 +1,124 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ + class B2DPoint; + class B2DRange; + class B2DPolyPolygon; +} + +namespace basegfx::utils +{ + /** Expand given parallelogram, such that it extends beyond + bound rect in a given direction. + + This method is useful when e.g. generating one-dimensional + gradients, such as linear or axial gradients: those + gradients vary only in one direction, the other has + constant color. Most of the time, those gradients extends + infinitely in the direction with the constant color, but + practically, one always has a limiting bound rect into + which the gradient is painted. The method at hand now + extends a given parallelogram (e.g. the transformed + bounding box of a gradient) virtually into infinity to the + top and to the bottom (i.e. normal to the line io_rLeftTop + io_rRightTop), such that the given rectangle is guaranteed + to be covered in that direction. + + @attention There might be some peculiarities with this + method, that might limit its usage to the described + gradients. One of them is the fact that when determining + how far the parallelogram has to be extended to the top or + the bottom, the upper and lower border are assumed to be + infinite lines. + + @param io_rLeftTop + Left, top edge of the parallelogramm. Note that this need + not be the left, top edge geometrically, it's just used + when determining the extension direction. Thus, it's + perfectly legal to affine-transform a rectangle, and given + the transformed point here. On method return, this + parameter will contain the adapted output. + + @param io_rLeftBottom + Left, bottom edge of the parallelogramm. Note that this need + not be the left, bottom edge geometrically, it's just used + when determining the extension direction. Thus, it's + perfectly legal to affine-transform a rectangle, and given + the transformed point here. On method return, this + parameter will contain the adapted output. + + @param io_rRightTop + Right, top edge of the parallelogramm. Note that this need + not be the right, top edge geometrically, it's just used + when determining the extension direction. Thus, it's + perfectly legal to affine-transform a rectangle, and given + the transformed point here. On method return, this + parameter will contain the adapted output. + + @param io_rRightBottom + Right, bottom edge of the parallelogramm. Note that this need + not be the right, bottom edge geometrically, it's just used + when determining the extension direction. Thus, it's + perfectly legal to affine-transform a rectangle, and given + the transformed point here. On method return, this + parameter will contain the adapted output. + + @param rFitTarget + The rectangle to fit the parallelogram into. + */ + BASEGFX_DLLPUBLIC void infiniteLineFromParallelogram( ::basegfx::B2DPoint& io_rLeftTop, + ::basegfx::B2DPoint& io_rLeftBottom, + ::basegfx::B2DPoint& io_rRightTop, + ::basegfx::B2DPoint& io_rRightBottom, + const ::basegfx::B2DRange& rFitTarget ); + + /** Creates polypolygon with the given number as seven-segment + digits + + @param fVal + Value to convert + + @param nTotalDigits + Total number of digits to display. If less is needed for + given number, fill space with blanks. + + @param nDecPlaces + Decimal places to show. When 0, display as integer. When + negative, fill given number of before-the-decimal point + with zero. + + @param bLitSegments + When true, return a polygon containing the segments that + are 'lit' for the given number. Return un-lit segments + otherwise. + */ + BASEGFX_DLLPUBLIC B2DPolyPolygon number2PolyPolygon(double fVal, + sal_Int32 nTotalDigits, + sal_Int32 nDecPlaces, + bool bLitSegments=true); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/unopolypolygon.hxx b/include/basegfx/utils/unopolypolygon.hxx new file mode 100644 index 000000000..48788b074 --- /dev/null +++ b/include/basegfx/utils/unopolypolygon.hxx @@ -0,0 +1,104 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace basegfx::unotools +{ + typedef comphelper::WeakComponentImplHelper< + css::rendering::XLinePolyPolygon2D, + css::rendering::XBezierPolyPolygon2D, + css::lang::XServiceInfo > UnoPolyPolygonBase; + + class BASEGFX_DLLPUBLIC UnoPolyPolygon + : public UnoPolyPolygonBase + { + public: + explicit UnoPolyPolygon( B2DPolyPolygon ); + + // XPolyPolygon2D + SAL_DLLPRIVATE virtual void SAL_CALL addPolyPolygon( const css::geometry::RealPoint2D& position, const css::uno::Reference< css::rendering::XPolyPolygon2D >& polyPolygon ) override; + SAL_DLLPRIVATE virtual ::sal_Int32 SAL_CALL getNumberOfPolygons( ) override; + SAL_DLLPRIVATE virtual ::sal_Int32 SAL_CALL getNumberOfPolygonPoints( ::sal_Int32 polygon ) override; + SAL_DLLPRIVATE virtual css::rendering::FillRule SAL_CALL getFillRule( ) override; + SAL_DLLPRIVATE virtual void SAL_CALL setFillRule( css::rendering::FillRule fillRule ) override; + SAL_DLLPRIVATE virtual sal_Bool SAL_CALL isClosed( ::sal_Int32 index ) override; + SAL_DLLPRIVATE virtual void SAL_CALL setClosed( ::sal_Int32 index, sal_Bool closedState ) override; + + // XLinePolyPolygon2D + SAL_DLLPRIVATE virtual css::uno::Sequence< css::uno::Sequence< css::geometry::RealPoint2D > > SAL_CALL getPoints( ::sal_Int32 nPolygonIndex, ::sal_Int32 nNumberOfPolygons, ::sal_Int32 nPointIndex, ::sal_Int32 nNumberOfPoints ) override; + SAL_DLLPRIVATE virtual void SAL_CALL setPoints( const css::uno::Sequence< css::uno::Sequence< css::geometry::RealPoint2D > >& points, ::sal_Int32 nPolygonIndex ) override; + SAL_DLLPRIVATE virtual css::geometry::RealPoint2D SAL_CALL getPoint( ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) override; + SAL_DLLPRIVATE virtual void SAL_CALL setPoint( const css::geometry::RealPoint2D& point, ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) override; + + // XBezierPolyPolygon2D + SAL_DLLPRIVATE virtual css::uno::Sequence< css::uno::Sequence< css::geometry::RealBezierSegment2D > > SAL_CALL getBezierSegments( ::sal_Int32 nPolygonIndex, ::sal_Int32 nNumberOfPolygons, ::sal_Int32 nPointIndex, ::sal_Int32 nNumberOfPoints ) override; + SAL_DLLPRIVATE virtual void SAL_CALL setBezierSegments( const css::uno::Sequence< css::uno::Sequence< css::geometry::RealBezierSegment2D > >& points, ::sal_Int32 nPolygonIndex ) override; + SAL_DLLPRIVATE virtual css::geometry::RealBezierSegment2D SAL_CALL getBezierSegment( ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) override; + SAL_DLLPRIVATE virtual void SAL_CALL setBezierSegment( const css::geometry::RealBezierSegment2D& point, ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) override; + + // XServiceInfo + SAL_DLLPRIVATE virtual OUString SAL_CALL getImplementationName() override; + SAL_DLLPRIVATE virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + SAL_DLLPRIVATE virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + + SAL_DLLPRIVATE B2DPolyPolygon getPolyPolygon() const; + + protected: + /// Check whether index is a valid polygon index + void checkIndex( sal_Int32 nIndex ) const // throw (css::lang::IndexOutOfBoundsException); + { + if( nIndex < 0 || o3tl::make_unsigned(nIndex) >= maPolyPoly.count() ) + throw css::lang::IndexOutOfBoundsException(); + } + + SAL_DLLPRIVATE B2DPolyPolygon getSubsetPolyPolygon( sal_Int32 nPolygonIndex, + sal_Int32 nNumberOfPolygons, + sal_Int32 nPointIndex, + sal_Int32 nNumberOfPoints ) const; + + /// Get cow copy of internal polygon. not thread-safe outside this object. + const B2DPolyPolygon& getPolyPolygonUnsafe() const + { + return maPolyPoly; + } + + /// Called whenever internal polypolygon gets modified + virtual void modifying() const {} + + private: + UnoPolyPolygon(const UnoPolyPolygon&) = delete; + UnoPolyPolygon& operator=(const UnoPolyPolygon&) = delete; + + B2DPolyPolygon maPolyPoly; + css::rendering::FillRule meFillRule; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/utils/zoomtools.hxx b/include/basegfx/utils/zoomtools.hxx new file mode 100644 index 000000000..242c10e6d --- /dev/null +++ b/include/basegfx/utils/zoomtools.hxx @@ -0,0 +1,23 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include + +namespace basegfx::zoomtools +{ +/** This namespace provides functions for optimized geometric zooming +*/ +BASEGFX_DLLPUBLIC tools::Long zoomOut(tools::Long nCurrent); +BASEGFX_DLLPUBLIC tools::Long zoomIn(tools::Long nCurrent); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/vector/b2dsize.hxx b/include/basegfx/vector/b2dsize.hxx new file mode 100644 index 000000000..117912699 --- /dev/null +++ b/include/basegfx/vector/b2dsize.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace basegfx +{ +// syntactic sugar: a B2DVector exactly models a Size object, +// thus, for interface clarity, we provide an alias name + +/// Alias name for interface clarity (not everybody is aware of the identity) +typedef B2DVector B2DSize; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/vector/b2dvector.hxx b/include/basegfx/vector/b2dvector.hxx new file mode 100644 index 000000000..17a9c60b0 --- /dev/null +++ b/include/basegfx/vector/b2dvector.hxx @@ -0,0 +1,237 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace basegfx +{ + class B2DHomMatrix; + + /** Base Point class with two double values + + This class derives all operators and common handling for + a 2D data class from B2DTuple. All necessary extensions + which are special for 2D Vectors are added here. + + @see B2DTuple + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B2DVector : public ::basegfx::B2DTuple + { + public: + /** Create a 2D Vector + + The vector is initialized to (0.0, 0.0) + */ + B2DVector() + {} + + /** Create a 2D Vector + + @param fX + This parameter is used to initialize the X-coordinate + of the 2D Vector. + + @param fY + This parameter is used to initialize the Y-coordinate + of the 2D Vector. + */ + B2DVector(double fX, double fY) + : B2DTuple(fX, fY) + {} + + /** Create a copy of a 2D Vector + + @param rVec + The 2D Vector which will be copied. + */ + explicit B2DVector(const ::basegfx::B2IVector& rVec) + : B2DTuple(rVec) + {} + + /** constructor with tuple to allow copy-constructing + from B2DTuple-based classes + */ + B2DVector(const ::basegfx::B2DTuple& rTuple) + : B2DTuple(rTuple) + {} + + /** *=operator to allow usage from B2DVector, too + */ + B2DVector& operator*=( const B2DVector& rPnt ) + { + mfX *= rPnt.mfX; + mfY *= rPnt.mfY; + return *this; + } + + /** *=operator to allow usage from B2DVector, too + */ + B2DVector& operator*=(double t) + { + mfX *= t; + mfY *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B2DTuple calculations + */ + B2DVector& operator=( const ::basegfx::B2DTuple& rVec ); + + /** Calculate the length of this 2D Vector + + @return The Length of the 2D Vector + */ + double getLength() const; + + /** Set the length of this 2D Vector + + @param fLen + The to be achieved length of the 2D Vector + */ + B2DVector& setLength(double fLen); + + /** Normalize this 2D Vector + + The length of the 2D Vector is set to 1.0 + */ + B2DVector& normalize(); + + /** Calculate the Scalar with another 2D Vector + + @param rVec + The second 2D Vector + + @return + The Scalar value of the two involved 2D Vectors + */ + double scalar( const B2DVector& rVec ) const { return((mfX * rVec.mfX) + (mfY * rVec.mfY)); } + + /** Calculate the length of the cross product with another 2D Vector + + In 2D, returning an actual vector does not make much + sense here. The magnitude, although, can be readily + used for tasks such as angle calculations, since for + the returned value, the following equation holds: + retVal = getLength(this)*getLength(rVec)*sin(theta), + with theta being the angle between the two vectors. + + @param rVec + The second 2D Vector + + @return + The length of the cross product of the two involved 2D Vectors + */ + double cross( const B2DVector& rVec ) const { return(mfX * rVec.getY() - mfY * rVec.getX()); } + + /** Calculate the Angle with another 2D Vector + + @param rVec + The second 2D Vector + + @return + The Angle value of the two involved 2D Vectors ranging from -pi to +pi + */ + double angle( const B2DVector& rVec ) const; + + /** Transform vector by given transformation matrix. + + Since this is a vector, translational components of the + matrix are disregarded. + */ + B2DVector& operator*=( const B2DHomMatrix& rMat ); + + static const B2DVector& getEmptyVector(); + }; + + // external operators + + + /** Calculate the orientation to another 2D Vector + + @param rVecA + The first 2D Vector + + @param rVecB + The second 2D Vector + + @return + The mathematical Orientation of the two involved 2D Vectors + */ + BASEGFX_DLLPUBLIC B2VectorOrientation getOrientation( const B2DVector& rVecA, const B2DVector& rVecB ); + + /** Calculate a perpendicular 2D Vector to the given one + + @param rVec + The source 2D Vector + + @attention This only works if the given 2D Vector is normalized. + + @return + A 2D Vector perpendicular to the one given in parameter rVec + */ + BASEGFX_DLLPUBLIC B2DVector getPerpendicular( const B2DVector& rNormalizedVec ); + + /** Calculate a perpendicular 2D Vector to the given one, + normalize the given one as preparation + + @param rVec + The source 2D Vector + + @return + A normalized 2D Vector perpendicular to the one given in parameter rVec + */ + BASEGFX_DLLPUBLIC B2DVector getNormalizedPerpendicular( const B2DVector& rVec ); + + /** Test two vectors which need not to be normalized for parallelism + + @param rVecA + The first 2D Vector + + @param rVecB + The second 2D Vector + + @return + bool if the two values are parallel. Also true if + one of the vectors is empty. + */ + BASEGFX_DLLPUBLIC bool areParallel( const B2DVector& rVecA, const B2DVector& rVecB ); + + /** Transform vector by given transformation matrix. + + Since this is a vector, translational components of the + matrix are disregarded. + */ + BASEGFX_DLLPUBLIC B2DVector operator*( const B2DHomMatrix& rMat, const B2DVector& rVec ); + + /** Test continuity between given vectors. + + The two given vectors are assumed to describe control points on a + common point. Calculate if there is a continuity between them. + */ + BASEGFX_DLLPUBLIC B2VectorContinuity getContinuity( const B2DVector& rBackVector, const B2DVector& rForwardVector ); + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/vector/b2enums.hxx b/include/basegfx/vector/b2enums.hxx new file mode 100644 index 000000000..803902370 --- /dev/null +++ b/include/basegfx/vector/b2enums.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +namespace basegfx +{ + /** Descriptor for the mathematical orientations of two 2D Vectors + */ + enum class B2VectorOrientation + { + /// mathematically positive oriented + Positive = 0, + + /// mathematically negative oriented + Negative, + + /// mathematically neutral, thus parallel + Neutral + }; + + /** Descriptor for the mathematical continuity of two 2D Vectors + */ + enum class B2VectorContinuity + { + /// none + NONE = 0, + + /// mathematically negative oriented + C1, + + /// mathematically neutral, thus parallel + C2 + }; + + /** Descriptor for possible line joins between two line segments + */ + enum class B2DLineJoin + { + NONE = 0, // no rounding + // removed unused Middle join type + Bevel = 2, // join edges with line + Miter = 3, // extend till cut + Round = 4 // create arc + }; + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/vector/b2isize.hxx b/include/basegfx/vector/b2isize.hxx new file mode 100644 index 000000000..926910b48 --- /dev/null +++ b/include/basegfx/vector/b2isize.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace basegfx +{ +// syntactic sugar: a B2IVector exactly models a Size object, +// thus, for interface clarity, we provide an alias name + +/// Alias name for interface clarity (not everybody is aware of the identity) +typedef B2IVector B2ISize; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/vector/b2ivector.hxx b/include/basegfx/vector/b2ivector.hxx new file mode 100644 index 000000000..b542fe880 --- /dev/null +++ b/include/basegfx/vector/b2ivector.hxx @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace basegfx +{ + class B2DHomMatrix; + + /** Base Point class with two sal_Int32 values + + This class derives all operators and common handling for + a 2D data class from B2ITuple. All necessary extensions + which are special for 2D Vectors are added here. + + @see B2ITuple + */ + class BASEGFX_DLLPUBLIC B2IVector : public ::basegfx::B2ITuple + { + public: + /** Create a 2D Vector + + The vector is initialized to (0, 0) + */ + B2IVector() + {} + + /** Create a 2D Vector + + @param nX + This parameter is used to initialize the X-coordinate + of the 2D Vector. + + @param nY + This parameter is used to initialize the Y-coordinate + of the 2D Vector. + */ + B2IVector(sal_Int32 nX, sal_Int32 nY) + : B2ITuple(nX, nY) + {} + + /** constructor with tuple to allow copy-constructing + from B2ITuple-based classes + */ + B2IVector(const ::basegfx::B2ITuple& rTuple) + : B2ITuple(rTuple) + {} + + /** *=operator to allow usage from B2IVector, too + */ + B2IVector& operator*=( const B2IVector& rPnt ) + { + mnX *= rPnt.mnX; + mnY *= rPnt.mnY; + return *this; + } + + /** *=operator to allow usage from B2IVector, too + */ + B2IVector& operator*=(sal_Int32 t) + { + mnX *= t; + mnY *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B2ITuple calculations + */ + B2IVector& operator=( const ::basegfx::B2ITuple& rVec ); + + /** Set the length of this 2D Vector + + @param fLen + The to be achieved length of the 2D Vector + */ + B2IVector& setLength(double fLen); + + /** Calculate the Scalar with another 2D Vector + + @param rVec + The second 2D Vector + + @return + The Scalar value of the two involved 2D Vectors + */ + double scalar( const B2IVector& rVec ) const { return((mnX * rVec.mnX) + (mnY * rVec.mnY)); } + + /** Transform vector by given transformation matrix. + + Since this is a vector, translational components of the + matrix are disregarded. + */ + B2IVector& operator*=( const B2DHomMatrix& rMat ); + }; + + // external operators + + template< typename charT, typename traits > + inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const basegfx::B2IVector& vector ) + { + return stream << "(" << vector.getX() << "," << vector.getY() << ")"; + } + +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basegfx/vector/b3dvector.hxx b/include/basegfx/vector/b3dvector.hxx new file mode 100644 index 000000000..399bba3ed --- /dev/null +++ b/include/basegfx/vector/b3dvector.hxx @@ -0,0 +1,258 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ + class B3DHomMatrix; + + /** Base Point class with three double values + + This class derives all operators and common handling for + a 3D data class from B3DTuple. All necessary extensions + which are special for 3D Vectors are added here. + + @see B3DTuple + */ + class SAL_WARN_UNUSED BASEGFX_DLLPUBLIC B3DVector : public ::basegfx::B3DTuple + { + public: + /** Create a 3D Vector + + The vector is initialized to (0.0, 0.0, 0.0) + */ + B3DVector() + {} + + /** Create a 3D Vector + + @param fX + This parameter is used to initialize the X-coordinate + of the 3D Vector. + + @param fY + This parameter is used to initialize the Y-coordinate + of the 3D Vector. + + @param fZ + This parameter is used to initialize the Z-coordinate + of the 3D Vector. + */ + B3DVector(double fX, double fY, double fZ) + : B3DTuple(fX, fY, fZ) + {} + + /** constructor with tuple to allow copy-constructing + from B3DTuple-based classes + */ + B3DVector(const ::basegfx::B3DTuple& rTuple) + : B3DTuple(rTuple) + {} + + /** *=operator to allow usage from B3DVector, too + */ + B3DVector& operator*=( const B3DVector& rPnt ) + { + mfX *= rPnt.mfX; + mfY *= rPnt.mfY; + mfZ *= rPnt.mfZ; + return *this; + } + + /** *=operator to allow usage from B3DVector, too + */ + B3DVector& operator*=(double t) + { + mfX *= t; + mfY *= t; + mfZ *= t; + return *this; + } + + /** assignment operator to allow assigning the results + of B3DTuple calculations + */ + B3DVector& operator=( const ::basegfx::B3DTuple& rVec ) + { + mfX = rVec.getX(); + mfY = rVec.getY(); + mfZ = rVec.getZ(); + return *this; + } + + /** Calculate the length of this 3D Vector + + @return The Length of the 3D Vector + */ + double getLength() const + { + double fLen(scalar(*this)); + if((0.0 == fLen) || (1.0 == fLen)) + return fLen; + return sqrt(fLen); + } + + /** Calculate the length in the XZ-Plane for this 3D Vector + + @return The XZ-Plane Length of the 3D Vector + */ + double getXZLength() const + { + double fLen((mfX * mfX) + (mfZ * mfZ)); // #i73040# + if((0.0 == fLen) || (1.0 == fLen)) + return fLen; + return sqrt(fLen); + } + + /** Calculate the length in the YZ-Plane for this 3D Vector + + @return The YZ-Plane Length of the 3D Vector + */ + double getYZLength() const + { + double fLen((mfY * mfY) + (mfZ * mfZ)); + if((0.0 == fLen) || (1.0 == fLen)) + return fLen; + return sqrt(fLen); + } + + /** Set the length of this 3D Vector + + @param fLen + The to be achieved length of the 3D Vector + */ + B3DVector& setLength(double fLen) + { + double fLenNow(scalar(*this)); + + if(!::basegfx::fTools::equalZero(fLenNow)) + { + const double fOne(1.0); + + if(!::basegfx::fTools::equal(fOne, fLenNow)) + { + fLen /= sqrt(fLenNow); + } + + mfX *= fLen; + mfY *= fLen; + mfZ *= fLen; + } + + return *this; + } + + /** Normalize this 3D Vector + + The length of the 3D Vector is set to 1.0 + */ + B3DVector& normalize(); + + /** get a 3D Vector which is perpendicular to this and a given 3D Vector + + @attention This only works if this and the given 3D Vector are + both normalized. + + @param rNormalizedVec + A normalized 3D Vector. + + @return + A 3D Vector perpendicular to this and the given one + */ + B3DVector getPerpendicular(const B3DVector& rNormalizedVec) const; + + /** Calculate the Scalar product + + This method calculates the Scalar product between this + and the given 3D Vector. + + @param rVec + A second 3D Vector. + + @return + The Scalar Product of two 3D Vectors + */ + double scalar(const B3DVector& rVec) const + { + return ((mfX * rVec.mfX) + (mfY * rVec.mfY) + (mfZ * rVec.mfZ)); + } + + /** Transform vector by given transformation matrix. + + Since this is a vector, translational components of the + matrix are disregarded. + */ + B3DVector& operator*=( const B3DHomMatrix& rMat ); + + static const B3DVector& getEmptyVector() + { + return static_cast( ::basegfx::B3DTuple::getEmptyTuple() ); + } + }; + + // external operators + + + /** Test two vectors which need not to be normalized for parallelism + + @param rVecA + The first 3D Vector + + @param rVecB + The second 3D Vector + + @return + bool if the two values are parallel. Also true if + one of the vectors is empty. + */ + BASEGFX_DLLPUBLIC bool areParallel( const B3DVector& rVecA, const B3DVector& rVecB ); + + /** Transform vector by given transformation matrix. + + Since this is a vector, translational components of the + matrix are disregarded. + */ + BASEGFX_DLLPUBLIC B3DVector operator*( const B3DHomMatrix& rMat, const B3DVector& rVec ); + + /** Calculate the Cross Product of two 3D Vectors + + @param rVecA + A first 3D Vector. + + @param rVecB + A second 3D Vector. + + @return + The Cross Product of both 3D Vectors + */ + inline B3DVector cross(const B3DVector& rVecA, const B3DVector& rVecB) + { + B3DVector aVec( + rVecA.getY() * rVecB.getZ() - rVecA.getZ() * rVecB.getY(), + rVecA.getZ() * rVecB.getX() - rVecA.getX() * rVecB.getZ(), + rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX()); + return aVec; + } +} // end of namespace basegfx + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/basicdllapi.h b/include/basic/basicdllapi.h new file mode 100644 index 000000000..90b1f7861 --- /dev/null +++ b/include/basic/basicdllapi.h @@ -0,0 +1,23 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_BASIC_BASICDLLAPI_H +#define INCLUDED_BASIC_BASICDLLAPI_H + +#include + +#if defined(BASIC_DLLIMPLEMENTATION) +#define BASIC_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define BASIC_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define BASIC_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_BASIC_BASICDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/basicmanagerrepository.hxx b/include/basic/basicmanagerrepository.hxx new file mode 100644 index 000000000..e9e906685 --- /dev/null +++ b/include/basic/basicmanagerrepository.hxx @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_BASICMANAGERREPOSITORY_HXX +#define INCLUDED_BASIC_BASICMANAGERREPOSITORY_HXX + +#include + +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::uno { template class Reference; } + +class BasicManager; + + +namespace basic +{ + + + //= BasicManagerRepository + + /** specifies a callback for instances which are interested in BasicManagers + created by the BasicManagerRepository. + */ + class BASIC_DLLPUBLIC SAL_NO_VTABLE BasicManagerCreationListener + { + public: + /** is called when a BasicManager has been created + + @param _rxForDocument + denotes the document for which the BasicManager has been created. If this is , + then the BasicManager is the application-wide BasicManager. + + @param _pBasicManager + denotes the BasicManager which has been created. The listener might for instance + decide to add global variables to it, or otherwise initialize it. + */ + virtual void onBasicManagerCreated( + const css::uno::Reference< css::frame::XModel >& _rxForDocument, + BasicManager& _rBasicManager + ) = 0; + + protected: + ~BasicManagerCreationListener() {} + }; + + + //= BasicManagerRepository + + class BASIC_DLLPUBLIC BasicManagerRepository + { + public: + /** returns the BasicManager belonging to the given document + + If the BasicManager does not yet exist, it is created. In this case, if the application's + BasicManager does not yet exist, it is also created. This is necessary since + the application's BasicManager acts as parent for all document's BasicManagers. + + If you're interested in this case - the implicit creation of the application's BasicManager -, + then you need to register as BasicManagerCreationListener. + + @param _rxDocumentModel + denotes the document model whose BasicManager is to be retrieved. Must not be . + The document should support the XDocumentPropertiesSupplier + interface, for retrieving + its title, which is needed in some error conditions. + Also it must support the XStorageBasedDocument interface, since we + must be able to retrieve the document's storage. If this interface is not + supported, creating a new BasicManager will certainly fail. + + @return + the BasicManager for this model. + + @attention + The returned BasicManager instances is owned by the repository. In particular, + you are not allowed to delete it. Instead, the given model is observed: As soon + as it's closed, the associated BasicManager is deleted. + */ + static BasicManager* getDocumentBasicManager( + const css::uno::Reference< css::frame::XModel >& _rxDocumentModel + ); + + /** returns the application-wide BasicManager + + @attention + If the BasicManager is newly created, then it is still owned by the repository. + In particular, you are not allowed to delete it. Instead, call resetApplicationBasicManager + to release the BasicManager. + */ + static BasicManager* getApplicationBasicManager(); + + /** resets the application-wide BasicManager to + */ + static void resetApplicationBasicManager(); + + /** registers a BasicManagerCreationListener instance which is notified whenever + the repository creates a BasicManager instance. + + Note that this listener is not called when somebody else + creates BasicManager instances. + + If the same listener is registered multiple times, it is also notified + multiple times, and needs to be revoked once for each registration. + */ + static void registerCreationListener( + BasicManagerCreationListener& _rListener + ); + + /** revokes a BasicManagerCreationListener instance which has previously + been registered to be notified about created BasicManager instances. + */ + static void revokeCreationListener( + BasicManagerCreationListener& _rListener + ); + }; + + +} // namespace basic + + +#endif // INCLUDED_BASIC_BASICMANAGERREPOSITORY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/basmgr.hxx b/include/basic/basmgr.hxx new file mode 100644 index 000000000..166b62489 --- /dev/null +++ b/include/basic/basmgr.hxx @@ -0,0 +1,221 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_BASIC_BASMGR_HXX +#define INCLUDED_BASIC_BASMGR_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::script { class XLibraryContainer; } +namespace com::sun::star::script { class XPersistentLibraryContainer; } +namespace com::sun::star::script { class XStarBasicAccess; } + +class BasicManager; + +// Basic XML Import/Export +BASIC_DLLPUBLIC css::uno::Reference< css::script::XStarBasicAccess > + getStarBasicAccess( BasicManager* pMgr ); + +class SotStorage; + +enum class BasicErrorReason +{ + OPENLIBSTORAGE = 0x0002, + OPENMGRSTREAM = 0x0004, + OPENLIBSTREAM = 0x0008, + LIBNOTFOUND = 0x0010, + STORAGENOTFOUND = 0x0020, + BASICLOADERROR = 0x0040, + STDLIB = 0x0100 +}; + +class BasicError +{ +private: + ErrCode nErrorId; + BasicErrorReason nReason; + +public: + BasicError( const BasicError& rErr ); + BasicError( ErrCode nId, BasicErrorReason nR ); + + ErrCode const & GetErrorId() const { return nErrorId; } +}; + +class BasicLibInfo; + +namespace basic { class ImplRepository; } + +// Library password handling for 5.0 documents +class BASIC_DLLPUBLIC OldBasicPassword +{ +public: + virtual void setLibraryPassword( const OUString& rLibraryName, const OUString& rPassword ) = 0; + +protected: + ~OldBasicPassword() {} +}; + +struct LibraryContainerInfo +{ + css::uno::Reference< css::script::XPersistentLibraryContainer > mxScriptCont; + css::uno::Reference< css::script::XPersistentLibraryContainer > mxDialogCont; + OldBasicPassword* mpOldBasicPassword; + + LibraryContainerInfo() + :mpOldBasicPassword( nullptr ) + { + } + + LibraryContainerInfo + ( + css::uno::Reference< css::script::XPersistentLibraryContainer > xScriptCont, + css::uno::Reference< css::script::XPersistentLibraryContainer > xDialogCont, + OldBasicPassword* pOldBasicPassword + ) + : mxScriptCont(std::move( xScriptCont )) + , mxDialogCont(std::move( xDialogCont )) + , mpOldBasicPassword( pOldBasicPassword ) + {} +}; + +#define LIB_NOTFOUND 0xFFFF + +class UNLESS_MERGELIBS(BASIC_DLLPUBLIC) BasicManager final : public SfxBroadcaster +{ + friend class LibraryContainer_Impl; + friend class StarBasicAccess_Impl; + friend class BasMgrContainerListenerImpl; + friend class ::basic::ImplRepository; + +private: + std::vector aErrors; + + OUString aName; + OUString maStorageName; + bool mbDocMgr; + + LibraryContainerInfo maContainerInfo; + std::vector> maLibs; + OUString aBasicLibPath; + + bool ImpLoadLibrary( BasicLibInfo* pLibInfo, SotStorage* pCurStorage ); + void ImpCreateStdLib( StarBASIC* pParentFromStdLib ); + void ImpMgrNotLoaded( const OUString& rStorageName ); + BasicLibInfo* CreateLibInfo(); + void LoadBasicManager( SotStorage& rStorage, std::u16string_view rBaseURL ); + void LoadOldBasicManager( SotStorage& rStorage ); + bool ImplLoadBasic( SvStream& rStrm, StarBASICRef& rOldBasic ) const; + static bool ImplEncryptStream( SvStream& rStream ); + BasicLibInfo* FindLibInfo( StarBASIC const * pBasic ); + static void CheckModules( StarBASIC* pBasic, bool bReference ); + +public: + BasicManager( SotStorage& rStorage, std::u16string_view rBaseURL, StarBASIC* pParentFromStdLib = nullptr, OUString const * pLibPath = nullptr, bool bDocMgr = false ); + BasicManager( StarBASIC* pStdLib, OUString const * pLibPath = nullptr, bool bDocMgr = false ); + + virtual ~BasicManager() override; + + void SetStorageName( const OUString& rName ) { maStorageName = rName; } + const OUString& GetStorageName() const { return maStorageName; } + void SetName( const OUString& rName ) { aName = rName; } + const OUString& GetName() const { return aName; } + + + IF_MERGELIBS(BASIC_DLLPUBLIC) sal_uInt16 GetLibCount() const; + IF_MERGELIBS(BASIC_DLLPUBLIC) StarBASIC* GetLib( sal_uInt16 nLib ) const; + IF_MERGELIBS(BASIC_DLLPUBLIC) StarBASIC* GetLib( std::u16string_view rName ) const; + sal_uInt16 GetLibId( std::u16string_view rName ) const; + + OUString GetLibName( sal_uInt16 nLib ); + + /** announces the library containers which belong to this BasicManager + + The method will automatically add two global constants, BasicLibraries and DialogLibraries, + to the BasicManager. + */ + void SetLibraryContainerInfo( const LibraryContainerInfo& rInfo ); + + const css::uno::Reference< css::script::XPersistentLibraryContainer >& + GetDialogLibraryContainer() const; + const css::uno::Reference< css::script::XPersistentLibraryContainer >& + GetScriptLibraryContainer() const; + + bool LoadLib( sal_uInt16 nLib ); + IF_MERGELIBS(BASIC_DLLPUBLIC) + bool RemoveLib( sal_uInt16 nLib, bool bDelBasicFromStorage ); + + // Modify-Flag will be reset only during save. + bool IsBasicModified() const; + + std::vector& GetErrors() { return aErrors;} + + /** sets a global constant in the basic library, referring to some UNO object, to a new value. + + If a constant with this name already existed before, its value is changed, and the old constant is + returned in pOldValue. If it does not yet exist, it is newly created, and inserted into the basic library. + */ + IF_MERGELIBS(BASIC_DLLPUBLIC) + void SetGlobalUNOConstant( const OUString& rName, const css::uno::Any& _rValue, css::uno::Any* pOldValue = nullptr ); + + /** retrieves a global constant in the basic library, referring to some UNO object, returns true if a value is found ( value is in aOut ) false otherwise. */ + IF_MERGELIBS(BASIC_DLLPUBLIC) + bool GetGlobalUNOConstant( const OUString& rName, css::uno::Any& aOut ); + /** determines whether there are password-protected modules whose size exceeds the + legacy module size + @param _out_rModuleNames + takes the names of modules whose size exceeds the legacy limit + */ + bool LegacyPsswdBinaryLimitExceeded( std::vector< OUString >& _out_rModuleNames ); + bool HasExeCode( std::u16string_view ); + /// determines whether the Basic Manager has a given macro, given by fully qualified name + IF_MERGELIBS(BASIC_DLLPUBLIC) + bool HasMacro( OUString const& i_fullyQualifiedName ) const; + /// executes a given macro + ErrCode ExecuteMacro( OUString const& i_fullyQualifiedName, SbxArray* i_arguments, SbxValue* i_retValue ); + /// executes a given macro + ErrCode ExecuteMacro( OUString const& i_fullyQualifiedName, std::u16string_view i_commaSeparatedArgs, SbxValue* i_retValue ); + +private: + BASIC_DLLPRIVATE bool IsReference( sal_uInt16 nLib ); + + BASIC_DLLPRIVATE StarBASIC* GetStdLib() const; + BASIC_DLLPRIVATE StarBASIC* AddLib( SotStorage& rStorage, const OUString& rLibName, bool bReference ); + BASIC_DLLPRIVATE void RemoveLib( sal_uInt16 nLib ); + BASIC_DLLPRIVATE bool HasLib( std::u16string_view rName ) const; + + BASIC_DLLPRIVATE StarBASIC* CreateLibForLibContainer( const OUString& rLibName, + const css::uno::Reference< css::script::XLibraryContainer >& xScriptCont ); + // For XML import/export: + BASIC_DLLPRIVATE StarBASIC* CreateLib( const OUString& rLibName ); + BASIC_DLLPRIVATE StarBASIC* CreateLib( const OUString& rLibName, const OUString& Password, + const OUString& LinkTargetURL ); + BasicManager& operator=(BasicManager const &) = delete; //MSVC2015 workaround + BasicManager( BasicManager const&) = delete; //MSVC2015 workaround +}; + +#endif // INCLUDED_BASIC_BASMGR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/basrdll.hxx b/include/basic/basrdll.hxx new file mode 100644 index 000000000..2748bf3fd --- /dev/null +++ b/include/basic/basrdll.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_BASRDLL_HXX +#define INCLUDED_BASIC_BASRDLL_HXX + +#include +#include + +class BASIC_DLLPUBLIC BasicDLL +{ +private: + tools::SvRef m_xImpl; + +public: + BasicDLL(); + ~BasicDLL(); + + static void BasicBreak(); + + static void EnableBreak(bool bEnable); + static void SetDebugMode(bool bDebugMode); +}; + +#endif // INCLUDED_BASIC_BASRDLL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/codecompletecache.hxx b/include/basic/codecompletecache.hxx new file mode 100644 index 000000000..2c6c0873f --- /dev/null +++ b/include/basic/codecompletecache.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_CODECOMPLETECACHE_HXX +#define INCLUDED_BASIC_CODECOMPLETECACHE_HXX + +#include +#include +#include +#include + +typedef std::unordered_map< OUString, OUString > CodeCompleteVarTypes; +/* variable name, type */ +typedef std::unordered_map< OUString, CodeCompleteVarTypes > CodeCompleteVarScopes; +/* procedure, CodeCompleteVarTypes */ + +class BASIC_DLLPUBLIC CodeCompleteOptions +{ +/* + * class to store basic code completion + * options + * */ +private: + bool bIsCodeCompleteOn; + bool bIsProcedureAutoCompleteOn; + bool bIsAutoCloseQuotesOn; + bool bIsAutoCloseParenthesisOn; + bool bIsAutoCorrectOn; + bool bExtendedTypeDeclarationOn; + +public: + CodeCompleteOptions(); + + static bool IsCodeCompleteOn(); + static void SetCodeCompleteOn( bool b ); + + static bool IsExtendedTypeDeclaration(); + static void SetExtendedTypeDeclaration( bool b ); + + static bool IsProcedureAutoCompleteOn(); + static void SetProcedureAutoCompleteOn( bool b ); + + static bool IsAutoCloseQuotesOn(); + static void SetAutoCloseQuotesOn( bool b ); + + static bool IsAutoCloseParenthesisOn(); + static void SetAutoCloseParenthesisOn( bool b ); + + static bool IsAutoCorrectOn(); + static void SetAutoCorrectOn( bool b ); +}; + +class UNLESS_MERGELIBS(BASIC_DLLPUBLIC) CodeCompleteDataCache final +{ +/* + * cache to store data for + * code completion + * */ +private: + CodeCompleteVarScopes aVarScopes; + CodeCompleteVarTypes aGlobalVars; + +public: + CodeCompleteDataCache(){} + + friend BASIC_DLLPUBLIC std::ostream& operator<< (std::ostream& aStream, const CodeCompleteDataCache& aCache); + + void InsertGlobalVar( const OUString& sVarName, const OUString& sVarType ); + void InsertLocalVar( const OUString& sProcName, const OUString& sVarName, const OUString& sVarType ); + OUString GetVarType( std::u16string_view sVarName ) const; + OUString GetCorrectCaseVarName( std::u16string_view sVarName, std::u16string_view sActProcName ) const; + void Clear(); +}; + +#endif // INCLUDED_BASIC_CODECOMPLETECACHE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/modsizeexceeded.hxx b/include/basic/modsizeexceeded.hxx new file mode 100644 index 000000000..8910be30b --- /dev/null +++ b/include/basic/modsizeexceeded.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_MODSIZEEXCEEDED_HXX +#define INCLUDED_BASIC_MODSIZEEXCEEDED_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::task { class XInteractionContinuation; } + +#if defined(_MSC_VER) && !defined(__clang__) +// MSVC automatically applies dllexport to template instantiations if they are a base class +// of a dllexport class, and this template instantiation is a case of that. If we don't +// dllimport here, MSVC will complain about duplicate symbols in a mergelibs build. +template class __declspec(dllimport) cppu::WeakImplHelper< css::task::XInteractionRequest >; +#endif + +class UNLESS_MERGELIBS(BASIC_DLLPUBLIC) ModuleSizeExceeded final : public cppu::WeakImplHelper< css::task::XInteractionRequest > +{ +// C++ interface +public: + ModuleSizeExceeded( const std::vector& sModules ); + + bool isAbort() const; + bool isApprove() const; + +// UNO interface +public: + virtual css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > SAL_CALL getContinuations() override { return m_lContinuations; } + css::uno::Any SAL_CALL getRequest() override + { + return m_aRequest; + } + +// member +private: + css::uno::Any m_aRequest; + css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > m_lContinuations; + css::uno::Reference< css::task::XInteractionContinuation > m_xAbort; + css::uno::Reference< css::task::XInteractionContinuation> m_xApprove; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbdef.hxx b/include/basic/sbdef.hxx new file mode 100644 index 000000000..d864ed8de --- /dev/null +++ b/include/basic/sbdef.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBDEF_HXX +#define INCLUDED_BASIC_SBDEF_HXX + +#include +#include +#include +#include +#include + +class ErrCode; + +// Returns type name for Basic type, array flag is ignored +// implementation: basic/source/runtime/methods.cxx +BASIC_DLLPUBLIC OUString getBasicTypeName( SbxDataType eType ); + +// Returns type name for Basic objects, especially +// important for SbUnoObj instances +// implementation: basic/source/classes/sbunoobj.cxx +class SbxObject; +BASIC_DLLPUBLIC OUString getBasicObjectTypeName( SbxObject* pObj ); + +// Allows Basic IDE to set watch mode to suppress errors +// implementation: basic/source/runtime/runtime.cxx +BASIC_DLLPUBLIC void setBasicWatchMode( bool bOn ); + +// Debug Flags: +enum class BasicDebugFlags { + NONE = 0x0000, + Break = 0x0001, // Break-Callback + StepInto = 0x0002, // Single Step-Callback + StepOver = 0x0004, // Additional flag Step Over + Continue = 0x0008, // Do not change flags + StepOut = 0x0010, // Leave Sub +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +#define SBXID_BASIC 0x6273 // sb: StarBASIC +#define SBXID_BASICMOD 0x6d62 // bm: StarBASIC Module +#define SBXID_BASICPROP 0x7262 // pr: StarBASIC Property +#define SBXID_BASICMETHOD 0x6d65 // me: StarBASIC Method +#define SBXID_JSCRIPTMOD 0x6a62 // jm: JavaScript Module +#define SBXID_JSCRIPTMETH 0x6a64 // jm: JavaScript Module + +enum class PropertyMode +{ + NONE, + Get, + Let, + Set +}; + +BASIC_DLLPUBLIC extern std::pair const RID_BASIC_START[]; +BASIC_DLLPUBLIC std::locale BasResLocale(); +OUString BasResId(TranslateId pId); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sberrors.hxx b/include/basic/sberrors.hxx new file mode 100644 index 000000000..5976df8b9 --- /dev/null +++ b/include/basic/sberrors.hxx @@ -0,0 +1,176 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBERRORS_HXX +#define INCLUDED_BASIC_SBERRORS_HXX + +#include + +#define ERRCODE_BASIC_SYNTAX ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 1) // unspecified syntax error +#define ERRCODE_BASIC_BAD_ARGUMENT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::NotSupported, 2) // Invalid procedure call +#define ERRCODE_BASIC_MATH_OVERFLOW ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Sbx, 3) // overflow +#define ERRCODE_BASIC_OUT_OF_RANGE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Sbx, 4) // Invalid array index / Subscript out of range +#define ERRCODE_BASIC_ZERODIV ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Sbx, 5) // Division by zero +#define ERRCODE_BASIC_CONVERSION ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Sbx, 6) // wrong data type +#define ERRCODE_BASIC_BAD_PARAMETER ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 7) // invalid Parameter +#define ERRCODE_BASIC_PROC_UNDEFINED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 8) // Sub or Function not defined +#define ERRCODE_BASIC_INTERNAL_ERROR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Unknown, 9) // generic object error +#define ERRCODE_BASIC_NO_OBJECT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 10) // Object variable not set +#define ERRCODE_BASIC_CANNOT_LOAD ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Create, 11) // Can't load module +#define ERRCODE_BASIC_BAD_INDEX ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Sbx, 12) // Invalid object index +#define ERRCODE_BASIC_NO_ACTIVE_OBJECT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Access, 13) // No active view or document +#define ERRCODE_BASIC_BAD_PROP_VALUE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 14) // Bad property value +#define ERRCODE_BASIC_PROP_READONLY ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Read, 15) // Property is read only +#define ERRCODE_BASIC_PROP_WRITEONLY ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Write, 16) // Property is write only +#define ERRCODE_BASIC_INVALID_OBJECT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Access, 17) // Invalid object reference +#define ERRCODE_BASIC_NO_METHOD ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 18) // Property or Method unknown +#define ERRCODE_BASIC_INVALID_USAGE_OBJECT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Access, 19) // Invalid object usage +#define ERRCODE_BASIC_NO_OLE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Access, 20) // Class does not support OLE +#define ERRCODE_BASIC_BAD_METHOD ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 21) // Method not supported +#define ERRCODE_BASIC_OLE_ERROR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 22) // OLE Automation Error +#define ERRCODE_BASIC_BAD_ACTION ErrCode( ErrCodeArea::Sbx, ErrCodeClass::NotSupported, 23) // Object doesn't support this action +#define ERRCODE_BASIC_NO_NAMED_ARGS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 24) // Object doesn't support named args +#define ERRCODE_BASIC_BAD_LOCALE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::NotSupported, 25) // Object doesn't support current locale setting +#define ERRCODE_BASIC_NAMED_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 26) // Named argument not found +#define ERRCODE_BASIC_NOT_OPTIONAL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 27) // Argument not optional +#define ERRCODE_BASIC_WRONG_ARGS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Sbx, 28) // Invalid number of arguments +#define ERRCODE_BASIC_NOT_A_COLL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 29) // Object not a collection + +#define ERRCODE_BASIC_NO_GOSUB ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 30 ) // Return without Gosub +#define ERRCODE_BASIC_REDO_FROM_START ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 31 ) // Redo form start (SB internal) +#define ERRCODE_BASIC_NO_MEMORY ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 32 ) // Out of memory +#define ERRCODE_BASIC_ALREADY_DIM ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 33 ) // Array already dimensioned +#define ERRCODE_BASIC_DUPLICATE_DEF ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 34 ) // Duplicate definition +#define ERRCODE_BASIC_VAR_UNDEFINED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 35 ) // Variable undefined (SB) +#define ERRCODE_BASIC_USER_ABORT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 36 ) // User interrupt occurred +#define ERRCODE_BASIC_BAD_RESUME ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 37 ) // Resume without error +#define ERRCODE_BASIC_STACK_OVERFLOW ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 38 ) // Out of stack space +#define ERRCODE_BASIC_BAD_DLL_LOAD ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 39 ) // Error in loading DLL +#define ERRCODE_BASIC_BAD_DLL_CALL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 40 ) // Bad DLL calling convention +#define ERRCODE_BASIC_BAD_CHANNEL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 41 ) // Bad file name or number +#define ERRCODE_BASIC_FILE_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 42 ) // File not found +#define ERRCODE_BASIC_BAD_FILE_MODE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 43 ) // Bad file mode +#define ERRCODE_BASIC_FILE_ALREADY_OPEN ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 44 ) // File already open +#define ERRCODE_BASIC_IO_ERROR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 45 ) // Device I/O error +#define ERRCODE_BASIC_FILE_EXISTS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 46 ) // File already exists +#define ERRCODE_BASIC_BAD_RECORD_LENGTH ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 47 ) // bad record length +#define ERRCODE_BASIC_DISK_FULL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 48 ) // disk full +#define ERRCODE_BASIC_READ_PAST_EOF ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 49 ) // Input past end of file +#define ERRCODE_BASIC_BAD_RECORD_NUMBER ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 50 ) // Bad record number +#define ERRCODE_BASIC_TOO_MANY_FILES ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 51 ) // Too many files +#define ERRCODE_BASIC_NO_DEVICE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 52 ) // Device not available +#define ERRCODE_BASIC_ACCESS_DENIED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 53 ) // Permission denied +#define ERRCODE_BASIC_NOT_READY ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 54 ) // Disk not ready +#define ERRCODE_BASIC_NOT_IMPLEMENTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 55 ) // Feature not implemented +#define ERRCODE_BASIC_DIFFERENT_DRIVE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 56 ) // No rename with different drive +#define ERRCODE_BASIC_ACCESS_ERROR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 57 ) // Path/File access error +#define ERRCODE_BASIC_PATH_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 58 ) // Path not found +#define ERRCODE_BASIC_BAD_PATTERN ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 59 ) // Invalid pattern string +#define ERRCODE_BASIC_IS_NULL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 60 ) // Invalid use of Null + +#define ERRCODE_BASIC_DDE_ERROR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 61 ) +#define ERRCODE_BASIC_DDE_WAITINGACK ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 62 ) +#define ERRCODE_BASIC_DDE_OUTOFCHANNELS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 63 ) +#define ERRCODE_BASIC_DDE_NO_RESPONSE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 64 ) +#define ERRCODE_BASIC_DDE_MULT_RESPONSES ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 65 ) +#define ERRCODE_BASIC_DDE_CHANNEL_LOCKED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 66 ) +#define ERRCODE_BASIC_DDE_NOTPROCESSED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 67 ) +#define ERRCODE_BASIC_DDE_TIMEOUT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 68 ) +#define ERRCODE_BASIC_DDE_USER_INTERRUPT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 69 ) +#define ERRCODE_BASIC_DDE_BUSY ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 70 ) +#define ERRCODE_BASIC_DDE_NO_DATA ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 71 ) +#define ERRCODE_BASIC_DDE_WRONG_DATA_FORMAT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 72 ) +#define ERRCODE_BASIC_DDE_PARTNER_QUIT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 73 ) +#define ERRCODE_BASIC_DDE_CONV_CLOSED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 74 ) +#define ERRCODE_BASIC_DDE_NO_CHANNEL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 75 ) +#define ERRCODE_BASIC_DDE_INVALID_LINK ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 76 ) +#define ERRCODE_BASIC_DDE_QUEUE_OVERFLOW ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 77 ) +#define ERRCODE_BASIC_DDE_LINK_ALREADY_EST ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 78 ) +#define ERRCODE_BASIC_DDE_LINK_INV_TOPIC ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 79 ) +#define ERRCODE_BASIC_DDE_DLL_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 80 ) + +#define ERRCODE_BASIC_NEEDS_OBJECT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 81 ) // Object required +#define ERRCODE_BASIC_BAD_ORDINAL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 82 ) // Invalid ordinal +#define ERRCODE_BASIC_DLLPROC_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 83 ) // Specified DLL function not found +#define ERRCODE_BASIC_BAD_CLIPBD_FORMAT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 84 ) // Invalid clipboard format + +#define ERRCODE_BASIC_PROPERTY_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 85 ) // Class not have property +#define ERRCODE_BASIC_METHOD_NOT_FOUND ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 86 ) // Class does not have method +#define ERRCODE_BASIC_ARG_MISSING ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 87 ) // Missing required argument +#define ERRCODE_BASIC_BAD_NUMBER_OF_ARGS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 88 ) // Bad number of arguments +#define ERRCODE_BASIC_METHOD_FAILED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 89 ) // Method failed +#define ERRCODE_BASIC_SETPROP_FAILED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 90 ) // Unable to set property +#define ERRCODE_BASIC_GETPROP_FAILED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 91 ) // Unable to get property + +// Compiler Errors (do not occur at runtime) +// These IDs can shift at any time + +#define ERRCODE_BASIC_UNEXPECTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 92 ) // Unexpected symbol: xx +#define ERRCODE_BASIC_EXPECTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 93 ) // Expected: xx +#define ERRCODE_BASIC_SYMBOL_EXPECTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 94 ) // Symbol expected +#define ERRCODE_BASIC_VAR_EXPECTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 95 ) // Variable expected +#define ERRCODE_BASIC_LABEL_EXPECTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 96 ) // Label expected +#define ERRCODE_BASIC_LVALUE_EXPECTED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 97 ) // Lvalue expected +#define ERRCODE_BASIC_VAR_DEFINED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 98 ) // Variable xxx already defined +#define ERRCODE_BASIC_PROC_DEFINED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 99 ) // Procedure xx already defined +#define ERRCODE_BASIC_LABEL_DEFINED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 100 ) // Label xxx already defined +#define ERRCODE_BASIC_UNDEF_VAR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 101 ) // Variable xx undefined +#define ERRCODE_BASIC_UNDEF_ARRAY ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 102 ) // Array or function xx undefined +#define ERRCODE_BASIC_UNDEF_PROC ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 103 ) // Procedure xxx undefined +#define ERRCODE_BASIC_UNDEF_LABEL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 104 ) // Label xxx undefined +#define ERRCODE_BASIC_UNDEF_TYPE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 105 ) // Unknown user defined type xxx +#define ERRCODE_BASIC_BAD_EXIT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 106 ) // Exit XXX expected +#define ERRCODE_BASIC_BAD_BLOCK ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 107 ) // Unterminated statement block: missing XX +#define ERRCODE_BASIC_BAD_BRACKETS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 108 ) // Parentheses do not match +#define ERRCODE_BASIC_BAD_DECLARATION ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 109 ) // Symbol xx defined differently +#define ERRCODE_BASIC_BAD_PARAMETERS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 110 ) // Parameters do not match +#define ERRCODE_BASIC_BAD_CHAR_IN_NUMBER ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 111 ) // Bad character in number +#define ERRCODE_BASIC_MUST_HAVE_DIMS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 112 ) // Array needs dimensioning +#define ERRCODE_BASIC_NO_IF ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 113 ) // Else/Endif without If +#define ERRCODE_BASIC_NOT_IN_SUBR ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 114 ) // xxx not allowed within a sub +#define ERRCODE_BASIC_NOT_IN_MAIN ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 115 ) // xxx not allowed outside a sub +#define ERRCODE_BASIC_WRONG_DIMS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 116 ) // Dimensions do not match +#define ERRCODE_BASIC_BAD_OPTION ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 117 ) // Unknown option: xxx +#define ERRCODE_BASIC_CONSTANT_REDECLARED ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 118 ) // Constant xx redeclared +#define ERRCODE_BASIC_PROG_TOO_LARGE ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 119 ) // Program is too large +#define ERRCODE_BASIC_NO_STRINGS_ARRAYS ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 120 ) +#define ERRCODE_BASIC_EXCEPTION ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 121 ) + +#define ERRCODE_BASMGR_STDLIBOPEN ErrCode( ErrCodeArea::Sbx, 122) +#define ERRCODE_BASMGR_STDLIBSAVE ErrCode( ErrCodeArea::Sbx, 123) +#define ERRCODE_BASMGR_LIBLOAD ErrCode( ErrCodeArea::Sbx, 124) +#define ERRCODE_BASMGR_LIBCREATE ErrCode( ErrCodeArea::Sbx, 125) +#define ERRCODE_BASMGR_LIBSAVE ErrCode( ErrCodeArea::Sbx, 126) +#define ERRCODE_BASMGR_LIBDEL ErrCode( ErrCodeArea::Sbx, 127) +#define ERRCODE_BASMGR_MGROPEN ErrCode( ErrCodeArea::Sbx, 128) +#define ERRCODE_BASMGR_MGRSAVE ErrCode( ErrCodeArea::Sbx, 129) +#define ERRCODE_BASMGR_REMOVELIB ErrCode( ErrCodeArea::Sbx, 130) +#define ERRCODE_BASMGR_UNLOADLIB ErrCode( ErrCodeArea::Sbx, 131) + +#define ERRCODE_BASIC_COMPAT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Runtime, 132 ) +#define ERRCODE_BASIC_ARRAY_FIX ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 133 ) // This array is fixed +#define ERRCODE_BASIC_STRING_OVERFLOW ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 134 ) // Out of string space +#define ERRCODE_BASIC_EXPR_TOO_COMPLEX ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 135 ) // Expression too complex +#define ERRCODE_BASIC_OPER_NOT_PERFORM ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 136 ) // Can't perform requested operation +#define ERRCODE_BASIC_TOO_MANY_DLL ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 137 ) // Too many dll application clients +#define ERRCODE_BASIC_LOOP_NOT_INIT ErrCode( ErrCodeArea::Sbx, ErrCodeClass::Compiler, 138 ) // For loop not initialized + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbmeth.hxx b/include/basic/sbmeth.hxx new file mode 100644 index 000000000..fefd84aed --- /dev/null +++ b/include/basic/sbmeth.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBMETH_HXX +#define INCLUDED_BASIC_SBMETH_HXX + +#include +#include +#include +#include + +class SbModule; + +class BASIC_DLLPUBLIC SbMethod : public SbxMethod +{ + friend class SbiRuntime; + friend class SbiFactory; + friend class SbModule; + friend class SbClassModuleObject; + friend class SbiCodeGen; + friend class SbJScriptMethod; + friend class SbIfaceMapperMethod; + + SbxVariable* mCaller; // caller + SbModule* pMod; + BasicDebugFlags nDebugFlags; + sal_uInt16 nLine1, nLine2; + sal_uInt32 nStart; + bool bInvalid; + SbxArrayRef refStatics; + BASIC_DLLPRIVATE SbMethod( const OUString&, SbxDataType, SbModule* ); + BASIC_DLLPRIVATE SbMethod( const SbMethod& ); + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; + virtual ~SbMethod() override; + +public: + SBX_DECL_PERSIST_NODATA(SBXID_BASICMETHOD,2); + virtual SbxInfo* GetInfo() override; + SbxArray* GetStatics(); + void ClearStatics(); + SbModule* GetModule() { return pMod; } + BasicDebugFlags GetDebugFlags() const { return nDebugFlags; } + void SetDebugFlags( BasicDebugFlags n ) { nDebugFlags = n; } + void GetLineRange( sal_uInt16&, sal_uInt16& ); + + // Interface to execute a method from the applications + ErrCode Call( SbxValue* pRet, SbxVariable* pCaller = nullptr ); + virtual void Broadcast( SfxHintId nHintId ) override; +}; + +typedef tools::SvRef SbMethodRef; + +class SbIfaceMapperMethod final : public SbMethod +{ + friend class SbiRuntime; + + SbMethodRef mxImplMeth; + +public: + SbIfaceMapperMethod( const OUString& rName, SbMethod* pImplMeth ) + : SbMethod( rName, pImplMeth->GetType(), nullptr ) + , mxImplMeth( pImplMeth ) + {} + virtual ~SbIfaceMapperMethod() override; + SbMethod* getImplMethod() + { return mxImplMeth.get(); } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbmod.hxx b/include/basic/sbmod.hxx new file mode 100644 index 000000000..a71f7253a --- /dev/null +++ b/include/basic/sbmod.hxx @@ -0,0 +1,165 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBMOD_HXX +#define INCLUDED_BASIC_SBMOD_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::script { class XInvocation; } + +class SbMethod; +class SbProperty; +typedef std::deque< sal_uInt16 > SbiBreakpoints; +class SbiImage; +class SbClassModuleObject; +class CodeCompleteDataCache; + + +class ModuleInitDependencyMap; +struct ClassModuleRunInitItem; +struct SbClassData; + +class BASIC_DLLPUBLIC SbModule : public SbxObject +{ + friend class SbiCodeGen; + friend class SbMethod; + friend class SbiRuntime; + friend class StarBASIC; + friend class SbClassModuleObject; + + std::vector< OUString > mModuleVariableNames; + + BASIC_DLLPRIVATE static void implClearIfVarDependsOnDeletedBasic( SbxVariable* pVar, StarBASIC* pDeletedBasic ); + + SbModule(const SbModule&) = delete; + SbModule& operator=(const SbModule&) = delete; +protected: + css::uno::Reference< css::script::XInvocation > mxWrapper; + OUString aOUSource; + OUString aComment; + std::unique_ptr pImage; // the Image + SbiBreakpoints* pBreaks; // Breakpoints + std::unique_ptr pClassData; + bool mbVBACompat; + sal_Int32 mnType; + SbxObjectRef pDocObject; // an impl object ( used by Document Modules ) + bool bIsProxyModule; + + SAL_DLLPRIVATE static void implProcessModuleRunInit( ModuleInitDependencyMap& rMap, ClassModuleRunInitItem& rItem ); + SAL_DLLPRIVATE void StartDefinitions(); + SAL_DLLPRIVATE SbMethod* GetMethod( const OUString&, SbxDataType ); + SAL_DLLPRIVATE SbProperty* GetProperty( const OUString&, SbxDataType ); + SAL_DLLPRIVATE void GetProcedureProperty( const OUString&, SbxDataType ); + SAL_DLLPRIVATE void GetIfaceMapperMethod( const OUString&, SbMethod* ); + SAL_DLLPRIVATE void EndDefinitions( bool=false ); + SAL_DLLPRIVATE void Run( SbMethod* ); + SAL_DLLPRIVATE void RunInit(); + SAL_DLLPRIVATE void ClearPrivateVars(); + SAL_DLLPRIVATE void ClearVarsDependingOnDeletedBasic( StarBASIC* pDeletedBasic ); + SAL_DLLPRIVATE void GlobalRunInit( bool bBasicStart ); // for all modules + SAL_DLLPRIVATE void GlobalRunDeInit(); + SAL_DLLPRIVATE const sal_uInt8* FindNextStmnt( const sal_uInt8*, sal_uInt16&, sal_uInt16& ) const; + SAL_DLLPRIVATE const sal_uInt8* FindNextStmnt( const sal_uInt8*, sal_uInt16&, sal_uInt16&, + bool bFollowJumps, const SbiImage* pImg=nullptr ) const; + SAL_DLLPRIVATE virtual bool LoadData( SvStream&, sal_uInt16 ) override; + SAL_DLLPRIVATE virtual bool StoreData( SvStream& ) const override; + SAL_DLLPRIVATE virtual bool LoadCompleted() override; + SAL_DLLPRIVATE virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; + SAL_DLLPRIVATE void handleProcedureProperties( SfxBroadcaster& rBC, const SfxHint& rHint ); + virtual ~SbModule() override; +public: + SBX_DECL_PERSIST_NODATA(SBXID_BASICMOD,2); + SbModule( const OUString&, bool bCompat = false ); + SAL_DLLPRIVATE virtual void SetParent( SbxObject* ) override; + SAL_DLLPRIVATE virtual void Clear() override; + + SAL_DLLPRIVATE virtual SbxVariable* Find( const OUString&, SbxClassType ) override; + + const OUString& GetSource32() const { return aOUSource;} + void SetSource32( const OUString& r ); + + bool Compile(); + bool IsCompiled() const; + SAL_DLLPRIVATE const SbxObject* FindType( const OUString& aTypeName ) const; + + SAL_DLLPRIVATE bool IsBreakable( sal_uInt16 nLine ) const; + SAL_DLLPRIVATE bool IsBP( sal_uInt16 nLine ) const; + bool SetBP( sal_uInt16 nLine ); + bool ClearBP( sal_uInt16 nLine ); + void ClearAllBP(); + + // Store only image, no source (needed for new password protection) + SAL_DLLPRIVATE void StoreBinaryData( SvStream& ); + SAL_DLLPRIVATE void LoadBinaryData( SvStream& ); + SAL_DLLPRIVATE bool ExceedsLegacyModuleSize(); + SAL_DLLPRIVATE void fixUpMethodStart( bool bCvtToLegacy, SbiImage* pImg = nullptr ) const; + SAL_DLLPRIVATE bool HasExeCode(); + bool IsVBACompat() const { return mbVBACompat;} + SAL_DLLPRIVATE void SetVBACompat( bool bCompat ); + sal_Int32 GetModuleType() const { return mnType; } + void SetModuleType( sal_Int32 nType ) { mnType = nType; } + bool isProxyModule() const { return bIsProxyModule; } + SAL_DLLPRIVATE void AddVarName( const OUString& aName ); + SAL_DLLPRIVATE void RemoveVars(); + css::uno::Reference< css::script::XInvocation > const & GetUnoModule(); + bool createCOMWrapperForIface( css::uno::Any& o_rRetAny, SbClassModuleObject* pProxyClassModuleObject ); + void GetCodeCompleteDataFromParse(CodeCompleteDataCache& aCache); + const SbxArrayRef& GetMethods() const { return pMethods;} + SbMethod* FindMethod( const OUString&, SbxClassType ); + static OUString GetKeywordCase( const OUString& sKeyword ); +}; + +typedef tools::SvRef SbModuleRef; +typedef std::vector SbModules; + +// Object class for instances of class modules +class UNLESS_MERGELIBS(BASIC_DLLPUBLIC) SbClassModuleObject final : public SbModule +{ + SbModule* mpClassModule; + bool mbInitializeEventDone; + +public: + SbClassModuleObject( SbModule* pClassModule ); + virtual ~SbClassModuleObject() override; + + // Overridden to support NameAccess etc. + virtual SbxVariable* Find( const OUString&, SbxClassType ) override; + + virtual void Notify( SfxBroadcaster&, const SfxHint& rHint ) override; + + SbModule* getClassModule() + { return mpClassModule; } + + void triggerInitializeEvent(); + void triggerTerminateEvent(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbstar.hxx b/include/basic/sbstar.hxx new file mode 100644 index 000000000..1629ab16c --- /dev/null +++ b/include/basic/sbstar.hxx @@ -0,0 +1,157 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBSTAR_HXX +#define INCLUDED_BASIC_SBSTAR_HXX + +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::script { struct ModuleInfo; } + +class SbMethod; + +class BASIC_DLLPUBLIC StarBASIC final : public SbxObject +{ + friend class SbiScanner; + friend class SbiExpression; // Access to RTL + friend class SbiInstance; // runtime instance + friend class SbiRuntime; // currently running procedure + friend class DocBasicItem; + + SbModules pModules; // List of all modules + SbxObjectRef pRtl; // Runtime Library + SbxArrayRef xUnoListeners; // Listener handled by CreateUnoListener + + // Handler-Support: + Link aErrorHdl; // Error handler + Link aBreakHdl; // Breakpoint handler + bool bNoRtl; // if true: do not search RTL + bool bBreak; // if true: Break, otherwise Step + bool bDocBasic; + bool bVBAEnabled; + bool bQuit; + + SbxObjectRef pVBAGlobals; + + BASIC_DLLPRIVATE void implClearDependingVarsOnDelete( StarBASIC* pDeletedBasic ); + bool CError( ErrCode, const OUString&, sal_Int32, sal_Int32, sal_Int32 ); + BASIC_DLLPRIVATE bool RTError( ErrCode, const OUString& rMsg, sal_Int32, sal_Int32, sal_Int32 ); + BASIC_DLLPRIVATE BasicDebugFlags BreakPoint( sal_Int32 nLine, sal_Int32 nCol1, sal_Int32 nCol2 ); + BASIC_DLLPRIVATE BasicDebugFlags StepPoint( sal_Int32 nLine, sal_Int32 nCol1, sal_Int32 nCol2 ); + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; + bool ErrorHdl(); + BasicDebugFlags BreakHdl(); + virtual ~StarBASIC() override; + +public: + + SBX_DECL_PERSIST_NODATA(SBXID_BASIC,1); + + StarBASIC( StarBASIC* pParent = nullptr, bool bIsDocBasic = false ); + + // #51727 SetModified overridden so that the Modified-State is + // not delivered to Parent. + virtual void SetModified( bool ) override; + + virtual void Insert( SbxVariable* ) override; + using SbxObject::Remove; + virtual void Remove( SbxVariable* ) override; + virtual void Clear() override; + + // Compiler-Interface + SbModule* MakeModule( const OUString& rName, const OUString& rSrc ); + SbModule* MakeModule( const OUString& rName, const css::script::ModuleInfo& mInfo, const OUString& rSrc ); + static void Stop(); + static void Error( ErrCode, const OUString& rMsg = {} ); + static void FatalError( ErrCode ); + static void FatalError( ErrCode, const OUString& rMsg ); + static bool IsRunning(); + static ErrCode GetErrBasic(); + // #66536 make additional message accessible by RTL function Error + static OUString GetErrorMsg(); + static sal_Int32 GetErl(); + + virtual SbxVariable* Find( const OUString&, SbxClassType ) override; + virtual bool Call( const OUString&, SbxArray* = nullptr ) override; + + SbModules& GetModules() { return pModules; } + SbxObject* GetRtl() { return pRtl.get(); } + SbModule* FindModule( std::u16string_view ); + // Run init code of all modules (including the inserted Doc-Basics) + void InitAllModules( StarBASIC const * pBasicNotToInit = nullptr ); + void DeInitAllModules(); + void ClearAllModuleVars(); + + // Calls for error and break handler + static sal_uInt16 GetLine(); + static sal_uInt16 GetCol1(); + static sal_uInt16 GetCol2(); + static void SetErrorData( ErrCode nCode, sal_uInt16 nLine, + sal_uInt16 nCol1, sal_uInt16 nCol2 ); + + // Specific to error handler + static void MakeErrorText( ErrCode, std::u16string_view aMsg ); + static const OUString& GetErrorText(); + static ErrCode const & GetErrorCode(); + static sal_uInt16 GetVBErrorCode( ErrCode nError ); + static ErrCode GetSfxFromVBError( sal_uInt16 nError ); + bool IsBreak() const { return bBreak; } + + static Link const & GetGlobalErrorHdl(); + static void SetGlobalErrorHdl( const Link& rNewHdl ); + + static void SetGlobalBreakHdl( const Link& rNewHdl ); + + SbxArrayRef const & getUnoListeners(); + + static SbxBase* FindSBXInCurrentScope( const OUString& rName ); + static SbMethod* GetActiveMethod( sal_uInt16 nLevel = 0 ); + static SbModule* GetActiveModule(); + void SetVBAEnabled( bool bEnabled ); + bool isVBAEnabled() const; + + const SbxObjectRef& getRTL() const { return pRtl; } + bool IsDocBasic() const { return bDocBasic; } + SbxVariable* VBAFind( const OUString& rName, SbxClassType t ); + bool GetUNOConstant( const OUString& rName, css::uno::Any& aOut ); + void QuitAndExitApplication(); + bool IsQuitApplication() const { return bQuit; }; + + SbxObject* getVBAGlobals( ); + + static css::uno::Reference< css::frame::XModel > + GetModelFromBasic( SbxObject* pBasic ); + + static void DetachAllDocBasicItems(); +}; + +typedef tools::SvRef StarBASICRef; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbuno.hxx b/include/basic/sbuno.hxx new file mode 100644 index 000000000..4c53215d9 --- /dev/null +++ b/include/basic/sbuno.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBUNO_HXX +#define INCLUDED_BASIC_SBUNO_HXX + +#include +#include +#include + +namespace com::sun::star::uno { class Any; } +namespace com::sun::star::beans { struct Property; } + +class SbxObject; + +// Returns a SbxObject that wraps a Uno Interface +// Implementation in basic/source/classes/sbunoobj.cxx +BASIC_DLLPUBLIC SbxObjectRef GetSbUnoObject( const OUString& aName, const css::uno::Any& aUnoObj_ ); + +// Force creation of all properties for debugging +BASIC_DLLPUBLIC void createAllObjectProperties( SbxObject* pObj ); +BASIC_DLLPUBLIC void SetSbUnoObjectDfltPropName( SbxObject* pObj ); + +BASIC_DLLPUBLIC css::uno::Any sbxToUnoValue( const SbxValue* pVar ); +css::uno::Any sbxToUnoValue( const SbxValue* pVar, const css::uno::Type& rType, css::beans::Property const * pUnoProperty = nullptr ); + +BASIC_DLLPUBLIC void unoToSbxValue( SbxVariable* pVar, const css::uno::Any& aValue ); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbx.hxx b/include/basic/sbx.hxx new file mode 100644 index 000000000..7997f53ef --- /dev/null +++ b/include/basic/sbx.hxx @@ -0,0 +1,213 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBX_HXX +#define INCLUDED_BASIC_SBX_HXX + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +class SvStream; + +class SfxBroadcaster; + +// Parameter information +struct SbxParamInfo +{ + const OUString aName; // Name of the parameter + SbxDataType eType; // Data type + SbxFlagBits nFlags; // Flag-Bits + sal_uInt32 nUserData; // IDs etc. + SbxParamInfo( OUString s, SbxDataType t, SbxFlagBits n ) + : aName(std::move( s )), eType( t ), nFlags( n ), nUserData( 0 ) {} +}; + +typedef std::vector> SbxParams; + +class UNLESS_MERGELIBS(BASIC_DLLPUBLIC) SbxInfo final : public SvRefBase +{ + friend class SbxVariable; + friend class SbMethod; + + OUString aComment; + OUString aHelpFile; + sal_uInt32 nHelpId; + SbxParams m_Params; + + SbxInfo(SbxInfo const&) = delete; + void operator=(SbxInfo const&) = delete; + + void LoadData( SvStream&, sal_uInt16 ); + void StoreData( SvStream& ) const; + virtual ~SbxInfo() override; +public: + SbxInfo(); + SbxInfo( OUString , sal_uInt32 ); + + void AddParam( const OUString&, SbxDataType, SbxFlagBits=SbxFlagBits::Read ); + const SbxParamInfo* GetParam( sal_uInt16 n ) const; // index starts with 1! + const OUString& GetComment() const { return aComment; } + const OUString& GetHelpFile() const { return aHelpFile; } + sal_uInt32 GetHelpId() const { return nHelpId; } + + void SetComment( const OUString& r ) { aComment = r; } +}; + +class BASIC_DLLPUBLIC SbxHint final : public SfxHint +{ + SbxVariable* pVar; +public: + SbxHint( SfxHintId n, SbxVariable* v ) : SfxHint( n ), pVar( v ) {} + SbxVariable* GetVar() const { return pVar; } +}; + +// SbxArray is an unidimensional, dynamic Array +// The variables convert from SbxVariablen. Put()/Insert() into the +// declared datatype, if they are not SbxVARIANT. + +struct SbxVarEntry; + +class BASIC_DLLPUBLIC SbxArray : public SbxBase +{ +// #100883 Method to set method directly to parameter array + friend class SbMethod; + friend class SbClassModuleObject; + friend SbxObjectRef cloneTypeObjectImpl( const SbxObject& rTypeObj ); + BASIC_DLLPRIVATE void PutDirect( SbxVariable* pVar, sal_uInt32 nIdx ); + + std::vector mVarEntries; // The variables + SbxDataType eType; // Data type of the array + +protected: + virtual ~SbxArray() override; + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; + +public: + SBX_DECL_PERSIST_NODATA(SBXID_ARRAY,1); + SbxArray( SbxDataType=SbxVARIANT ); + SbxArray( const SbxArray& ) = delete; + SbxArray& operator=( const SbxArray& ); + virtual void Clear() override; + sal_uInt32 Count() const; + virtual SbxDataType GetType() const override; + SbxVariableRef& GetRef(sal_uInt32); + SbxVariable* Get(sal_uInt32); + void Put(SbxVariable*, sal_uInt32); + void Insert(SbxVariable*, sal_uInt32); + void Remove( sal_uInt32 ); + void Remove( SbxVariable const * ); + void Merge( SbxArray* ); + OUString GetAlias(sal_uInt32); + void PutAlias(const OUString&, sal_uInt32); + SbxVariable* Find( const OUString&, SbxClassType ); +}; + +// SbxDimArray is an array that can dimensioned using BASIC conventions. +struct SbxDim { // an array-dimension: + sal_Int32 nLbound, nUbound; // Limitations + sal_Int32 nSize; // Number of elements +}; + +class BASIC_DLLPUBLIC SbxDimArray final : public SbxArray +{ + std::vector m_vDimensions; // Dimension table + BASIC_DLLPRIVATE void AddDimImpl(sal_Int32, sal_Int32, bool bAllowSize0); + bool mbHasFixedSize; + + sal_uInt32 Offset(const sal_Int32*); + sal_uInt32 Offset(SbxArray*); + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; + virtual ~SbxDimArray() override; +public: + SBX_DECL_PERSIST_NODATA(SBXID_DIMARRAY,1); + SbxDimArray( SbxDataType=SbxVARIANT ); + SbxDimArray( const SbxDimArray& ) = delete; + SbxDimArray& operator=( const SbxDimArray& ); + virtual void Clear() override; + SbxVariable* Get( SbxArray* ); + + using SbxArray::GetRef; + using SbxArray::Get; + SbxVariable* Get(const sal_Int32*); + using SbxArray::Put; + void Put(SbxVariable*, const sal_Int32*); + sal_Int32 GetDims() const { return m_vDimensions.size(); } + void AddDim(sal_Int32, sal_Int32); + void unoAddDim(sal_Int32, sal_Int32); + bool GetDim(sal_Int32, sal_Int32&, sal_Int32&) const; + bool hasFixedSize() const { return mbHasFixedSize; }; + void setHasFixedSize( bool bHasFixedSize ) {mbHasFixedSize = bHasFixedSize; }; +}; + +class SbxCollection : public SbxObject +{ + void Initialize(); +protected: + virtual ~SbxCollection() override; + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; + // Overridable methods (why not pure virtual?): + virtual void CollAdd( SbxArray* pPar ); + void CollItem( SbxArray* pPar ); + virtual void CollRemove( SbxArray* pPar ); + +public: + SBX_DECL_PERSIST_NODATA(SBXID_COLLECTION,1); + SbxCollection(); + SbxCollection( const SbxCollection& ); + SbxCollection& operator=( const SbxCollection& ); + virtual SbxVariable* Find( const OUString&, SbxClassType ) override; + virtual void Clear() override; +}; + +class SbxStdCollection final : public SbxCollection +{ + OUString aElemClass; + bool bAddRemoveOk; + virtual ~SbxStdCollection() override; + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; + virtual void CollAdd( SbxArray* pPar ) override; + virtual void CollRemove( SbxArray* pPar ) override; +public: + SBX_DECL_PERSIST_NODATA(SBXID_FIXCOLLECTION,1); + SbxStdCollection(); + SbxStdCollection( const SbxStdCollection& ); + SbxStdCollection& operator=( const SbxStdCollection& ); + virtual void Insert( SbxVariable* ) override; +}; + +typedef tools::SvRef SbxArrayRef; +typedef tools::SvRef SbxInfoRef; +typedef tools::SvRef SbxDimArrayRef; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbxcore.hxx b/include/basic/sbxcore.hxx new file mode 100644 index 000000000..e5f726e8d --- /dev/null +++ b/include/basic/sbxcore.hxx @@ -0,0 +1,135 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBXCORE_HXX +#define INCLUDED_BASIC_SBXCORE_HXX + +#include +#include +#include +#include + +class SvStream; +class ErrCode; + +// The following Macro defines four (five) necessary methods within a +// SBX object. LoadPrivateData() and StorePrivateData() must be implemented. +// They are necessary for loading/storing the data of derived classes. +// Load() and Store() must not be overridden. + +// This version of the Macros does not define Load/StorePrivateData()-methods +#define SBX_DECL_PERSIST_NODATA( nSbxId, nVer ) \ + virtual sal_uInt16 GetVersion() const override { return nVer; } \ + virtual sal_uInt16 GetSbxId() const override { return nSbxId; } + +class SbxFactory; +class SbxObject; +class SbxBase; + +typedef tools::SvRef SbxBaseRef; +typedef tools::SvRef SbxObjectRef; + +class BASIC_DLLPUBLIC SbxBase : virtual public SvRefBase +{ + virtual bool LoadData( SvStream&, sal_uInt16 ) = 0; + virtual bool StoreData( SvStream& ) const = 0; +protected: + SbxFlagBits nFlags; // Flag-Bits + + SbxBase(); + SbxBase( const SbxBase& ); + SbxBase& operator=( const SbxBase& ); + virtual ~SbxBase() override; + + virtual sal_uInt16 GetVersion() const = 0; + virtual sal_uInt16 GetSbxId() const = 0; + +public: + inline void SetFlags( SbxFlagBits n ); + inline SbxFlagBits GetFlags() const; + inline void SetFlag( SbxFlagBits n ); + inline void ResetFlag( SbxFlagBits n ); + inline bool IsSet( SbxFlagBits n ) const; + inline bool IsReset( SbxFlagBits n ) const; + inline bool CanRead() const; + inline bool CanWrite() const; + inline bool IsModified() const; + inline bool IsHidden() const; + inline bool IsVisible() const; + + virtual bool IsFixed() const; + virtual void SetModified( bool ); + + virtual SbxDataType GetType() const; + + virtual void Clear() = 0; + + static SbxBaseRef Load( SvStream& ); + bool Store( SvStream& ); + virtual bool LoadCompleted(); + + static ErrCode const & GetError(); + static void SetError( ErrCode ); + static bool IsError(); + static void ResetError(); + + // Set the factory for Load/Store/Create + static void AddFactory( SbxFactory* ); + static void RemoveFactory( SbxFactory const * ); + + static SbxBaseRef Create( sal_uInt16, sal_uInt32 ); + static SbxObjectRef CreateObject( const OUString& ); +}; + +inline void SbxBase::SetFlags( SbxFlagBits n ) +{ nFlags = n; } + +inline SbxFlagBits SbxBase::GetFlags() const +{ return nFlags; } + +inline void SbxBase::SetFlag( SbxFlagBits n ) +{ nFlags |= n; } + +inline void SbxBase::ResetFlag( SbxFlagBits n ) +{ nFlags &= ~n; } + +inline bool SbxBase::IsSet( SbxFlagBits n ) const +{ return ( nFlags & n ) != SbxFlagBits::NONE; } + +inline bool SbxBase::IsReset( SbxFlagBits n ) const +{ return ( nFlags & n ) == SbxFlagBits::NONE; } + +inline bool SbxBase::CanRead() const +{ return IsSet( SbxFlagBits::Read ); } + +inline bool SbxBase::CanWrite() const +{ return IsSet( SbxFlagBits::Write ); } + +inline bool SbxBase::IsModified() const +{ return IsSet( SbxFlagBits::Modified ); } + +inline bool SbxBase::IsHidden() const +{ return IsSet( SbxFlagBits::Hidden ); } + +inline bool SbxBase::IsVisible() const +{ return IsReset( SbxFlagBits::Invisible ); } + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbxdef.hxx b/include/basic/sbxdef.hxx new file mode 100644 index 000000000..e85f1a209 --- /dev/null +++ b/include/basic/sbxdef.hxx @@ -0,0 +1,219 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef INCLUDED_BASIC_SBXDEF_HXX +#define INCLUDED_BASIC_SBXDEF_HXX + +#include +#include + +enum class SbxClassType { // SBX-class-IDs (order is important!) + DontCare = 1, // don't care (search, not 0 due to StarBASIC) + Array, // Array of SbxVariables + Value, // simple value + Variable, // Variable (from here there is Broadcaster) + Method, // Method (Function or Sub) + Property, // Property + Object // Object +}; + +enum SbxDataType { + SbxEMPTY = 0, // * Uninitialized + SbxNULL = 1, // * Contains no valid data + SbxINTEGER = 2, // * Integer (sal_Int16) + SbxLONG = 3, // * Long integer (sal_Int32) + SbxSINGLE = 4, // * Single-precision floating point number (float) + SbxDOUBLE = 5, // * Double-precision floating point number (double) + SbxCURRENCY = 6, // Currency (sal_Int64) + SbxDATE = 7, // * Date (double) + SbxSTRING = 8, // * String (StarView) + SbxOBJECT = 9, // * SbxBase object pointer + SbxERROR = 10, // * Error (sal_uInt16) + SbxBOOL = 11, // * Boolean (0 or -1) + + SbxVARIANT = 12, // * Display for variant datatype + SbxDATAOBJECT = 13, // * Common data object w/o ref count + + SbxCHAR = 16, // * signed char + SbxBYTE = 17, // * unsigned char + SbxUSHORT = 18, // * unsigned short (sal_uInt16) + SbxULONG = 19, // * unsigned long (sal_uInt32) + + SbxINT = 22, // * signed machine-dependent int + SbxUINT = 23, // * unsigned machine-dependent int + + SbxVOID = 24, // * no value (= SbxEMPTY) + SbxHRESULT = 25, // HRESULT + SbxPOINTER = 26, // generic pointer + SbxDIMARRAY = 27, // dimensioned array + SbxCARRAY = 28, // C style array + SbxUSERDEF = 29, // user defined + SbxLPSTR = 30, // * null terminated string + + SbxLPWSTR = 31, // wide null terminated string + SbxCoreSTRING = 32, // from 1997-4-10 for GetCoreString(), only for converting< + + SbxWSTRING = 33, // from 2000-10-4 Reimplemented for backwards compatibility (#78919) + SbxWCHAR = 34, // from 2000-10-4 Reimplemented for backwards compatibility (#78919) + SbxSALINT64 = 35, // for currency internal, signed 64-bit int and UNO hyper + SbxSALUINT64= 36, // for currency internal, unsigned 64-bit int and UNO unsigned hyper + SbxDECIMAL = 37, // for UNO/automation Decimal + + SbxVECTOR = 0x1000, // simple counted array + SbxARRAY = 0x2000, // array + SbxBYREF = 0x4000, // access by reference + + // tdf#79426, tdf#125180 + SbxMISSING = 0x8000, // Parameter is missing +}; + +const sal_uInt32 SBX_TYPE_WITH_EVENTS_FLAG = 0x10000; +const sal_uInt32 SBX_TYPE_DIM_AS_NEW_FLAG = 0x20000; +const sal_uInt32 SBX_FIXED_LEN_STRING_FLAG = 0x10000; // same value as above as no conflict possible +const sal_uInt32 SBX_TYPE_VAR_TO_DIM_FLAG = 0x40000; + +enum SbxOperator { + // Arithmetical: + SbxEXP, // this ^ var + SbxMUL, // this * var + SbxDIV, // this / var + SbxMOD, // this MOD var (max INT32!) + SbxPLUS, // this + var + SbxMINUS, // this - var + SbxNEG, // -this (var is ignored) + SbxIDIV, // this / var (both operands max. sal_Int32!) + // Boolean operators (max sal_Int32!): + // Boolean operators (TODO deprecate this limit: max INT32!) + SbxAND, // this & var + SbxOR, // this | var + SbxXOR, // this ^ var + SbxEQV, // ~this ^ var + SbxIMP, // ~this | var + SbxNOT, // ~this (var is ignored) + + // String concatenation: + SbxCAT, // this & var (VBA: this + var) + + // Comparisons: + SbxEQ, // this = var + SbxNE, // this <> var + SbxLT, // this < var + SbxGT, // this > var + SbxLE, // this <= var + SbxGE // this >= var +}; + +enum class SbxNameType { // Type of the questioned name of a variable + NONE, // plain name + CaseInsensitive, // plain name - case insensitive + ShortTypes, // Name%(A%,B$) +}; + + +// Flag-Bits: +enum class SbxFlagBits { + NONE = 0x0000, + Read = 0x0001, // Read permission + Write = 0x0002, // Write permission + ReadWrite = 0x0003, // Read/Write permission + DontStore = 0x0004, // Don't store object + Modified = 0x0008, // Object was changed + Fixed = 0x0010, // Fixed data type (SbxVariable) + Const = 0x0020, // Definition of const value + Optional = 0x0040, // Parameter is optional + Hidden = 0x0080, // Element is invisible + Invisible = 0x0100, // Element is not found by Find() + ExtSearch = 0x0200, // Object is searched completely + ExtFound = 0x0400, // Variable was found through extended search + GlobalSearch = 0x0800, // Global search via Parents + Reserved = 0x1000, // reserved + Private = 0x1000, // #110004, #112015, cannot conflict with SbxFlagBits::Reserved + NoBroadcast = 0x2000, // No broadcast on Get/Put + Reference = 0x4000, // Parameter is Reference (DLL-call) + NoModify = 0x8000, // SetModified is suppressed + WithEvents = 0x0080, // Same value as unused SbxFlagBits::Hidden + DimAsNew = 0x0800, // Same value as SbxFlagBits::GlobalSearch, cannot conflict as one + // is used for objects, the other for variables only + VarToDim = 0x2000, // Same value as SbxFlagBits::NoBroadcast, cannot conflict as + // used for variables without broadcaster only +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +// List of all creators for Load/Store + +constexpr auto SBXCR_SBX = 0x20584253; // SBX(blank) + +// List of predefined SBX-IDs. New SBX-IDs must be precisely defined so that +// they are unique within the Stream and appropriate Factory. + +constexpr auto SBXID_VALUE = 0x4E4E; // NN: SbxValue +constexpr auto SBXID_VARIABLE = 0x4156; // VA: SbxVariable +constexpr auto SBXID_ARRAY = 0x5241; // AR: SbxArray +constexpr auto SBXID_DIMARRAY = 0x4944; // DI: SbxDimArray +constexpr auto SBXID_OBJECT = 0x424F; // OB: SbxObject +constexpr auto SBXID_COLLECTION = 0x4F43; // CO: SbxCollection +constexpr auto SBXID_FIXCOLLECTION = 0x4346; // FC: SbxStdCollection +constexpr auto SBXID_METHOD = 0x454D; // ME: SbxMethod +constexpr auto SBXID_PROPERTY = 0x5250; // PR: SbxProperty + +// StarBASIC restricts the base data type to different intervals. +// These intervals are fixed to create 'portability and independent +// of the implementation. Only type double is greedy and takes +// what it gets. + +constexpr auto SbxMAXCHAR = u'\xFFFF'; +constexpr auto SbxMINCHAR = 0; +constexpr auto SbxMAXBYTE = 255; +constexpr auto SbxMAXINT = 32767; +constexpr auto SbxMININT = -32768; +constexpr sal_uInt16 SbxMAXUINT = 65535; +constexpr auto SbxMAXLNG = 2147483647; +constexpr sal_Int32 SbxMINLNG = -2147483647-1; +constexpr sal_uInt32 SbxMAXULNG = 0xffffffff; + + // Currency stored as SbxSALINT64 == sal_Int64 + // value range limits are ~(2^63 - 1)/10000 + // fixed precision has 4 digits right of decimal pt +constexpr auto CURRENCY_FACTOR = 10000; +constexpr auto CURRENCY_FACTOR_SQUARE = 100000000; + +// TODO effective MAX/MINCURR limits: +// true value ( 922337203685477.5807) is too precise for correct comparison to 64bit double +constexpr auto SbxMAXCURR = 922337203685477.5807; +constexpr auto SbxMINCURR = -922337203685477.5808; + +constexpr auto SbxMAXSNG = 3.402823e+38; +constexpr auto SbxMINSNG = -3.402823e+38; +constexpr auto SbxMAXSNG2 = 1.175494351e-38; +constexpr auto SbxMINSNG2 = -1.175494351e-38; + +// Max valid offset index of a Sbx-Array (due to 64K limit) +constexpr auto SBX_MAXINDEX = 0x3FF0; +constexpr auto SBX_MAXINDEX32 = SbxMAXLNG; + +// The numeric values of sal_True and FALSE +enum SbxBOOL { SbxFALSE = 0, SbxTRUE = -1 }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbxmeth.hxx b/include/basic/sbxmeth.hxx new file mode 100644 index 000000000..b32a40f14 --- /dev/null +++ b/include/basic/sbxmeth.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBXMETH_HXX +#define INCLUDED_BASIC_SBXMETH_HXX + +#include +#include + +class BASIC_DLLPUBLIC SbxMethod : public SbxVariable +{ + bool mbIsRuntimeFunction; + SbxDataType mbRuntimeFunctionReturnType; +public: + SBX_DECL_PERSIST_NODATA(SBXID_METHOD,1); + SbxMethod( const OUString& r, SbxDataType t, bool bIsRuntimeFunction=false ); + SbxMethod( const SbxMethod& r ); + virtual ~SbxMethod() override; + SbxMethod& operator=( const SbxMethod& r ) { SbxVariable::operator=( r ); return *this; } + virtual SbxClassType GetClass() const override; + bool IsRuntimeFunction() const { return mbIsRuntimeFunction; } + SbxDataType GetRuntimeFunctionReturnType() const{ return mbRuntimeFunctionReturnType; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbxobj.hxx b/include/basic/sbxobj.hxx new file mode 100644 index 000000000..10d4c074c --- /dev/null +++ b/include/basic/sbxobj.hxx @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBXOBJ_HXX +#define INCLUDED_BASIC_SBXOBJ_HXX + +#include +#include +#include + + +class SbxProperty; + +class BASIC_DLLPUBLIC SbxObject : public SbxVariable, public SfxListener +{ + BASIC_DLLPRIVATE SbxArray* FindVar( SbxVariable const *, sal_uInt32& ); +protected: + SbxArrayRef pMethods; // Methods + SbxArrayRef pProps; // Properties + SbxArrayRef pObjs; // Objects + SbxProperty* pDfltProp; // Default-Property + OUString aClassName; // Classname + OUString aDfltPropName; + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; + virtual ~SbxObject() override; + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; +public: + SBX_DECL_PERSIST_NODATA(SBXID_OBJECT,1); + SbxObject( const OUString& rClassname ); + SbxObject( const SbxObject& ); + SbxObject& operator=( const SbxObject& ); + virtual SbxDataType GetType() const override; + virtual SbxClassType GetClass() const override; + virtual void Clear() override; + + virtual bool IsClass( const OUString& ) const; + const OUString& GetClassName() const { return aClassName; } + void SetClassName( const OUString &rNew ) { aClassName = rNew; } + // Default-Property + SbxProperty* GetDfltProperty(); + void SetDfltProperty( const OUString& r ); + // Search for an element + virtual SbxVariable* Find( const OUString&, SbxClassType ); + SbxVariable* FindQualified( const OUString&, SbxClassType ); + // Quick-Call-Interface for Methods + virtual bool Call( const OUString&, SbxArray* = nullptr ); + // Execution of DDE-Commands + SbxVariable* Execute( const OUString& ); + // Manage elements + SbxVariable* Make( const OUString&, SbxClassType, SbxDataType, bool bIsRuntimeFunction = false ); + virtual void Insert( SbxVariable* ); + // AB 23.4.1997, Optimization, Insertion without check for duplicate Entries and + // without Broadcasts, only used in SO2/auto.cxx + void QuickInsert( SbxVariable* ); + void Remove( const OUString&, SbxClassType ); + virtual void Remove( SbxVariable* ); + + // Direct access on arrays + SbxArray* GetMethods() { return pMethods.get(); } + SbxArray* GetProperties() { return pProps.get(); } + SbxArray* GetObjects() { return pObjs.get(); } + // Debugging + void Dump( SvStream&, bool bDumpAll ); +}; + +#endif // INCLUDED_BASIC_SBXOBJ_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/sbxvar.hxx b/include/basic/sbxvar.hxx new file mode 100644 index 000000000..0c5f84b60 --- /dev/null +++ b/include/basic/sbxvar.hxx @@ -0,0 +1,336 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_SBXVAR_HXX +#define INCLUDED_BASIC_SBXVAR_HXX + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +namespace com::sun::star::bridge::oleautomation { struct Decimal; } + +class SbxDecimal; +enum class SfxHintId; + +struct SbxValues +{ + union { + sal_uInt8 nByte; + sal_uInt16 nUShort; + sal_Unicode nChar; + sal_Int16 nInteger; + sal_uInt32 nULong; + sal_Int32 nLong; + unsigned int nUInt; + int nInt; + sal_uInt64 uInt64; + sal_Int64 nInt64; + + float nSingle; + double nDouble; + + OUString* pOUString; + SbxDecimal* pDecimal; + + SbxBase* pObj; + + sal_uInt8* pByte; + sal_uInt16* pUShort; + sal_Unicode* pChar; + sal_Int16* pInteger; + sal_uInt32* pULong; + sal_Int32* pLong; + sal_uInt64* puInt64; + sal_Int64* pnInt64; + + float* pSingle; + double* pDouble; + + void* pData; + }; + SbxDataType eType; + + SbxValues(): pData( nullptr ), eType(SbxEMPTY) {} + SbxValues( SbxDataType e ): eType(e) {} + SbxValues( double _nDouble ): nDouble( _nDouble ), eType(SbxDOUBLE) {} + + void clear(SbxDataType type) { + // A hacky way of zeroing the union value corresponding to the given type (even though the + // relevant zero value need not be represented by all-zero bits, in general) without evoking + // GCC 8 -Wclass-memaccess or loplugin:classmemaccess, and without having to turn the + // anonymous union into a non-anonymous one: + auto const p = static_cast(this); + std::memset(p, 0, offsetof(SbxValues, eType)); + eType = type; + } +}; + +class BASIC_DLLPUBLIC SbxValue : public SbxBase +{ + // #55226 Transport additional infos + BASIC_DLLPRIVATE SbxValue* TheRealValue( bool bObjInObjError ) const; +protected: + SbxValues aData; // Data + OUString aPic; // Picture-String + OUString aToolString; // tool string copy + + virtual void Broadcast( SfxHintId ); // Broadcast-Call + virtual ~SbxValue() override; + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; +public: + SBX_DECL_PERSIST_NODATA(SBXID_VALUE,1); + SbxValue(); + SbxValue( SbxDataType ); + SbxValue( const SbxValue& ); + SbxValue& operator=( const SbxValue& ); + virtual void Clear() override; + virtual bool IsFixed() const override; + + bool IsInteger() const { return GetType() == SbxINTEGER ; } + bool IsLong() const { return GetType() == SbxLONG ; } + bool IsDouble() const { return GetType() == SbxDOUBLE ; } + bool IsString() const { return GetType() == SbxSTRING ; } + bool IsCurrency() const { return GetType() == SbxCURRENCY ; } + bool IsObject() const { return GetType() == SbxOBJECT ; } + bool IsBool() const { return GetType() == SbxBOOL ; } + bool IsErr() const { return GetType() == SbxERROR ; } + bool IsEmpty() const { return GetType() == SbxEMPTY ; } + bool IsNull() const { return GetType() == SbxNULL ; } + bool IsNumeric() const; + bool IsNumericRTL() const; // #41692 Interface for Basic + bool ImpIsNumeric( bool bOnlyIntntl ) const; // Implementation + + virtual SbxDataType GetType() const override; + SbxDataType GetFullType() const { return aData.eType;} + bool SetType( SbxDataType ); + + bool Get( SbxValues& ) const; + const SbxValues& GetValues_Impl() const { return aData; } + bool Put( const SbxValues& ); + + SbxValues * data() { return &aData; } + + sal_Unicode GetChar() const { return Get(SbxCHAR).nChar; } + sal_Int16 GetInteger() const { return Get(SbxINTEGER).nInteger; } + sal_Int32 GetLong() const { return Get(SbxLONG).nLong; } + sal_Int64 GetInt64() const { return Get(SbxSALINT64).nInt64; } + sal_uInt64 GetUInt64() const { return Get(SbxSALUINT64).uInt64; } + + sal_Int64 GetCurrency() const { return Get(SbxCURRENCY).nInt64; } + SbxDecimal* GetDecimal() const { return Get(SbxDECIMAL).pDecimal; } + + float GetSingle() const { return Get(SbxSINGLE).nSingle; } + double GetDouble() const { return Get(SbxDOUBLE).nDouble; } + double GetDate() const { return Get(SbxDATE).nDouble; } + + bool GetBool() const { return Get(SbxBOOL).nUShort != 0; } + const OUString& GetCoreString() const; + OUString GetOUString() const; + + SbxBase* GetObject() const { return Get(SbxOBJECT).pObj; } + sal_uInt8 GetByte() const { return Get(SbxBYTE).nByte; } + sal_uInt16 GetUShort() const { return Get(SbxUSHORT).nUShort; } + sal_uInt32 GetULong() const { return Get(SbxULONG).nULong; } + + bool PutInteger( sal_Int16 ); + bool PutLong( sal_Int32 ); + bool PutSingle( float ); + bool PutDouble( double ); + void PutDate( double ); + bool PutBool( bool ); + void PutErr( sal_uInt16 ); + void PutStringExt( const OUString& ); // with extended analysis (International, "sal_True"/"sal_False") + bool PutInt64( sal_Int64 ); + bool PutUInt64( sal_uInt64 ); + bool PutString( const OUString& ); + bool PutChar( sal_Unicode ); + bool PutByte( sal_uInt8 ); + bool PutUShort( sal_uInt16 ); + bool PutULong( sal_uInt32 ); + bool PutEmpty(); + void PutNull(); + + // Special methods + void PutDecimal( css::bridge::oleautomation::Decimal const & rAutomationDec ); + bool PutDecimal( SbxDecimal* pDecimal ); // This function is needed for Windows build, don't remove + void fillAutomationDecimal( css::bridge::oleautomation::Decimal& rAutomationDec ) const; + bool PutCurrency( sal_Int64 ); + // Interface for CDbl in Basic + static ErrCode ScanNumIntnl( const OUString& rSrc, double& nVal, bool bSingle = false ); + + bool PutObject( SbxBase* ); + + bool Convert( SbxDataType ); + bool Compute( SbxOperator, const SbxValue& ); + bool Compare( SbxOperator, const SbxValue& ) const; + bool Scan( const OUString&, sal_uInt16* ); + void Format( OUString&, const OUString* = nullptr ) const; + + // The following operators are defined for easier handling. + // TODO: Ensure error conditions (overflow, conversions) + // are taken into consideration in Compute and Compare + + inline bool operator <=( const SbxValue& ) const; + inline bool operator >=( const SbxValue& ) const; + + inline SbxValue& operator *=( const SbxValue& ); + inline SbxValue& operator /=( const SbxValue& ); + inline SbxValue& operator +=( const SbxValue& ); + inline SbxValue& operator -=( const SbxValue& ); + +private: + SbxValues Get(SbxDataType t) const; +}; + +inline bool SbxValue::operator<=( const SbxValue& r ) const +{ return Compare( SbxLE, r ); } + +inline bool SbxValue::operator>=( const SbxValue& r ) const +{ return Compare( SbxGE, r ); } + +inline SbxValue& SbxValue::operator*=( const SbxValue& r ) +{ Compute( SbxMUL, r ); return *this; } + +inline SbxValue& SbxValue::operator/=( const SbxValue& r ) +{ Compute( SbxDIV, r ); return *this; } + +inline SbxValue& SbxValue::operator+=( const SbxValue& r ) +{ Compute( SbxPLUS, r ); return *this; } + +inline SbxValue& SbxValue::operator-=( const SbxValue& r ) +{ Compute( SbxMINUS, r ); return *this; } + +class SbxArray; +class SbxInfo; + +typedef tools::SvRef SbxArrayRef; + +typedef tools::SvRef SbxInfoRef; + +class SfxBroadcaster; + +class SbxVariableImpl; +class StarBASIC; + +class BASIC_DLLPUBLIC SbxVariable : public SbxValue +{ + friend class SbMethod; + + OUString m_aDeclareClassName; + css::uno::Reference< css::uno::XInterface > m_xComListener; + StarBASIC* m_pComListenerParentBasic = nullptr; + std::unique_ptr mpBroadcaster; // Broadcaster, if needed + OUString maName; // Name, if available + mutable OUString maNameCI; // Name, case insensitive - cached for fast comparison + SbxArrayRef mpPar; // Parameter-Array, if set + sal_uInt16 nHash = 0; // Hash-ID for search + +protected: + SbxInfoRef pInfo; // Probably called information + sal_uInt32 nUserData= 0; // User data for Call() + SbxObject* pParent = nullptr; // Currently attached object + virtual ~SbxVariable() override; + virtual bool LoadData( SvStream&, sal_uInt16 ) override; + virtual bool StoreData( SvStream& ) const override; +public: + SBX_DECL_PERSIST_NODATA(SBXID_VARIABLE,2); + SbxVariable(); + SbxVariable( SbxDataType ); + SbxVariable( const SbxVariable& ); + SbxVariable& operator=( const SbxVariable& ); + + void Dump( SvStream&, bool bDumpAll ); + + void SetName( const OUString& ); + const OUString& GetName( SbxNameType = SbxNameType::NONE ) const; + sal_uInt16 GetHashCode() const { return nHash; } + static OUString NameToCaseInsensitiveName(const OUString& rName); + + virtual void SetModified( bool ) override; + + sal_uInt32 GetUserData() const { return nUserData; } + void SetUserData( sal_uInt32 n ) { nUserData = n; } + + virtual SbxDataType GetType() const override; + virtual SbxClassType GetClass() const; + + // Parameter-Interface + virtual SbxInfo* GetInfo(); + void SetInfo( SbxInfo* p ); + void SetParameters( SbxArray* p ); + SbxArray* GetParameters() const; + + // Sfx-Broadcasting-Support: + // Due to data reduction and better DLL-hierarchy currently via casting + SfxBroadcaster& GetBroadcaster(); + bool IsBroadcaster() const { return mpBroadcaster != nullptr; } + virtual void Broadcast( SfxHintId nHintId ) override; + + const SbxObject* GetParent() const { return pParent; } + SbxObject* GetParent() { return pParent;} + virtual void SetParent( SbxObject* ); + + const OUString& GetDeclareClassName() const; + void SetDeclareClassName( const OUString& ); + void SetComListener( const css::uno::Reference< css::uno::XInterface >& xComListener, + StarBASIC* pParentBasic ); + void ClearComListener(); + + // Create a simple hashcode: the first six characters are evaluated. + static constexpr sal_uInt16 MakeHashCode(std::u16string_view aName) + { + sal_uInt16 n = 0; + const auto first6 = aName.substr(0, 6); + for (const auto& c : first6) + { + if (!rtl::isAscii(c)) + continue; // Just skip it to let non-ASCII strings have some hash variance + n = static_cast((n << 3) + rtl::toAsciiUpperCase(c)); + } + return n; + } +}; + +typedef tools::SvRef SbxObjectRef; +typedef tools::SvRef SbxVariableRef; + +//tdf#59222 SbxEnsureParentVariable is a SbxVariable which keeps a reference to +//its parent, ensuring it always exists while this SbxVariable exists +class SbxEnsureParentVariable final : public SbxVariable +{ + SbxObjectRef xParent; +public: + SbxEnsureParentVariable(const SbxVariable& r); + virtual void SetParent(SbxObject* p) override; +}; + +#endif // INCLUDED_BASIC_SBXVAR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/basic/vbahelper.hxx b/include/basic/vbahelper.hxx new file mode 100644 index 000000000..8d18b66b1 --- /dev/null +++ b/include/basic/vbahelper.hxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_BASIC_VBAHELPER_HXX +#define INCLUDED_BASIC_VBAHELPER_HXX + +#include +#include + +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::uno { template class Reference; } + +namespace basic::vba { + +/* This header contains public helper functions for VBA used from this module + and from other VBA implementation modules such as vbahelper. + */ + + +/** Locks or unlocks the controllers of all documents that have the same type + as the specified document. + + First, the global module manager (com.sun.star.frame.ModuleManager) is + asked for the type of the passed model, and all open documents with the + same type will be locked or unlocked. + + @param rxModel + A document model determining the type of the documents to be locked or + unlocked. + + @param bLockControllers + Passing true will lock all controllers, passing false will unlock them. + */ +BASIC_DLLPUBLIC void lockControllersOfAllDocuments( + const css::uno::Reference< css::frame::XModel >& rxModel, + bool bLockControllers ); + + +/** Enables or disables the container windows of all controllers of all + documents that have the same type as the specified document. + + First, the global module manager (com.sun.star.frame.ModuleManager) is + asked for the type of the passed model, and the container windows of all + open documents with the same type will be enabled or disabled. + + @param rxModel + A document model determining the type of the documents to be enabled or + disabled. + + @param bEnableWindows + Passing true will enable all container windows of all controllers, + passing false will disable them. + */ +BASIC_DLLPUBLIC void enableContainerWindowsOfAllDocuments( + const css::uno::Reference< css::frame::XModel >& rxModel, + bool bEnableWindows ); + + +/** Registers the passed path as working directory for the application the + passed document belongs to. + + @param rxModel + A document model determining the type of the application whose working + directory has been changed. + + @param rPath + The new working directory. + */ +BASIC_DLLPUBLIC void registerCurrentDirectory( + const css::uno::Reference< css::frame::XModel >& rxModel, + const OUString& rPath ); + + +} // namespace basic::vba + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/canvas/canvastools.hxx b/include/canvas/canvastools.hxx new file mode 100644 index 000000000..63aea6239 --- /dev/null +++ b/include/canvas/canvastools.hxx @@ -0,0 +1,560 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CANVAS_CANVASTOOLS_HXX +#define INCLUDED_CANVAS_CANVASTOOLS_HXX + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace basegfx +{ + class B2DHomMatrix; + class B2DRange; + class B2IRange; + class B2IPoint; + class B2DPolyPolygon; +} + +namespace com::sun::star::geometry +{ + struct RealSize2D; + struct IntegerSize2D; + struct AffineMatrix2D; + struct Matrix2D; +} + +namespace com::sun::star::rendering +{ + struct RenderState; + struct ViewState; + struct IntegerBitmapLayout; + class XCanvas; + struct Texture; + class XIntegerBitmapColorSpace; +} + +namespace com::sun::star::awt +{ + struct Rectangle; + class XWindow2; +} + +namespace com::sun::star::beans { + struct PropertyValue; +} + +class Color; +class OutputDevice; + +namespace canvas +{ + namespace tools + { + /** Compute the next highest power of 2 of a 32-bit value + + Code devised by Sean Anderson, in good ole HAKMEM + tradition. + + @return 1 << (lg(x - 1) + 1) + */ + inline sal_uInt32 nextPow2( sal_uInt32 x ) + { + --x; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + + return ++x; + } + + /** + * + * Count the number of 1-bits of a n-bit value + * + */ + + /** Round given floating point value down to next integer + */ + inline sal_Int32 roundDown( const double& rVal ) + { + return static_cast< sal_Int32 >( floor( rVal ) ); + } + + /** Round given floating point value up to next integer + */ + inline sal_Int32 roundUp( const double& rVal ) + { + return static_cast< sal_Int32 >( ceil( rVal ) ); + } + + /** Create a RealSize2D with both coordinate values set to +infinity + */ + CANVASTOOLS_DLLPUBLIC css::geometry::RealSize2D createInfiniteSize2D(); + + + // View- and RenderState utilities + + + CANVASTOOLS_DLLPUBLIC css::rendering::RenderState& + initRenderState( css::rendering::RenderState& renderState ); + + CANVASTOOLS_DLLPUBLIC css::rendering::ViewState& + initViewState( css::rendering::ViewState& viewState ); + + CANVASTOOLS_DLLPUBLIC ::basegfx::B2DHomMatrix& + getViewStateTransform( ::basegfx::B2DHomMatrix& transform, + const css::rendering::ViewState& viewState ); + + CANVASTOOLS_DLLPUBLIC css::rendering::ViewState& + setViewStateTransform( css::rendering::ViewState& viewState, + const ::basegfx::B2DHomMatrix& transform ); + + CANVASTOOLS_DLLPUBLIC ::basegfx::B2DHomMatrix& + getRenderStateTransform( ::basegfx::B2DHomMatrix& transform, + const css::rendering::RenderState& renderState ); + + CANVASTOOLS_DLLPUBLIC css::rendering::RenderState& + setRenderStateTransform( css::rendering::RenderState& renderState, + const ::basegfx::B2DHomMatrix& transform ); + + CANVASTOOLS_DLLPUBLIC css::rendering::RenderState& + appendToRenderState( css::rendering::RenderState& renderState, + const ::basegfx::B2DHomMatrix& transform ); + + CANVASTOOLS_DLLPUBLIC css::rendering::RenderState& + prependToRenderState( css::rendering::RenderState& renderState, + const ::basegfx::B2DHomMatrix& transform ); + + CANVASTOOLS_DLLPUBLIC ::basegfx::B2DHomMatrix& + mergeViewAndRenderTransform( ::basegfx::B2DHomMatrix& transform, + const css::rendering::ViewState& viewState, + const css::rendering::RenderState& renderState ); + + + // Matrix utilities + + + CANVASTOOLS_DLLPUBLIC css::geometry::AffineMatrix2D& + setIdentityAffineMatrix2D( css::geometry::AffineMatrix2D& matrix ); + + CANVASTOOLS_DLLPUBLIC css::geometry::Matrix2D& + setIdentityMatrix2D( css::geometry::Matrix2D& matrix ); + + + // Special utilities + + + /** Calc the bounding rectangle of a transformed rectangle. + + The method applies the given transformation to the + specified input rectangle, and returns the bounding box of + the resulting output area. + + @param o_Rect + Output rectangle + + @param i_Rect + Input rectangle + + @param i_Transformation + Transformation to apply to the input rectangle + + @return a reference to the resulting rectangle + */ + CANVASTOOLS_DLLPUBLIC ::basegfx::B2DRange& calcTransformedRectBounds( ::basegfx::B2DRange& o_Rect, + const ::basegfx::B2DRange& i_Rect, + const ::basegfx::B2DHomMatrix& i_Transformation ); + + /** Calc a transform that maps the upper, left corner of a + rectangle to the origin. + + The method is a specialized version of + calcRectToRectTransform() (Removed now), mapping the input rectangle's + the upper, left corner to the origin, and leaving the size + untouched. + + @param o_transform + Output parameter, to receive the resulting transformation + matrix. + + @param i_srcRect + Input parameter, specifies the original source + rectangle. The resulting transformation will exactly map + the source rectangle's upper, left corner to the origin. + + @param i_transformation + The original transformation matrix. This is changed with + translations (if necessary), to exactly map the source + rectangle to the origin. + + @return a reference to the resulting transformation matrix + + @see calcRectToRectTransform() + @see calcTransformedRectBounds() + */ + CANVASTOOLS_DLLPUBLIC ::basegfx::B2DHomMatrix& calcRectToOriginTransform( ::basegfx::B2DHomMatrix& o_transform, + const ::basegfx::B2DRange& i_srcRect, + const ::basegfx::B2DHomMatrix& i_transformation ); + + /** Check whether a given rectangle is within another + transformed rectangle. + + This method checks for polygonal containedness, i.e. the + transformed rectangle is not represented as an axis-aligned + rectangle anymore (like calcTransformedRectBounds()), but + polygonal. Thus, the insideness test is based on tight + bounds. + + @param rContainedRect + This rectangle is checked, whether it is fully within the + transformed rTransformRect. + + @param rTransformRect + This rectangle is transformed, and then checked whether it + fully contains rContainedRect. + + @param rTransformation + This transformation is applied to rTransformRect + */ + CANVASTOOLS_DLLPUBLIC bool isInside( const ::basegfx::B2DRange& rContainedRect, + const ::basegfx::B2DRange& rTransformRect, + const ::basegfx::B2DHomMatrix& rTransformation ); + + /** Clip a scroll to the given bound rect + + @param io_rSourceArea + Source area to scroll. The resulting clipped source area + is returned therein. + + @param io_rDestPoint + Destination point of the scroll (upper, left corner of + rSourceArea after the scroll). The new, resulting + destination point is returned therein.q + + @param o_ClippedAreas + Vector of rectangles in the destination area + coordinate system, which are clipped away from the source + area, and thus need extra updates (i.e. they are not + correctly copy from the scroll operation, since there was + no information about them in the source). + + @param rBounds + Bounds to clip against. + + @return false, if the resulting scroll area is empty + */ + CANVASTOOLS_DLLPUBLIC bool clipScrollArea( ::basegfx::B2IRange& io_rSourceArea, + ::basegfx::B2IPoint& io_rDestPoint, + ::std::vector< ::basegfx::B2IRange >& o_ClippedAreas, + const ::basegfx::B2IRange& rBounds ); + + /** Clip a blit between two differently surfaces. + + This method clips source and dest rect for a clip between + two differently clipped surfaces, such that the resulting + blit rects are fully within both clip areas. + + @param io_rSourceArea + Source area of the blit. Returned therein is the computed + clipped source area. + + @param io_rDestPoint + Dest area of the blit. Returned therein is the computed + clipped dest area. + + @param rSourceBounds + Clip bounds of the source surface + + @param rDestBounds + Clip bounds of the dest surface + + @return false, if the resulting blit is empty, i.e. fully + clipped away. + */ + CANVASTOOLS_DLLPUBLIC ::basegfx::B2IRange spritePixelAreaFromB2DRange( const ::basegfx::B2DRange& rRange ); + + /** Retrieve various internal properties of the actual canvas implementation. + + This method retrieves a bunch of internal, implementation- + and platform-dependent values from the canvas + implementation. Among them are for example operating + system window handles. The actual layout and content of + the returned sequence is dependent on the component + implementation, undocumented and subject to change. + + @param i_rxCanvas + Input parameter, the canvas representation for which the device information + is to be retrieved + + @param o_rxParams + Output parameter, the sequence of Anys that hold the device parameters. Layout is as described above + + @return A reference to the resulting sequence of parameters + */ + CANVASTOOLS_DLLPUBLIC css::uno::Sequence< css::uno::Any >& getDeviceInfo( + const css::uno::Reference< css::rendering::XCanvas >& i_rxCanvas, + css::uno::Sequence< css::uno::Any >& o_rxParams ); + + /** Return a color space for a default RGBA integer format + + Use this method for dead-simple bitmap implementations, + that map all their formats to 8888 RGBA color. + */ + CANVASTOOLS_DLLPUBLIC css::uno::Reference< css::rendering::XIntegerBitmapColorSpace> const & getStdColorSpace(); + + /** Return a color space for a default RGB integer format + + Use this method for dead-simple bitmap implementations, + that map all their formats to 8888 RGB color (the last byte + is unused). + */ + CANVASTOOLS_DLLPUBLIC css::uno::Reference< css::rendering::XIntegerBitmapColorSpace> const & getStdColorSpaceWithoutAlpha(); + + /** Return a memory layout for a default RGBA integer format + + Use this method for dead-simple bitmap implementations, + that map all their formats to 8888 RGBA color. + */ + CANVASTOOLS_DLLPUBLIC css::rendering::IntegerBitmapLayout getStdMemoryLayout( + const css::geometry::IntegerSize2D& rBitmapSize ); + + /// Convert standard 8888 RGBA color to vcl color + CANVASTOOLS_DLLPUBLIC css::uno::Sequence colorToStdIntSequence( const ::Color& rColor ); + + // Modelled closely after boost::numeric_cast, only that we + // issue some trace output here and throw a RuntimeException + + /** Cast numeric value into another (numeric) data type + + Apart from converting the numeric value, this template + also checks if any overflow, underflow, or sign + information is lost (if yes, it throws an + uno::RuntimeException. + */ + template< typename Target, typename Source > inline Target numeric_cast( Source arg ) + { + // typedefs abbreviating respective trait classes + typedef ::std::numeric_limits< Source > SourceLimits; + typedef ::std::numeric_limits< Target > TargetLimits; + +#undef min +#undef max + + if( ( arg<0 && !TargetLimits::is_signed) || // losing the sign here + ( SourceLimits::is_signed && argTargetLimits::max() ) ) // overflow will happen + { +# if OSL_DEBUG_LEVEL > 2 + SAL_WARN("canvas", "numeric_cast detected data loss"); +#endif + throw css::uno::RuntimeException( + "numeric_cast detected data loss", + nullptr ); + } + + return static_cast(arg); + } + + CANVASTOOLS_DLLPUBLIC css::awt::Rectangle getAbsoluteWindowRect( + const css::awt::Rectangle& rRect, + const css::uno::Reference< css::awt::XWindow2 >& xWin ); + + /** Retrieve for small bound marks around each corner of the given rectangle + */ + CANVASTOOLS_DLLPUBLIC ::basegfx::B2DPolyPolygon getBoundMarksPolyPolygon( const ::basegfx::B2DRange& rRange ); + + /** Calculate number of gradient "strips" to generate (takes + into account device resolution) + + @param nColorSteps + Maximal integer difference between all color stops, needed + for smooth gradient color differences + */ + CANVASTOOLS_DLLPUBLIC int calcGradientStepCount( ::basegfx::B2DHomMatrix& rTotalTransform, + const css::rendering::ViewState& viewState, + const css::rendering::RenderState& renderState, + const css::rendering::Texture& texture, + int nColorSteps ); + + /** A very simplistic map for ASCII strings and arbitrary value + types. + + This class internally references a constant, static array of + sorted MapEntries, and performs a binary search to look up + values for a given query string. Note that this map is static, + i.e. not meant to be extended at runtime. + + @tpl ValueType + The value type this map should store, associated with an ASCII + string. + */ + template< typename ValueType > class ValueMap + { + public: + struct MapEntry + { + const char* maKey; + ValueType maValue; + }; + + /** Create a ValueMap for the given array of MapEntries. + + @param pMap + Pointer to a static array of MapEntries. Must + live longer than this object! Make absolutely sure that + the string entries passed via pMap are ASCII-only - + everything else might not yield correct string + comparisons, and thus will result in undefined behaviour. + + @param nEntries + Number of entries for pMap + + @param bCaseSensitive + Whether the map query should be performed case sensitive + or not. When bCaseSensitive is false, all MapEntry strings + must be lowercase! + */ + ValueMap( const MapEntry* pMap, + ::std::size_t nEntries, + bool bCaseSensitive ) : + mpMap( pMap ), + mnEntries( nEntries ), + mbCaseSensitive( bCaseSensitive ) + { +#ifdef DBG_UTIL + // Ensure that map entries are sorted (and all lowercase, if this + // map is case insensitive) + const OString aStr( pMap->maKey ); + if( !mbCaseSensitive && + aStr != aStr.toAsciiLowerCase() ) + { + SAL_WARN("canvas", "ValueMap::ValueMap(): Key is not lowercase " << pMap->maKey); + } + + if( mnEntries <= 1 ) + return; + + for( ::std::size_t i=0; imaKey, aSearchKey.maKey ) == 0 ) + { + // yep, correct entry found + o_rResult = pRes->maValue; + return true; + } + } + + // not found + return false; + } + + private: + static bool mapComparator( const MapEntry& rLHS, + const MapEntry& rRHS ) + { + return strcmp( rLHS.maKey, + rRHS.maKey ) < 0; + } + + const MapEntry* mpMap; + ::std::size_t mnEntries; + bool mbCaseSensitive; + }; + + CANVASTOOLS_DLLPUBLIC void clipOutDev(const css::rendering::ViewState& viewState, + const css::rendering::RenderState& renderState, + OutputDevice& rOutDev, + OutputDevice* p2ndOutDev=nullptr); + + CANVASTOOLS_DLLPUBLIC void extractExtraFontProperties(const css::uno::Sequence& rExtraFontProperties, + sal_uInt32& rEmphasisMark); + } +} + +#endif /* INCLUDED_CANVAS_CANVASTOOLS_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/canvas/canvastoolsdllapi.h b/include/canvas/canvastoolsdllapi.h new file mode 100644 index 000000000..a3748371a --- /dev/null +++ b/include/canvas/canvastoolsdllapi.h @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CANVAS_CANVASTOOLSDLLAPI_H +#define INCLUDED_CANVAS_CANVASTOOLSDLLAPI_H + +#include +#include + +#if defined(CANVASTOOLS_DLLIMPLEMENTATION) +#define CANVASTOOLS_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define CANVASTOOLS_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define CANVASTOOLS_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/canvas/elapsedtime.hxx b/include/canvas/elapsedtime.hxx new file mode 100644 index 000000000..cf73af960 --- /dev/null +++ b/include/canvas/elapsedtime.hxx @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CANVAS_ELAPSEDTIME_HXX +#define INCLUDED_CANVAS_ELAPSEDTIME_HXX + +#include +#include + +namespace canvas::tools +{ + /** Calculate elapsed time. + + This class provides several time-measurement and + -management functions. In its simplest use-case, it + measures the time from its creation. + */ + class CANVASTOOLS_DLLPUBLIC ElapsedTime + { + public: + /** Create a new ElapsedTime object + + The moment of construction starts the time + measurement. That means, a subsequent getElapsedTime() + call will return the time difference between object + creation and getElapsedTime() call. + */ + ElapsedTime(); + + /** Creates a new ElapsedTime object based on another + timer. + + The moment of construction starts the time + measurement. That means, a subsequent getElapsedTime() + call will return the time difference between object + creation and getElapsedTime() call. All time values + are not taken from the system's time base, but from + the provided timer. + */ + ElapsedTime( std::shared_ptr xTimeBase ); + + /** Reset the time + + The instance of the reset() call starts the time + measurement from scratch. That means, a subsequent + getElapsedTime() call will return the time difference + between reset() and getElapsedTime() call. + */ + void reset(); + + /** Query the elapsed time + + This method returns the elapsed time in seconds + between either the construction of this object, or the + last reset() call, if any (but see the time modulation + methods below, for means to modify the otherwise + continuous flow of time). + + @return the elapsed time in seconds. + */ + double getElapsedTime() const; + + /** Pauses the running timer. + + This method stops the time, as returned by this + object, until continueTimer() is called. During this + period, getElapsedTime() will always return the same + time value (i.e. the instant when pauseTimer() was + called). + */ + void pauseTimer(); + + /** Continues the paused timer. + + This method re-enables the time flow, that is, time + starts running again for clients calling + getElapsedTime(). The (subtle) difference to the + holdTimer/releaseTimer() methods below is, that there + is no perceived time 'jump' between the pauseTimer() + call and the continueTimer() call, i.e. the time + starts over with the same value it has stopped on + pauseTimer(). + */ + void continueTimer(); + + /** Adjusts the timer, hold and pause times. + + This method modifies the time as returned by this + object by the specified amount. This affects the time + as returned by getElapsedTime(), regardless of the + mode (e.g. paused, or on hold). + + @param fOffset + This value will be added to the current time, i.e. the + next call to getElapsedTime() (when performed + immediately) will be adjusted by fOffset. + */ + void adjustTimer( double fOffset ); + + /** Holds the current time. + + This call makes the timer hold the current time + (e.g. getElapsedTime() will return the time when + holdTimer() was called), while the underlying time is + running on. When releaseTimer() is called, the time + will 'jump' to the then-current, underlying time. This + is equivalent to pressing the "interim time" button on + a stop watch, which shows this stopped time, while the + clock keeps running internally. + */ + void holdTimer(); + + /** Releases a held timer. + + After this call, the timer again returns the running + time on getElapsedTime(). + */ + void releaseTimer(); + + private: + static double getSystemTime(); + double getCurrentTime() const; + double getElapsedTimeImpl() const; // does not set m_fLastQueriedTime + + const std::shared_ptr m_pTimeBase; + + /// To validate adjustTimer() calls with bLimitToLastQueriedTime=true + mutable double m_fLastQueriedTime; + + /// Start time, from which the difference to the time base is returned + double m_fStartTime; + + /// Instant, when last pause or hold started, relative to m_fStartTime + double m_fFrozenTime; + + /// True, when in pause mode + bool m_bInPauseMode; + + /// True, when in hold mode + bool m_bInHoldMode; + }; + +} + +#endif /* INCLUDED_CANVAS_ELAPSEDTIME_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/codemaker.hxx b/include/codemaker/codemaker.hxx new file mode 100644 index 000000000..cf22b8a1f --- /dev/null +++ b/include/codemaker/codemaker.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_CODEMAKER_HXX +#define INCLUDED_CODEMAKER_CODEMAKER_HXX + +#include + +namespace rtl +{ +class OString; +class OUString; +} + +namespace codemaker +{ +rtl::OString convertString(rtl::OUString const& string); +} + +#endif // INCLUDED_CODEMAKER_CODEMAKER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/commoncpp.hxx b/include/codemaker/commoncpp.hxx new file mode 100644 index 000000000..9c55fcc6a --- /dev/null +++ b/include/codemaker/commoncpp.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_COMMONCPP_HXX +#define INCLUDED_CODEMAKER_COMMONCPP_HXX + +#include + +#include + +#include + +namespace rtl { + class OString; + class OUString; +} + +namespace codemaker::cpp { + +/** Stick a namespace scope to c++ type + + @param type + Undecorated type + + @param ns_alias + Use common namespace aliases instead of fully specified (nested) + namespace. currently replaces com::sun::star with css. + */ +rtl::OString scopedCppName(rtl::OString const & type, bool ns_alias=true); + +rtl::OString translateUnoToCppType( + codemaker::UnoType::Sort sort, std::u16string_view nucleus); + +enum class IdentifierTranslationMode { + Global, + NonGlobal +}; + +rtl::OString translateUnoToCppIdentifier( + rtl::OString const & identifier, std::string_view prefix, + IdentifierTranslationMode transmode = IdentifierTranslationMode::Global, + rtl::OString const * forbidden = nullptr); + +} + +#endif // INCLUDED_CODEMAKER_COMMONCPP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/commonjava.hxx b/include/codemaker/commonjava.hxx new file mode 100644 index 000000000..daac32263 --- /dev/null +++ b/include/codemaker/commonjava.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_COMMONJAVA_HXX +#define INCLUDED_CODEMAKER_COMMONJAVA_HXX + +#include + +#include + +#include + +namespace rtl { class OString; } + +namespace codemaker::java { + +rtl::OString translateUnoToJavaType( + codemaker::UnoType::Sort sort, std::string_view nucleus, + bool referenceType); + +rtl::OString translateUnoToJavaIdentifier( + rtl::OString const & identifier, std::string_view prefix); + +} + +#endif // INCLUDED_CODEMAKER_COMMONJAVA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/exceptiontree.hxx b/include/codemaker/exceptiontree.hxx new file mode 100644 index 000000000..4d5055f8e --- /dev/null +++ b/include/codemaker/exceptiontree.hxx @@ -0,0 +1,119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_EXCEPTIONTREE_HXX +#define INCLUDED_CODEMAKER_EXCEPTIONTREE_HXX + +#include +#include + +#include +#include +#include + +class TypeManager; + +namespace codemaker { + +/** + Represents a node of the hierarchy from the ExceptionTree class. + */ +struct ExceptionTreeNode { + typedef std::vector< std::unique_ptr > Children; + + // Internally used by ExceptionTree: + ExceptionTreeNode(rtl::OString theName): + name(std::move(theName)), present(false) {} + + // Internally used by ExceptionTree: + ~ExceptionTreeNode() { clearChildren(); } + + // Internally used by ExceptionTree: + void setPresent() { present = true; clearChildren(); } + + // Internally used by ExceptionTree: + ExceptionTreeNode * add(rtl::OString const & theName); + + rtl::OString name; + bool present; + Children children; + +private: + ExceptionTreeNode(ExceptionTreeNode const &) = delete; + ExceptionTreeNode& operator =(ExceptionTreeNode const &) = delete; + + void clearChildren(); +}; + +/** + Represents the hierarchy formed by a set of UNO exception types. + + The hierarchy is rooted at com.sun.star.uno.Exception. For each exception E + from the given set S, the hierarchy from com.sun.star.uno.Exception to the + first supertype E' of E which is itself a member of S is represented (i.e., + subtypes that are hidden by supertypes are pruned from the hierarchy). The + exception com.sun.star.uno.RuntimeException and its subtypes are pruned + completely from the hierarchy. Each node of the hierarchy is represented by + an instance of ExceptionTreeNode, where `name` gives the name of the UNO + exception type, `present` is true iff the given exception type is a member of + the set S, and `children` contains all the relevant direct subtypes of the + given exception type, in no particular order (for nodes other than the root + node it holds that `children` is non-empty iff `present` is false). + */ +class ExceptionTree { +public: + ExceptionTree(): m_root("com.sun.star.uno.Exception") {} + + /** + Builds the exception hierarchy, by adding one exception type at a time. + + This function can be called more than once for the same exception name. + + @param name the name of a UNO exception type; it is an error if the given + name does not represent a UNO exception type + + @param manager a type manager, used to resolve type names; it is an error + if different calls to this member function use different, incompatible + type managers + */ + void add( + rtl::OString const & name, + rtl::Reference< TypeManager > const & manager); + + /** + Gives access to the resultant exception hierarchy. + + @return a reference to the root of the exception hierarchy, as + formed by all previous calls to add; it is an error if any calls to add + follow the first call to getRoot + */ + ExceptionTreeNode const & getRoot() const { return m_root; } + +private: + ExceptionTree(ExceptionTree const &) = delete; + ExceptionTree& operator =(const ExceptionTree&) = delete; + + ExceptionTreeNode m_root; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/generatedtypeset.hxx b/include/codemaker/generatedtypeset.hxx new file mode 100644 index 000000000..cc2827cb9 --- /dev/null +++ b/include/codemaker/generatedtypeset.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_GENERATEDTYPESET_HXX +#define INCLUDED_CODEMAKER_GENERATEDTYPESET_HXX + +#include + +#include + +/// @HTML + +namespace codemaker +{ +/** + A simple class to track which types have already been processed by a code + maker. + +

This class is not multi-thread–safe.

+ */ +class GeneratedTypeSet +{ +public: + GeneratedTypeSet() {} + + /** + Add a type to the set of generated types. + +

If the type was already present, nothing happens.

+ + @param type a UNO type registry name + */ + void add(OString const& type) { m_set.insert(type); } + + /** + Checks whether a given type has already been generated. + + @param type a UNO type registry name + + @return true iff the given type has already been generated + */ + bool contains(OString const& type) const { return m_set.find(type) != m_set.end(); } + +private: + GeneratedTypeSet(GeneratedTypeSet const&) = delete; + GeneratedTypeSet& operator=(GeneratedTypeSet const&) = delete; + + std::unordered_set m_set; +}; +} + +#endif // INCLUDED_CODEMAKER_GENERATEDTYPESET_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/global.hxx b/include/codemaker/global.hxx new file mode 100644 index 000000000..e62e1a973 --- /dev/null +++ b/include/codemaker/global.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_GLOBAL_HXX +#define INCLUDED_CODEMAKER_GLOBAL_HXX + +#include +#include +#include + +#include +#include +#include + +typedef ::std::vector< ::rtl::OString > StringVector; + + +// FileStream + +class FileStream final +{ +public: + FileStream(); + ~FileStream(); + + bool isValid() const; + + void createTempFile(const ::rtl::OString& sPath); + void close(); + + const ::rtl::OString& getName() const { return m_name; } + + bool write(void const * buffer, sal_uInt64 size); + + // friend functions + friend FileStream &operator<<(FileStream& o, sal_uInt32 i); + friend FileStream &operator<<(FileStream& o, char const * s); + friend FileStream &operator<<(FileStream& o, ::rtl::OString const * s); + friend FileStream &operator<<(FileStream& o, const ::rtl::OString& s); + friend FileStream &operator<<(FileStream& o, ::rtl::OStringBuffer const * s); + friend FileStream &operator<<(FileStream& o, const ::rtl::OStringBuffer& s); + friend FileStream & operator <<(FileStream & out, std::u16string_view s); + +private: + oslFileHandle m_file; + ::rtl::OString m_name; +}; + + +// Helper functions + +::rtl::OString getTempDir(const ::rtl::OString& sFileName); + +::rtl::OString createFileNameFromType(const ::rtl::OString& destination, + const ::rtl::OString& type, + const ::rtl::OString& postfix); + +bool fileExists(const ::rtl::OString& fileName); +bool makeValidTypeFile(const ::rtl::OString& targetFileName, + const ::rtl::OString& tmpFileName, + bool bFileCheck); +bool removeTypeFile(const ::rtl::OString& fileName); + +::rtl::OUString convertToFileUrl(const ::rtl::OString& fileName); + +class CannotDumpException final { +public: + CannotDumpException(OUString message): message_(std::move(message)) {} + + ~CannotDumpException() noexcept; + + const OUString& getMessage() const { return message_; } + +private: + OUString message_; +}; + +#endif // INCLUDED_CODEMAKER_GLOBAL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/options.hxx b/include/codemaker/options.hxx new file mode 100644 index 000000000..803274901 --- /dev/null +++ b/include/codemaker/options.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_OPTIONS_HXX +#define INCLUDED_CODEMAKER_OPTIONS_HXX + +#include +#include +#include + +typedef std::unordered_map +< + ::rtl::OString, + ::rtl::OString, + OStringHash +> OptionMap; + +class IllegalArgument +{ +public: + IllegalArgument(::rtl::OString msg) + : m_message(std::move(msg)) {} + + ::rtl::OString m_message; +}; + +class Options +{ +public: + Options(); + virtual ~Options(); + + /// @throws IllegalArgument + virtual bool initOptions(int ac, char* av[], bool bCmdFile=false) = 0; + + virtual ::rtl::OString prepareHelp() = 0; + + const ::rtl::OString& getProgramName() const { return m_program;} + bool isValid(const ::rtl::OString& option) const; + /// @throws IllegalArgument + const OString& getOption(const ::rtl::OString& option) const; + + const StringVector& getInputFiles() const { return m_inputFiles;} + + const StringVector& getExtraInputFiles() const + { return m_extra_input_files; } +protected: + ::rtl::OString m_program; + StringVector m_inputFiles; + StringVector m_extra_input_files; + OptionMap m_options; +}; + +#endif // INCLUDED_CODEMAKER_OPTIONS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/typemanager.hxx b/include/codemaker/typemanager.hxx new file mode 100644 index 000000000..3e6f67fe4 --- /dev/null +++ b/include/codemaker/typemanager.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_TYPEMANAGER_HXX +#define INCLUDED_CODEMAKER_TYPEMANAGER_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace unoidl { + class Entity; + class Manager; + class MapCursor; + class Provider; +} + +class TypeManager final : public salhelper::SimpleReferenceObject { +public: + TypeManager(); + + void loadProvider(OUString const & uri, bool primary); + + bool foundAtPrimaryProvider(OUString const & name) const; + + codemaker::UnoType::Sort getSort( + OUString const & name, rtl::Reference< unoidl::Entity > * entity = nullptr, + rtl::Reference< unoidl::MapCursor > * cursor = nullptr) const; + + codemaker::UnoType::Sort decompose( + std::u16string_view name, bool resolveTypedefs, OUString * nucleus, + sal_Int32 * rank, std::vector< OUString > * arguments, + rtl::Reference< unoidl::Entity > * entity) const; + +private: + virtual ~TypeManager() override; + + rtl::Reference< unoidl::Manager > manager_; + std::vector< rtl::Reference< unoidl::Provider > > primaryProviders_; +}; + + +inline OString u2b(std::u16string_view s) { + return OUStringToOString(s, RTL_TEXTENCODING_UTF8); +} + +inline OUString b2u(std::string_view s) { + return OStringToOUString(s, RTL_TEXTENCODING_UTF8); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/codemaker/unotype.hxx b/include/codemaker/unotype.hxx new file mode 100644 index 000000000..606321873 --- /dev/null +++ b/include/codemaker/unotype.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CODEMAKER_UNOTYPE_HXX +#define INCLUDED_CODEMAKER_UNOTYPE_HXX + +#include + +#include + +namespace rtl { class OString; } + +namespace codemaker::UnoType { + /** + An enumeration of all the sorts of relevant UNOIDL entities. + */ + enum class Sort { + Void, + Boolean, + Byte, + Short, + UnsignedShort, + Long, + UnsignedLong, + Hyper, + UnsignedHyper, + Float, + Double, + Char, + String, + Type, + Any, + Sequence, + Module, + Enum, + PlainStruct, + PolymorphicStructTemplate, + InstantiatedPolymorphicStruct, + Exception, + Interface, + Typedef, + ConstantGroup, + SingleInterfaceBasedService, + AccumulationBasedService, + InterfaceBasedSingleton, + ServiceBasedSingleton + }; + + /** + Decomposes a UNO type name or UNO type registry name. + + @param type a binary UNO type name or UNO type registry name + + @param rank if non-null, returns the rank of the denoted UNO type (which + is zero for any given type that does not denote a UNO sequence type) + + @param arguments if non-null, the type arguments are stripped from an + instantiated polymorphic struct type and returned via this parameter (in + the correct order); if null, type arguments are not stripped from + instantiated polymorphic struct types + + @return the base part of the given type + */ + rtl::OString decompose( + rtl::OString const & type, sal_Int32 * rank = nullptr, + std::vector< rtl::OString > * arguments = nullptr); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Any.h b/include/com/sun/star/uno/Any.h new file mode 100644 index 000000000..f232ccd90 --- /dev/null +++ b/include/com/sun/star/uno/Any.h @@ -0,0 +1,493 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_ANY_H +#define INCLUDED_COM_SUN_STAR_UNO_ANY_H + +#include "sal/config.h" + +#include + +#include "rtl/ustring.hxx" +#include "uno/any2.h" +#include "typelib/typedescription.h" +#include "cppu/unotype.hxx" +#include "com/sun/star/uno/TypeClass.hdl" +#include "rtl/alloc.h" + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + +class Type; + +/** C++ class representing an IDL any. + This class is used to transport any type defined in IDL. The class inherits from the + binary C representation of uno_Any. + You can insert a value by using the <<= operators. + No any can hold an any. You can extract values from an any by using the >>= operators which + return true if the any contains an assignable value (no data loss), e.g. the any contains a + short and you >>= it into a long variable. +*/ +class SAL_WARN_UNUSED SAL_DLLPUBLIC_RTTI Any : public uno_Any +{ +public: + /// @cond INTERNAL + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new ( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete ( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new ( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete ( void *, void * ) + {} + /// @endcond + + /** Default constructor: Any holds no value; its type is void. + */ + inline Any(); + + /** Templated ctor. Sets a copy of the given value. + + @param value value of the Any + */ + template + explicit inline Any( T const & value ); + /// Ctor support for C++ bool. + explicit inline Any( bool value ); + +#if defined LIBO_INTERNAL_ONLY + template + explicit inline Any(rtl::OUStringConcat && value); + template + explicit Any(rtl::OUStringConcat const &) = delete; + template explicit inline Any(rtl::OUStringNumber && value); + template explicit Any(rtl::OUStringNumber const &) = delete; + template explicit inline Any(const rtl::OUStringLiteral& value); +#endif + + /** Copy constructor: Sets value of the given any. + + @param rAny another any + */ + inline Any( const Any & rAny ); + + /** Constructor: Sets a copy of the given data. + + @param pData_ value + @param rType type of value + */ + inline Any( const void * pData_, const Type & rType ); + + /** Constructor: Sets a copy of the given data. + + @param pData_ value + @param pTypeDescr type of value + */ + inline Any( const void * pData_, typelib_TypeDescription * pTypeDescr ); + + /** Constructor: Sets a copy of the given data. + + @param pData_ value + @param pType_ type of value + */ + inline Any( const void * pData_, typelib_TypeDescriptionReference * pType_ ); + +#if defined LIBO_INTERNAL_ONLY + Any(bool const *, Type const &) = delete; + Any(bool const *, typelib_TypeDescription *) = delete; + Any(bool const *, typelib_TypeDescriptionReference *) = delete; + Any(sal_Bool const *, Type const &) = delete; + Any(sal_Bool const *, typelib_TypeDescription *) = delete; + Any(sal_Bool const *, typelib_TypeDescriptionReference *) = delete; + Any(std::nullptr_t, Type const & type): + Any(static_cast(nullptr), type) {} + Any(std::nullptr_t, typelib_TypeDescription * type): + Any(static_cast(nullptr), type) {} + Any(std::nullptr_t, typelib_TypeDescriptionReference * type): + Any(static_cast(nullptr), type) {} +#endif + + /** Destructor: Destructs any content and frees memory. + */ + inline ~Any(); + + /** Assignment operator: Sets the value of the given any. + + @param rAny another any (right side) + @return this any + */ + inline Any & SAL_CALL operator = ( const Any & rAny ); + +#if defined LIBO_INTERNAL_ONLY + inline Any(Any && other) noexcept; + inline Any & operator =(Any && other) noexcept; +#endif + + /** Gets the type of the set value. + + @return a Type object of the set value + */ + const Type & SAL_CALL getValueType() const + { return * reinterpret_cast< const Type * >( &pType ); } + /** Gets the type of the set value. + + @return the unacquired type description reference of the set value + */ + typelib_TypeDescriptionReference * SAL_CALL getValueTypeRef() const + { return pType; } + + /** Gets the type description of the set value. Provides ownership of the type description! + Call an explicit typelib_typedescription_release() to release afterwards. + + @param ppTypeDescr a pointer to type description pointer + */ + void SAL_CALL getValueTypeDescription( typelib_TypeDescription ** ppTypeDescr ) const + { ::typelib_typedescriptionreference_getDescription( ppTypeDescr, pType ); } + + /** Gets the type class of the set value. + + @return the type class of the set value + */ + TypeClass SAL_CALL getValueTypeClass() const + { return static_cast(pType->eTypeClass); } + + /** Gets the type name of the set value. + + @return the type name of the set value + */ + inline ::rtl::OUString SAL_CALL getValueTypeName() const; + + /** Tests if any contains a value. + + @return true if any has a value, false otherwise + */ + bool SAL_CALL hasValue() const + { return (typelib_TypeClass_VOID != pType->eTypeClass); } + + /** Gets a pointer to the set value. + + @return a pointer to the set value + */ + const void * SAL_CALL getValue() const + { return pData; } + + /** Provides a value of specified type, so you can easily write e.g. +
+        sal_Int32 myVal = myAny.get();
+        
+ Widening conversion without data loss is taken into account. + Throws a com::sun::star::uno::RuntimeException if the specified type + cannot be provided. + + @return value of specified type + @exception com::sun::star::uno::RuntimeException + in case the specified type cannot be provided + */ + template + inline T get() const; + + /** Sets a value. If the any already contains a value, that value will be destructed + and its memory freed. + + @param pData_ pointer to value + @param rType type of value + */ + inline void SAL_CALL setValue( const void * pData_, const Type & rType ); + /** Sets a value. If the any already contains a value, that value will be destructed + and its memory freed. + + @param pData_ pointer to value + @param pType_ type of value + */ + inline void SAL_CALL setValue( const void * pData_, typelib_TypeDescriptionReference * pType_ ); + /** Sets a value. If the any already contains a value, that value will be destructed + and its memory freed. + + @param pData_ pointer to value + @param pTypeDescr type description of value + */ + inline void SAL_CALL setValue( const void * pData_, typelib_TypeDescription * pTypeDescr ); + +#if defined LIBO_INTERNAL_ONLY + void setValue(bool const *, Type const &) = delete; + void setValue(bool const *, typelib_TypeDescriptionReference *) = delete; + void setValue(bool const *, typelib_TypeDescription *) = delete; + void setValue(sal_Bool const *, Type const &) = delete; + void setValue(sal_Bool const *, typelib_TypeDescriptionReference *) + = delete; + void setValue(sal_Bool const *, typelib_TypeDescription *) = delete; + void setValue(std::nullptr_t, Type const & type) + { setValue(static_cast(nullptr), type); } + void setValue(std::nullptr_t, typelib_TypeDescriptionReference * type) + { setValue(static_cast(nullptr), type); } + void setValue(std::nullptr_t, typelib_TypeDescription * type) + { setValue(static_cast(nullptr), type); } +#endif + + /** Clears this any. If the any already contains a value, that value will be destructed + and its memory freed. After this has been called, the any does not contain a value. + */ + inline void SAL_CALL clear(); + + /** Tests whether this any is extractable to a value of given type. + Widening conversion without data loss is taken into account. + + @param rType destination type + @return true if this any is extractable to value of given type (e.g. using >>= operator) + */ + inline bool SAL_CALL isExtractableTo( const Type & rType ) const; + + /** Tests whether this any can provide a value of specified type. + Widening conversion without data loss is taken into account. + + @return true if this any can provide a value of specified type + (e.g. using >>= operator) + */ + template + inline bool has() const; + + /** Equality operator: compares two anys. + The values need not be of equal type, e.g. a short integer is compared to a long integer. + + @param rAny another any (right side) + @return true if both any contains equal values + */ + inline bool SAL_CALL operator == ( const Any & rAny ) const; + /** Inequality operator: compares two anys. + The values need not be of equal type, e.g. a short integer is compared to a long integer. + + @param rAny another any (right side) + @return true if both any contains unequal values + */ + inline bool SAL_CALL operator != ( const Any & rAny ) const; + +private: +#if !defined LIBO_INTERNAL_ONLY + /// @cond INTERNAL + // Forbid use with ambiguous type (sal_Unicode, sal_uInt16): + explicit Any(sal_uInt16) SAL_DELETED_FUNCTION; + /// @endcond +#endif +}; + +#if !defined LIBO_INTERNAL_ONLY +/// @cond INTERNAL +// Forbid use with ambiguous type (sal_Unicode, sal_uInt16): +template<> sal_uInt16 Any::get() const SAL_DELETED_FUNCTION; +template<> bool Any::has() const SAL_DELETED_FUNCTION; +/// @endcond +#endif + +#if !defined LIBO_INTERNAL_ONLY +/** Template function to generically construct an any from a C++ value. + + @deprecated Just use an Any constructor with an appropriately typed argument. (When the + (UNO) type recorded in the Any instance shall be different from what would + be deduced from the (C++) type of the argument, cast the argument to the appropriate type + first.) + + @tparam C value type + @param value a value + @return an any +*/ +template< class C > +inline Any SAL_CALL makeAny( const C & value ); + +template<> inline Any SAL_CALL makeAny(sal_uInt16 const & value); + +template<> Any SAL_CALL makeAny(Any const &) SAL_DELETED_FUNCTION; +#endif + +/** Wrap a value in an Any, if necessary. + + (A difference to the deprecated makeAny is that makeAny cannot be called on an Any, while + toAny just returns the given Any.) + + @since LibreOffice 5.0 +*/ +template inline Any toAny(T const & value); + +template<> inline Any toAny(Any const & value); + +#if defined LIBO_INTERNAL_ONLY + +/** Extract a value from an Any, if necessary. + + The difference to operator >>= is that operator >>= cannot be called with an + Any as right-hand side (in LIBO_INTERNAL_ONLY), while fromAny just passes on + the given Any (and always succeeds) in the specialization for T = Any. + + @tparam T any type representing a UNO type + + @param any any Any value + + @param value a non-null pointer, receiving the extracted value if + extraction succeeded (and left unmodified otherwise) + + @return true iff extraction succeeded + + @since LibreOffice 5.3 +*/ +template inline bool fromAny(Any const & any, T * value); + +template<> inline bool fromAny(Any const & any, Any * value); + +#endif + +class BaseReference; + +/** Template binary <<= operator to set the value of an any. + + @tparam C value type + @param rAny destination any (left side) + @param value source value (right side) +*/ +template< class C > +inline void SAL_CALL operator <<= ( Any & rAny, const C & value ); + +// additionally for C++ bool: +template<> +inline void SAL_CALL operator <<= ( Any & rAny, bool const & value ); + +/** Template binary >>= operator to assign a value from an any. + If the any does not contain a value that can be assigned without data loss, then this + operation will fail returning false. + + @tparam C value type + @param rAny source any (left side) + @param value destination value (right side) + @return true if assignment was possible without data loss +*/ +template< class C > +inline bool SAL_CALL operator >>= ( const Any & rAny, C & value ); + +/** Template equality operator: compares set value of left side any to right side value. + The values need not be of equal type, e.g. a short integer is compared to a long integer. + This operator can be implemented as template member function, if all supported compilers + can cope with template member functions. + + @tparam C value type + @param rAny another any (left side) + @param value a value (right side) + @return true if values are equal, false otherwise +*/ +template< class C > +inline bool SAL_CALL operator == ( const Any & rAny, const C & value ); +/** Template inequality operator: compares set value of left side any to right side value. + The values need not be of equal type, e.g. a short integer is compared to a long integer. + This operator can be implemented as template member function, if all supported compilers + can cope with template member functions. + + @tparam C value type + @param rAny another any (left side) + @param value a value (right side) + @return true if values are unequal, false otherwise +*/ +template< class C > +inline bool SAL_CALL operator != ( const Any & rAny, const C & value ); + +// additional specialized >>= and == operators +// bool +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Bool & value ); +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const sal_Bool & value ); +template<> +inline bool SAL_CALL operator >>= ( Any const & rAny, bool & value ); +template<> +inline bool SAL_CALL operator == ( Any const & rAny, bool const & value ); +// byte +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int8 & value ); +// short +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int16 & value ); +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_uInt16 & value ); +// long +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int32 & value ); +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_uInt32 & value ); +// hyper +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int64 & value ); +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_uInt64 & value ); +// float +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, float & value ); +// double +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, double & value ); +// string +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, ::rtl::OUString & value ); +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const ::rtl::OUString & value ); +// type +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, Type & value ); +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const Type & value ); +// any +#if !defined LIBO_INTERNAL_ONLY +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, Any & value ); +#endif +// interface +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const BaseReference & value ); + +} +} +} +} + +/** Gets the meta type of IDL type any. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type any + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const ::com::sun::star::uno::Any * ) +{ + return ::cppu::UnoType< ::com::sun::star::uno::Any >::get(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Any.hxx b/include/com/sun/star/uno/Any.hxx new file mode 100644 index 000000000..d73b2a586 --- /dev/null +++ b/include/com/sun/star/uno/Any.hxx @@ -0,0 +1,765 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_ANY_HXX +#define INCLUDED_COM_SUN_STAR_UNO_ANY_HXX + +#include "sal/config.h" + +#include +#include +#include +#include +#include +#include + +#include "com/sun/star/uno/Any.h" +#include "uno/data.h" +#include "uno/sequence2.h" +#include "com/sun/star/uno/Type.hxx" +#include "com/sun/star/uno/Reference.h" +#include "com/sun/star/uno/genfunc.hxx" +#include "com/sun/star/uno/RuntimeException.hpp" +#include "cppu/cppudllapi.h" +#include "cppu/unotype.hxx" + +extern "C" CPPU_DLLPUBLIC rtl_uString * SAL_CALL cppu_Any_extraction_failure_msg( + uno_Any const * pAny, typelib_TypeDescriptionReference * pType ) + SAL_THROW_EXTERN_C(); + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + + +inline Any::Any() +{ + ::uno_any_construct( this, NULL, NULL, cpp_acquire ); +} + + +template +inline Any::Any( T const & value ) +{ + ::uno_type_any_construct( + this, const_cast(&value), + ::cppu::getTypeFavourUnsigned(&value).getTypeLibType(), + cpp_acquire ); +} + +inline Any::Any( bool value ) +{ + sal_Bool b = value; + ::uno_type_any_construct( + this, &b, cppu::UnoType::get().getTypeLibType(), + cpp_acquire ); +} + +#if defined LIBO_INTERNAL_ONLY +template +Any::Any(rtl::OUStringConcat && value): + Any(rtl::OUString(std::move(value))) +{} +template +Any::Any(rtl::OUStringNumber && value): Any(rtl::OUString(std::move(value))) {} +template +Any::Any(const rtl::OUStringLiteral& value): Any(rtl::OUString(value)) {} +#endif + +inline Any::Any( const Any & rAny ) +{ + ::uno_type_any_construct( this, rAny.pData, rAny.pType, cpp_acquire ); +} + +inline Any::Any( const void * pData_, const Type & rType ) +{ + ::uno_type_any_construct( + this, const_cast< void * >( pData_ ), rType.getTypeLibType(), + cpp_acquire ); +} + +inline Any::Any( const void * pData_, typelib_TypeDescription * pTypeDescr ) +{ + ::uno_any_construct( + this, const_cast< void * >( pData_ ), pTypeDescr, cpp_acquire ); +} + +inline Any::Any( const void * pData_, typelib_TypeDescriptionReference * pType_ ) +{ + ::uno_type_any_construct( + this, const_cast< void * >( pData_ ), pType_, cpp_acquire ); +} + +inline Any::~Any() +{ + ::uno_any_destruct( + this, cpp_release ); +} + +inline Any & Any::operator = ( const Any & rAny ) +{ + if (this != &rAny) + { + ::uno_type_any_assign( + this, rAny.pData, rAny.pType, + cpp_acquire, cpp_release ); + } + return *this; +} + +#if defined LIBO_INTERNAL_ONLY + +Any::Any(Any && other) noexcept { + uno_any_construct(this, nullptr, nullptr, &cpp_acquire); + std::swap(other.pType, pType); + std::swap(other.pData, pData); + std::swap(other.pReserved, pReserved); + if (pData == &other.pReserved) { + pData = &pReserved; + } + // This leaves other.pData (where "other" is now VOID) dangling to somewhere (cf. + // CONSTRUCT_EMPTY_ANY, cppu/source/uno/prim.hxx), but what's relevant is + // only that it isn't a nullptr (as e.g. >>= -> uno_type_assignData -> + // _assignData takes a null pSource to mean "construct a default value"). +} + +Any & Any::operator =(Any && other) noexcept { + std::swap(other.pType, pType); + std::swap(other.pData, pData); + std::swap(other.pReserved, pReserved); + if (pData == &other.pReserved) { + pData = &pReserved; + } + if (other.pData == &pReserved) { + other.pData = &other.pReserved; + } + return *this; +} + +#endif + +inline ::rtl::OUString Any::getValueTypeName() const +{ + return ::rtl::OUString( pType->pTypeName ); +} + +inline void Any::setValue( const void * pData_, const Type & rType ) +{ + ::uno_type_any_assign( + this, const_cast< void * >( pData_ ), rType.getTypeLibType(), + cpp_acquire, cpp_release ); +} + +inline void Any::setValue( const void * pData_, typelib_TypeDescriptionReference * pType_ ) +{ + ::uno_type_any_assign( + this, const_cast< void * >( pData_ ), pType_, + cpp_acquire, cpp_release ); +} + +inline void Any::setValue( const void * pData_, typelib_TypeDescription * pTypeDescr ) +{ + ::uno_any_assign( + this, const_cast< void * >( pData_ ), pTypeDescr, + cpp_acquire, cpp_release ); +} + +inline void Any::clear() +{ + ::uno_any_clear( + this, cpp_release ); +} + +inline bool Any::isExtractableTo( const Type & rType ) const +{ + return ::uno_type_isAssignableFromData( + rType.getTypeLibType(), pData, pType, + cpp_queryInterface, cpp_release ); +} + + +template +inline bool Any::has() const +{ + Type const & rType = ::cppu::getTypeFavourUnsigned(static_cast< T * >(NULL)); + return ::uno_type_isAssignableFromData( + rType.getTypeLibType(), pData, pType, + cpp_queryInterface, + cpp_release ); +} + +#if defined LIBO_INTERNAL_ONLY +template<> bool Any::has() const = delete; +#endif + +inline bool Any::operator == ( const Any & rAny ) const +{ + return ::uno_type_equalData( + pData, pType, rAny.pData, rAny.pType, + cpp_queryInterface, cpp_release ); +} + +inline bool Any::operator != ( const Any & rAny ) const +{ + return (! ::uno_type_equalData( + pData, pType, rAny.pData, rAny.pType, + cpp_queryInterface, cpp_release )); +} + + +#if !defined LIBO_INTERNAL_ONLY +template< class C > +inline Any SAL_CALL makeAny( const C & value ) +{ + return Any(value); +} + +template<> Any makeAny(sal_uInt16 const & value) +{ return Any(&value, cppu::UnoType::get()); } +#endif + +template Any toAny(T const & value) { + return Any(value); +} + +template<> Any toAny(Any const & value) { return value; } + +#if defined LIBO_INTERNAL_ONLY + +template +Any toAny(rtl::OUStringConcat && value) +{ return Any(std::move(value)); } + +template +Any toAny(rtl::OUStringNumber && value) +{ return Any(std::move(value)); } + +template bool fromAny(Any const & any, T * value) { + assert(value != nullptr); + return any >>= *value; +} + +template<> bool fromAny(Any const & any, Any * value) { + assert(value != nullptr); + *value = any; + return true; +} + +#endif + +template< class C > +inline void SAL_CALL operator <<= ( Any & rAny, const C & value ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned(&value); + ::uno_type_any_assign( + &rAny, const_cast< C * >( &value ), rType.getTypeLibType(), + cpp_acquire, cpp_release ); +} + +// additionally for C++ bool: + +template<> +inline void SAL_CALL operator <<= ( Any & rAny, bool const & value ) +{ + sal_Bool b = value; + ::uno_type_any_assign( + &rAny, &b, cppu::UnoType::get().getTypeLibType(), + cpp_acquire, cpp_release ); +} + + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +template< class C1, class C2 > +inline void operator <<= ( Any & rAny, rtl::OUStringConcat< C1, C2 >&& value ) +{ + const rtl::OUString str( std::move(value) ); + const Type & rType = ::cppu::getTypeFavourUnsigned(&str); + ::uno_type_any_assign( + &rAny, const_cast< rtl::OUString * >( &str ), rType.getTypeLibType(), + cpp_acquire, cpp_release ); +} +template +void operator <<=(Any &, rtl::OUStringConcat const &) = delete; +template< class C > +inline void operator <<= ( Any & rAny, rtl::OUStringNumber< C >&& value ) +{ + const rtl::OUString str( std::move(value) ); + const Type & rType = ::cppu::getTypeFavourUnsigned(&str); + ::uno_type_any_assign( + &rAny, const_cast< rtl::OUString * >( &str ), rType.getTypeLibType(), + cpp_acquire, cpp_release ); +} +template +void operator <<=(Any &, rtl::OUStringNumber const &) = delete; +#endif + +#if defined LIBO_INTERNAL_ONLY +template<> void SAL_CALL operator <<=(Any &, Any const &) = delete; +#endif + +template< class C > +inline bool SAL_CALL operator >>= ( const Any & rAny, C & value ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned(&value); + return ::uno_type_assignData( + &value, rType.getTypeLibType(), + rAny.pData, rAny.pType, + cpp_queryInterface, + cpp_acquire, cpp_release ); +} + +// bool + +template<> +inline bool SAL_CALL operator >>= ( const ::com::sun::star::uno::Any & rAny, sal_Bool & value ) +{ + if (typelib_TypeClass_BOOLEAN == rAny.pType->eTypeClass) + { + value = bool(* static_cast< const sal_Bool * >( rAny.pData )); + return true; + } + return false; +} + +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const sal_Bool & value ) +{ + return (typelib_TypeClass_BOOLEAN == rAny.pType->eTypeClass && + bool(value) == bool(* static_cast< const sal_Bool * >( rAny.pData ))); +} + + +template<> +inline bool SAL_CALL operator >>= ( Any const & rAny, bool & value ) +{ + if (rAny.pType->eTypeClass == typelib_TypeClass_BOOLEAN) + { + value = *static_cast< sal_Bool const * >( rAny.pData ); + return true; + } + return false; +} + + +template<> +inline bool SAL_CALL operator == ( Any const & rAny, bool const & value ) +{ + return (rAny.pType->eTypeClass == typelib_TypeClass_BOOLEAN && + (value == + bool(*static_cast< sal_Bool const * >( rAny.pData )))); +} + +// byte + +template<> +inline bool SAL_CALL operator >>= ( const ::com::sun::star::uno::Any & rAny, sal_Int8 & value ) +{ + if (typelib_TypeClass_BYTE == rAny.pType->eTypeClass) + { + value = * static_cast< const sal_Int8 * >( rAny.pData ); + return true; + } + return false; +} +// short + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int16 & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = * static_cast< const sal_Int8 * >( rAny.pData ); + return true; + case typelib_TypeClass_SHORT: + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_Int16 * >( rAny.pData ); + return true; + default: + return false; + } +} + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_uInt16 & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = static_cast( * static_cast< const sal_Int8 * >( rAny.pData ) ); + return true; + case typelib_TypeClass_SHORT: + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + default: + return false; + } +} +// long + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int32 & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = * static_cast< const sal_Int8 * >( rAny.pData ); + return true; + case typelib_TypeClass_SHORT: + value = * static_cast< const sal_Int16 * >( rAny.pData ); + return true; + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + case typelib_TypeClass_LONG: + case typelib_TypeClass_UNSIGNED_LONG: + value = * static_cast< const sal_Int32 * >( rAny.pData ); + return true; + default: + return false; + } +} + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_uInt32 & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = static_cast( * static_cast< const sal_Int8 * >( rAny.pData ) ); + return true; + case typelib_TypeClass_SHORT: + value = static_cast( * static_cast< const sal_Int16 * >( rAny.pData ) ); + return true; + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + case typelib_TypeClass_LONG: + case typelib_TypeClass_UNSIGNED_LONG: + value = * static_cast< const sal_uInt32 * >( rAny.pData ); + return true; + default: + return false; + } +} +// hyper + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_Int64 & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = * static_cast< const sal_Int8 * >( rAny.pData ); + return true; + case typelib_TypeClass_SHORT: + value = * static_cast< const sal_Int16 * >( rAny.pData ); + return true; + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + case typelib_TypeClass_LONG: + value = * static_cast< const sal_Int32 * >( rAny.pData ); + return true; + case typelib_TypeClass_UNSIGNED_LONG: + value = * static_cast< const sal_uInt32 * >( rAny.pData ); + return true; + case typelib_TypeClass_HYPER: + case typelib_TypeClass_UNSIGNED_HYPER: + value = * static_cast< const sal_Int64 * >( rAny.pData ); + return true; + default: + return false; + } +} + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, sal_uInt64 & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = static_cast( * static_cast< const sal_Int8 * >( rAny.pData ) ); + return true; + case typelib_TypeClass_SHORT: + value = static_cast( * static_cast< const sal_Int16 * >( rAny.pData ) ); + return true; + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + case typelib_TypeClass_LONG: + value = static_cast( * static_cast< const sal_Int32 * >( rAny.pData ) ); + return true; + case typelib_TypeClass_UNSIGNED_LONG: + value = * static_cast< const sal_uInt32 * >( rAny.pData ); + return true; + case typelib_TypeClass_HYPER: + case typelib_TypeClass_UNSIGNED_HYPER: + value = * static_cast< const sal_uInt64 * >( rAny.pData ); + return true; + default: + return false; + } +} +// float + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, float & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = * static_cast< const sal_Int8 * >( rAny.pData ); + return true; + case typelib_TypeClass_SHORT: + value = * static_cast< const sal_Int16 * >( rAny.pData ); + return true; + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + case typelib_TypeClass_FLOAT: + value = * static_cast< const float * >( rAny.pData ); + return true; + default: + return false; + } +} +// double + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, double & value ) +{ + switch (rAny.pType->eTypeClass) + { + case typelib_TypeClass_BYTE: + value = * static_cast< const sal_Int8 * >( rAny.pData ); + return true; + case typelib_TypeClass_SHORT: + value = * static_cast< const sal_Int16 * >( rAny.pData ); + return true; + case typelib_TypeClass_UNSIGNED_SHORT: + value = * static_cast< const sal_uInt16 * >( rAny.pData ); + return true; + case typelib_TypeClass_LONG: + value = * static_cast< const sal_Int32 * >( rAny.pData ); + return true; + case typelib_TypeClass_UNSIGNED_LONG: + value = * static_cast< const sal_uInt32 * >( rAny.pData ); + return true; + case typelib_TypeClass_FLOAT: + value = * static_cast< const float * >( rAny.pData ); + return true; + case typelib_TypeClass_DOUBLE: + value = * static_cast< const double * >( rAny.pData ); + return true; + default: + return false; + } +} +// string + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, ::rtl::OUString & value ) +{ + if (typelib_TypeClass_STRING == rAny.pType->eTypeClass) + { + value = * static_cast< const ::rtl::OUString * >( rAny.pData ); + return true; + } + return false; +} + +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const ::rtl::OUString & value ) +{ + return (typelib_TypeClass_STRING == rAny.pType->eTypeClass && + value == * static_cast< const ::rtl::OUString * >( rAny.pData ) ); +} +// type + +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, Type & value ) +{ + if (typelib_TypeClass_TYPE == rAny.pType->eTypeClass) + { + value = * static_cast< const Type * >( rAny.pData ); + return true; + } + return false; +} + +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const Type & value ) +{ + return (typelib_TypeClass_TYPE == rAny.pType->eTypeClass && + value.equals( * static_cast< const Type * >( rAny.pData ) )); +} +// any + +#if defined LIBO_INTERNAL_ONLY +template<> bool SAL_CALL operator >>=(Any const &, Any &) = delete; +#else +template<> +inline bool SAL_CALL operator >>= ( const Any & rAny, Any & value ) +{ + if (&rAny != &value) + { + ::uno_type_any_assign( + &value, rAny.pData, rAny.pType, + cpp_acquire, cpp_release ); + } + return true; +} +#endif +// interface + +template<> +inline bool SAL_CALL operator == ( const Any & rAny, const BaseReference & value ) +{ + if (typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass) + { + return static_cast< const BaseReference * >( rAny.pData )->operator == ( value ); + } + return false; +} + +// operator to compare to an any. + +template< class C > +inline bool SAL_CALL operator == ( const Any & rAny, const C & value ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned(&value); + return ::uno_type_equalData( + rAny.pData, rAny.pType, + const_cast< C * >( &value ), rType.getTypeLibType(), + cpp_queryInterface, cpp_release ); +} +// operator to compare to an any. may use specialized operators ==. + +template< class C > +inline bool SAL_CALL operator != ( const Any & rAny, const C & value ) +{ + return (! operator == ( rAny, value )); +} + +template +T Any::get() const +{ + T value = T(); + if (! (*this >>= value)) { + throw RuntimeException( + ::rtl::OUString( + cppu_Any_extraction_failure_msg( + this, + ::cppu::getTypeFavourUnsigned(&value).getTypeLibType() ), + SAL_NO_ACQUIRE ) ); + } + return value; +} + +#if defined LIBO_INTERNAL_ONLY +template<> Any Any::get() const = delete; +#endif + +/** + Support for Any in std::ostream (and thus in CPPUNIT_ASSERT or SAL_INFO + macros, for example). + + @since LibreOffice 4.2 +*/ +template +inline std::basic_ostream &operator<<(std::basic_ostream &o, Any const &any) { + o << "eTypeClass) { + case typelib_TypeClass_VOID: + break; + case typelib_TypeClass_BOOLEAN: + o << ' ' << any.get(); + break; + case typelib_TypeClass_BYTE: + case typelib_TypeClass_SHORT: + case typelib_TypeClass_LONG: + case typelib_TypeClass_HYPER: + o << ' ' << any.get(); + break; + case typelib_TypeClass_UNSIGNED_SHORT: + case typelib_TypeClass_UNSIGNED_LONG: + case typelib_TypeClass_UNSIGNED_HYPER: + o << ' ' << any.get(); + break; + case typelib_TypeClass_FLOAT: + case typelib_TypeClass_DOUBLE: + o << ' ' << any.get(); + break; + case typelib_TypeClass_CHAR: { + std::ios_base::fmtflags flgs = o.setf( + std::ios_base::hex, std::ios_base::basefield); + charT fill = o.fill('0'); + o << " U+" << std::setw(4) + << unsigned(*static_cast(any.getValue())); + o.setf(flgs); + o.fill(fill); + break; + } + case typelib_TypeClass_STRING: + o << ' ' << any.get(); + break; + case typelib_TypeClass_TYPE: + o << ' ' << any.get().getTypeName(); + break; + case typelib_TypeClass_SEQUENCE: + o << " len " + << ((*static_cast(any.getValue()))-> + nElements); + break; + case typelib_TypeClass_ENUM: + o << ' ' << *static_cast(any.getValue()); + break; + case typelib_TypeClass_STRUCT: + case typelib_TypeClass_EXCEPTION: + o << ' ' << any.getValue(); + break; + case typelib_TypeClass_INTERFACE: + o << ' ' << *static_cast(any.getValue()); + break; + default: + assert(false); // this cannot happen + break; + } + o << '>'; + return o; +} + +} +} +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Reference.h b/include/com/sun/star/uno/Reference.h new file mode 100644 index 000000000..85c0d929e --- /dev/null +++ b/include/com/sun/star/uno/Reference.h @@ -0,0 +1,571 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_REFERENCE_H +#define INCLUDED_COM_SUN_STAR_UNO_REFERENCE_H + +#include "sal/config.h" + +#include +#include + +#if defined LIBO_INTERNAL_ONLY +#include +#endif + +#include "rtl/alloc.h" + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + +class RuntimeException; +class XInterface; +class Type; +class Any; + +/** Enum defining UNO_REF_NO_ACQUIRE for setting reference without acquiring a given interface. + Deprecated, please use SAL_NO_ACQUIRE. + @deprecated +*/ +enum UnoReference_NoAcquire +{ + /** This enum value can be used for creating a reference granting a given interface, + i.e. transferring ownership to it. + */ + UNO_REF_NO_ACQUIRE +}; + +/** This base class serves as a base class for all template reference classes and + has been introduced due to compiler problems with templated operators ==, =!. +*/ +class BaseReference +{ +protected: + /** the interface pointer + */ + XInterface * _pInterface; + + /** Queries given interface for type rType. + + @param pInterface interface pointer + @param rType interface type + @return interface of demanded type (may be null) + */ + inline static XInterface * SAL_CALL iquery( XInterface * pInterface, const Type & rType ); + /** Queries given interface for type rType. + Throws a RuntimeException if the demanded interface cannot be queried. + + @param pInterface interface pointer + @param rType interface type + @return interface of demanded type + */ + inline static XInterface * SAL_CALL iquery_throw( XInterface * pInterface, const Type & rType ); + +public: + /** Gets interface pointer. This call does not acquire the interface. + + @return UNacquired interface pointer + */ + XInterface * SAL_CALL get() const + { return _pInterface; } + + /** Checks if reference is null. + + @return true if reference acquires an interface, i.e. true if it is not null + */ + bool SAL_CALL is() const + { return (NULL != _pInterface); } + +#if defined LIBO_INTERNAL_ONLY + /** Checks if reference is null. + + @return true if reference acquires an interface, i.e. true if it is not null + */ + explicit operator bool() const + { return is(); } +#endif + + /** Equality operator: compares two interfaces + Checks if both references are null or refer to the same object. + + @param pInterface another interface + @return true if both references are null or refer to the same object, false otherwise + */ + inline bool SAL_CALL operator == ( XInterface * pInterface ) const; + /** Inequality operator: compares two interfaces + Checks if both references are null or refer to the same object. + + @param pInterface another interface + @return false if both references are null or refer to the same object, true otherwise + */ + inline bool SAL_CALL operator != ( XInterface * pInterface ) const; + + /** Equality operator: compares two interfaces + Checks if both references are null or refer to the same object. + + @param rRef another reference + @return true if both references are null or refer to the same object, false otherwise + */ + inline bool SAL_CALL operator == ( const BaseReference & rRef ) const; + /** Inequality operator: compares two interfaces + Checks if both references are null or refer to the same object. + + @param rRef another reference + @return false if both references are null or refer to the same object, true otherwise + */ + inline bool SAL_CALL operator != ( const BaseReference & rRef ) const; + + /** Needed by some STL containers. + + @param rRef another reference + @return true, if this reference is less than rRef + */ + inline bool SAL_CALL operator < ( const BaseReference & rRef ) const; +}; + +/** Enum defining UNO_QUERY for implicit interface query. +*/ +enum UnoReference_Query +{ + /** This enum value can be used for implicit interface query. + */ + UNO_QUERY +}; +/** Enum defining UNO_QUERY_THROW for implicit interface query. + If the demanded interface is unavailable, then a RuntimeException is thrown. +*/ +enum UnoReference_QueryThrow +{ + /** This enum value can be used for implicit interface query. + */ + UNO_QUERY_THROW +}; +/** Enum defining UNO_SET_THROW for throwing if attempts are made to assign a null + interface + + @since UDK 3.2.8 +*/ +enum UnoReference_SetThrow +{ + UNO_SET_THROW +}; + +/** Template reference class for interface type derived from BaseReference. + A special constructor given the UNO_QUERY identifier queries interfaces + for reference type. +*/ +template< class interface_type > +class SAL_DLLPUBLIC_RTTI Reference : public BaseReference +{ + /** Queries given interface for type interface_type. + + @param pInterface interface pointer + @return interface of demanded type (may be null) + */ + inline static XInterface * SAL_CALL iquery( XInterface * pInterface ); + /** Queries given interface for type interface_type. + Throws a RuntimeException if the demanded interface cannot be queried. + + @param pInterface interface pointer + @return interface of demanded type + */ + inline static XInterface * SAL_CALL iquery_throw( XInterface * pInterface ); + /** Returns the given interface if it is not , throws a RuntimeException otherwise. + + @param pInterface interface pointer + @return pInterface + */ + inline static interface_type * SAL_CALL iset_throw( interface_type * pInterface ); + + /** Cast from an "interface pointer" (e.g., BaseReference::_pInterface) to a + pointer to this interface_type. + + To work around ambiguities in the case of multiple-inheritance interface + types (which inherit XInterface more than once), use reinterpret_cast + (resp. a sequence of two static_casts, to avoid warnings about + reinterpret_cast used between related classes) to switch from a pointer + to XInterface to a pointer to this derived interface_type. In + principle, this is not guaranteed to work. In practice, it seems to + work on all supported platforms. + */ + static interface_type * castFromXInterface(XInterface * p) { + return static_cast< interface_type * >(static_cast< void * >(p)); + } + + /** Cast from a pointer to this interface_type to an "interface pointer" + (e.g., BaseReference::_pInterface). + + To work around ambiguities in the case of multiple-inheritance interface + types (which inherit XInterface more than once), use reinterpret_cast + (resp. a sequence of two static_casts, to avoid warnings about + reinterpret_cast used between related classes) to switch from a pointer + to this derived interface_type to a pointer to XInterface. In + principle, this is not guaranteed to work. In practice, it seems to + work on all supported platforms. + */ + static XInterface * castToXInterface(interface_type * p) { + return static_cast< XInterface * >(static_cast< void * >(p)); + } + +public: + /// @cond INTERNAL + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new ( ::size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete ( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new ( ::size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete ( void *, void * ) + {} + /// @endcond + + /** Destructor: Releases interface if set. + */ + inline ~Reference() COVERITY_NOEXCEPT_FALSE; + + /** Default Constructor: Sets null reference. + */ + inline Reference(); + + /** Copy constructor: Copies interface reference. + + @param rRef another reference + */ + inline Reference( const Reference< interface_type > & rRef ); + +#if defined LIBO_INTERNAL_ONLY + /** Move constructor + + @param rRef another reference + */ + inline Reference( Reference< interface_type > && rRef ) noexcept; + + /** Up-casting conversion constructor: Copies interface reference. + + Does not work for up-casts to ambiguous bases. For the special case of + up-casting to Reference< XInterface >, see the corresponding conversion + operator. + + @param rRef another reference + */ + template< class derived_type > + inline Reference( + const Reference< derived_type > & rRef, + std::enable_if_t< + std::is_base_of_v + && !std::is_same_v, void *> = nullptr); +#endif + + /** Constructor: Sets given interface pointer. + + @param pInterface an interface pointer + */ + inline Reference( interface_type * pInterface ); + + /** Constructor: Sets given interface pointer without acquiring it. + + @param pInterface another reference + @param dummy SAL_NO_ACQUIRE to force obvious distinction to other constructors + */ + inline Reference( interface_type * pInterface, __sal_NoAcquire dummy); + /** Constructor: Sets given interface pointer without acquiring it. + Deprecated, please use SAL_NO_ACQUIRE version. + + @deprecated + @param pInterface another reference + @param dummy UNO_REF_NO_ACQUIRE to force obvious distinction to other constructors + */ + inline SAL_DEPRECATED("use SAL_NO_ACQUIRE version") Reference( interface_type * pInterface, UnoReference_NoAcquire dummy ); + + /** Constructor: Queries given interface for reference interface type (interface_type). + + @param rRef another reference + @param dummy UNO_QUERY to force obvious distinction to other constructors + */ + inline Reference( const BaseReference & rRef, UnoReference_Query dummy ); + /** Constructor: Queries given interface for reference interface type (interface_type). + + @param pInterface an interface pointer + @param dummy UNO_QUERY to force obvious distinction to other constructors + */ + inline Reference( XInterface * pInterface, UnoReference_Query dummy); + /** Constructor: Queries given any for reference interface type (interface_type). + + @param rAny an any + @param dummy UNO_QUERY to force obvious distinction to other constructors + */ + inline Reference( const Any & rAny, UnoReference_Query dummy); + /** Constructor: Queries given interface for reference interface type (interface_type). + Throws a RuntimeException if the demanded interface cannot be queried. + + @param rRef another reference + @param dummy UNO_QUERY_THROW to force obvious distinction + to other constructors + */ + inline Reference( const BaseReference & rRef, UnoReference_QueryThrow dummy ); +#ifdef LIBO_INTERNAL_ONLY + /** + Prevent code from calling the QUERY_THROW constructor, when they meant to use the SET_THROW constructor. + */ + Reference( const Reference< interface_type > & rRef, UnoReference_QueryThrow dummy ) = delete; +#endif + /** Constructor: Queries given interface for reference interface type (interface_type). + Throws a RuntimeException if the demanded interface cannot be queried. + + @param pInterface an interface pointer + @param dummy UNO_QUERY_THROW to force obvious distinction + to other constructors + */ + inline Reference( XInterface * pInterface, UnoReference_QueryThrow dummy ); + /** Constructor: Queries given any for reference interface type (interface_type). + Throws a RuntimeException if the demanded interface cannot be queried. + + @param rAny an any + @param dummy UNO_QUERY_THROW to force obvious distinction + to other constructors + */ + inline Reference( const Any & rAny, UnoReference_QueryThrow dummy ); + /** Constructor: assigns from the given interface of the same type. Throws a RuntimeException + if the source interface is NULL. + + @param rRef another interface reference of the same type + @param dummy UNO_SET_THROW to distinguish from default copy constructor + + @since UDK 3.2.8 + */ + inline Reference( const Reference< interface_type > & rRef, UnoReference_SetThrow dummy ); + /** Constructor: assigns from the given interface of the same type. Throws a RuntimeException + if the source interface is NULL. + + @param pInterface an interface pointer + @param dummy UNO_SET_THROW to distinguish from default assignment constructor + + @since UDK 3.2.8 + */ + inline Reference( interface_type * pInterface, UnoReference_SetThrow dummy ); + + /** Cast operator to Reference< XInterface >: Reference objects are binary compatible and + any interface must be derived from com.sun.star.uno.XInterface. + This a useful direct cast possibility. + */ + SAL_CALL operator const Reference< XInterface > & () const + { return * reinterpret_cast< const Reference< XInterface > * >( this ); } + + /** Dereference operator: Used to call interface methods. + + @return UNacquired interface pointer + */ + interface_type * SAL_CALL operator -> () const { + assert(_pInterface != NULL); + return castFromXInterface(_pInterface); + } + + /** Indirection operator. + + @since LibreOffice 6.3 + @return UNacquired interface reference + */ + interface_type & SAL_CALL operator * () const { + assert(_pInterface != NULL); + return *castFromXInterface(_pInterface); + } + + /** Gets interface pointer. This call does not acquire the interface. + + @return UNacquired interface pointer + */ + interface_type * SAL_CALL get() const + { return castFromXInterface(_pInterface); } + + /** Clears reference, i.e. releases interface. Reference is null after clear() call. + */ + inline void SAL_CALL clear(); + + /** Sets the given interface. An interface already set will be released. + + @param rRef another reference + @return true, if non-null interface was set + */ + inline bool SAL_CALL set( const Reference< interface_type > & rRef ); + /** Sets the given interface. An interface already set will be released. + + @param pInterface another interface + @return true, if non-null interface was set + */ + inline bool SAL_CALL set( interface_type * pInterface ); + + /** Sets interface pointer without acquiring it. An interface already set will be released. + + @param pInterface an interface pointer + @param dummy SAL_NO_ACQUIRE to force obvious distinction to set methods + @return true, if non-null interface was set + */ + inline bool SAL_CALL set( interface_type * pInterface, __sal_NoAcquire dummy); + /** Sets interface pointer without acquiring it. An interface already set will be released. + Deprecated, please use SAL_NO_ACQUIRE version. + + @deprecated + @param pInterface an interface pointer + @param dummy UNO_REF_NO_ACQUIRE to force obvious distinction to set methods + @return true, if non-null interface was set + */ + inline SAL_DEPRECATED("use SAL_NO_ACQUIRE version") bool SAL_CALL set( interface_type * pInterface, UnoReference_NoAcquire dummy); + + /** Queries given interface for reference interface type (interface_type) and sets it. + An interface already set will be released. + + @param pInterface an interface pointer + @param dummy UNO_QUERY to force obvious distinction to set methods + @return true, if non-null interface was set + */ + inline bool SAL_CALL set( XInterface * pInterface, UnoReference_Query dummy ); + /** Queries given interface for reference interface type (interface_type) and sets it. + An interface already set will be released. + + @param rRef another reference + @param dummy UNO_QUERY to force obvious distinction to set methods + @return true, if non-null interface was set + */ + inline bool SAL_CALL set( const BaseReference & rRef, UnoReference_Query dummy); + + /** Queries given any for reference interface type (interface_type) + and sets it. An interface already set will be released. + + @param rAny + an Any containing an interface + @param dummy + UNO_QUERY to force obvious distinction + to set methods + @return + true, if non-null interface was set + */ + inline bool set( Any const & rAny, UnoReference_Query dummy ); + + /** Queries given interface for reference interface type (interface_type) and sets it. + An interface already set will be released. + Throws a RuntimeException if the demanded interface cannot be set. + + @param pInterface an interface pointer + @param dummy UNO_QUERY_THROW to force obvious distinction + to set methods + */ + inline void SAL_CALL set( XInterface * pInterface, UnoReference_QueryThrow dummy ); + /** Queries given interface for reference interface type (interface_type) and sets it. + An interface already set will be released. + Throws a RuntimeException if the demanded interface cannot be set. + + @param rRef another reference + @param dummy UNO_QUERY_THROW to force obvious distinction + to set methods + */ + inline void SAL_CALL set( const BaseReference & rRef, UnoReference_QueryThrow dummy ); +#ifdef LIBO_INTERNAL_ONLY + /** + Prevent code from calling the QUERY_THROW version, when they meant to use the SET_THROW version. + */ + void set( const Reference< interface_type > & rRef, UnoReference_QueryThrow dummy ) = delete; +#endif + + /** Queries given any for reference interface type (interface_type) and + sets it. An interface already set will be released. + Throws a RuntimeException if the demanded interface cannot be set. + + @param rAny + an Any containing an interface + @param dummy + UNO_QUERY_THROW to force obvious distinction to set methods + */ + inline void set( Any const & rAny, UnoReference_QueryThrow dummy); + /** sets the given interface + An interface already set will be released. + Throws a RuntimeException if the source interface is @b NULL. + + @param pInterface an interface pointer + @param dummy UNO_SET_THROW to force obvious distinction to other set methods + + @since UDK 3.2.8 + */ + inline void SAL_CALL set( interface_type * pInterface, UnoReference_SetThrow dummy); + /** sets the given interface + An interface already set will be released. + Throws a RuntimeException if the source interface is @b NULL. + + @param rRef an interface reference + @param dummy UNO_SET_THROW to force obvious distinction to other set methods + + @since UDK 3.2.8 + */ + inline void SAL_CALL set( const Reference< interface_type > & rRef, UnoReference_SetThrow dummy); + + + /** Assignment operator: Acquires given interface pointer and sets reference. + An interface already set will be released. + + @param pInterface an interface pointer + @return this reference + */ + inline Reference< interface_type > & SAL_CALL operator = ( interface_type * pInterface ); + /** Assignment operator: Acquires given interface reference and sets reference. + An interface already set will be released. + + @param rRef an interface reference + @return this reference + */ + inline Reference< interface_type > & SAL_CALL operator = ( const Reference< interface_type > & rRef ); +#if defined LIBO_INTERNAL_ONLY + /** Assignment move operator: Acquires given interface reference and sets reference. + An interface already set will be released. + + @param rRef an interface reference + @return this reference + */ + inline Reference< interface_type > & operator = ( Reference< interface_type > && rRef ) noexcept; +#endif + /** Queries given interface reference for type interface_type. + + @param rRef interface reference + @return interface reference of demanded type (may be null) + */ + SAL_WARN_UNUSED_RESULT inline static Reference< interface_type > SAL_CALL query( const BaseReference & rRef ); + /** Queries given interface for type interface_type. + + @param pInterface interface pointer + @return interface reference of demanded type (may be null) + */ + SAL_WARN_UNUSED_RESULT inline static Reference< interface_type > SAL_CALL query( XInterface * pInterface ); +}; + +} +} +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Reference.hxx b/include/com/sun/star/uno/Reference.hxx new file mode 100644 index 000000000..7632c5504 --- /dev/null +++ b/include/com/sun/star/uno/Reference.hxx @@ -0,0 +1,481 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_REFERENCE_HXX +#define INCLUDED_COM_SUN_STAR_UNO_REFERENCE_HXX + +#include "sal/config.h" + +#include +#include + +#include "com/sun/star/uno/Reference.h" +#include "com/sun/star/uno/RuntimeException.hpp" +#include "com/sun/star/uno/XInterface.hpp" +#include "com/sun/star/uno/Any.hxx" +#include "cppu/cppudllapi.h" + +extern "C" CPPU_DLLPUBLIC rtl_uString * SAL_CALL cppu_unsatisfied_iquery_msg( + typelib_TypeDescriptionReference * pType ) + SAL_THROW_EXTERN_C(); +extern "C" CPPU_DLLPUBLIC rtl_uString * SAL_CALL cppu_unsatisfied_iset_msg( + typelib_TypeDescriptionReference * pType ) + SAL_THROW_EXTERN_C(); + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + + +inline XInterface * BaseReference::iquery( + XInterface * pInterface, const Type & rType ) +{ + if (pInterface) + { + Any aRet( pInterface->queryInterface( rType ) ); + if (typelib_TypeClass_INTERFACE == aRet.pType->eTypeClass) + { + XInterface * pRet = static_cast< XInterface * >( aRet.pReserved ); + aRet.pReserved = NULL; + return pRet; + } + } + return NULL; +} + +template< class interface_type > +inline XInterface * Reference< interface_type >::iquery( + XInterface * pInterface ) +{ + return BaseReference::iquery(pInterface, interface_type::static_type()); +} + +inline XInterface * BaseReference::iquery_throw( + XInterface * pInterface, const Type & rType ) +{ + XInterface * pQueried = iquery( pInterface, rType ); + if (pQueried) + return pQueried; + throw RuntimeException( + ::rtl::OUString( cppu_unsatisfied_iquery_msg( rType.getTypeLibType() ), SAL_NO_ACQUIRE ), + Reference< XInterface >( pInterface ) ); +} + +template< class interface_type > +inline XInterface * Reference< interface_type >::iquery_throw( + XInterface * pInterface ) +{ + return BaseReference::iquery_throw( + pInterface, interface_type::static_type()); +} + +template< class interface_type > +inline interface_type * Reference< interface_type >::iset_throw( + interface_type * pInterface ) +{ + if (pInterface) + { + castToXInterface(pInterface)->acquire(); + return pInterface; + } + throw RuntimeException( + ::rtl::OUString( cppu_unsatisfied_iset_msg( interface_type::static_type().getTypeLibType() ), SAL_NO_ACQUIRE ), + NULL ); +} + +template< class interface_type > +inline Reference< interface_type >::~Reference() COVERITY_NOEXCEPT_FALSE +{ + if (_pInterface) + _pInterface->release(); +} + +template< class interface_type > +inline Reference< interface_type >::Reference() +{ + _pInterface = NULL; +} + +template< class interface_type > +inline Reference< interface_type >::Reference( const Reference< interface_type > & rRef ) +{ + _pInterface = rRef._pInterface; + if (_pInterface) + _pInterface->acquire(); +} + +#if defined LIBO_INTERNAL_ONLY +template< class interface_type > +inline Reference< interface_type >::Reference( Reference< interface_type > && rRef ) noexcept +{ + _pInterface = rRef._pInterface; + rRef._pInterface = nullptr; +} + +template< class interface_type > template< class derived_type > +inline Reference< interface_type >::Reference( + const Reference< derived_type > & rRef, + std::enable_if_t< + std::is_base_of_v + && !std::is_same_v, void *>) +{ + interface_type * p = rRef.get(); + _pInterface = castToXInterface(p); + if (_pInterface) + _pInterface->acquire(); +} +#endif + +template< class interface_type > +inline Reference< interface_type >::Reference( interface_type * pInterface ) +{ + _pInterface = castToXInterface(pInterface); + if (_pInterface) + _pInterface->acquire(); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( interface_type * pInterface, __sal_NoAcquire ) +{ + _pInterface = castToXInterface(pInterface); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( interface_type * pInterface, UnoReference_NoAcquire ) +{ + _pInterface = castToXInterface(pInterface); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( const BaseReference & rRef, UnoReference_Query ) +{ + _pInterface = iquery( rRef.get() ); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( XInterface * pInterface, UnoReference_Query ) +{ + _pInterface = iquery( pInterface ); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( const Any & rAny, UnoReference_Query ) +{ + _pInterface = (typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass + ? iquery( static_cast< XInterface * >( rAny.pReserved ) ) : NULL); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( const BaseReference & rRef, UnoReference_QueryThrow ) +{ + _pInterface = iquery_throw( rRef.get() ); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( XInterface * pInterface, UnoReference_QueryThrow ) +{ + _pInterface = iquery_throw( pInterface ); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( const Any & rAny, UnoReference_QueryThrow ) +{ + _pInterface = iquery_throw( typelib_TypeClass_INTERFACE == rAny.pType->eTypeClass + ? static_cast< XInterface * >( rAny.pReserved ) : NULL ); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( const Reference< interface_type > & rRef, UnoReference_SetThrow ) +{ + _pInterface = castToXInterface( iset_throw( rRef.get() ) ); +} + +template< class interface_type > +inline Reference< interface_type >::Reference( interface_type * pInterface, UnoReference_SetThrow ) +{ + _pInterface = castToXInterface( iset_throw( pInterface ) ); +} + + +template< class interface_type > +inline void Reference< interface_type >::clear() +{ + if (_pInterface) + { + XInterface * const pOld = _pInterface; + _pInterface = NULL; + pOld->release(); + } +} + +template< class interface_type > +inline bool Reference< interface_type >::set( + interface_type * pInterface ) +{ + if (pInterface) + castToXInterface(pInterface)->acquire(); + XInterface * const pOld = _pInterface; + _pInterface = castToXInterface(pInterface); + if (pOld) + pOld->release(); + return (NULL != pInterface); +} + +template< class interface_type > +inline bool Reference< interface_type >::set( + interface_type * pInterface, __sal_NoAcquire ) +{ + XInterface * const pOld = _pInterface; + _pInterface = castToXInterface(pInterface); + if (pOld) + pOld->release(); + return (NULL != pInterface); +} + +template< class interface_type > +inline bool Reference< interface_type >::set( + interface_type * pInterface, UnoReference_NoAcquire ) +{ + return set( pInterface, SAL_NO_ACQUIRE ); +} + + +template< class interface_type > +inline bool Reference< interface_type >::set( + const Reference< interface_type > & rRef ) +{ + return set( castFromXInterface( rRef._pInterface ) ); +} + +template< class interface_type > +inline bool Reference< interface_type >::set( + XInterface * pInterface, UnoReference_Query ) +{ + return set( castFromXInterface(iquery( pInterface )), SAL_NO_ACQUIRE ); +} + +template< class interface_type > +inline bool Reference< interface_type >::set( + const BaseReference & rRef, UnoReference_Query ) +{ + return set( castFromXInterface(iquery( rRef.get() )), SAL_NO_ACQUIRE ); +} + + +template< class interface_type > +inline bool Reference< interface_type >::set( + Any const & rAny, UnoReference_Query ) +{ + return set( + castFromXInterface( + iquery( + rAny.pType->eTypeClass == typelib_TypeClass_INTERFACE + ? static_cast< XInterface * >( rAny.pReserved ) : NULL )), + SAL_NO_ACQUIRE ); +} + + +template< class interface_type > +inline void Reference< interface_type >::set( + XInterface * pInterface, UnoReference_QueryThrow ) +{ + set( castFromXInterface(iquery_throw( pInterface )), SAL_NO_ACQUIRE ); +} + +template< class interface_type > +inline void Reference< interface_type >::set( + const BaseReference & rRef, UnoReference_QueryThrow ) +{ + set( castFromXInterface(iquery_throw( rRef.get() )), SAL_NO_ACQUIRE ); +} + + +template< class interface_type > +inline void Reference< interface_type >::set( + Any const & rAny, UnoReference_QueryThrow ) +{ + set( castFromXInterface( + iquery_throw( + rAny.pType->eTypeClass == typelib_TypeClass_INTERFACE + ? static_cast< XInterface * >( rAny.pReserved ) : NULL )), + SAL_NO_ACQUIRE ); +} + +template< class interface_type > +inline void Reference< interface_type >::set( + interface_type * pInterface, UnoReference_SetThrow ) +{ + set( iset_throw( pInterface ), SAL_NO_ACQUIRE ); +} + +template< class interface_type > +inline void Reference< interface_type >::set( + const Reference< interface_type > & rRef, UnoReference_SetThrow ) +{ + set( rRef.get(), UNO_SET_THROW ); +} + + +template< class interface_type > +inline Reference< interface_type > & Reference< interface_type >::operator = ( + interface_type * pInterface ) +{ + set( pInterface ); + return *this; +} + +template< class interface_type > +inline Reference< interface_type > & Reference< interface_type >::operator = ( + const Reference< interface_type > & rRef ) +{ + set( castFromXInterface( rRef._pInterface ) ); + return *this; +} + +#if defined LIBO_INTERNAL_ONLY +template< class interface_type > +inline Reference< interface_type > & Reference< interface_type >::operator = ( + Reference< interface_type > && rRef ) noexcept +{ + if (_pInterface) + _pInterface->release(); + _pInterface = rRef._pInterface; + rRef._pInterface = nullptr; + return *this; +} +#endif + +template< class interface_type > +inline Reference< interface_type > Reference< interface_type >::query( + const BaseReference & rRef ) +{ + return Reference< interface_type >( + castFromXInterface(iquery( rRef.get() )), SAL_NO_ACQUIRE ); +} + +template< class interface_type > +inline Reference< interface_type > Reference< interface_type >::query( + XInterface * pInterface ) +{ + return Reference< interface_type >( + castFromXInterface(iquery( pInterface )), SAL_NO_ACQUIRE ); +} + + +inline bool BaseReference::operator == ( XInterface * pInterface ) const +{ + if (_pInterface == pInterface) + return true; + try + { + // only the query to XInterface must return the same pointer if they belong to same objects + Reference< XInterface > x1( _pInterface, UNO_QUERY ); + Reference< XInterface > x2( pInterface, UNO_QUERY ); + return (x1._pInterface == x2._pInterface); + } + catch (RuntimeException &) + { + return false; + } +} + + +inline bool BaseReference::operator < ( + const BaseReference & rRef ) const +{ + if (_pInterface == rRef._pInterface) + return false; + try + { + // only the query to XInterface must return the same pointer: + Reference< XInterface > x1( _pInterface, UNO_QUERY ); + Reference< XInterface > x2( rRef, UNO_QUERY ); + return (x1._pInterface < x2._pInterface); + } + catch (RuntimeException &) + { + return false; + } +} + + +inline bool BaseReference::operator != ( XInterface * pInterface ) const +{ + return (! operator == ( pInterface )); +} + +inline bool BaseReference::operator == ( const BaseReference & rRef ) const +{ + return operator == ( rRef._pInterface ); +} + +inline bool BaseReference::operator != ( const BaseReference & rRef ) const +{ + return (! operator == ( rRef._pInterface )); +} + +#if defined LIBO_INTERNAL_ONLY +/** + Support for BaseReference in std::ostream (and thus in CPPUNIT_ASSERT or + SAL_INFO macros, for example). + + @since LibreOffice 5.4 +*/ +template std::basic_ostream & +operator <<( + std::basic_ostream & stream, BaseReference const & ref) +{ return stream << ref.get(); } +#endif + +} +} +} +} + +#if defined LIBO_INTERNAL_ONLY +namespace std +{ + +/** + Make css::uno::Reference hashable by default for use in STL containers. + + @since LibreOffice 6.3 +*/ +template +struct hash<::css::uno::Reference> +{ + std::size_t operator()(::css::uno::Reference const & s) const + { return size_t(s.get()); } +}; + +} + +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Sequence.h b/include/com/sun/star/uno/Sequence.h new file mode 100644 index 000000000..1b9f6a2aa --- /dev/null +++ b/include/com/sun/star/uno/Sequence.h @@ -0,0 +1,361 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_SEQUENCE_H +#define INCLUDED_COM_SUN_STAR_UNO_SEQUENCE_H + +#include "typelib/typedescription.h" +#include "uno/sequence2.h" +#include "com/sun/star/uno/Type.h" +#include "rtl/alloc.h" + +#include + +#if defined LIBO_INTERNAL_ONLY +#include +#include +#endif + +namespace rtl +{ +class ByteSequence; +} + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + +/** Template C++ class representing an IDL sequence. Template argument is the + sequence element type. C++ Sequences are reference counted and shared, + so the sequence keeps a handle to its data. To keep value semantics, + copies are only generated if the sequence is to be modified (new handle). + + @tparam E element type of sequence +*/ +template< class E > +class SAL_WARN_UNUSED SAL_DLLPUBLIC_RTTI Sequence +{ + /** sequence handle + */ + uno_Sequence * _pSequence; + +public: + /// @cond INTERNAL + + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new ( ::size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete ( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new ( ::size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete ( void *, void * ) + {} + + /** Static pointer to typelib type of sequence. + Don't use directly, call getCppuType(). + */ + static typelib_TypeDescriptionReference * s_pType; + + /// @endcond + + /** typedefs the element type of the sequence + */ + typedef E ElementType; + + /** Default constructor: Creates an empty sequence. + */ + inline Sequence(); + + /** Copy constructor: Creates a copy of given sequence. + + @param rSeq another sequence of same type + */ + inline Sequence( const Sequence & rSeq ); + + /** Constructor: Takes over ownership of given sequence. + + @param pSequence a sequence + @param dummy SAL_NO_ACQUIRE to force obvious distinction to other + constructors + */ + inline Sequence( uno_Sequence * pSequence, __sal_NoAcquire dummy ); + + /** Constructor: Creates a copy of given elements. + + @param pElements an array of elements + @param len length of array + */ + inline Sequence( const E * pElements, sal_Int32 len ); + + /** Constructor: Creates a default constructed sequence of given length. + + @param len initial sequence length + */ + inline explicit Sequence( sal_Int32 len ); + +#if defined LIBO_INTERNAL_ONLY + /** Create a sequence with the given elements. + + @param init an initializer_list + + @since LibreOffice 5.0 + */ + inline Sequence(std::initializer_list init); +#endif + + /** Destructor: Releases sequence handle. Last handle will destruct + elements and free memory. + */ + inline ~Sequence(); + + /** Assignment operator: Acquires given sequence handle and releases + previously set handle. + + @param rSeq another sequence of same type + @return this sequence + */ + inline Sequence & SAL_CALL operator = ( const Sequence & rSeq ); + +#if defined LIBO_INTERNAL_ONLY + inline Sequence & operator =(Sequence && other); +#endif + + /** Gets length of the sequence. + + @return length of sequence + */ + sal_Int32 SAL_CALL getLength() const + { return _pSequence->nElements; } + + /** Tests whether the sequence has elements, i.e. elements count is + greater than zero. + + @return true, if elements count is greater than zero + */ + bool SAL_CALL hasElements() const + { return (_pSequence->nElements > 0); } + +#if defined LIBO_INTERNAL_ONLY + /** This function allows to use Sequence in cases where std::size is needed, and the like. + + @since LibreOffice 6.4 + */ + sal_uInt32 size() const + { assert(getLength() >= 0); return static_cast(getLength()); } +#endif + + /** Gets a pointer to elements array for reading. + If the sequence has a length of 0, then the returned pointer is + undefined. + + @return pointer to elements array + */ + const E * SAL_CALL getConstArray() const + { return reinterpret_cast< const E * >( _pSequence->elements ); } + + /** Gets a pointer to elements array for reading and writing. + In general if the sequence has a handle acquired by other sequences + (reference count > 1), then a new sequence is created copy constructing + all elements to keep value semantics! + If the sequence has a length of 0, then the returned pointer is + undefined. + + @return pointer to elements array + */ + inline E * SAL_CALL getArray(); + +#if !defined LIBO_INTERNAL_ONLY + /** This function allows to use Sequence in standard algorithms, like std::find + and others. + + @since LibreOffice 4.2 + */ + inline E * begin(); +#endif + + /** This function allows to use Sequence in standard algorithms, like std::find + and others. + + @since LibreOffice 4.2 + */ + inline E const * begin() const; + +#if !defined LIBO_INTERNAL_ONLY + /** This function allows to use Sequence in standard algorithms, like std::find + and others. + + @since LibreOffice 4.2 + */ + inline E * end(); +#endif + + /** This function allows to use Sequence in standard algorithms, like std::find + and others. + + @since LibreOffice 4.2 + */ + inline E const * end() const; + +// Non-const operator[] is not available in internal code. Consider explicit use +// of getArray(), out of tight loops if possible to avoid unneeded COW overhead. +#if !defined LIBO_INTERNAL_ONLY + /** Non-const index operator: Obtains a reference to element indexed at + given position. + The implementation does not check for array bounds! + In general if the sequence has a handle acquired by other sequences + (reference count > 1), then a new sequence is created copy constructing + all elements to keep value semantics! + + @param nIndex index + @return non-const C++ reference to element + */ + inline E & SAL_CALL operator [] ( sal_Int32 nIndex ); +#endif + + /** Const index operator: Obtains a reference to element indexed at + given position. The implementation does not check for array bounds! + + @param nIndex index + @return const C++ reference to element + */ + inline const E & SAL_CALL operator [] ( sal_Int32 nIndex ) const; + + /** Equality operator: Compares two sequences. + + @param rSeq another sequence of same type (right side) + @return true if both sequences are equal, false otherwise + */ + inline bool SAL_CALL operator == ( const Sequence & rSeq ) const; + + /** Inequality operator: Compares two sequences. + + @param rSeq another sequence of same type (right side) + @return false if both sequences are equal, true otherwise + */ + inline bool SAL_CALL operator != ( const Sequence & rSeq ) const; + + /** Reallocates sequence to new length. + If the new length is smaller than the former, then upper elements will + be destructed (and their memory freed). If the new length is greater + than the former, then upper (new) elements are default constructed. + If the sequence has a handle acquired by other sequences + (reference count > 1), then the remaining elements are copy constructed + to a new sequence handle to keep value semantics! + + @param nSize new size of sequence + */ + inline void SAL_CALL realloc( sal_Int32 nSize ); + + /** Provides UNacquired sequence handle. + + @return UNacquired sequence handle + */ + uno_Sequence * SAL_CALL get() const + { return _pSequence; } + +#if defined LIBO_INTERNAL_ONLY + /** Swaps sequences efficiently exchanging their underlying representations. + + @param other another sequence of same type + + @since LibreOffice 7.3 + */ + inline void swap(Sequence& other); +#endif +}; + +// Find uses of illegal Sequence (instead of Sequence) during +// compilation: +template<> class Sequence { + Sequence(Sequence const &) SAL_DELETED_FUNCTION; +}; + +/** Creates a UNO byte sequence from a SAL byte sequence. + + @param rByteSequence a byte sequence + @return a UNO byte sequence +*/ +inline ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL toUnoSequence( + const ::rtl::ByteSequence & rByteSequence ); + +} +} +} +} + +/** Gets the meta type of IDL sequence. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @tparam E element type of sequence + @return type of IDL sequence + + @deprecated + Use cppu::UnoType instead. +*/ +template< class E > SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & +SAL_CALL getCppuType( const ::com::sun::star::uno::Sequence< E > * ); + +/** Gets the meta type of IDL sequence. + This function has been introduced, because one cannot get the (templated) + cppu type out of C++ array types. + + @attention + the given element type must be the same as the template argument type! + @tparam E element type of sequence + @param rElementType element type of sequence + @return type of IDL sequence + + @deprecated + Use cppu::UnoType instead. +*/ +template< class E > SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & +SAL_CALL getCppuSequenceType( const ::com::sun::star::uno::Type & rElementType ); + +/** Gets the meta type of IDL sequence< char >. + This function has been introduced due to ambiguities with unsigned short. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL sequence< char > + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & +SAL_CALL getCharSequenceCppuType(); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Sequence.hxx b/include/com/sun/star/uno/Sequence.hxx new file mode 100644 index 000000000..34d5def3b --- /dev/null +++ b/include/com/sun/star/uno/Sequence.hxx @@ -0,0 +1,406 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_SEQUENCE_HXX +#define INCLUDED_COM_SUN_STAR_UNO_SEQUENCE_HXX + +#include "sal/config.h" + +#include +#include +#if defined LIBO_INTERNAL_ONLY +# include +# include +# include +#endif + +#include "osl/interlck.h" +#include "com/sun/star/uno/Sequence.h" +#include "typelib/typedescription.h" +#include "uno/data.h" +#include "com/sun/star/uno/genfunc.hxx" +#include "cppu/unotype.hxx" + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + +/// @cond INTERNAL +template< class E > +typelib_TypeDescriptionReference * Sequence< E >::s_pType = NULL; +/// @endcond + +template< class E > +inline Sequence< E >::Sequence() +{ + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + ::uno_type_sequence_construct( + &_pSequence, rType.getTypeLibType(), + NULL, 0, cpp_acquire ); + // no bad_alloc, because empty sequence is statically allocated in cppu +} + +template< class E > +inline Sequence< E >::Sequence( const Sequence & rSeq ) +{ + osl_atomic_increment( &rSeq._pSequence->nRefCount ); + _pSequence = rSeq._pSequence; +} + +template< class E > +inline Sequence< E >::Sequence( + uno_Sequence * pSequence, __sal_NoAcquire ) + : _pSequence( pSequence ) +{ +} + +template< class E > +inline Sequence< E >::Sequence( const E * pElements, sal_Int32 len ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + + bool success = + ::uno_type_sequence_construct( + &_pSequence, rType.getTypeLibType(), + const_cast< E * >( pElements ), len, cpp_acquire ); + if (! success) + throw ::std::bad_alloc(); +} + +template< class E > +inline Sequence< E >::Sequence( sal_Int32 len ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + bool success = + ::uno_type_sequence_construct( + &_pSequence, rType.getTypeLibType(), + NULL, len, cpp_acquire ); + if (! success) + throw ::std::bad_alloc(); +} + +#if defined LIBO_INTERNAL_ONLY +template Sequence::Sequence(std::initializer_list init) { + if (!uno_type_sequence_construct( + &_pSequence, cppu::getTypeFavourUnsigned(this).getTypeLibType(), + const_cast(init.begin()), init.size(), cpp_acquire)) + { + throw std::bad_alloc(); + } +} +#endif + +template< class E > +inline Sequence< E >::~Sequence() +{ + if (osl_atomic_decrement( &_pSequence->nRefCount ) == 0) + { + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + uno_type_sequence_destroy( + _pSequence, rType.getTypeLibType(), cpp_release ); + } +} + +template< class E > +inline Sequence< E > & Sequence< E >::operator = ( const Sequence & rSeq ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + ::uno_type_sequence_assign( + &_pSequence, rSeq._pSequence, rType.getTypeLibType(), cpp_release ); + return *this; +} + +#if defined LIBO_INTERNAL_ONLY +template Sequence & Sequence::operator =(Sequence && other) { + std::swap(_pSequence, other._pSequence); + return *this; +} +#endif + +template< class E > +inline bool Sequence< E >::operator == ( const Sequence & rSeq ) const +{ + if (_pSequence == rSeq._pSequence) + return true; + if (_pSequence->nElements != rSeq._pSequence->nElements) + return false; + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + return ::uno_type_equalData( + const_cast< Sequence * >( this ), rType.getTypeLibType(), + const_cast< Sequence * >( &rSeq ), rType.getTypeLibType(), + cpp_queryInterface, + cpp_release ); +} + +template< class E > +inline bool Sequence< E >::operator != ( const Sequence & rSeq ) const +{ + return (! operator == ( rSeq )); +} + +template< class E > +inline E * Sequence< E >::getArray() +{ + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + bool success = + ::uno_type_sequence_reference2One( + &_pSequence, rType.getTypeLibType(), + cpp_acquire, cpp_release ); + if (! success) + throw ::std::bad_alloc(); + return reinterpret_cast< E * >( _pSequence->elements ); +} + +#if !defined LIBO_INTERNAL_ONLY +template E * Sequence::begin() { return getArray(); } +#endif + +template E const * Sequence::begin() const +{ return getConstArray(); } + +#if !defined LIBO_INTERNAL_ONLY +template E * Sequence::end() { return begin() + getLength(); } +#endif + +template E const * Sequence::end() const +{ return begin() + getLength(); } + +#if !defined LIBO_INTERNAL_ONLY +template< class E > +inline E & Sequence< E >::operator [] ( sal_Int32 nIndex ) +{ + // silence spurious -Werror=strict-overflow warnings from GCC 4.8.2 + assert(nIndex >= 0 && static_cast(nIndex) < static_cast(getLength())); + return getArray()[ nIndex ]; +} +#endif + +template< class E > +inline const E & Sequence< E >::operator [] ( sal_Int32 nIndex ) const +{ + // silence spurious -Werror=strict-overflow warnings from GCC 4.8.2 + assert(nIndex >= 0 && static_cast(nIndex) < static_cast(getLength())); + return reinterpret_cast< const E * >( _pSequence->elements )[ nIndex ]; +} + +template< class E > +inline void Sequence< E >::realloc( sal_Int32 nSize ) +{ + const Type & rType = ::cppu::getTypeFavourUnsigned( this ); + bool success = + ::uno_type_sequence_realloc( + &_pSequence, rType.getTypeLibType(), nSize, + cpp_acquire, cpp_release ); + if (!success) + throw ::std::bad_alloc(); +} + +#if defined LIBO_INTERNAL_ONLY +template inline void Sequence::swap(Sequence& other) +{ + std::swap(_pSequence, other._pSequence); +} +#endif + +inline ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL toUnoSequence( + const ::rtl::ByteSequence & rByteSequence ) +{ + return * reinterpret_cast< const ::com::sun::star::uno::Sequence< sal_Int8 > * >( &rByteSequence ); +} + +#if defined LIBO_INTERNAL_ONLY + +/// @cond INTERNAL + +namespace uno_detail { + +template< typename value_t, typename charT, typename traits > +void sequence_output_elems( std::basic_ostream &os, const value_t *pAry, sal_Int32 nLen, std::true_type ) +{ + // for integral types, use hex notation + auto const flags = os.setf(std::ios_base::hex); + for(sal_Int32 i=0; i 1 ) + os << "0x" << *pAry++; + os.setf(flags); +} + +template< typename value_t, typename charT, typename traits > +void sequence_output_elems( std::basic_ostream &os, const value_t *pAry, sal_Int32 nLen, std::false_type ) +{ + // every other type: rely on their own ostream operator<< + for(sal_Int32 i=0; i 1 ) + os << *pAry++; +} + +template< typename value_t, typename charT, typename traits > +void sequence_output_bytes( std::basic_ostream &os, const value_t *pAry, sal_Int32 nLen ) +{ + // special case bytes - ostream operator<< outputs those as char + // values, but we need raw ints here + auto const flags = os.setf(std::ios_base::hex); + for(sal_Int32 i=0; i 1 ) + os << "0x" << (0xFF & +*pAry++); + os.setf(flags); +} + +} + +/** + Support for Sequence in std::ostream (and thus in CPPUNIT_ASSERT or SAL_INFO + macros, for example). + + @since LibreOffice 6.1 +*/ +template< typename value_t, typename charT, typename traits > +inline std::basic_ostream &operator<<(std::basic_ostream &os, css::uno::Sequence const& v) +{ + const value_t *pAry = v.getConstArray(); + sal_Int32 nLen = v.getLength(); + if constexpr (std::is_same::value) { + uno_detail::sequence_output_bytes(os, pAry, nLen); + } else { + uno_detail::sequence_output_elems(os, pAry, nLen, std::is_integral()); + } + return os; +} + +template inline auto asNonConstRange(css::uno::Sequence& s) +{ + // Two iterators [begin, end] representing the non-const range of the Sequence. + // It only calls Sequence::getArray once, to avoid the second COW overhead when + // Sequence::begin() and Sequence::end() are called in pairs. + // Inheriting from pair allows to use std::tie to unpack the two iterators. + struct SequenceRange : public std::pair + { + SequenceRange(E* ptr, sal_Int32 len) : std::pair(ptr, ptr + len) {} + // These allow to pass it as range-expression to range-based for loops + E* begin() { return std::pair::first; } + E* end() { return std::pair::second; } + E& operator[](sal_Int32 i) { assert(i >= 0 && i < end() - begin()); return begin()[i]; } + }; + return SequenceRange(s.getLength() ? s.getArray() : nullptr, s.getLength()); +}; + +/// @endcond + +#endif + +} +} +} +} + +namespace cppu { + +template< typename T > inline ::com::sun::star::uno::Type const & +getTypeFavourUnsigned( + SAL_UNUSED_PARAMETER ::com::sun::star::uno::Sequence< T > const *) +{ + if (::com::sun::star::uno::Sequence< T >::s_pType == NULL) { + ::typelib_static_sequence_type_init( + &::com::sun::star::uno::Sequence< T >::s_pType, + (::cppu::getTypeFavourUnsigned( + static_cast< + typename ::com::sun::star::uno::Sequence< T >::ElementType * >( + NULL)). + getTypeLibType())); + } + return detail::getTypeFromTypeDescriptionReference( + &::com::sun::star::uno::Sequence< T >::s_pType); +} + +template< typename T > inline ::com::sun::star::uno::Type const & +getTypeFavourChar( + SAL_UNUSED_PARAMETER ::com::sun::star::uno::Sequence< T > const *) +{ + //TODO On certain platforms with weak memory models, the following code can + // result in some threads observing that td points to garbage: + static typelib_TypeDescriptionReference * td = NULL; + if (td == NULL) { + ::typelib_static_sequence_type_init( + &td, + (::cppu::getTypeFavourChar( + static_cast< + typename ::com::sun::star::uno::Sequence< T >::ElementType * >( + NULL)). + getTypeLibType())); + } + return detail::getTypeFromTypeDescriptionReference(&td); +} + +} + +// generic sequence template +template< class E > +inline const ::com::sun::star::uno::Type & +SAL_CALL getCppuType( + SAL_UNUSED_PARAMETER const ::com::sun::star::uno::Sequence< E > * ) +{ + return ::cppu::getTypeFavourUnsigned( + static_cast< ::com::sun::star::uno::Sequence< E > * >(0)); +} + +// generic sequence template for given element type (e.g. C++ arrays) +template< class E > +inline const ::com::sun::star::uno::Type & +SAL_CALL getCppuSequenceType( const ::com::sun::star::uno::Type & rElementType ) +{ + if (! ::com::sun::star::uno::Sequence< E >::s_pType) + { + ::typelib_static_sequence_type_init( + & ::com::sun::star::uno::Sequence< E >::s_pType, + rElementType.getTypeLibType() ); + } + return * reinterpret_cast< const ::com::sun::star::uno::Type * >( + & ::com::sun::star::uno::Sequence< E >::s_pType ); +} + +// char sequence +inline const ::com::sun::star::uno::Type & +SAL_CALL getCharSequenceCppuType() +{ + static typelib_TypeDescriptionReference * s_pType_com_sun_star_uno_Sequence_Char = NULL; + if (! s_pType_com_sun_star_uno_Sequence_Char) + { + const ::com::sun::star::uno::Type & rElementType = cppu::UnoType::get(); + ::typelib_static_sequence_type_init( + & s_pType_com_sun_star_uno_Sequence_Char, + rElementType.getTypeLibType() ); + } + return * reinterpret_cast< const ::com::sun::star::uno::Type * >( + & s_pType_com_sun_star_uno_Sequence_Char ); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Type.h b/include/com/sun/star/uno/Type.h new file mode 100644 index 000000000..5dc1b41e0 --- /dev/null +++ b/include/com/sun/star/uno/Type.h @@ -0,0 +1,502 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_TYPE_H +#define INCLUDED_COM_SUN_STAR_UNO_TYPE_H + +#include "typelib/typedescription.h" +#include "com/sun/star/uno/TypeClass.hdl" +#include "rtl/ustring.hxx" +#include "rtl/alloc.h" + + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + +/** Enum defining UNO_TYPE_NO_ACQUIRE for type description reference transfer. +*/ +enum UnoType_NoAcquire +{ + /** This enum value can be used for creating a Type object granting a given type description + reference, i.e. transferring ownership to it. + */ + UNO_TYPE_NO_ACQUIRE +}; + +/** C++ class representing an IDL meta type. This class is used to represent a type, + i.e. a type name and its type class. + Internally the type holds a C type description reference of the runtime. + You can obtain a full type description of a type by calling member function getDescription(). + + @see typelib_TypeDescriptionReference +*/ +class SAL_WARN_UNUSED SAL_DLLPUBLIC_RTTI Type +{ + /** the C typelib reference pointer + */ + typelib_TypeDescriptionReference * _pType; + +public: + /// @cond INTERNAL + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new ( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete ( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new ( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete ( void *, void * ) + {} + /// @endcond + + /** Default Constructor: Type is set to void. + */ + inline Type(); + + /** Constructor: Type is constructed by given name and type class. + + @param eTypeClass type class of type + @param rTypeName name of type + */ + inline Type( TypeClass eTypeClass, const ::rtl::OUString & rTypeName ); + + /** Constructor: Type is constructed by given name and type class. + + @param eTypeClass type class of type + @param pTypeName name of type + */ + inline Type( TypeClass eTypeClass, const char * pTypeName ); + + /** Constructor: Type is (copy) constructed by given C type description reference. + + @param pType C type description reference + */ + inline Type( typelib_TypeDescriptionReference * pType ); + + /** Constructor: Type is (copy) constructed by given C type description reference + without acquiring it. + + @param pType C type description reference + @param dummy UNO_TYPE_NO_ACQUIRE to force obvious distinction to other constructors + */ + inline Type( typelib_TypeDescriptionReference * pType, UnoType_NoAcquire dummy ); + /** Constructor: Type is (copy) constructed by given C type description reference + without acquiring it. + + @param pType C type description reference + @param dummy SAL_NO_ACQUIRE to force obvious distinction to other constructors + */ + inline Type( typelib_TypeDescriptionReference * pType, __sal_NoAcquire dummy ); + + /** Copy constructor: Type is copy constructed by given type. + + @param rType another type + */ + inline Type( const Type & rType ); + + /** Destructor: Releases acquired C type description reference. + */ + ~Type() + { ::typelib_typedescriptionreference_release( _pType ); } + + /** Assignment operator: Acquires right side type and releases previously set type. + + @param rType another type (right side) + @return this type + */ + inline Type & SAL_CALL operator = ( const Type & rType ); + +#if defined LIBO_INTERNAL_ONLY + inline Type & SAL_CALL operator = ( Type && ); +#endif + + /** Gets the type class of set type. + + @return type class of set type + */ + TypeClass SAL_CALL getTypeClass() const + { return static_cast(_pType->eTypeClass); } + + /** Gets the name of the set type. + + @return name of the set type + */ + inline ::rtl::OUString SAL_CALL getTypeName() const; + + /** Obtains a full type description of set type. + + @param ppDescr [inout] type description + */ + void SAL_CALL getDescription( typelib_TypeDescription ** ppDescr ) const + { ::typelib_typedescriptionreference_getDescription( ppDescr, _pType ); } + + /** Gets the C typelib type description reference pointer. Does not acquire the reference! + + @return UNacquired type description reference + */ + typelib_TypeDescriptionReference * SAL_CALL getTypeLibType() const + { return _pType; } + + /** Tests if values of this reflected type can be assigned by values of given type. + This includes widening conversion (e.g., long assignable from short), as long as there + is no data loss. + + @param rType another type + @return true if values of this type can be assigned from values of given type, + false otherwise + */ + bool SAL_CALL isAssignableFrom( const Type & rType ) const + { return ::typelib_typedescriptionreference_isAssignableFrom( _pType, rType._pType ); } + + /** Compares two types. + + @param rType another type + @return true if both types refer the same type, false otherwise + */ + bool SAL_CALL equals( const Type & rType ) const + { return ::typelib_typedescriptionreference_equals( _pType, rType._pType ); } + /** Equality operator: Compares two types. + + @param rType another type + @return true if both types refer the same type, false otherwise + */ + bool SAL_CALL operator == ( const Type & rType ) const + { return ::typelib_typedescriptionreference_equals( _pType, rType._pType ); } + /** Inequality operator: Compares two types. + + @param rType another type + @return false if both types refer the same type, true otherwise + */ + bool SAL_CALL operator != ( const Type & rType ) const + { return (! ::typelib_typedescriptionreference_equals( _pType, rType._pType )); } +}; + +/** Helper class to specify a type pointer for idl arrays. +*/ +template< class T > +class Array +{ +public: + static typelib_TypeDescriptionReference * s_pType; +}; + +} +} +} +} + +/** Gets the meta type of IDL type "type". + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type "type" + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const ::com::sun::star::uno::Type * ); + +/** Gets the meta type of IDL type void. + @return type of IDL type void + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuVoidType(); +/** Gets the meta type of IDL type void. + + @return type of IDL type void + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getVoidCppuType(); + +/** Gets the meta type of IDL type boolean. + + @return type of IDL type boolean + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuBooleanType(); +/** Gets the meta type of IDL type boolean. + + @return type of IDL type boolean + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getBooleanCppuType(); +/** Gets the meta type of IDL type boolean. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type boolean + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_Bool * ); +/** Gets the meta type of IDL type boolean. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type boolean + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( + bool const * ); + +/** Gets the meta type of IDL type char. + + @return type of IDL type char + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCharCppuType(); +/** Gets the meta type of IDL type char. + + @return type of IDL type char + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuCharType(); + +/** Gets the meta type of IDL type byte. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type byte + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_Int8 * ); + +/** Gets the meta type of IDL type string. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type string + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const ::rtl::OUString * ); + +/** Gets the meta type of IDL type short. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type short + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_Int16 * ); + +/** Gets the meta type of IDL type unsigned short. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type unsigned short + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_uInt16 * ); + +/** Gets the meta type of IDL type long. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type long + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_Int32 * ); + +/** Gets the meta type of IDL type unsigned long. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type unsigned long + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_uInt32 * ); + +/** Gets the meta type of IDL type hyper. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type hyper + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_Int64 * ); + +/** Gets the meta type of IDL type unsigned hyper. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type unsigned hyper + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const sal_uInt64 * ); + +/** Gets the meta type of IDL type float. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type float + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const float * ); + +/** Gets the meta type of IDL type double. + + There are cases (involving templates) where uses of getCppuType are known to + not compile. Use cppu::UnoType or cppu::getTypeFavourUnsigned instead. + + The dummy parameter is just a typed pointer for function signature. + + @return type of IDL type double + + @deprecated + Use cppu::UnoType instead. +*/ +SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( const double * ); + +/** Gets the meta type of an IDL type. + + The difference between this function template (with a type parameter) and + the overloaded getCppuType function with a single (dummy) parameter of a + specific type is that this function template may not work for the UNO type + "unsigned short" (sal_uInt16 in C++), while the overloaded one-parameter + function may not work for the UNO type "char" (sal_Unicode in C++, which may + have the same underlying C++ type as sal_uInt16 on certain platforms). + + @return type of the given IDL type + + @deprecated + Use cppu::UnoType instead (or the internal-only cppu::getTypeFavourChar). + Also note that getCppuType< com::sun::star::uno::Sequence< sal_Unicode > >() + does not work as expected. + + @since UDK 3.2.0 +*/ +template< typename T > SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL +getCppuType(); + +/** Gets the meta type of IDL type char. + + @return type of IDL type char + + @deprecated + Use cppu::UnoType instead (or the internal-only cppu::getTypeFavourChar). + Also note that getCppuType< com::sun::star::uno::Sequence< sal_Unicode > >() + does not work as expected. + + @since UDK 3.2.0 +*/ +template<> SAL_DEPRECATED("use cppu::UnoType") +inline const ::com::sun::star::uno::Type & SAL_CALL +getCppuType< sal_Unicode >(); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/Type.hxx b/include/com/sun/star/uno/Type.hxx new file mode 100644 index 000000000..f62d0a17b --- /dev/null +++ b/include/com/sun/star/uno/Type.hxx @@ -0,0 +1,231 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_TYPE_HXX +#define INCLUDED_COM_SUN_STAR_UNO_TYPE_HXX + +#include "sal/config.h" + +#include +#include + +#include "com/sun/star/uno/Type.h" +#include "cppu/unotype.hxx" + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + + +inline Type::Type() +{ + _pType = reinterpret_cast< const ::com::sun::star::uno::Type * >( + ::typelib_static_type_getByTypeClass( typelib_TypeClass_VOID ) )->getTypeLibType(); + ::typelib_typedescriptionreference_acquire( _pType ); +} + +inline Type::Type( TypeClass eTypeClass, const ::rtl::OUString & rTypeName ) + : _pType( NULL ) +{ + ::typelib_typedescriptionreference_new( &_pType, static_cast(eTypeClass), rTypeName.pData ); +} + +inline Type::Type( TypeClass eTypeClass, const char * pTypeName ) + : _pType( NULL ) +{ + ::typelib_typedescriptionreference_newByAsciiName( &_pType, static_cast(eTypeClass), pTypeName ); +} + +inline Type::Type( typelib_TypeDescriptionReference * pType ) + : _pType( pType ) +{ + ::typelib_typedescriptionreference_acquire( _pType ); +} + +inline Type::Type( typelib_TypeDescriptionReference * pType, UnoType_NoAcquire ) + : _pType( pType ) +{ +} + +inline Type::Type( typelib_TypeDescriptionReference * pType, __sal_NoAcquire ) + : _pType( pType ) +{ +} + +inline Type::Type( const Type & rType ) + : _pType( rType._pType ) +{ + ::typelib_typedescriptionreference_acquire( _pType ); +} + +inline ::rtl::OUString Type::getTypeName() const +{ + return ::rtl::OUString( _pType->pTypeName ); +} + +inline Type & Type::operator = ( const Type & rType ) +{ + ::typelib_typedescriptionreference_assign( &_pType, rType._pType ); + return *this; +} + +#if defined LIBO_INTERNAL_ONLY +inline Type & Type::operator = ( Type && rType ) +{ + std::swap(_pType, rType._pType); + return *this; +} +#endif + + +template< class T > +typelib_TypeDescriptionReference * Array< T >::s_pType = NULL; + +#if defined LIBO_INTERNAL_ONLY +/** + Support for Type in std::ostream (and thus in CPPUNIT_ASSERT or SAL_INFO + macros, for example). + + @since LibreOffice 5.4 +*/ +template std::basic_ostream & +operator <<(std::basic_ostream & stream, Type const & type) +{ return stream << type.getTypeName(); } +#endif + +} +} +} +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const ::com::sun::star::uno::Type * ) +{ + return ::cppu::UnoType< ::com::sun::star::uno::Type >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuVoidType() +{ + return ::cppu::UnoType::get(); +} +inline const ::com::sun::star::uno::Type & SAL_CALL getVoidCppuType() +{ + return ::cppu::UnoType::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuBooleanType() +{ + return ::cppu::UnoType< bool >::get(); +} +inline const ::com::sun::star::uno::Type & SAL_CALL getBooleanCppuType() +{ + return ::cppu::UnoType< bool >::get(); +} +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_Bool * ) +{ + return ::cppu::UnoType< bool >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( + SAL_UNUSED_PARAMETER bool const * ) +{ + return ::cppu::UnoType< bool >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCharCppuType() +{ + return ::cppu::UnoType< ::cppu::UnoCharType >::get(); +} +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuCharType() +{ + return ::cppu::UnoType< ::cppu::UnoCharType >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_Int8 * ) +{ + return ::cppu::UnoType< ::sal_Int8 >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const ::rtl::OUString * ) +{ + return ::cppu::UnoType< ::rtl::OUString >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_Int16 * ) +{ + return ::cppu::UnoType< ::sal_Int16 >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_uInt16 * ) +{ + return ::cppu::UnoType< ::cppu::UnoUnsignedShortType >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_Int32 * ) +{ + return ::cppu::UnoType< ::sal_Int32 >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_uInt32 * ) +{ + return ::cppu::UnoType< ::sal_uInt32 >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_Int64 * ) +{ + return ::cppu::UnoType< ::sal_Int64 >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const sal_uInt64 * ) +{ + return ::cppu::UnoType< ::sal_uInt64 >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const float * ) +{ + return ::cppu::UnoType< float >::get(); +} + +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType( SAL_UNUSED_PARAMETER const double * ) +{ + return ::cppu::UnoType< double >::get(); +} + +template< typename T > +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType() +{ + return ::cppu::UnoType< T >::get(); +} + +template<> +inline const ::com::sun::star::uno::Type & SAL_CALL getCppuType< sal_Unicode >() +{ + return ::cppu::UnoType< ::cppu::UnoCharType >::get(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/genfunc.h b/include/com/sun/star/uno/genfunc.h new file mode 100644 index 000000000..4ec0ec203 --- /dev/null +++ b/include/com/sun/star/uno/genfunc.h @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_GENFUNC_H +#define INCLUDED_COM_SUN_STAR_UNO_GENFUNC_H + +#include "sal/types.h" + +typedef struct _typelib_TypeDescriptionReference typelib_TypeDescriptionReference; + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ +/** Function to acquire a C++ interface. + + @param pCppI C++ interface pointer +*/ +inline void SAL_CALL cpp_acquire(void* pCppI); +/** Function to release a C++ interface. + + @param pCppI C++ interface pointer +*/ +inline void SAL_CALL cpp_release(void* pCppI); +/** Function to query for a C++ interface. + + @param pCppI C++ interface pointer + @param pType demanded interface type + @return acquired C++ interface pointer or null +*/ +inline void* SAL_CALL cpp_queryInterface(void* pCppI, typelib_TypeDescriptionReference* pType); +} +} +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/com/sun/star/uno/genfunc.hxx b/include/com/sun/star/uno/genfunc.hxx new file mode 100644 index 000000000..ad1b8bc7e --- /dev/null +++ b/include/com/sun/star/uno/genfunc.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_COM_SUN_STAR_UNO_GENFUNC_HXX +#define INCLUDED_COM_SUN_STAR_UNO_GENFUNC_HXX + +#include "sal/config.h" + +#include + +#include "com/sun/star/uno/genfunc.h" +#include "com/sun/star/uno/Any.hxx" +#include "com/sun/star/uno/XInterface.hpp" + + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + + +inline void SAL_CALL cpp_acquire( void * pCppI ) +{ + static_cast< XInterface * >( pCppI )->acquire(); +} + +inline void SAL_CALL cpp_release( void * pCppI ) +{ + static_cast< XInterface * >( pCppI )->release(); +} + +inline void * SAL_CALL cpp_queryInterface( void * pCppI, typelib_TypeDescriptionReference * pType ) +{ + if (pCppI) + { + try + { + Any aRet( static_cast< XInterface * >( pCppI )->queryInterface( + * reinterpret_cast< const Type * >( &pType ) ) ); + if (typelib_TypeClass_INTERFACE == aRet.pType->eTypeClass) + { + XInterface * pRet = static_cast< XInterface * >( aRet.pReserved ); + aRet.pReserved = NULL; + return pRet; + } + } + catch (RuntimeException &) + { + } + } + return NULL; +} + +} +} +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/AccessibleImplementationHelper.hxx b/include/comphelper/AccessibleImplementationHelper.hxx new file mode 100644 index 000000000..b6c8d9ab0 --- /dev/null +++ b/include/comphelper/AccessibleImplementationHelper.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace com::sun::star::awt +{ +struct KeyStroke; +} +namespace com::sun::star::uno +{ +template class Sequence; +} + +namespace comphelper +{ +/** + * Helper function used for converting keybinding to string. + * + * @param keySet the key stroke sequence. + */ +COMPHELPER_DLLPUBLIC OUString +GetkeyBindingStrByXkeyBinding(const css::uno::Sequence& keySet); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/comphelper/ChainablePropertySet.hxx b/include/comphelper/ChainablePropertySet.hxx new file mode 100644 index 000000000..fb4fbd744 --- /dev/null +++ b/include/comphelper/ChainablePropertySet.hxx @@ -0,0 +1,148 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_CHAINABLEPROPERTYSET_HXX +#define INCLUDED_COMPHELPER_CHAINABLEPROPERTYSET_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper { class SolarMutex; } +namespace comphelper { struct PropertyInfo; } + +namespace comphelper +{ + class ChainablePropertySetInfo; +} + +/* + * A ChainablePropertySet has the following features: + * + * 1. It implements both the PropertySet and MultiPropertySet interfaces. + * 2. It can be 'included' in a MasterPropertySet to seamlessly appear as if + * if it's properties were in the master. + * + * To be used as a base class for PropertySets, the subclass must implement + * the 6 protected pure virtual functions. If a mutex is passed to the + * constructor, this is locked before any call to _getSingleValue or + * _setSingleValue and released after all processing has completed + * (including _postSetValues or _postGetValues ) + * + * Any MasterPropertySet implementations that can include an + * implementation of a given ChainablePropertySet must be + * declared as a 'friend' in the implementation of the ChainablePropertySet. + * + */ + +namespace comphelper +{ + typedef cppu::WeakImplHelper + < + css::beans::XPropertySet, + css::beans::XMultiPropertySet, + css::lang::XServiceInfo + > + ChainablePropertySetBase; + class COMPHELPER_DLLPUBLIC ChainablePropertySet : public ChainablePropertySetBase, + public css::beans::XPropertyState + { + friend class MasterPropertySet; + protected: + SolarMutex* const mpMutex; + rtl::Reference < ChainablePropertySetInfo > mxInfo; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _preSetValues () = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _setSingleValue(const comphelper::PropertyInfo & rInfo, const css::uno::Any &rValue) = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _postSetValues () = 0; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _preGetValues () = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _getSingleValue( const comphelper::PropertyInfo & rInfo, css::uno::Any & rValue ) = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + virtual void _postGetValues () = 0; + + public: + ChainablePropertySet( comphelper::ChainablePropertySetInfo* pInfo, SolarMutex* pMutex ) + noexcept; + virtual ~ChainablePropertySet() + noexcept override; + + css::uno::Any SAL_CALL queryInterface( const css::uno::Type& aType ) override + { return ChainablePropertySetBase::queryInterface( aType ); } + void SAL_CALL acquire( ) noexcept override + { ChainablePropertySetBase::acquire( ); } + void SAL_CALL release( ) noexcept override + { ChainablePropertySetBase::release( ); } + + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; + virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; + virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; + virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + + // XMultiPropertySet + virtual void SAL_CALL setPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Sequence< css::uno::Any >& aValues ) override; + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames ) override; + virtual void SAL_CALL addPropertiesChangeListener( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertiesChangeListener( const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL firePropertiesChangeEvent( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + + // XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState( const OUString& PropertyName ) override; + virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) override; + virtual void SAL_CALL setPropertyToDefault( const OUString& PropertyName ) override; + virtual css::uno::Any SAL_CALL getPropertyDefault( const OUString& aPropertyName ) override; + }; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/ChainablePropertySetInfo.hxx b/include/comphelper/ChainablePropertySetInfo.hxx new file mode 100644 index 000000000..5ece0701c --- /dev/null +++ b/include/comphelper/ChainablePropertySetInfo.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_CHAINABLEPROPERTYSETINFO_HXX +#define INCLUDED_COMPHELPER_CHAINABLEPROPERTYSETINFO_HXX + +#include +#include +#include +#include + +/* + * A ChainablePropertySetInfo is usually initialised with a pointer to the first element + * of a null-terminated static table of PropertyInfo structs. This is placed in a hash_map + * for fast access + * + */ +namespace comphelper +{ + // workaround for incremental linking bugs in MSVC2015 + class SAL_DLLPUBLIC_TEMPLATE ChainablePropertySetInfo_Base : public cppu::WeakImplHelper< css::beans::XPropertySetInfo > {}; + + class COMPHELPER_DLLPUBLIC ChainablePropertySetInfo final : public ChainablePropertySetInfo_Base + { + public: + ChainablePropertySetInfo( PropertyInfo const * pMap ); + + void remove( const OUString& aName ); + + private: + virtual ~ChainablePropertySetInfo() + noexcept override; + + // XPropertySetInfo + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() override; + virtual css::beans::Property SAL_CALL getPropertyByName( const OUString& aName ) override; + virtual sal_Bool SAL_CALL hasPropertyByName( const OUString& Name ) override; + + PropertyInfoHash maMap; + css::uno::Sequence < css::beans::Property > maProperties; + + friend class ChainablePropertySet; + friend class MasterPropertySet; + }; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/DirectoryHelper.hxx b/include/comphelper/DirectoryHelper.hxx new file mode 100644 index 000000000..321e9f960 --- /dev/null +++ b/include/comphelper/DirectoryHelper.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace comphelper +{ +class COMPHELPER_DLLPUBLIC DirectoryHelper +{ +public: + static std::u16string_view splitAtLastToken(std::u16string_view rSrc, sal_Unicode aToken, + OUString& rRight); + static bool fileExists(const OUString& rBaseURL); + static bool dirExists(const OUString& rDirURL); + + // all rDirs and rFiles strings are already URI encoded, so safe for concat + static void scanDirsAndFiles(const OUString& rDirURL, std::set& rDirs, + std::set>& rFiles); + static bool deleteDirRecursively(const OUString& rDirURL); + static bool moveDirContent(const OUString& rSourceDirURL, std::u16string_view rTargetDirURL, + const std::set& rExcludeList); +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/IdPropArrayHelper.hxx b/include/comphelper/IdPropArrayHelper.hxx new file mode 100644 index 000000000..8b70db849 --- /dev/null +++ b/include/comphelper/IdPropArrayHelper.hxx @@ -0,0 +1,106 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include +#include +#include + +namespace comphelper +{ + + typedef std::unordered_map< sal_Int32, ::cppu::IPropertyArrayHelper* > OIdPropertyArrayMap; + template + class OIdPropertyArrayUsageHelper + { + public: + OIdPropertyArrayUsageHelper(); + virtual ~OIdPropertyArrayUsageHelper() + { + std::unique_lock aGuard(theMutex()); + assert(s_nRefCount > 0 && "OIdPropertyArrayUsageHelper::~OIdPropertyArrayUsageHelper : suspicious call : have a refcount of 0 !"); + if (!--s_nRefCount) + { + // delete the element + for (auto const& elem : *s_pMap) + delete elem.second; + delete s_pMap; + s_pMap = nullptr; + } + } + + /** call this in the getInfoHelper method of your derived class. The method returns the array helper of the + class, which is created if necessary. + */ + ::cppu::IPropertyArrayHelper* getArrayHelper(sal_Int32 nId); + + protected: + /** used to implement the creation of the array helper which is shared amongst all instances of the class. + This method needs to be implemented in derived classes. +
+ The method gets called with Mutex acquired. + @return a pointer to the newly created array helper. Must not be NULL. + */ + virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 nId) const = 0; + private: + static sal_Int32 s_nRefCount; + static OIdPropertyArrayMap* s_pMap; + static std::mutex& theMutex() + { + static std::mutex SINGLETON; + return SINGLETON; + } + }; + + template + sal_Int32 OIdPropertyArrayUsageHelper< TYPE >::s_nRefCount = 0; + + template + OIdPropertyArrayMap* OIdPropertyArrayUsageHelper< TYPE >::s_pMap = nullptr; + + template + OIdPropertyArrayUsageHelper::OIdPropertyArrayUsageHelper() + { + std::unique_lock aGuard(theMutex()); + // create the map if necessary + if (!s_pMap) + s_pMap = new OIdPropertyArrayMap; + ++s_nRefCount; + } + + template + ::cppu::IPropertyArrayHelper* OIdPropertyArrayUsageHelper::getArrayHelper(sal_Int32 nId) + { + assert(s_nRefCount && "OIdPropertyArrayUsageHelper::getArrayHelper : suspicious call : have a refcount of 0 !"); + std::unique_lock aGuard(theMutex()); + // do we have the array already? + auto& rEntry = (*s_pMap)[nId]; + if (!rEntry) + { + rEntry = createArrayHelper(nId); + assert(rEntry && "OIdPropertyArrayUsageHelper::getArrayHelper : createArrayHelper returned nonsense !"); + } + return (*s_pMap)[nId]; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/MasterPropertySet.hxx b/include/comphelper/MasterPropertySet.hxx new file mode 100644 index 000000000..acd9ce9c4 --- /dev/null +++ b/include/comphelper/MasterPropertySet.hxx @@ -0,0 +1,135 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_MASTERPROPERTYSET_HXX +#define INCLUDED_COMPHELPER_MASTERPROPERTYSET_HXX +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper { class SolarMutex; } +namespace comphelper { struct PropertyInfo; } + +namespace comphelper +{ + class MasterPropertySetInfo; + class ChainablePropertySet; + struct SlaveData + { + rtl::Reference < ChainablePropertySet > mxSlave; + bool mbInit; + + SlaveData ( ChainablePropertySet *pSlave); + bool IsInit () const { return mbInit;} + void SetInit ( bool bInit) { mbInit = bInit; } + }; +} + +/* + * A MasterPropertySet implements all of the features of a ChainablePropertySet + * (it is not inherited from ChainablePropertySet to prevent MasterPropertySets + * being chained to each other), but also allows properties implemented in + * other ChainablePropertySets to be included as 'native' properties in a + * given MasterPropertySet implementation. These are registered using the + * 'registerSlave' method, and require that the implementation of the + * ChainablePropertySet and the implementation of the ChainablePropertySetInfo + * both declare the implementation of the MasterPropertySet as a friend. + */ +namespace comphelper +{ + class COMPHELPER_DLLPUBLIC MasterPropertySet : public css::beans::XPropertySet, + public css::beans::XPropertyState, + public css::beans::XMultiPropertySet + { + protected: + SolarMutex* const mpMutex; + sal_uInt8 mnLastId; + std::map< sal_uInt8, comphelper::SlaveData* > maSlaveMap; + rtl::Reference< MasterPropertySetInfo > mxInfo; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + virtual void _preSetValues () = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _setSingleValue( const comphelper::PropertyInfo & rInfo, const css::uno::Any &rValue ) = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + virtual void _postSetValues () = 0; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + virtual void _preGetValues () = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _getSingleValue( const comphelper::PropertyInfo & rInfo, css::uno::Any & rValue ) = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + virtual void _postGetValues () = 0; + + public: + MasterPropertySet( comphelper::MasterPropertySetInfo* pInfo, SolarMutex* pMutex ) + noexcept; + virtual ~MasterPropertySet() + noexcept; + void registerSlave ( ChainablePropertySet *pNewSet ) + noexcept; + + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; + virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; + virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; + virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + + // XMultiPropertySet + virtual void SAL_CALL setPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Sequence< css::uno::Any >& aValues ) override; + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames ) override; + virtual void SAL_CALL addPropertiesChangeListener( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertiesChangeListener( const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL firePropertiesChangeEvent( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + + // XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState( const OUString& PropertyName ) override; + virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) override; + virtual void SAL_CALL setPropertyToDefault( const OUString& PropertyName ) override; + virtual css::uno::Any SAL_CALL getPropertyDefault( const OUString& aPropertyName ) override; + }; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/MasterPropertySetInfo.hxx b/include/comphelper/MasterPropertySetInfo.hxx new file mode 100644 index 000000000..0e50cc457 --- /dev/null +++ b/include/comphelper/MasterPropertySetInfo.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_MASTERPROPERTYSETINFO_HXX +#define INCLUDED_COMPHELPER_MASTERPROPERTYSETINFO_HXX +#include +#include +#include +#include + +namespace comphelper +{ + // workaround for incremental linking bugs in MSVC2015 + class SAL_DLLPUBLIC_TEMPLATE MasterPropertySetInfo_Base : public cppu::WeakImplHelper< css::beans::XPropertySetInfo > {}; + + class COMPHELPER_DLLPUBLIC MasterPropertySetInfo final : public MasterPropertySetInfo_Base + { + public: + MasterPropertySetInfo( PropertyInfo const * pMap ); + + private: + virtual ~MasterPropertySetInfo() + noexcept override; + + void add( PropertyInfoHash &rHash, sal_uInt8 nMapId ); + + // XPropertySetInfo + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() override; + virtual css::beans::Property SAL_CALL getPropertyByName( const OUString& aName ) override; + virtual sal_Bool SAL_CALL hasPropertyByName( const OUString& Name ) override; + + PropertyDataHash maMap; + css::uno::Sequence < css::beans::Property > maProperties; + + friend class MasterPropertySet; + }; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/PropertyInfoHash.hxx b/include/comphelper/PropertyInfoHash.hxx new file mode 100644 index 000000000..8c584ce5a --- /dev/null +++ b/include/comphelper/PropertyInfoHash.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYINFOHASH_HXX +#define INCLUDED_COMPHELPER_PROPERTYINFOHASH_HXX + +#include +#include +#include + +namespace comphelper +{ + struct PropertyInfo + { + OUString maName; + css::uno::Type maType; + sal_Int32 mnHandle; + sal_Int16 mnAttributes; + + PropertyInfo(OUString const & aName, sal_Int32 nHandle, css::uno::Type const & aType, sal_Int16 nAttributes) + : maName(aName), maType(aType), mnHandle(nHandle), mnAttributes(nAttributes) {} + PropertyInfo(OUString && aName, sal_Int32 nHandle, css::uno::Type const & aType, sal_Int16 nAttributes) + : maName(std::move(aName)), maType(aType), mnHandle(nHandle), mnAttributes(nAttributes) {} + }; + struct PropertyData + { + sal_uInt8 mnMapId; + const PropertyInfo *mpInfo; + PropertyData ( sal_uInt8 nMapId, PropertyInfo const *pInfo ) + : mnMapId ( nMapId ) + , mpInfo ( pInfo ) {} + }; +} + +typedef std::unordered_map < OUString, + ::comphelper::PropertyInfo const * > PropertyInfoHash; +typedef std::unordered_map < OUString, + ::comphelper::PropertyData* > PropertyDataHash; +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/SelectionMultiplex.hxx b/include/comphelper/SelectionMultiplex.hxx new file mode 100644 index 000000000..ab980984a --- /dev/null +++ b/include/comphelper/SelectionMultiplex.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SELECTIONMULTIPLEX_HXX +#define INCLUDED_COMPHELPER_SELECTIONMULTIPLEX_HXX + +#include +#include +#include +#include + +namespace com::sun::star::view { class XSelectionSupplier; } + +//= selection helper classes + + +namespace comphelper +{ + + + //= OSelectionChangeListener + + /// simple listener adapter for selections + class COMPHELPER_DLLPUBLIC OSelectionChangeListener + { + friend class OSelectionChangeMultiplexer; + + public: + virtual ~OSelectionChangeListener(); + + /// @throws css::uno::RuntimeException + virtual void _selectionChanged( const css::lang::EventObject& aEvent ) = 0; + /// @throws css::uno::RuntimeException + virtual void _disposing(const css::lang::EventObject& _rSource); + }; + + + //= OSelectionChangeMultiplexer + + /// multiplexer for selection changes + class COMPHELPER_DLLPUBLIC OSelectionChangeMultiplexer final : public cppu::WeakImplHelper< css::view::XSelectionChangeListener> + { + friend class OSelectionChangeListener; + css::uno::Reference< css::view::XSelectionSupplier> m_xSet; + OSelectionChangeListener* m_pListener; + sal_Int32 m_nLockCount; + + OSelectionChangeMultiplexer(const OSelectionChangeMultiplexer&) = delete; + OSelectionChangeMultiplexer& operator=(const OSelectionChangeMultiplexer&) = delete; + + virtual ~OSelectionChangeMultiplexer() override; + public: + OSelectionChangeMultiplexer(OSelectionChangeListener* _pListener, const css::uno::Reference< css::view::XSelectionSupplier>& _rxSet); + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XSelectionChangeListener + virtual void SAL_CALL selectionChanged( const css::lang::EventObject& aEvent ) override; + + /// incremental lock + void lock(); + /// incremental unlock + void unlock(); + /// get the lock count + sal_Int32 locked() const { return m_nLockCount; } + + void dispose(); + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_SELECTIONMULTIPLEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/SetFlagContextHelper.hxx b/include/comphelper/SetFlagContextHelper.hxx new file mode 100644 index 000000000..b1b15eabb --- /dev/null +++ b/include/comphelper/SetFlagContextHelper.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_SETFLAGCONTEXTHELPER_HXX +#define INCLUDED_COMPHELPER_SETFLAGCONTEXTHELPER_HXX + +#include +#include +#include +#include + +namespace comphelper +{ +// Used to flag some named value to be true for all code running in this context +class SetFlagContext final : public cppu::WeakImplHelper +{ +public: + explicit SetFlagContext(OUString sName, css::uno::Reference xContext) + : m_sName(std::move(sName)) + , mxNextContext(std::move(xContext)) + { + } + SetFlagContext(const SetFlagContext&) = delete; + SetFlagContext& operator=(const SetFlagContext&) = delete; + + virtual css::uno::Any SAL_CALL getValueByName(OUString const& Name) override + { + if (Name == m_sName) + return css::uno::Any(true); + else if (mxNextContext.is()) + return mxNextContext->getValueByName(Name); + else + return css::uno::Any(); + } + +private: + OUString m_sName; + css::uno::Reference mxNextContext; +}; + +// Returns a new context that reports the named value to be true +inline css::uno::Reference NewFlagContext(const OUString& sName) +{ + return new SetFlagContext(sName, css::uno::getCurrentContext()); +} + +// A specialization for preventing "Java must be enabled" interaction +inline css::uno::Reference NoEnableJavaInteractionContext() +{ + return NewFlagContext("DontEnableJava"); +} + +inline bool IsContextFlagActive(const OUString& sName) +{ + bool bFlag = false; + if (const auto xContext = css::uno::getCurrentContext()) + xContext->getValueByName(sName) >>= bFlag; + return bFlag; +} + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_SETFLAGCONTEXTHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessiblecomponenthelper.hxx b/include/comphelper/accessiblecomponenthelper.hxx new file mode 100644 index 000000000..963bea96b --- /dev/null +++ b/include/comphelper/accessiblecomponenthelper.hxx @@ -0,0 +1,142 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLECOMPONENTHELPER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLECOMPONENTHELPER_HXX + +#include +#include +#include +#include +#include +#include + + +namespace comphelper +{ + + + //= OCommonAccessibleComponent + + /** base class encapsulating common functionality for the helper classes implementing + the XAccessibleComponent respectively XAccessibleExtendendComponent + */ + class COMPHELPER_DLLPUBLIC OCommonAccessibleComponent : public OAccessibleContextHelper + { + protected: + /// see the respective base class ctor for an extensive comment on this, please + OCommonAccessibleComponent(); + virtual ~OCommonAccessibleComponent() override; + + protected: + /// implements the calculation of the bounding rectangle - still waiting to be overwritten + /// + /// @throws css::uno::RuntimeException + virtual css::awt::Rectangle implGetBounds( ) = 0; + + protected: + /** non-virtual versions of the methods which can be implemented using implGetBounds + note: getLocationOnScreen relies on a valid parent (XAccessibleContext::getParent()->getAccessibleContext()), + which itself implements XAccessibleComponent + + @throws css::uno::RuntimeException + */ + bool containsPoint( const css::awt::Point& aPoint ); + /// @throws css::uno::RuntimeException + css::awt::Point getLocation( ); + /// @throws css::uno::RuntimeException + css::awt::Point getLocationOnScreen( ); + /// @throws css::uno::RuntimeException + css::awt::Size getSize( ); + /// @throws css::uno::RuntimeException + css::awt::Rectangle getBounds( ); + }; + + + //= OAccessibleComponentHelper + + + struct OAccessibleComponentHelper_Base : + public ::cppu::ImplHelper1< css::accessibility::XAccessibleComponent > + { + protected: + ~OAccessibleComponentHelper_Base() {} + }; + + /** a helper class for implementing an AccessibleContext which at the same time + supports an XAccessibleComponent interface. + */ + class COMPHELPER_DLLPUBLIC OAccessibleComponentHelper + :public OCommonAccessibleComponent + ,public OAccessibleComponentHelper_Base + { + protected: + OAccessibleComponentHelper(); + + public: + // XInterface + DECLARE_XINTERFACE( ) + DECLARE_XTYPEPROVIDER( ) + + // XAccessibleComponent - default implementations + virtual sal_Bool SAL_CALL containsPoint( const css::awt::Point& aPoint ) override; + virtual css::awt::Point SAL_CALL getLocation( ) override; + virtual css::awt::Point SAL_CALL getLocationOnScreen( ) override; + virtual css::awt::Size SAL_CALL getSize( ) override; + virtual css::awt::Rectangle SAL_CALL getBounds( ) override; + }; + + + //= OAccessibleExtendedComponentHelper + + + typedef ::cppu::ImplHelper1 < css::accessibility::XAccessibleExtendedComponent + > OAccessibleExtendedComponentHelper_Base; + + /** a helper class for implementing an AccessibleContext which at the same time + supports an XAccessibleExtendedComponent interface. + */ + class COMPHELPER_DLLPUBLIC OAccessibleExtendedComponentHelper + :public OCommonAccessibleComponent + ,public OAccessibleExtendedComponentHelper_Base + { + protected: + OAccessibleExtendedComponentHelper( ); + + public: + // XInterface + DECLARE_XINTERFACE( ) + DECLARE_XTYPEPROVIDER( ) + + // XAccessibleComponent - default implementations + virtual sal_Bool SAL_CALL containsPoint( const css::awt::Point& aPoint ) override; + virtual css::awt::Point SAL_CALL getLocation( ) override; + virtual css::awt::Point SAL_CALL getLocationOnScreen( ) override; + virtual css::awt::Size SAL_CALL getSize( ) override; + virtual css::awt::Rectangle SAL_CALL getBounds( ) override; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_ACCESSIBLECOMPONENTHELPER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessiblecontexthelper.hxx b/include/comphelper/accessiblecontexthelper.hxx new file mode 100644 index 000000000..dc367fbe1 --- /dev/null +++ b/include/comphelper/accessiblecontexthelper.hxx @@ -0,0 +1,219 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLECONTEXTHELPER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLECONTEXTHELPER_HXX + +#include +#include +#include +#include +#include +#include +#include + + +namespace comphelper +{ + + + //= OAccessibleContextHelper + + + typedef ::cppu::WeakAggComponentImplHelper2 < css::accessibility::XAccessibleContext2, + css::accessibility::XAccessibleEventBroadcaster + > OAccessibleContextHelper_Base; + + /** helper class for implementing an AccessibleContext + */ + class COMPHELPER_DLLPUBLIC OAccessibleContextHelper + :public ::cppu::BaseMutex + ,public OAccessibleContextHelper_Base + { + friend class OContextEntryGuard; + private: + css::uno::WeakReference< css::accessibility::XAccessible > m_aCreator; // the XAccessible which created our XAccessibleContext + AccessibleEventNotifier::TClientId m_nClientId; + + protected: + virtual ~OAccessibleContextHelper( ) override; + + OAccessibleContextHelper( ); + + /** late construction + @param _rxAccessible + the Accessible object which created this context. +

If your derived implementation implements the XAccessible (and does not follow the proposed + separation of XAccessible from XAccessibleContext), you may pass this here.

+ +

The object is hold weak, so its life time is not affected.

+ +

The object is needed for performance reasons: for getAccessibleIndexInParent, + all children (which are XAccessible's theirself) of our parent have to be asked. If we know our + XAccessible, we can compare it with all the children, instead of asking all children for their + context and comparing this context with ourself.

+ */ + void lateInit( const css::uno::Reference< css::accessibility::XAccessible >& _rxAccessible ); + + /** retrieves the creator previously set with lateInit + */ + css::uno::Reference< css::accessibility::XAccessible > + getAccessibleCreator( ) const; + + public: + // XAccessibleEventBroadcaster + virtual void SAL_CALL addAccessibleEventListener( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener ) override; + virtual void SAL_CALL removeAccessibleEventListener( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener ) override; + + // XAccessibleContext - still waiting to be overwritten + virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) override = 0; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) override = 0; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) override = 0; + virtual sal_Int16 SAL_CALL getAccessibleRole( ) override = 0; + virtual OUString SAL_CALL getAccessibleDescription( ) override = 0; + virtual OUString SAL_CALL getAccessibleName( ) override = 0; + virtual css::uno::Reference< css::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) override = 0; + virtual css::uno::Reference< css::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) override = 0; + + // XAccessibleContext2 - default implementation + virtual OUString SAL_CALL getAccessibleId( ) override; + + // XAccessibleContext - default implementations + /** default implementation for retrieving the index of this object within the parent +

This basic implementation here returns the index i of the child for which + <parent>.getAccessibleChild( i ) equals our creator.

+ */ + virtual sal_Int32 SAL_CALL getAccessibleIndexInParent( ) override; + /** default implementation for retrieving the locale +

This basic implementation returns the locale of the parent context, + as retrieved via getAccessibleParent()->getAccessibleContext.

+ */ + virtual css::lang::Locale SAL_CALL getLocale( ) override; + + protected: + // OComponentHelper + virtual void SAL_CALL disposing() override; + + protected: + // helper + /** notifies all AccessibleEventListeners of a certain event + + @precond not to be called with our mutex locked + @param _nEventId + the id of the event. See AccessibleEventType + @param _rOldValue + the old value to be notified + @param _rNewValue + the new value to be notified + */ + void NotifyAccessibleEvent( + const sal_Int16 _nEventId, + const css::uno::Any& _rOldValue, + const css::uno::Any& _rNewValue + ); + + // life time control + /// checks whether the object is alive (returns then) or disposed + bool isAlive() const; + /// checks for being alive. If the object is already disposed (i.e. not alive), an exception is thrown. + void ensureAlive() const; + + /** ensures that the object is disposed. + @precond + to be called from within the destructor of your derived class only! + */ + void ensureDisposed( ); + + /** shortcut for retrieving the context of the parent (returned by getAccessibleParent) + */ + css::uno::Reference< css::accessibility::XAccessibleContext > + implGetParentContext(); + + // access to the base class' broadcast helper/mutex + ::osl::Mutex& GetMutex() { return m_aMutex; } + }; + + + //= OContextEntryGuard + + /** helper class for guarding the entry into OAccessibleContextHelper methods. + +

The class has two responsibilities: +

  • it locks the mutex of an OAccessibleContextHelper instance, as long as the guard lives
  • +
  • it checks if a given OAccessibleContextHelper instance is alive, else an exception is thrown + our of the constructor of the guard
  • +
+
+ This makes it your first choice (hopefully :) for guarding any interface method implementations of + you derived class. +

+ */ + class OContextEntryGuard : public ::osl::ClearableMutexGuard + { + public: + /** constructs the guard + +

The given context (it's mutex, respectively) is locked, and an exception is thrown if the context + is not alive anymore. In the latter case, of course, the mutex is freed, again.

+ + @param _pContext + the context which shall be guarded + @precond _pContext != NULL + */ + inline OContextEntryGuard( OAccessibleContextHelper* _pContext ); + }; + + + inline OContextEntryGuard::OContextEntryGuard( OAccessibleContextHelper* _pContext ) + : ::osl::ClearableMutexGuard( _pContext->GetMutex() ) + { + _pContext->ensureAlive(); + } + + + //= OExternalLockGuard + + class OExternalLockGuard + :public osl::Guard + ,public OContextEntryGuard + { + public: + inline OExternalLockGuard( OAccessibleContextHelper* _pContext ); + }; + + + inline OExternalLockGuard::OExternalLockGuard( OAccessibleContextHelper* _pContext ) + :osl::Guard( SolarMutex::get() ) + ,OContextEntryGuard( _pContext ) + { + // Only lock the external mutex, + // release the ::osl::Mutex of the OAccessibleContextHelper instance. + // If you call into another UNO object with locked ::osl::Mutex, + // this may lead to dead locks. + clear(); + } + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_ACCESSIBLECONTEXTHELPER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessibleeventnotifier.hxx b/include/comphelper/accessibleeventnotifier.hxx new file mode 100644 index 000000000..75828cda6 --- /dev/null +++ b/include/comphelper/accessibleeventnotifier.hxx @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLEEVENTNOTIFIER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLEEVENTNOTIFIER_HXX + +#include + +namespace com::sun::star::uno { class XInterface; } +namespace com::sun::star::uno { template class Reference; } +namespace com::sun::star::accessibility { class XAccessibleEventListener; } +namespace com::sun::star::accessibility { struct AccessibleEventObject; } + +namespace comphelper { + +class COMPHELPER_DLLPUBLIC AccessibleEventNotifier +{ +public: + typedef sal_uInt32 TClientId; + +public: + AccessibleEventNotifier() = delete; + ~AccessibleEventNotifier() = delete; + AccessibleEventNotifier( const AccessibleEventNotifier& ) = delete; + AccessibleEventNotifier& operator=( const AccessibleEventNotifier& ) = delete; + + /** registers a client of this class, means a broadcaster of AccessibleEvents + +

No precaution is taken to care for disposal of this component. When the component + dies, it must call revokeClient or revokeClientNotifyDisposing + explicitly itself.

+ */ + static TClientId registerClient(); + + /** revokes a broadcaster of AccessibleEvents + +

Note that no disposing event is fired when you use this method, the client is simply revoked. + You can for instance revoke a client if the last listener for it is revoked, but the client + itself is not disposed.
+ When the client is disposed, you should prefer revokeClientNotifyDisposing

+ +

Any possibly pending events for this client are removed from the queue.

+ + @seealso revokeClientNotifyDisposing + */ + static void revokeClient( const TClientId _nClient ); + + /** revokes a client, with additionally notifying a disposing event to all listeners registered for + this client + +

Any other possibly pending events for this client are removed from the queue

+ + @param _nClient + the id of the client which should be revoked + @param _rxEventSource + the source to be notified together with the XComponent::disposing + call. + */ + static void revokeClientNotifyDisposing( + const TClientId _nClient, + const css::uno::Reference< css::uno::XInterface >& _rxEventSource ); + + /** registers a listener for the given client + + @param _nClient + the id of the client for which a listener should be registered + @return + the number of event listeners currently registered for this client + */ + static sal_Int32 addEventListener( + const TClientId _nClient, + const css::uno::Reference< css::accessibility::XAccessibleEventListener >& _rxListener ); + + /** revokes a listener for the given client + + @param _nClient + the id of the client for which a listener should be revoked + @return + the number of event listeners currently registered for this client + */ + static sal_Int32 removeEventListener( + const TClientId _nClient, + const css::uno::Reference< css::accessibility::XAccessibleEventListener >& _rxListener ); + + /** adds an event, which is to be broadcasted, to the queue + + @param _nClient + the id of the client which needs to broadcast the event + */ + static void addEvent( + const TClientId _nClient, + const css::accessibility::AccessibleEventObject& _rEvent ); + +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_ACCESSIBLEEVENTNOTIFIER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessiblekeybindinghelper.hxx b/include/comphelper/accessiblekeybindinghelper.hxx new file mode 100644 index 000000000..fe6b03521 --- /dev/null +++ b/include/comphelper/accessiblekeybindinghelper.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLEKEYBINDINGHELPER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLEKEYBINDINGHELPER_HXX + +#include +#include +#include +#include +#include + +namespace comphelper +{ + + + // OAccessibleKeyBindingHelper + + + typedef ::cppu::WeakImplHelper < css::accessibility::XAccessibleKeyBinding + > OAccessibleKeyBindingHelper_Base; + + /** a helper class for implementing an accessible keybinding + */ + class COMPHELPER_DLLPUBLIC OAccessibleKeyBindingHelper final : public OAccessibleKeyBindingHelper_Base + { + private: + typedef ::std::vector< css::uno::Sequence< css::awt::KeyStroke > > KeyBindings; + KeyBindings m_aKeyBindings; + std::mutex m_aMutex; + + virtual ~OAccessibleKeyBindingHelper() override; + + public: + OAccessibleKeyBindingHelper(); + OAccessibleKeyBindingHelper( const OAccessibleKeyBindingHelper& rHelper ); + + /// @throws css::uno::RuntimeException + void AddKeyBinding( const css::uno::Sequence< css::awt::KeyStroke >& rKeyBinding ); + /// @throws css::uno::RuntimeException + void AddKeyBinding( const css::awt::KeyStroke& rKeyStroke ); + + // XAccessibleKeyBinding + virtual sal_Int32 SAL_CALL getAccessibleKeyBindingCount() override; + virtual css::uno::Sequence< css::awt::KeyStroke > SAL_CALL getAccessibleKeyBinding( sal_Int32 nIndex ) override; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_ACCESSIBLEKEYBINDINGHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessibleselectionhelper.hxx b/include/comphelper/accessibleselectionhelper.hxx new file mode 100644 index 000000000..3a49c1ffd --- /dev/null +++ b/include/comphelper/accessibleselectionhelper.hxx @@ -0,0 +1,135 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLESELECTIONHELPER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLESELECTIONHELPER_HXX + +#include +#include +#include +#include +#include +#include + +#define ACCESSIBLE_SELECTION_CHILD_ALL (sal_Int32(-1)) +#define ACCESSIBLE_SELECTION_CHILD_SELF ((sal_Int32)-2) + + +namespace comphelper +{ + + + //= OCommonAccessibleSelection + + /** base class encapsulating common functionality for the helper classes implementing + the XAccessibleSelection + */ + class COMPHELPER_DLLPUBLIC OCommonAccessibleSelection + { + protected: + + OCommonAccessibleSelection(); + + ~OCommonAccessibleSelection(); + + protected: + + // access to context - still waiting to be overwritten + /// @throws css::uno::RuntimeException + virtual css::uno::Reference< css::accessibility::XAccessibleContext > + implGetAccessibleContext() = 0; + + // return if the specified child is visible => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx) + /// @throws css::uno::RuntimeException + virtual bool + implIsSelected( sal_Int32 nAccessibleChildIndex ) = 0; + + // select the specified child => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx) + /// @throws css::uno::RuntimeException + virtual void + implSelect( sal_Int32 nAccessibleChildIndex, bool bSelect ) = 0; + + protected: + + /** non-virtual versions of the methods which can be implemented using implIsSelected and implSelect + + @throws css::lang::IndexOutOfBoundsException + @throws css::uno::RuntimeException + */ + void selectAccessibleChild( sal_Int32 nChildIndex ); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::uno::RuntimeException + bool isAccessibleChildSelected( sal_Int32 nChildIndex ); + /// @throws css::uno::RuntimeException + void clearAccessibleSelection( ); + /// @throws css::uno::RuntimeException + void selectAllAccessibleChildren( ); + /// @throws css::uno::RuntimeException + sal_Int32 getSelectedAccessibleChildCount( ); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::uno::RuntimeException + css::uno::Reference< css::accessibility::XAccessible > getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::uno::RuntimeException + void deselectAccessibleChild( sal_Int32 nSelectedChildIndex ); + }; + + + //= OAccessibleSelectionHelper + + + typedef ::cppu::ImplHelper1< css::accessibility::XAccessibleSelection > OAccessibleSelectionHelper_Base; + + /** a helper class for implementing an AccessibleSelection which at the same time + supports an XAccessibleSelection interface. + */ + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OAccessibleSelectionHelper : public OAccessibleComponentHelper, + public OCommonAccessibleSelection, + public OAccessibleSelectionHelper_Base + { + protected: + + OAccessibleSelectionHelper(); + + // return ourself here by default + virtual css::uno::Reference< css::accessibility::XAccessibleContext > implGetAccessibleContext() override; + + public: + + // XInterface + DECLARE_XINTERFACE( ) + DECLARE_XTYPEPROVIDER( ) + + // XAccessibleSelection - default implementations + virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) override; + virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) override; + virtual void SAL_CALL clearAccessibleSelection( ) override; + virtual void SAL_CALL selectAllAccessibleChildren( ) override; + virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) override; + virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) override; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_ACCESSIBLESELECTIONHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessibletexthelper.hxx b/include/comphelper/accessibletexthelper.hxx new file mode 100644 index 000000000..607004aee --- /dev/null +++ b/include/comphelper/accessibletexthelper.hxx @@ -0,0 +1,176 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLETEXTHELPER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLETEXTHELPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::i18n { class XBreakIterator; } +namespace com::sun::star::i18n { class XCharacterClassification; } +namespace com::sun::star::i18n { struct Boundary; } + +namespace comphelper +{ + + + // OCommonAccessibleText + + /** base class encapsulating common functionality for the helper classes implementing + the XAccessibleText + */ + class COMPHELPER_DLLPUBLIC OCommonAccessibleText + { + private: + css::uno::Reference < css::i18n::XBreakIterator > m_xBreakIter; + css::uno::Reference < css::i18n::XCharacterClassification > m_xCharClass; + + protected: + OCommonAccessibleText(); + virtual ~OCommonAccessibleText(); + + css::uno::Reference < css::i18n::XBreakIterator > const & implGetBreakIterator(); + css::uno::Reference < css::i18n::XCharacterClassification > const & implGetCharacterClassification(); + static bool implIsValidBoundary( css::i18n::Boundary const & rBoundary, sal_Int32 nLength ); + static bool implIsValidIndex( sal_Int32 nIndex, sal_Int32 nLength ); + static bool implIsValidRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex, sal_Int32 nLength ); + static sal_Unicode implGetCharacter( std::u16string_view rText, sal_Int32 nIndex ); + static OUString implGetTextRange( std::u16string_view rText, sal_Int32 nStartIndex, sal_Int32 nEndIndex ); + virtual OUString implGetText() = 0; + virtual css::lang::Locale implGetLocale() = 0; + virtual void implGetSelection( sal_Int32& nStartIndex, sal_Int32& nEndIndex ) = 0; + void implGetGlyphBoundary( const OUString& rText, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ); + bool implGetWordBoundary( const OUString& rText, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ); + void implGetSentenceBoundary( const OUString& rText, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ); + virtual void implGetParagraphBoundary( const OUString& rText, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ); + virtual void implGetLineBoundary( const OUString& rText, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ); + + /** non-virtual versions of the methods + + @throws css::lang::IndexOutOfBoundsException + @throws css::uno::RuntimeException + */ + OUString getSelectedText(); + /// @throws css::uno::RuntimeException + sal_Int32 getSelectionStart(); + /// @throws css::uno::RuntimeException + sal_Int32 getSelectionEnd(); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::lang::IllegalArgumentException + /// @throws css::uno::RuntimeException + css::accessibility::TextSegment getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::lang::IllegalArgumentException + /// @throws css::uno::RuntimeException + css::accessibility::TextSegment getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::lang::IllegalArgumentException + /// @throws css::uno::RuntimeException + css::accessibility::TextSegment getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ); + + public: + + /** Helper method, that detects the difference between + two strings and returns the deleted selection and + the inserted selection if available. + + @returns true if there are differences between the + two strings and false if both are equal + + @see css::accessibility::AccessibleEventId + css::accessibility::TextSegment + */ + static bool implInitTextChangedEvent( + std::u16string_view rOldString, + std::u16string_view rNewString, + /*out*/ css::uno::Any& rDeleted, + /*out*/ css::uno::Any& rInserted); // throw() + }; + + + // OAccessibleTextHelper + + + typedef ::cppu::ImplHelper1 < css::accessibility::XAccessibleText + > OAccessibleTextHelper_Base; + + /** a helper class for implementing an AccessibleExtendedComponent which at the same time + supports an XAccessibleText interface + */ + class COMPHELPER_DLLPUBLIC OAccessibleTextHelper : public OAccessibleExtendedComponentHelper, + public OCommonAccessibleText, + public OAccessibleTextHelper_Base + { + protected: + OAccessibleTextHelper(); + + public: + // XInterface + DECLARE_XINTERFACE( ) + + // XTypeProvider + DECLARE_XTYPEPROVIDER( ) + + // XAccessibleText + virtual OUString SAL_CALL getSelectedText() override; + virtual sal_Int32 SAL_CALL getSelectionStart() override; + virtual sal_Int32 SAL_CALL getSelectionEnd() override; + virtual css::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + virtual css::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + virtual css::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + }; + + +} // namespace comphelper + + +// OAccessibleTextHelper is a helper class for implementing the +// XAccessibleText interface. + +// The following methods have a default implementation: + +// getCharacter +// getSelectedText +// getSelectionStart +// getSelectionEnd +// getTextRange +// getTextAtIndex +// getTextBeforeIndex +// getTextBehindIndex + +// The following methods must be overridden by derived classes: + +// implGetText +// implGetLocale +// implGetSelection +// getCaretPosition +// setCaretPosition +// getCharacterAttributes +// getCharacterBounds +// getIndexAtPoint +// setSelection +// copyText + +#endif // INCLUDED_COMPHELPER_ACCESSIBLETEXTHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accessiblewrapper.hxx b/include/comphelper/accessiblewrapper.hxx new file mode 100644 index 000000000..13fb29bff --- /dev/null +++ b/include/comphelper/accessiblewrapper.hxx @@ -0,0 +1,401 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCESSIBLEWRAPPER_HXX +#define INCLUDED_COMPHELPER_ACCESSIBLEWRAPPER_HXX + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { class XComponentContext; } + +namespace comphelper +{ + + + //= OAccessibleWrapper + + + class OAccessibleContextWrapper; + class OWrappedAccessibleChildrenManager; + + struct OAccessibleWrapper_Base : + public ::cppu::ImplHelper1 < css::accessibility::XAccessible > + { + protected: + ~OAccessibleWrapper_Base() {} + }; + + /** a class which aggregates a proxy for an XAccessible, and wrapping the context returned by this + XAccessible. + */ + class COMPHELPER_DLLPUBLIC OAccessibleWrapper:public OAccessibleWrapper_Base + ,public OComponentProxyAggregation + + { + private: + css::uno::Reference< css::accessibility::XAccessible > + m_xParentAccessible; + css::uno::WeakReference< css::accessibility::XAccessibleContext > + m_aContext; + + protected: + css::uno::Reference< css::accessibility::XAccessible > + m_xInnerAccessible; + + public: + /** ctor + @param _rxContext + a service factory + + @param _rxInnerAccessible + the object to wrap + + @param _rxParentAccessible + The XAccessible which is our parent + */ + OAccessibleWrapper( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + const css::uno::Reference< css::accessibility::XAccessible >& _rxInnerAccessible, + const css::uno::Reference< css::accessibility::XAccessible >& _rxParentAccessible + ); + DECLARE_XINTERFACE() + DECLARE_XTYPEPROVIDER() + + // returns the context without creating it + css::uno::Reference< css::accessibility::XAccessibleContext > + getContextNoCreate( ) const; + + protected: + virtual css::uno::Reference< css::accessibility::XAccessibleContext > SAL_CALL + getAccessibleContext( ) override; + + const css::uno::Reference< css::accessibility::XAccessible >& + getParent() const { return m_xParentAccessible; } + + // own overridables + virtual rtl::Reference createAccessibleContext( + const css::uno::Reference< css::accessibility::XAccessibleContext >& _rxInnerContext + ); + + protected: + virtual ~OAccessibleWrapper( ) override; + + private: + OAccessibleWrapper( const OAccessibleWrapper& ) = delete; + OAccessibleWrapper& operator=( const OAccessibleWrapper& ) = delete; + }; + + + //= OAccessibleContextWrapperHelper + + + typedef ::cppu::ImplHelper1 < css::accessibility::XAccessibleEventListener + > OAccessibleContextWrapperHelper_Base; + + /** Helper for wrapping an XAccessibleContext by aggregating a proxy for it. + +

This class does not have own ref counting. In addition, it does not implement + the XAccessibleContext interface, but provides all the methods from this interface + which must be implemented using the inner context (such as getAccessibleChild*).

+ +

Children of the aggregated XAccessibleContext are wrapped, too.

+ +

AccessibleEvents fired by the inner context are multiplexed, especially, any references to + children in such events are translated. This means that even in such events, no un-wrapped object + will ever leave this class - if the aggregated context notifies a child event, the child passed + to the event is wrapped

+ + @seealso OAccessibleContextWrapper + */ + class COMPHELPER_DLLPUBLIC OAccessibleContextWrapperHelper + :private OComponentProxyAggregationHelper + ,public OAccessibleContextWrapperHelper_Base + { + protected: + /// the context we're wrapping (properly typed, in opposite to OComponentProxyAggregationHelper::m_xInner) + css::uno::Reference< css::accessibility::XAccessibleContext > + m_xInnerContext; + /// the XAccessible which created this context + css::uno::Reference< css::accessibility::XAccessible > + m_xOwningAccessible; + /// the XAccessible which is to be returned in getAccessibleParent + css::uno::Reference< css::accessibility::XAccessible > + m_xParentAccessible; + + rtl::Reference m_xChildMapper; // for mapping children from our inner context to our callers + + protected: + /** ctor + + @param _rxContext + a service factory + + @param _rxInnerAccessibleContext + the object to wrap + + @param _rxOwningAccessible + The XAccessible which created this object. This is necessary because children + of our wrapped context need to be wrapped, too, and if they're asked for a parent, + they of course should return the proper parent
+ The object will be held with a hard reference + + @param _rxParentAccessible + The XAccessible to return in the getAccessibleParent call + */ + OAccessibleContextWrapperHelper( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + ::cppu::OBroadcastHelper& _rBHelper, + const css::uno::Reference< css::accessibility::XAccessibleContext >& _rxInnerAccessibleContext, + const css::uno::Reference< css::accessibility::XAccessible >& _rxOwningAccessible, + const css::uno::Reference< css::accessibility::XAccessible >& _rxParentAccessible + ); + + /// to be called from within your ctor - does the aggregation of a proxy for m_xInnerContext + void aggregateProxy( + oslInterlockedCount& _rRefCount, + ::cppu::OWeakObject& _rDelegator + ); + + protected: + // XInterface + css::uno::Any SAL_CALL queryInterface( const css::uno::Type& _rType ) override; + + // XTypeProvider + DECLARE_XTYPEPROVIDER( ) + + // XAccessibleContext + /// @throws css::uno::RuntimeException + sal_Int32 baseGetAccessibleChildCount( ); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::uno::RuntimeException + css::uno::Reference< css::accessibility::XAccessible > baseGetAccessibleChild( sal_Int32 i ); + /// @throws css::uno::RuntimeException + css::uno::Reference< css::accessibility::XAccessibleRelationSet > baseGetAccessibleRelationSet( ); + + // XAccessibleEventListener + virtual void SAL_CALL notifyEvent( const css::accessibility::AccessibleEventObject& aEvent ) override; + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XComponent/OComponentProxyAggregationHelper + virtual void SAL_CALL dispose() override; + + // own overridables + /** notify an accessible event which has been translated (if necessary) + +

Usually, you derive your class from both OAccessibleContextWrapperHelper and XAccessibleEventBroadcaster, + and simply call all your XAccessibleEventListener with the given event.

+ +

The mutex of the BroadcastHelper passed to the instance's ctor is not locked when calling + into this method

+ + @throws css::uno::RuntimeException + */ + virtual void notifyTranslatedEvent( const css::accessibility::AccessibleEventObject& _rEvent ) = 0; + + protected: + virtual ~OAccessibleContextWrapperHelper( ) override; + + OAccessibleContextWrapperHelper(const OAccessibleContextWrapperHelper&) = delete; + OAccessibleContextWrapperHelper& operator=(const OAccessibleContextWrapperHelper&) = delete; + }; + + + //= OAccessibleContextWrapper + + typedef ::cppu::WeakComponentImplHelper< css::accessibility::XAccessibleEventBroadcaster + , css::accessibility::XAccessibleContext + > OAccessibleContextWrapper_CBase; + + class COMPHELPER_DLLPUBLIC OAccessibleContextWrapper + :public cppu::BaseMutex + ,public OAccessibleContextWrapper_CBase + ,public OAccessibleContextWrapperHelper + { + private: + ::comphelper::AccessibleEventNotifier::TClientId m_nNotifierClient; // for notifying AccessibleEvents + + public: + /** ctor + + @param _rxContext + a service factory + + @param _rxInnerAccessibleContext + the object to wrap + + @param _rxOwningAccessible + The XAccessible which created this object. This is necessary because children + of our wrapped context need to be wrapped, too, and if they're asked for a parent, + they of course should return the proper parent
+ The object will be held with a hard reference + + @param _rxParentAccessible + The XAccessible to return in the getAccessibleParent call + */ + OAccessibleContextWrapper( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + const css::uno::Reference< css::accessibility::XAccessibleContext >& _rxInnerAccessibleContext, + const css::uno::Reference< css::accessibility::XAccessible >& _rxOwningAccessible, + const css::uno::Reference< css::accessibility::XAccessible >& _rxParentAccessible + ); + + // XInterface + DECLARE_XINTERFACE( ) + // XTypeProvider + DECLARE_XTYPEPROVIDER( ) + + // XAccessibleContext + virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) override; + virtual sal_Int32 SAL_CALL getAccessibleIndexInParent( ) override; + virtual sal_Int16 SAL_CALL getAccessibleRole( ) override; + virtual OUString SAL_CALL getAccessibleDescription( ) override; + virtual OUString SAL_CALL getAccessibleName( ) override; + virtual css::uno::Reference< css::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) override; + virtual css::uno::Reference< css::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) override; + virtual css::lang::Locale SAL_CALL getLocale( ) override; + + // XAccessibleEventBroadcaster + virtual void SAL_CALL addAccessibleEventListener( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener ) override; + virtual void SAL_CALL removeAccessibleEventListener( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener ) override; + + // OAccessibleContextWrapper + virtual void notifyTranslatedEvent( const css::accessibility::AccessibleEventObject& _rEvent ) override; + + // OComponentHelper + using OAccessibleContextWrapperHelper::disposing; + virtual void SAL_CALL disposing() override; + + protected: + virtual ~OAccessibleContextWrapper() override; + + private: + OAccessibleContextWrapper( const OAccessibleContextWrapper& ) = delete; + OAccessibleContextWrapper& operator=( const OAccessibleContextWrapper& ) = delete; + }; + + + //= OWrappedAccessibleChildrenManager + + + typedef ::std::map < css::uno::Reference< css::accessibility::XAccessible > + , rtl::Reference< comphelper::OAccessibleWrapper > + > AccessibleMap; + // TODO: think about if we should hold these objects weak + + typedef ::cppu::WeakImplHelper< css::lang::XEventListener + > OWrappedAccessibleChildrenManager_Base; + /** manages wrapping XAccessible's to XAccessible's + */ + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OWrappedAccessibleChildrenManager final : public OWrappedAccessibleChildrenManager_Base + { + css::uno::Reference< css::uno::XComponentContext > + m_xContext; + css::uno::WeakReference< css::accessibility::XAccessible > + m_aOwningAccessible; // the XAccessible which belongs to the XAccessibleContext which we work for + AccessibleMap m_aChildrenMap; // for caching children + bool m_bTransientChildren; // are we prohibited to cache our children? + + public: + /// ctor + OWrappedAccessibleChildrenManager( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext + ); + + /** specifies if the children are to be considered transient (i.e.: not cached) +

to be called only once per lifetime

+ */ + void setTransientChildren( bool _bSet ); + + /** sets the XAccessible which belongs to the XAccessibleContext which we work for +

to be called only once per lifetime

+ */ + void setOwningAccessible( const css::uno::Reference< css::accessibility::XAccessible >& _rxAcc ); + + /// retrieves a wrapper for the given accessible + css::uno::Reference< css::accessibility::XAccessible > + getAccessibleWrapperFor( + const css::uno::Reference< css::accessibility::XAccessible >& _rxKey + ); + + /// erases the given key from the map (if it is present there) + void removeFromCache( const css::uno::Reference< css::accessibility::XAccessible >& _rxKey ); + + /// invalidates (i.e. empties) the map + void invalidateAll( ); + + /** disposes (i.e. clears) the manager + +

Note that the XAccessibleContext's of the mapped XAccessible objects are disposed, too.

+ */ + void dispose(); + + /** handles a notification as got from the parent of the children we're managing +

This applies only to the notifications which have a direct impact on our map.

+ */ + void handleChildNotification( const css::accessibility::AccessibleEventObject& _rEvent ); + + /** translates events as got from the parent of the children we're managing +

This applies only to the notifications which deal with child objects which we manage.

+ */ + void translateAccessibleEvent( + const css::accessibility::AccessibleEventObject& _rEvent, + css::accessibility::AccessibleEventObject& _rTranslatedEvent + ); + + private: + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + void implTranslateChildEventValue( const css::uno::Any& _rInValue, css::uno::Any& _rOutValue ); + + virtual ~OWrappedAccessibleChildrenManager( ) override; + + OWrappedAccessibleChildrenManager( const OWrappedAccessibleChildrenManager& ) = delete; + OWrappedAccessibleChildrenManager& operator=( const OWrappedAccessibleChildrenManager& ) = delete; + }; + + +} // namespace accessibility + + +#endif // INCLUDED_COMPHELPER_ACCESSIBLEWRAPPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/accimplaccess.hxx b/include/comphelper/accimplaccess.hxx new file mode 100644 index 000000000..e716d4d18 --- /dev/null +++ b/include/comphelper/accimplaccess.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX +#define INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX + +#include +#include +#include + +namespace comphelper +{ + //= OAccessibleImplementationAccess + + typedef ::cppu::ImplHelper1 < css::lang::XUnoTunnel + > OAccImpl_Base; + + /** This is a helper class which allows accessing several aspects of the implementation + of an AccessibleContext. + +

For instance, when you want to implement a context which can be re-parented, you: +

  • derive your class from OAccessibleImplementationAccess
  • +
  • use setAccessibleParent( component, new_parent ) +
+

+ +

Another aspect which can be controlled from the outside are states. If you have a class which + has only partial control over it's states, you may consider deriving from OAccessibleImplementationAccess.
+ For instance, say you have an implementation (say component A) which is unable to know or to + determine if the represented object is selected, but another component (say B) which uses A (and integrates + it into a tree of accessibility components) is.
+ In this case, if A is derived from OAccessibleImplementationAccess, B can manipulate this + foreign-controlled state flag "SELECTED" by using the static helper methods on this class.

+ +

Please note that the support for foreign controlled states is rather restrictive: You can't have states + which may be controlled by a foreign instances. This is implied by the fact that a derived + class can ask for states which are set only, not for the ones which are reset currently. +

+ */ + class COMPHELPER_DLLPUBLIC OAccessibleImplementationAccess : public OAccImpl_Base + { + protected: + OAccessibleImplementationAccess( ); + virtual ~OAccessibleImplementationAccess( ); + + // XUnoTunnel + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& _rIdentifier ) override; + + public: + COMPHELPER_DLLPRIVATE static const css::uno::Sequence & getUnoTunnelId(); + }; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/anycompare.hxx b/include/comphelper/anycompare.hxx new file mode 100644 index 000000000..3618106db --- /dev/null +++ b/include/comphelper/anycompare.hxx @@ -0,0 +1,219 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ANYCOMPARE_HXX +#define INCLUDED_COMPHELPER_ANYCOMPARE_HXX + +#include + +#include +#include + +#include + +#include +#include + + +namespace comphelper +{ + + + //= IKeyPredicateLess + + class SAL_NO_VTABLE IKeyPredicateLess + { + public: + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const = 0; + virtual ~IKeyPredicateLess() {} + }; + + + //= LessPredicateAdapter + + struct LessPredicateAdapter + { + LessPredicateAdapter( const IKeyPredicateLess& _predicate ) + :m_predicate( _predicate ) + { + } + + bool operator()( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const + { + return m_predicate.isLess( _lhs, _rhs ); + } + + private: + IKeyPredicateLess const & m_predicate; + }; + + + //= ScalarPredicateLess + + template< typename SCALAR > + class ScalarPredicateLess final : public IKeyPredicateLess + { + public: + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const override + { + SCALAR lhs(0), rhs(0); + if ( !( _lhs >>= lhs ) + || !( _rhs >>= rhs ) + ) + throw css::lang::IllegalArgumentException(); + return lhs < rhs; + } + }; + + + //= StringPredicateLess + + class StringPredicateLess final : public IKeyPredicateLess + { + public: + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const override + { + OUString lhs, rhs; + if ( !( _lhs >>= lhs ) + || !( _rhs >>= rhs ) + ) + throw css::lang::IllegalArgumentException(); + return lhs < rhs; + } + }; + + + //= StringCollationPredicateLess + + class StringCollationPredicateLess final : public IKeyPredicateLess + { + public: + StringCollationPredicateLess( css::uno::Reference< css::i18n::XCollator > i_collator ) + :m_collator(std::move( i_collator )) + { + } + + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const override + { + OUString lhs, rhs; + if ( !( _lhs >>= lhs ) + || !( _rhs >>= rhs ) + ) + throw css::lang::IllegalArgumentException(); + return m_collator->compareString( lhs, rhs ) < 0; + } + + private: + css::uno::Reference< css::i18n::XCollator > const m_collator; + }; + + + //= TypePredicateLess + + class TypePredicateLess final : public IKeyPredicateLess + { + public: + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const override + { + css::uno::Type lhs, rhs; + if ( !( _lhs >>= lhs ) + || !( _rhs >>= rhs ) + ) + throw css::lang::IllegalArgumentException(); + return lhs.getTypeName() < rhs.getTypeName(); + } + }; + + + //= EnumPredicateLess + + class EnumPredicateLess final : public IKeyPredicateLess + { + public: + EnumPredicateLess( css::uno::Type const & _enumType ) + :m_enumType( _enumType ) + { + } + + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const override + { + sal_Int32 lhs(0), rhs(0); + if ( !::cppu::enum2int( lhs, _lhs ) + || !::cppu::enum2int( rhs, _rhs ) + || !_lhs.getValueType().equals( m_enumType ) + || !_rhs.getValueType().equals( m_enumType ) + ) + throw css::lang::IllegalArgumentException(); + return lhs < rhs; + } + + private: + css::uno::Type const m_enumType; + }; + + + //= InterfacePredicateLess + + class InterfacePredicateLess final : public IKeyPredicateLess + { + public: + virtual bool isLess( css::uno::Any const & _lhs, css::uno::Any const & _rhs ) const override + { + if ( ( _lhs.getValueTypeClass() != css::uno::TypeClass_INTERFACE ) + || ( _rhs.getValueTypeClass() != css::uno::TypeClass_INTERFACE ) + ) + throw css::lang::IllegalArgumentException(); + + css::uno::Reference< css::uno::XInterface > lhs( _lhs, css::uno::UNO_QUERY ); + css::uno::Reference< css::uno::XInterface > rhs( _rhs, css::uno::UNO_QUERY ); + return lhs.get() < rhs.get(); + } + }; + + + //= getStandardLessPredicate + + /** creates a default IKeyPredicateLess instance for the given UNO type + @param i_type + the type for which a predicate instance should be created + @param i_collator + specifies a collator instance to use, or . If , strings will be compared using the < + operator, otherwise the collator will be used. The parameter is ignored if i_type does not specify + the string type. + @return + a default implementation of IKeyPredicateLess, which is able to compare values of the given type. If no + such default implementation is known for the given type, then is returned. + */ + ::std::unique_ptr< IKeyPredicateLess > COMPHELPER_DLLPUBLIC + getStandardLessPredicate( + css::uno::Type const & i_type, + css::uno::Reference< css::i18n::XCollator > const & i_collator + ); + + /** + Compare two Anys. + */ + bool COMPHELPER_DLLPUBLIC anyLess( css::uno::Any const & lhs, css::uno::Any const & rhs); + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_ANYCOMPARE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/anytohash.hxx b/include/comphelper/anytohash.hxx new file mode 100644 index 000000000..0aa14f47e --- /dev/null +++ b/include/comphelper/anytohash.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ANYTOHASH_HXX +#define INCLUDED_COMPHELPER_ANYTOHASH_HXX + +#include + +#include + +namespace com::sun::star::uno +{ +class Any; +} + +namespace comphelper +{ +/** Tries to get a hash value for an ANY value. + + Not all cases may be implemented, in which case no value is returned. + + @param value + ANY value + @return + hash of given ANY value, or not available +*/ +COMPHELPER_DLLPUBLIC std::optional anyToHash(css::uno::Any const& value); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/anytostring.hxx b/include/comphelper/anytostring.hxx new file mode 100644 index 000000000..6d100221e --- /dev/null +++ b/include/comphelper/anytostring.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ANYTOSTRING_HXX +#define INCLUDED_COMPHELPER_ANYTOSTRING_HXX + +#include +#include + +namespace com::sun::star::uno +{ +class Any; +} + +namespace comphelper +{ +/** Creates a STRING representation out of an ANY value. + + @param value + ANY value + @return + STRING representation of given ANY value +*/ +COMPHELPER_DLLPUBLIC OUString anyToString(css::uno::Any const& value); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/asyncnotification.hxx b/include/comphelper/asyncnotification.hxx new file mode 100644 index 000000000..ea6b067cc --- /dev/null +++ b/include/comphelper/asyncnotification.hxx @@ -0,0 +1,226 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ASYNCNOTIFICATION_HXX +#define INCLUDED_COMPHELPER_ASYNCNOTIFICATION_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper +{ + //= AnyEvent + + /** the very basic instance to hold a description of an event + */ + class COMPHELPER_DLLPUBLIC AnyEvent : public salhelper::SimpleReferenceObject + { + public: + AnyEvent(); + + protected: + virtual ~AnyEvent() override; + + private: + AnyEvent( AnyEvent const & ) = delete; + AnyEvent& operator=( AnyEvent const & ) = delete; + }; + + + //= typedefs + + typedef ::rtl::Reference< AnyEvent > AnyEventRef; + + + //= IEventProcessor + + /** an event processor + + @see AsyncEventNotifier + */ + class SAL_NO_VTABLE IEventProcessor + { + public: + /** process a single event + */ + virtual void processEvent( const AnyEvent& _rEvent ) = 0; + + virtual void SAL_CALL acquire() noexcept = 0; + virtual void SAL_CALL release() noexcept = 0; + + protected: + ~IEventProcessor() {} + }; + + + //= AsyncEventNotifier + + struct EventNotifierImpl; + + /** a helper class for notifying events asynchronously + + If you need to notify certain events to external components, you usually should + not do this while you have mutexes locked, to prevent multi-threading issues. + + However, you do not always have complete control over all mutex guards on the stack. + If, in such a case, the listener notification is one-way, you can decide to do it + asynchronously. + + The ->AsyncEventNotifier helps you to process such events asynchronously. Every + event is tied to an ->IEventProcessor which is responsible for processing it. + + The AsyncEventNotifier is implemented as a thread itself, which sleeps as long as there are no + events in the queue. As soon as you add an event, the thread is woken up, processes the event, + and sleeps again. + */ + class COMPHELPER_DLLPUBLIC AsyncEventNotifierBase + { + friend struct EventNotifierImpl; + + protected: + std::unique_ptr m_xImpl; + + SAL_DLLPRIVATE virtual ~AsyncEventNotifierBase(); + + // Thread + SAL_DLLPRIVATE virtual void execute(); + + public: + AsyncEventNotifierBase(); + + /** terminates the thread + + Note that this is a cooperative termination - if you call this from a thread different + from the notification thread itself, then it will block until the notification thread + finished processing the current event. If you call it from the notification thread + itself, it will return immediately, and the thread will be terminated as soon as + the current notification is finished. + */ + virtual void SAL_CALL terminate(); + + /** adds an event to the queue, together with the instance which is responsible for + processing it + + @param _rEvent + the event to add to the queue + @param _xProcessor + the processor for the event.
+ Beware of life time issues here. If your event processor dies or becomes otherwise + nonfunctional, you are responsible for removing all respective events from the queue. + You can do this by calling ->removeEventsForProcessor + */ + void addEvent( const AnyEventRef& _rEvent, const ::rtl::Reference< IEventProcessor >& _xProcessor ); + + /** removes all events for the given event processor from the queue + */ + void removeEventsForProcessor( const ::rtl::Reference< IEventProcessor >& _xProcessor ); + }; + + /** This class is usable with rtl::Reference. + As always, the thread must be joined somewhere. + */ + class COMPHELPER_DLLPUBLIC AsyncEventNotifier final + : public AsyncEventNotifierBase + , public salhelper::Thread + { + + private: + SAL_DLLPRIVATE virtual ~AsyncEventNotifier() override; + + SAL_DLLPRIVATE virtual void execute() override; + + public: + /** constructs a notifier thread + + @param name the thread name, see ::osl_setThreadName; must not be + null + */ + AsyncEventNotifier(char const* name); + + virtual void SAL_CALL terminate() override; + }; + + /** This is a hack (when proper joining is not possible), use of which + should be avoided by good design. + */ + class COMPHELPER_DLLPUBLIC AsyncEventNotifierAutoJoin final + : public AsyncEventNotifierBase + , private osl::Thread + { + + private: + SAL_DLLPRIVATE AsyncEventNotifierAutoJoin(char const* name); + + SAL_DLLPRIVATE virtual void SAL_CALL run() override; + SAL_DLLPRIVATE virtual void SAL_CALL onTerminated() override; + + public: + // only public so shared_ptr finds it + SAL_DLLPRIVATE virtual ~AsyncEventNotifierAutoJoin() override; + + static std::shared_ptr + newAsyncEventNotifierAutoJoin(char const* name); + + virtual void SAL_CALL terminate() override; + + using osl::Thread::join; + using osl::Thread::operator new; + using osl::Thread::operator delete; // clang really wants this? + + static void launch(std::shared_ptr const&); + }; + + + //= EventHolder + + /** AnyEvent derivee holding a foreign event instance + */ + template < typename EVENT_OBJECT > + class SAL_DLLPUBLIC_RTTI EventHolder final : public AnyEvent + { + public: + typedef EVENT_OBJECT EventObjectType; + + private: + EventObjectType const m_aEvent; + + public: + EventHolder( EventObjectType _aEvent ) + :m_aEvent(std::move( _aEvent )) + { + } + + const EventObjectType& getEventObject() const { return m_aEvent; } + }; + + COMPHELPER_DLLPUBLIC void JoinAsyncEventNotifiers(); + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_ASYNCNOTIFICATION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/asyncquithandler.hxx b/include/comphelper/asyncquithandler.hxx new file mode 100644 index 000000000..ce3db23a1 --- /dev/null +++ b/include/comphelper/asyncquithandler.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ASYNCQUITHANDLER_HXX +#define INCLUDED_COMPHELPER_ASYNCQUITHANDLER_HXX + +#include +#include + +// Use: Application::PostUserEvent( LINK( &AsyncQuitHandler::instance(), AsyncQuitHandler, OnAsyncQuit ) ); + +class COMPHELPER_DLLPUBLIC AsyncQuitHandler +{ + AsyncQuitHandler(); + +public: + AsyncQuitHandler(const AsyncQuitHandler&) = delete; + const AsyncQuitHandler& operator=(const AsyncQuitHandler&) = delete; + + static AsyncQuitHandler& instance(); + static void QuitApplication(); + + DECL_STATIC_LINK(AsyncQuitHandler, OnAsyncQuit, void*, void); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/attributelist.hxx b/include/comphelper/attributelist.hxx new file mode 100644 index 000000000..0309ab608 --- /dev/null +++ b/include/comphelper/attributelist.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ATTRIBUTELIST_HXX +#define INCLUDED_COMPHELPER_ATTRIBUTELIST_HXX + +#include + +#include +#include + +#include +#include +#include +#include + +namespace comphelper +{ + +struct TagAttribute +{ + OUString sName; + OUString sType; + OUString sValue; +}; + +class COMPHELPER_DLLPUBLIC AttributeList final : + public ::cppu::WeakImplHelper +{ + std::vector mAttributes; +public: + AttributeList(); + AttributeList(const AttributeList &r); + + virtual ~AttributeList() override; + + // methods that are not contained in any interface + void AddAttribute(const OUString &sName , const OUString &sType , const OUString &sValue) + { + mAttributes.push_back({sName, sType, sValue}); + } + void Clear() + { + mAttributes.clear(); + } + + // css::xml::sax::XAttributeList + virtual sal_Int16 SAL_CALL getLength() override + { + return static_cast(mAttributes.size()); + } + virtual OUString SAL_CALL getNameByIndex(sal_Int16 i) override + { + return mAttributes[i].sName; + } + virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i) override + { + return mAttributes[i].sType; + } + virtual OUString SAL_CALL getTypeByName(const OUString& aName) override; + virtual OUString SAL_CALL getValueByIndex(sal_Int16 i) override + { + return mAttributes[i].sValue; + } + virtual OUString SAL_CALL getValueByName(const OUString& aName) override; + + // css::util::XCloneable + virtual css::uno::Reference< XCloneable > SAL_CALL + createClone() override; +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_ATTRIBUTELIST_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/automationinvokedzone.hxx b/include/comphelper/automationinvokedzone.hxx new file mode 100644 index 000000000..81b0bfab6 --- /dev/null +++ b/include/comphelper/automationinvokedzone.hxx @@ -0,0 +1,36 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_AUTOMATIONINVOKEDZONE_HXX +#define INCLUDED_COMPHELPER_AUTOMATIONINVOKEDZONE_HXX + +#include + +// Helpers for use when calling into LO from an Automation (OLE +// Automation) client. + +namespace comphelper::Automation +{ +// Create an object of this class at the start of a function directly invoked from an Automation +// client. + +class COMPHELPER_DLLPUBLIC AutomationInvokedZone +{ +public: + AutomationInvokedZone(); + + ~AutomationInvokedZone(); + + static bool isActive(); +}; +} + +#endif // INCLUDED_COMPHELPER_AUTOMATIONINVOKEDZONE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/backupfilehelper.hxx b/include/comphelper/backupfilehelper.hxx new file mode 100644 index 000000000..abf8044a2 --- /dev/null +++ b/include/comphelper/backupfilehelper.hxx @@ -0,0 +1,216 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_BACKUPFILEHELPER_HXX +#define INCLUDED_COMPHELPER_BACKUPFILEHELPER_HXX + +#include + +#include +#include +#include +#include +#include + +namespace comphelper +{ + /** Helper class to backup/restore a single file + * + * This is a general class to manage backups/restore of the file + * given by the URL. The container holding the backups is created + * aside the original file, e.g for 'test.txt' a container + * called '.test.pack' will be used. If it was not yet backed-up + * this container file will be created at the 1st backup and deleted + * when the last gets removed. The container holds a stack with a + * maximum given number (in the constructor) of copies, these are by + * default compressed, but don't have to be (see tryPush). + * + * Due to being on a low system level here, no UNO API and not much + * other tooling can be used, as a consequence for the container a + * own simple format is used and e.g. the zip lib directly. + * + * You need to hand over the URL of the file to look at and + * a maximum number of allowed copies. That number is internally + * limited to an absolute max of 10 (see implementation). The number + * of allowed copies is limited to [1..max]. + * + * Calling tryPush() will check if there is no backup yet or if + * there is one that the file has changed. If yes, a new copy is + * created on a kind of 'stack' of copies. The return value can + * be used to see if a backup was indeed created. + * + * Calling tryPop() will do the opposite: if a backup is available, + * delete the orig file and re-instantiate the backup. The backup + * is taken off the 'stack' of copies. The return value can be + * used to check if this was done. + * + * isPopPossible can be called to see if there is a backup available + * before calling tryPop(). + * + * The 'stack' of copies works by using the same path, filename + * and extension, but adding a '_1' -> '_(num_of_copy)' to it. + */ + class COMPHELPER_DLLPUBLIC BackupFileHelper + { + private: + // internal data + std::set< OUString > maDirs; + std::set< std::pair< OUString, OUString > > maFiles; + + sal_uInt16 mnNumBackups; + sal_uInt16 mnMode; + + bool mbActive; + bool mbExtensions; + bool mbCompress; + + // internal flag if _exit() was called already - a hint to evtl. + // not create copies of potentially not well-defined data. This + // may be used in destructors of static instances - which unfortunately + // get called on WNT but not on linux. Thus I thought about encapsulating + // in some '#ifdefs', but it's just more safe to always do it and + // allows to add a SAL_WARN when one of these destructors is called + // after _exit() + static bool mbExitWasCalled; + + // internal detector if SafeModeName dir exists + static bool mbSafeModeDirExists; + + // internal upper limit (max) of allowed backups + static sal_uInt16 mnMaxAllowedBackups; + + // path to User's configuration directory and derived strings + static OUString maInitialBaseURL; + static OUString maUserConfigBaseURL; + static OUString maUserConfigWorkURL; + static OUString maRegModName; + static OUString maExt; + + // get path to User's configuration directory (created on-demand) + static const OUString& getInitialBaseURL(); + + // the name of the SafeMode directory for temporary processing + static const OUString& getSafeModeName(); + + public: + /** Constructor to handle Backups of the given file, will internally + * detect configuration values and URL to initial registrymodifications + * and thus the User configuration directory + */ + BackupFileHelper(); + + // allow to set static global flag when app had to call _exit() + static void setExitWasCalled(); + static bool getExitWasCalled(); + + // This call initializes the state of the UserDirectory as needed, it may + // initialize to SafeMode configuration or return from it by moving files + // in that directory + static void reactOnSafeMode(bool bSafeMode); + + /** tries to create a new backup, if there is none yet, or if the + * last differs from the base file. It will then put a new version + * on the 'stack' of copies and evtl. delete the oldest backup. + * Also may cleanup older backups when NumBackups given in the + * constructor has changed. + * + * tryPushExtensionInfo is the specialized version for ExtensionInfo + */ + void tryPush(); + void tryPushExtensionInfo(); + + /** finds out if a restore is possible + * + * @return bool + * returns true if a restore to an older backup is possible + * + * isPopPossibleExtensionInfo is the specialized version for ExtensionInfo + */ + bool isPopPossible(); + bool isPopPossibleExtensionInfo() const; + + /** tries to execute a restore. Will overwrite the base file + * in that case and take one version off the 'stack' of copies. + * Also may cleanup older backups when NumBackups given in the + * constructor has changed. + * + * tryPopExtensionInfo is the specialized version for ExtensionInfo + */ + void tryPop(); + void tryPopExtensionInfo(); + + /** tries to iterate the extensions and to disable all of them + */ + static bool isTryDisableAllExtensionsPossible(); + static void tryDisableAllExtensions(); + + /** Deinstall all User Extensions (installed for User only) + */ + static bool isTryDeinstallUserExtensionsPossible(); + static void tryDeinstallUserExtensions(); + + /** Reset shared Extensions + */ + static bool isTryResetSharedExtensionsPossible(); + static void tryResetSharedExtensions(); + + /** Reset bundled Extensions + */ + static bool isTryResetBundledExtensionsPossible(); + static void tryResetBundledExtensions(); + + /// Disables OpenGL and OpenCL + static void tryDisableHWAcceleration(); + + /** resets User-Customizations like Settings and UserInterface modifications + */ + static bool isTryResetCustomizationsPossible(); + static void tryResetCustomizations(); + + /** resets the whole UserProfile + */ + static void tryResetUserProfile(); + + /** Return the profile url */ + static const OUString& getUserProfileURL(); + + /** Return the url of the backed up profile (when in safe mode) */ + static const OUString& getUserProfileWorkURL(); + + private: + // internal helper methods + static OUString getPackURL(); + static const std::vector< OUString >& getCustomizationDirNames(); + static const std::vector< OUString >& getCustomizationFileNames(); + + // file push helpers + bool tryPush_Files(const std::set< OUString >& rDirs, const std::set< std::pair< OUString, OUString > >& rFiles, std::u16string_view rSourceURL, const OUString& rTargetURL); + bool tryPush_file(std::u16string_view rSourceURL, std::u16string_view rTargetURL, std::u16string_view rName, std::u16string_view rExt); + + // file pop possibilities helper + bool isPopPossible_files(const std::set< OUString >& rDirs, const std::set< std::pair< OUString, OUString > >& rFiles, std::u16string_view rSourceURL, std::u16string_view rTargetURL); + static bool isPopPossible_file(std::u16string_view rSourceURL, std::u16string_view rTargetURL, std::u16string_view rName, std::u16string_view rExt); + + // file pop helpers + bool tryPop_files(const std::set< OUString >& rDirs, const std::set< std::pair< OUString, OUString > >& rFiles, std::u16string_view rSourceURL, const OUString& rTargetURL); + bool tryPop_file(std::u16string_view rSourceURL, std::u16string_view rTargetURL, std::u16string_view rName, std::u16string_view rExt); + + // ExtensionInfo helpers + bool tryPush_extensionInfo(std::u16string_view rTargetURL); + static bool isPopPossible_extensionInfo(std::u16string_view rTargetURL); + bool tryPop_extensionInfo(std::u16string_view rTargetURL); + + // FileDirInfo helpers + void fillDirFileInfo(); + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/base64.hxx b/include/comphelper/base64.hxx new file mode 100644 index 000000000..78a0bacb5 --- /dev/null +++ b/include/comphelper/base64.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_BASE64_HXX +#define INCLUDED_COMPHELPER_BASE64_HXX + +#include + +#include + +#include + +#include +#include +#include + +namespace com::sun::star::uno +{ +template class Sequence; +} + +namespace comphelper +{ +class COMPHELPER_DLLPUBLIC Base64 +{ +public: + /** encodes the given byte sequence into Base64 */ + static void encode(OUStringBuffer& aStrBuffer, const css::uno::Sequence& aPass); + + static void encode(OStringBuffer& aStrBuffer, const css::uno::Sequence& aPass); + + // Decode a base 64 encoded string into a sequence of bytes. The first + // version can be used for attribute values only, because it does not + // return any chars left from conversion. + // For text submitted through the SAX characters call, the later method + // must be used! + static void decode(css::uno::Sequence& aPass, std::u16string_view sBuffer); + + static std::size_t decodeSomeChars(css::uno::Sequence& aPass, + std::u16string_view sBuffer); +}; +} + +#endif // INCLUDED_COMPHELPER_BASE64_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/basicio.hxx b/include/comphelper/basicio.hxx new file mode 100644 index 000000000..62260e3da --- /dev/null +++ b/include/comphelper/basicio.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_BASICIO_HXX +#define INCLUDED_COMPHELPER_BASICIO_HXX + +#include +#include +#include + +namespace com::sun::star::awt { struct FontDescriptor; } + +namespace comphelper +{ + +// bool +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, bool& _rVal); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, bool _bVal); +void operator <<( + css::uno::Reference const &, sal_Bool) + = delete; + +// OUString +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, OUString& _rStr); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, const OUString& _rStr); + +// sal_Int16 +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, sal_Int16& _rValue); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, sal_Int16 _nValue); + +// sal_uInt16 +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, sal_uInt16& _rValue); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, sal_uInt16 _nValue); + +// sal_uInt32 +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, sal_uInt32& _rValue); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, sal_uInt32 _nValue); + +// sal_Int16 +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, sal_Int32& _rValue); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, sal_Int32 _nValue); + +// FontDescriptor +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator >> (const css::uno::Reference& InStream, css::awt::FontDescriptor& rVal); +COMPHELPER_DLLPUBLIC const css::uno::Reference& operator << (const css::uno::Reference& OutStream, const css::awt::FontDescriptor& rVal); + +// sequences +template +const css::uno::Reference& operator >> (const css::uno::Reference& _rxInStream, css::uno::Sequence& _rSeq) +{ + _rSeq.realloc(_rxInStream->readLong()); + for (ELEMENT& rElement : asNonConstRange(_rSeq)) + _rxInStream >> rElement; + return _rxInStream; +} + +template +const css::uno::Reference& operator << (const css::uno::Reference& _rxOutStream, const css::uno::Sequence& _rSeq) +{ + _rxOutStream->writeLong(_rSeq.getLength()); + for (const ELEMENT& rElement : _rSeq) + _rxOutStream << rElement; + return _rxOutStream; +} + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_BASICIO_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/broadcasthelper.hxx b/include/comphelper/broadcasthelper.hxx new file mode 100644 index 000000000..65fa6d315 --- /dev/null +++ b/include/comphelper/broadcasthelper.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_BROADCASTHELPER_HXX +#define INCLUDED_COMPHELPER_BROADCASTHELPER_HXX + +#include +#include + +namespace comphelper +{ + // OMutexAndBroadcastHelper - a class which holds a Mutex and an OBroadcastHelper; + // needed because when deriving from OPropertySetHelper, + // the OBroadcastHelper has to be initialized before + // the OPropertySetHelper + + class OMutexAndBroadcastHelper + { + protected: + ::osl::Mutex m_aMutex; + ::cppu::OBroadcastHelper m_aBHelper; + + public: + OMutexAndBroadcastHelper() : m_aBHelper( m_aMutex ) { } + + ::osl::Mutex& GetMutex() { return m_aMutex; } + ::cppu::OBroadcastHelper& GetBroadcastHelper() { return m_aBHelper; } + const ::cppu::OBroadcastHelper& GetBroadcastHelper() const { return m_aBHelper; } + + }; +} + +#endif // INCLUDED_COMPHELPER_BROADCASTHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/bytereader.hxx b/include/comphelper/bytereader.hxx new file mode 100644 index 000000000..a7e899098 --- /dev/null +++ b/include/comphelper/bytereader.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#pragma once + +#include +#include + +namespace comphelper +{ +/** + * Interface that we can cast to, to bypass the inefficiency of using Sequence + * when reading via XInputStream. + */ +class COMPHELPER_DLLPUBLIC ByteReader +{ +public: + virtual ~ByteReader(); + virtual sal_Int32 readSomeBytes(sal_Int8* aData, sal_Int32 nBytesToRead) = 0; + + static const css::uno::Sequence& getUnoTunnelId(); +}; + +/** + * Interface that we can cast to, to bypass the inefficiency of using Sequence + * when writing via XOutputStream. + */ +class COMPHELPER_DLLPUBLIC ByteWriter +{ +public: + virtual ~ByteWriter(); + virtual sal_Int32 writeSomeBytes(const sal_Int8* aData, sal_Int32 nBytesToWrite) = 0; + + static const css::uno::Sequence& getUnoTunnelId(); +}; + +} // namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/comphelper/classids.hxx b/include/comphelper/classids.hxx new file mode 100644 index 000000000..4c345b84b --- /dev/null +++ b/include/comphelper/classids.hxx @@ -0,0 +1,334 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_CLASSIDS_HXX +#define INCLUDED_COMPHELPER_CLASSIDS_HXX + +/* + * StarWriter + */ + +/* 3.0 */ + +#define SO3_SW_CLASSID_30 \ + 0xDC5C7E40L, 0xB35C, 0x101B, 0x99, 0x61, 0x04, \ + 0x02, 0x1C, 0x00, 0x70, 0x02 + +/* 4.0 */ + +#define SO3_SW_CLASSID_40 \ + 0x8b04e9b0, 0x420e, 0x11d0, 0xa4, 0x5e, 0x0, \ + 0xa0, 0x24, 0x9d, 0x57, 0xb1 + +/* 5.0 */ + +#define SO3_SW_CLASSID_50 \ + 0xc20cf9d1, 0x85ae, 0x11d1, 0xaa, 0xb4, 0x0, \ + 0x60, 0x97, 0xda, 0x56, 0x1a + + /* 6.0, 7, 8 */ + +#define SO3_SW_CLASSID_60 \ + 0x8BC6B165, 0xB1B2, 0x4EDD, 0xAA, 0x47, 0xDA, \ + 0xE2, 0xEE, 0x68, 0x9D, 0xD6 + + /* ole embed 6.0, 7 */ + +#define SO3_SW_OLE_EMBED_CLASSID_60 \ + 0x30a2652a, 0xddf7, 0x45e7, 0xac, 0xa6, 0x3e, \ + 0xab, 0x26, 0xfc, 0x8a, 0x4e + + /* ole embed 8 */ + +#define SO3_SW_OLE_EMBED_CLASSID_8 \ + 0xf616b81f, 0x7bb8, 0x4f22, 0xb8, 0xa5, 0x47, \ + 0x42, 0x8d, 0x59, 0xf8, 0xad + +/* current */ + +#define SO3_SW_CLASSID SO3_SW_CLASSID_60 + +/* + * StarWriter/Web + */ + +/* 6.0, 7, 8 */ + +#define SO3_SWWEB_CLASSID_60 \ + 0xA8BBA60C, 0x7C60, 0x4550, 0x91, 0xCE, 0x39, \ + 0xC3, 0x90, 0x3F, 0xAC, 0x5E + +/* current */ + +#define SO3_SWWEB_CLASSID SO3_SWWEB_CLASSID_60 + +/* + * Globaldokument + */ + +/* 6.0, 7, 8 */ + +#define SO3_SWGLOB_CLASSID_60 \ + 0xB21A0A7C, 0xE403, 0x41FE, 0x95, 0x62, 0xBD, \ + 0x13, 0xEA, 0x6F, 0x15, 0xA0 + +/* current */ + +#define SO3_SWGLOB_CLASSID SO3_SWGLOB_CLASSID_60 + + +/* + * StarCalc + */ + +/* 3.0 */ + +#define SO3_SC_CLASSID_30 \ + 0x3F543FA0L, 0xB6A6, 0x101B, 0x99, 0x61, 0x04, \ + 0x02, 0x1C, 0x00, 0x70, 0x02 + +/* 4.0 */ + +#define SO3_SC_CLASSID_40 \ + 0x6361d441L, 0x4235, 0x11d0, 0x89, 0xcb, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 5.0 */ + +#define SO3_SC_CLASSID_50 \ + 0xc6a5b861L, 0x85d6, 0x11d1, 0x89, 0xcb, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 6.0 */ + +#define SO3_SC_CLASSID_60 \ + 0x47BBB4CB, 0xCE4C, 0x4E80, 0xA5, 0x91, 0x42, \ + 0xD9, 0xAE, 0x74, 0x95, 0x0F + +/* ole embed 6.0, 7 */ + +#define SO3_SC_OLE_EMBED_CLASSID_60 \ + 0x7b342dc4, 0x139a, 0x4a46, 0x8a, 0x93, 0xdb, \ + 0x8, 0x27, 0xcc, 0xee, 0x9c + +/* ole embed 8 */ + +#define SO3_SC_OLE_EMBED_CLASSID_8 \ + 0x7fa8ae11, 0xb3e3, 0x4d88, 0xaa, 0xbf, 0x25, \ + 0x55, 0x26, 0xcd, 0x1c, 0xe8 + +/* current */ + +#define SO3_SC_CLASSID SO3_SC_CLASSID_60 + +/**************************************************** +* StarImpress +****************************************************/ + +/* 3.0 */ + +#define SO3_SIMPRESS_CLASSID_30 \ + 0xAF10AAE0L, 0xB36D, 0x101B, 0x99, 0x61, 0x04, \ + 0x02, 0x1C, 0x00, 0x70, 0x02 + +/* 4.0 */ + +#define SO3_SIMPRESS_CLASSID_40 \ + 0x12d3cc0L, 0x4216, 0x11d0, 0x89, 0xcb, 0x0, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 5.0 */ + +#define SO3_SIMPRESS_CLASSID_50 \ + 0x565c7221L, 0x85bc, 0x11d1, 0x89, 0xd0, 0x0, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 6.0 */ + +#define SO3_SIMPRESS_CLASSID_60 \ + 0x9176E48A, 0x637A, 0x4D1F, 0x80, 0x3B, 0x99, \ + 0xD9, 0xBF, 0xAC, 0x10, 0x47 + +/* ole embed 6.0, 7 */ + +#define SO3_SIMPRESS_OLE_EMBED_CLASSID_60 \ + 0xe5a0b632, 0xdfba, 0x4549, 0x93, 0x46, 0xe4, \ + 0x14, 0xda, 0x6, 0xe6, 0xf8 + +/* ole embed 8 */ + +#define SO3_SIMPRESS_OLE_EMBED_CLASSID_8 \ + 0xee5d1ea4, 0xd445, 0x4289, 0xb2, 0xfc, 0x55, \ + 0xfc, 0x93, 0x69, 0x39, 0x17 + +/* current */ + +#define SO3_SIMPRESS_CLASSID SO3_SIMPRESS_CLASSID_60 + +/**************************************************** +* StarDraw +****************************************************/ + +/* 5.0 */ + +#define SO3_SDRAW_CLASSID_50 \ + 0x2e8905a0L, 0x85bd, 0x11d1, 0x89, 0xd0, 0x0, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 6.0 */ +#define SO3_SDRAW_CLASSID_60 \ + 0x4BAB8970, 0x8A3B, 0x45B3, 0x99, 0x1C, 0xCB, \ + 0xEE, 0xAC, 0x6B, 0xD5, 0xE3 + +/* ole embed 6.0, 7 */ + +#define SO3_SDRAW_OLE_EMBED_CLASSID_60 \ + 0x41662fc2, 0xd57, 0x4aff, 0xab, 0x27, 0xad, \ + 0x2e, 0x12, 0xe7, 0xc2, 0x73 + +/* ole embed 8 */ + +#define SO3_SDRAW_OLE_EMBED_CLASSID_8 \ + 0x448bb771, 0xcfe2, 0x47c4, 0xbc, 0xdf, 0x1f, \ + 0xbf, 0x37, 0x8e, 0x20, 0x2c + +/* current */ + +#define SO3_SDRAW_CLASSID SO3_SDRAW_CLASSID_60 + +/**************************************************** +* StarChart +****************************************************/ + +/* 3.0 */ + +#define SO3_SCH_CLASSID_30 \ + 0xFB9C99E0L, 0x2C6D, 0x101C, 0x8E, 0x2C, 0x00, \ + 0x00, 0x1B, 0x4C, 0xC7, 0x11 + +/* 4.0 */ + +#define SO3_SCH_CLASSID_40 \ + 0x2b3b7e0L, 0x4225, 0x11d0, 0x89, 0xca, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 5.0 */ + +#define SO3_SCH_CLASSID_50 \ + 0xbf884321L, 0x85dd, 0x11d1, 0x89, 0xd0, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 6.0 */ + +#define SO3_SCH_CLASSID_60 \ + 0x12DCAE26, 0x281F, 0x416F, 0xA2, 0x34, 0xC3, \ + 0x08, 0x61, 0x27, 0x38, 0x2E + +/* ole embed 6.0, 7 */ + +#define SO3_SCH_OLE_EMBED_CLASSID_60 \ + 0xd415cd93, 0x35c4, 0x4c6f, 0x81, 0x9d, 0xa6, \ + 0x64, 0xa1, 0xc8, 0x13, 0xae + +/* ole embed 8 */ + +#define SO3_SCH_OLE_EMBED_CLASSID_8 \ + 0xdd0a57f, 0xcf3b, 0x4fd2, 0xbd, 0xa4, 0x94, \ + 0x42, 0x71, 0x9b, 0x2a, 0x73 + +/* current */ + +#define SO3_SCH_CLASSID SO3_SCH_CLASSID_60 + +// Report chart + +#define SO3_RPTCH_CLASSID \ + 0x80243D39, 0x6741, 0x46C5, 0x92, 0x6E, 0x06, \ + 0x91, 0x64, 0xFF, 0x87, 0xBB + +/*************************************************** +* StarMath +***************************************************/ + +/* 3.0 */ + +#define SO3_SM_CLASSID_30 \ + 0xD4590460L, 0x35FD, 0x101C, 0xB1, 0x2A, 0x04, \ + 0x02, 0x1C, 0x00, 0x70, 0x02 + +/* 4.0 */ + +#define SO3_SM_CLASSID_40 \ + 0x2b3b7e1L, 0x4225, 0x11d0, 0x89, 0xca, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 5.0 */ + +#define SO3_SM_CLASSID_50 \ + 0xffb5e640L, 0x85de, 0x11d1, 0x89, 0xd0, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +/* 6.0, 7, 8 */ + +#define SO3_SM_CLASSID_60 \ + 0x078B7ABA, 0x54FC, 0x457F, 0x85, 0x51, 0x61, \ + 0x47, 0xE7, 0x76, 0xA9, 0x97 + +/* ole embed 6.0, 7 */ + +#define SO3_SM_OLE_EMBED_CLASSID_60 \ + 0xd0484de6, 0xaaee, 0x468a, 0x99, 0x1f, 0x8d, \ + 0x4b, 0x7, 0x37, 0xb5, 0x7a + +/* ole embed 8 */ + +#define SO3_SM_OLE_EMBED_CLASSID_8 \ + 0xd2d59cd1, 0xa6a, 0x4d36, 0xae, 0x20, 0x47, \ + 0x81, 0x70, 0x77, 0xd5, 0x7c + +/* current */ + +#define SO3_SM_CLASSID SO3_SM_CLASSID_60 + +#define SO3_OUT_CLASSID \ + 0x970b1e82, 0xcf2d, 0x11cf, 0x89, 0xca, 0x00, \ + 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +#define SO3_DUMMY_CLASSID \ + 0x970b1fff, 0xcf2d, 0x11cf, \ + 0x89,0xca,0x00,0x80,0x29,0xe4,0xb0,0xb1 + +#define SO3_APPLET_CLASSID \ + 0x970b1e81, 0xcf2d, 0x11cf, \ + 0x89,0xca,0x00,0x80,0x29,0xe4,0xb0,0xb1 + +#define SO3_PLUGIN_CLASSID \ + 0x4caa7761, 0x6b8b, 0x11cf, \ + 0x89,0xca,0x0,0x80,0x29,0xe4,0xb0,0xb1 + +#define SO3_IFRAME_CLASSID \ + 0x1a8a6701, 0xde58, 0x11cf, \ + 0x89, 0xca, 0x0, 0x80, 0x29, 0xe4, 0xb0, 0xb1 + +#define SO3_RPT_CLASSID_90 \ + 0xd7896d52, 0xb7af, 0x4820, \ + 0x9d, 0xfe, 0xd4, 0x04, 0xd0, 0x15, 0x96, 0x0f + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/compbase.hxx b/include/comphelper/compbase.hxx new file mode 100644 index 000000000..38380ede2 --- /dev/null +++ b/include/comphelper/compbase.hxx @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper +{ +/** + Serves two purposes + (1) extracts code that doesn't need to be templated + (2) helps to handle the custom where we have conflicting interfaces + e.g. multiple UNO interfaces that extend css::lang::XComponent +*/ +class COMPHELPER_DLLPUBLIC WeakComponentImplHelperBase : public cppu::OWeakObject, + public css::lang::XComponent +{ +public: + virtual ~WeakComponentImplHelperBase() override; + + // css::lang::XComponent + virtual void SAL_CALL dispose() override; + virtual void SAL_CALL + addEventListener(css::uno::Reference const& rxListener) override; + virtual void SAL_CALL + removeEventListener(css::uno::Reference const& rxListener) override; + + virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const& rType) override; + + /** + Called by dispose for subclasses to do dispose() work. + The mutex is held when called, and subclasses can unlock() the guard if necessary. + */ + virtual void disposing(std::unique_lock&); + +protected: + comphelper::OInterfaceContainerHelper4 maEventListeners; + mutable std::mutex m_aMutex; + bool m_bDisposed = false; +}; + +template +class SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper : public WeakComponentImplHelperBase, + public css::lang::XTypeProvider, + public Ifc... +{ +public: + virtual void SAL_CALL acquire() noexcept final override { OWeakObject::acquire(); } + + virtual void SAL_CALL release() noexcept final override { OWeakObject::release(); } + + // css::lang::XComponent + virtual void SAL_CALL dispose() noexcept final override + { + WeakComponentImplHelperBase::dispose(); + } + virtual void SAL_CALL addEventListener( + css::uno::Reference const& rxListener) final override + { + WeakComponentImplHelperBase::addEventListener(rxListener); + } + virtual void SAL_CALL removeEventListener( + css::uno::Reference const& rxListener) final override + { + WeakComponentImplHelperBase::removeEventListener(rxListener); + } + + virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const& rType) override + { + return WeakComponentImplHelper_query(rType, class_data_get(), this); + } + + // css::lang::XTypeProvider + virtual css::uno::Sequence SAL_CALL getTypes() override + { + static const css::uno::Sequence aTypeList{ + cppu::UnoType::get(), cppu::UnoType::get(), + cppu::UnoType::get(), cppu::UnoType::get()... + }; + return aTypeList; + } + virtual css::uno::Sequence SAL_CALL getImplementationId() override + { + return css::uno::Sequence(); + } + +private: + static cppu::class_data* class_data_get() + { + return cppu::detail::ImplClassData{}(); + } +}; + +/** WeakComponentImplHelper +*/ +COMPHELPER_DLLPUBLIC css::uno::Any +WeakComponentImplHelper_query(css::uno::Type const& rType, cppu::class_data* cd, + WeakComponentImplHelperBase* pBase); + +} // namespace comphelper + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/comphelper/comphelperdllapi.h b/include/comphelper/comphelperdllapi.h new file mode 100644 index 000000000..361326a4e --- /dev/null +++ b/include/comphelper/comphelperdllapi.h @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_COMPHELPERDLLAPI_H +#define INCLUDED_COMPHELPER_COMPHELPERDLLAPI_H + +#include + +#if defined(COMPHELPER_DLLIMPLEMENTATION) +#define COMPHELPER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define COMPHELPER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define COMPHELPER_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_COMPHELPER_COMPHELPERDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/componentbase.hxx b/include/comphelper/componentbase.hxx new file mode 100644 index 000000000..ce6353be4 --- /dev/null +++ b/include/comphelper/componentbase.hxx @@ -0,0 +1,139 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_COMPONENTBASE_HXX +#define INCLUDED_COMPHELPER_COMPONENTBASE_HXX + +#include +#include + + +namespace comphelper +{ + + + //= ComponentBase + + class COMPHELPER_DLLPUBLIC ComponentBase + { + protected: + /** creates a ComponentBase instance + + The instance is not initialized. As a consequence, every ComponentMethodGuard instantiated for + this component will throw a css::lang::NotInitializedException, + until ->setInitialized() is called. + */ + ComponentBase( ::cppu::OBroadcastHelper& _rBHelper ) + :m_rBHelper( _rBHelper ) + ,m_bInitialized( false ) + { + } + + struct NoInitializationNeeded { }; + + /** creates a ComponentBase instance + + The instance is already initialized, so there's no need to call setInitialized later on. Use this + constructor for component implementations which do not require explicit initialization. + */ + ComponentBase( ::cppu::OBroadcastHelper& _rBHelper, NoInitializationNeeded ) + :m_rBHelper( _rBHelper ) + ,m_bInitialized( true ) + { + } + + ~ComponentBase() COVERITY_NOEXCEPT_FALSE {} + + /** marks the instance as initialized + + Subsequent instantiations of a ComponentMethodGuard won't throw the NotInitializedException now. + */ + void setInitialized() { m_bInitialized = true; } + + public: + /// helper struct to grant access to selected public methods to the ComponentMethodGuard class + struct GuardAccess { friend class ComponentMethodGuard; private: GuardAccess() { } }; + + /// retrieves the component's mutex + ::osl::Mutex& getMutex( GuardAccess ) { return getMutex(); } + /// checks whether the component is already disposed, throws a DisposedException if so. + void checkDisposed( GuardAccess ) const; + /// checks whether the component is already initialized, throws a NotInitializedException if not. + void checkInitialized( GuardAccess ) const; + + protected: + /// retrieves the component's broadcast helper + ::cppu::OBroadcastHelper& getBroadcastHelper() { return m_rBHelper; } + /// retrieves the component's mutex + ::osl::Mutex& getMutex() { return m_rBHelper.rMutex; } + /// determines whether the instance is already disposed + bool impl_isDisposed() const { return m_rBHelper.bDisposed; } + + /// determines whether the component is already initialized + bool + impl_isInitialized_nothrow() const { return m_bInitialized; } + + /** returns the context to be used when throwing exceptions + + The default implementation returns . + */ + static css::uno::Reference< css::uno::XInterface > + getComponent(); + + private: + ::cppu::OBroadcastHelper& m_rBHelper; + bool m_bInitialized; + }; + + class ComponentMethodGuard + { + public: + enum class MethodType + { + /// allow the method to be called only when being initialized and not being disposed + Default, + /// allow the method to be called without being initialized + WithoutInit + + }; + + ComponentMethodGuard( ComponentBase& _rComponent, const MethodType _eType = MethodType::Default ) + :m_aMutexGuard( _rComponent.getMutex( ComponentBase::GuardAccess() ) ) + { + if ( _eType != MethodType::WithoutInit ) + _rComponent.checkInitialized( ComponentBase::GuardAccess() ); + _rComponent.checkDisposed( ComponentBase::GuardAccess() ); + } + + void clear() + { + m_aMutexGuard.clear(); + } + + private: + osl::ClearableMutexGuard m_aMutexGuard; + }; + + +} // namespace ComponentBase + + +#endif // INCLUDED_COMPHELPER_COMPONENTBASE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/componentguard.hxx b/include/comphelper/componentguard.hxx new file mode 100644 index 000000000..f3cf1bd5e --- /dev/null +++ b/include/comphelper/componentguard.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_COMPONENTGUARD_HXX +#define INCLUDED_COMPHELPER_COMPONENTGUARD_HXX + +#include + +#include +#include + + +namespace comphelper +{ + + + //= ComponentGuard + + class ComponentGuard + { + public: + ComponentGuard( ::cppu::OWeakObject& i_component, ::cppu::OBroadcastHelper & i_broadcastHelper ) + :m_aGuard( i_broadcastHelper.rMutex ) + { + if ( i_broadcastHelper.bDisposed ) + throw css::lang::DisposedException( OUString(), &i_component ); + } + + void clear() { m_aGuard.clear(); } + void reset() { m_aGuard.reset(); } + + private: + ::osl::ResettableMutexGuard m_aGuard; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_COMPONENTGUARD_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/configuration.hxx b/include/comphelper/configuration.hxx new file mode 100644 index 000000000..222b9d5af --- /dev/null +++ b/include/comphelper/configuration.hxx @@ -0,0 +1,342 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_CONFIGURATION_HXX +#define INCLUDED_COMPHELPER_CONFIGURATION_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace configuration { class XReadWriteAccess; } + namespace container { + class XHierarchicalNameAccess; + class XHierarchicalNameReplace; + class XNameAccess; + class XNameContainer; + } + namespace uno { class XComponentContext; } +} + +namespace comphelper { + +namespace detail { class ConfigurationWrapper; } + +/// A batch of configuration changes that is committed as a whole. +/// +/// Client code needs to call commit explicitly; otherwise the changes are lost +/// when the instance is destroyed. +/// +/// This is the only class from this header file that client code should use +/// directly. +class COMPHELPER_DLLPUBLIC ConfigurationChanges { +public: + static std::shared_ptr create(); + + ~ConfigurationChanges(); + + void commit() const; + +private: + ConfigurationChanges(const ConfigurationChanges&) = delete; + ConfigurationChanges& operator=(const ConfigurationChanges&) = delete; + + SAL_DLLPRIVATE ConfigurationChanges( + css::uno::Reference< css::uno::XComponentContext > + const & context); + + SAL_DLLPRIVATE void setPropertyValue( + OUString const & path, css::uno::Any const & value) + const; + + SAL_DLLPRIVATE css::uno::Reference< + css::container::XHierarchicalNameReplace > + getGroup(OUString const & path) const; + + SAL_DLLPRIVATE + css::uno::Reference< css::container::XNameContainer > + getSet(OUString const & path) const; + + css::uno::Reference< + css::configuration::XReadWriteAccess > access_; + + friend class detail::ConfigurationWrapper; +}; + +namespace detail { + +/// @internal +class COMPHELPER_DLLPUBLIC ConfigurationWrapper { +public: + static ConfigurationWrapper const & get(); + + bool isReadOnly(OUString const & path) const; + + css::uno::Any getPropertyValue(std::u16string_view path) const; + + static void setPropertyValue( + std::shared_ptr< ConfigurationChanges > const & batch, + OUString const & path, css::uno::Any const & value); + + css::uno::Any getLocalizedPropertyValue( + std::u16string_view path) const; + + static void setLocalizedPropertyValue( + std::shared_ptr< ConfigurationChanges > const & batch, + OUString const & path, css::uno::Any const & value); + + css::uno::Reference< + css::container::XHierarchicalNameAccess > + getGroupReadOnly(OUString const & path) const; + + static css::uno::Reference< + css::container::XHierarchicalNameReplace > + getGroupReadWrite( + std::shared_ptr< ConfigurationChanges > const & batch, + OUString const & path); + + css::uno::Reference< css::container::XNameAccess > + getSetReadOnly(OUString const & path) const; + + static css::uno::Reference< css::container::XNameContainer > + getSetReadWrite( + std::shared_ptr< ConfigurationChanges > const & batch, + OUString const & path); + + std::shared_ptr< ConfigurationChanges > createChanges() const; + +private: + SAL_DLLPRIVATE explicit ConfigurationWrapper(); + + SAL_DLLPRIVATE ~ConfigurationWrapper(); + + ConfigurationWrapper(const ConfigurationWrapper&) = delete; + ConfigurationWrapper& operator=(const ConfigurationWrapper&) = delete; + + css::uno::Reference< css::uno::XComponentContext > context_; + + css::uno::Reference< css::configuration::XReadWriteAccess > access_; + // should really be a css.configuration.ReadOnlyAccess (with added + // css.beans.XHierarchicalPropertySetInfo), but then + // configmgr::Access::asProperty() would report all properties as + // READONLY, so isReadOnly() would not work +}; + +/// @internal +template< typename T > struct Convert { + static css::uno::Any toAny(T const & value) + { return css::uno::Any(value); } + + static T fromAny(css::uno::Any const & value) + { return value.get< T >(); } + +private: + Convert(const Convert&) = delete; + Convert& operator=(const Convert&) = delete; + + Convert() = delete; + ~Convert() = delete; +}; + +/// @internal +template< typename T > struct Convert< std::optional< T > > +{ + static css::uno::Any toAny(std::optional< T > const & value) { + return value + ? css::uno::Any(*value) + : css::uno::Any(); + } + + static std::optional< T > fromAny(css::uno::Any const & value) + { + return value.hasValue() + ? std::optional< T >(value.get< T >()) : std::optional< T >(); + } + +private: + Convert(const Convert&) = delete; + Convert& operator=(const Convert&) = delete; + + Convert() = delete; + ~Convert() = delete; +}; + +} + +/// A type-safe wrapper around a (non-localized) configuration property. +/// +/// Automatically generated headers for the various configuration properties +/// derive from this template and make available its member functions to access +/// each given configuration property. +template< typename T, typename U > struct ConfigurationProperty +{ + /// Get the read-only status of the given (non-localized) configuration + /// property. + static bool isReadOnly() + { + return detail::ConfigurationWrapper::get().isReadOnly(T::path()); + } + + /// Get the value of the given (non-localized) configuration property. + /// + /// For nillable properties, U is of type std::optional. + static U get() + { + // Folding this into one statement causes a bogus error at least with + // Red Hat GCC 4.6.2-1: + css::uno::Any a( + detail::ConfigurationWrapper::get().getPropertyValue( + T::path())); + return detail::Convert< U >::fromAny(a); + } + + /// Set the value of the given (non-localized) configuration property, via a + /// given changes batch. + /// + /// For nillable properties, U is of type std::optional. + static void set( + U const & value, + std::shared_ptr< ConfigurationChanges > const & batch) + { + comphelper::detail::ConfigurationWrapper::setPropertyValue( + batch, T::path(), detail::Convert< U >::toAny(value)); + } + +private: + ConfigurationProperty(const ConfigurationProperty&) = delete; + ConfigurationProperty& operator=(const ConfigurationProperty&) = delete; + + ConfigurationProperty() = delete; + ~ConfigurationProperty() = delete; +}; + +/// A type-safe wrapper around a localized configuration property. +/// +/// Automatically generated headers for the various localized configuration +/// properties derive from this template and make available its member functions +/// to access each given localized configuration property. +template< typename T, typename U > struct ConfigurationLocalizedProperty +{ + /// Get the value of the given localized configuration property, for the + /// locale currently set at the + /// com.sun.star.configuration.theDefaultProvider. + /// + /// For nillable properties, U is of type std::optional. + static U get() + { + // Folding this into one statement causes a bogus error at least with + // Red Hat GCC 4.6.2-1: + css::uno::Any a( + detail::ConfigurationWrapper::get(). + getLocalizedPropertyValue(T::path())); + return detail::Convert< U >::fromAny(a); + } + + /// Set the value of the given localized configuration property, for the + /// locale currently set at the + /// com.sun.star.configuration.theDefaultProvider, via a given changes + /// batch. + /// + /// For nillable properties, U is of type std::optional. + static void set( + U const & value, + std::shared_ptr< ConfigurationChanges > const & batch) + { + comphelper::detail::ConfigurationWrapper::setLocalizedPropertyValue( + batch, T::path(), detail::Convert< U >::toAny(value)); + } + +private: + ConfigurationLocalizedProperty(const ConfigurationLocalizedProperty&) = delete; + ConfigurationLocalizedProperty& operator=(const ConfigurationLocalizedProperty&) = delete; + + ConfigurationLocalizedProperty() = delete; + ~ConfigurationLocalizedProperty() = delete; +}; + +/// A type-safe wrapper around a configuration group. +/// +/// Automatically generated headers for the various configuration groups derive +/// from this template and make available its member functions to access each +/// given configuration group. +template< typename T > struct ConfigurationGroup { + /// Get read-only access to the given configuration group. + static css::uno::Reference< + css::container::XHierarchicalNameAccess > + get() + { + return detail::ConfigurationWrapper::get().getGroupReadOnly( + T::path()); + } + + /// Get read/write access to the given configuration group, storing any + /// modifications via the given changes batch. + static css::uno::Reference< + css::container::XHierarchicalNameReplace > + get(std::shared_ptr< ConfigurationChanges > const & batch) + { + return comphelper::detail::ConfigurationWrapper::getGroupReadWrite( + batch, T::path()); + } + +private: + ConfigurationGroup(const ConfigurationGroup&) = delete; + ConfigurationGroup& operator=(const ConfigurationGroup&) = delete; + + ConfigurationGroup() = delete; + ~ConfigurationGroup() = delete; +}; + +/// A type-safe wrapper around a configuration set. +/// +/// Automatically generated headers for the various configuration sets derive +/// from this template and make available its member functions to access each +/// given configuration set. +template< typename T > struct ConfigurationSet { + /// Get read-only access to the given configuration set. + static + css::uno::Reference< css::container::XNameAccess > + get() + { + return detail::ConfigurationWrapper::get().getSetReadOnly( + T::path()); + } + + /// Get read/write access to the given configuration set, storing any + /// modifications via the given changes batch. + static + css::uno::Reference< css::container::XNameContainer > + get(std::shared_ptr< ConfigurationChanges > const & batch) + { + return comphelper::detail::ConfigurationWrapper::getSetReadWrite( + batch, T::path()); + } + +private: + ConfigurationSet(const ConfigurationSet&) = delete; + ConfigurationSet& operator=(const ConfigurationSet&) = delete; + + ConfigurationSet() = delete; + ~ConfigurationSet() = delete; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/configurationhelper.hxx b/include/comphelper/configurationhelper.hxx new file mode 100644 index 000000000..162319316 --- /dev/null +++ b/include/comphelper/configurationhelper.hxx @@ -0,0 +1,239 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_CONFIGURATIONHELPER_HXX +#define INCLUDED_COMPHELPER_CONFIGURATIONHELPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { class XInterface; } + +namespace comphelper +{ + /** specify all possible modes, which can be used to open a configuration access. + * + * @see openConfig() + * @see readDirectKey() + * @see writeDirectKey() + */ + enum class EConfigurationModes + { + /// opens configuration in read/write mode (without LAZY writing!) + Standard = 0, + /// configuration will be opened readonly + ReadOnly = 1, + /// all localized nodes will be interpreted as XInterface instead of interpreting it as atomic value nodes + AllLocales = 2 + }; + + +} + +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace comphelper +{ + +class COMPHELPER_DLLPUBLIC ConfigurationHelper +{ +public: + /** returns access to the specified configuration package. + * + * This method should be used, if e.g. more than one request to the same + * configuration package is needed. The configuration access can be cached + * outside and used inbetween. + * + * @param rxContext + * the uno service manager, which should be used to create the + * configuration access. + * + * @param sPackage + * the name of the configuration package. + * e.g.
    + *
  • org.openoffice.Office.Common
  • + *
  • org.openoffice.Office.Common/Menu
  • + *
+ * + * @param eMode + * specify the open mode for the returned configuration access. + * It's interpreted as a flag field and can be any useful combination + * of values of EConfigurationModes. + * + * @throw Any exceptions the underlying configuration can throw. + * E.g. css::uno::Exception if the configuration could not be opened. + */ + static css::uno::Reference< css::uno::XInterface > openConfig(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& sPackage, + EConfigurationModes eMode ); + + + /** reads the value of an existing(!) configuration key, + * which is searched relative to the specified configuration access. + * + * This method must be used in combination with openConfig(). + * The cached configuration access must be provided here ... and + * all operations are made relative to this access point. + * + * @param xCFG + * the configuration root, where sRelPath should be interpreted. + * as relative path + * + * @param sRelPath + * path relative to xCFG parameter. + * + * @param sKey + * the configuration node, where we should read the value. + * + * @return [css.uno.Any] + * the value of sKey. + * + * @throw Any exceptions the underlying configuration can throw. + * E.g. css::container::NoSuchElementException if the specified + * key does not exists. + */ + static css::uno::Any readRelativeKey(const css::uno::Reference< css::uno::XInterface >& xCFG , + const OUString& sRelPath, + const OUString& sKey ); + + + /** writes a new value for an existing(!) configuration key, + * which is searched relative to the specified configuration access. + * + * This method must be used in combination with openConfig(). + * The cached configuration access must be provided here ... and + * all operations are made relative to this access point. + * + * @param xCFG + * the configuration root, where sRelPath should be interpreted. + * as relative path + * + * @param sRelPath + * path relative to xCFG parameter. + * + * @param sKey + * the configuration node, where we should write the new value. + * + * @param aValue + * the new value for sKey. + * + * @throw Any exceptions the underlying configuration can throw. + * E.g. css::container::NoSuchElementException if the specified + * key does not exists or css::uno::Exception if the provided configuration + * access does not allow writing for this key. + */ + static void writeRelativeKey(const css::uno::Reference< css::uno::XInterface >& xCFG , + const OUString& sRelPath, + const OUString& sKey , + const css::uno::Any& aValue ); + + + /** it checks if the specified set node exists ... or create an empty one + * otherwise. + * + * This method must be used in combination with openConfig(). + * The cached configuration access must be provided here ... and + * all operations are made relative to this access point. + * + * Further this method must be used only with configuration set's. + * Atomic keys can't be "created"... they "exist every time". + * + * @param xCFG + * the configuration root, where sRelPathToSet should be interpreted + * as relative path. + * + * @param sRelPathToSet + * path relative to xCFG parameter. + * + * @param sSetNode + * the set node, which should be checked if its exists ... + * or which should be created with default values. + * + * @return A reference to the found (or new created) set node. + * Can't be NULL .. in such case an exception occurs! + * + * @throw Any exceptions the underlying configuration can throw. + * E.g. css::uno::Exception if the provided configuration + * access does not allow writing for this set. + */ + static css::uno::Reference< css::uno::XInterface > makeSureSetNodeExists(const css::uno::Reference< css::uno::XInterface >& xCFG , + const OUString& sRelPathToSet, + const OUString& sSetNode ); + + + /** commit all changes made on the specified configuration access. + * + * This method must be used in combination with openConfig(). + * The cached configuration access must be provided here. + * + * @param xCFG + * the configuration root, where changes should be committed. + * + * @throw Any exceptions the underlying configuration can throw. + * E.g. css::uno::Exception if the provided configuration + * access does not allow writing for this set. + */ + static void flush(const css::uno::Reference< css::uno::XInterface >& xCFG); + + + /** does the same then openConfig() & readRelativeKey() together. + * + * This method should be used for reading one key at one code place only. + * Because it opens the specified configuration package, reads the key and + * closes the configuration again. + * + * So it's not very useful to use this method for reading multiple keys at the same time. + * (Excepting these keys exists inside different configuration packages ...)) + */ + static css::uno::Any readDirectKey(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& sPackage, + const OUString& sRelPath, + const OUString& sKey , + EConfigurationModes eMode ); + + + /** does the same then openConfig() / writeRelativeKey() & flush() together. + * + * This method should be used for writing one key at one code place only. + * Because it opens the specified configuration package, writes the key, flush + * all changes and closes the configuration again. + * + * So it's not very useful to use this method for writing multiple keys at the same time. + * (Excepting these keys exists inside different configuration packages ...)) + */ + static void writeDirectKey(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& sPackage, + const OUString& sRelPath, + const OUString& sKey , + const css::uno::Any& aValue , + EConfigurationModes eMode ); +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_CONFIGURATIONHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/configurationlistener.hxx b/include/comphelper/configurationlistener.hxx new file mode 100644 index 000000000..55342514c --- /dev/null +++ b/include/comphelper/configurationlistener.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_CONFIGURATIONLISTENER_HXX +#define INCLUDED_COMPHELPER_CONFIGURATIONLISTENER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyChangeEvent; } +namespace com::sun::star::uno { class XComponentContext; } + +namespace comphelper { + +class ConfigurationListener; + +class COMPHELPER_DLLPUBLIC ConfigurationListenerPropertyBase { +public: + OUString maName; + rtl::Reference mxListener; + + virtual ~ConfigurationListenerPropertyBase() {} + virtual void setProperty(const css::uno::Any &aProperty) = 0; + void dispose() { mxListener.clear(); } +}; + +/// Access to this class must be protected by the SolarMutex +template< typename uno_type > class ConfigurationListenerProperty : public ConfigurationListenerPropertyBase +{ + uno_type maValue; +protected: + virtual void setProperty(const css::uno::Any &aProperty) override + { + aProperty >>= maValue; + } +public: + /** + * Provide a mirror of the configmgr's version of this property + * for the lifecycle of this property. The property value tracks + * the same value in the configuration. + */ + inline ConfigurationListenerProperty(const rtl::Reference< ConfigurationListener > &xListener, + const OUString &rProp ); + + virtual inline ~ConfigurationListenerProperty() override; + + uno_type get() const { return maValue; } +}; + +// workaround for incremental linking bugs in MSVC2019 +class SAL_DLLPUBLIC_TEMPLATE ConfigurationListener_Base : public cppu::WeakImplHelper< css::beans::XPropertyChangeListener > {}; +class COMPHELPER_DLLPUBLIC ConfigurationListener final : public ConfigurationListener_Base +{ + css::uno::Reference< css::beans::XPropertySet > mxConfig; + std::vector< ConfigurationListenerPropertyBase * > maListeners; + bool mbDisposed; +public: + /// Public health warning, you -must- dispose this if you use it. + ConfigurationListener(const OUString &rPath, + css::uno::Reference< css::uno::XComponentContext > + const & xContext = comphelper::getProcessComponentContext()) + : mxConfig( ConfigurationHelper::openConfig( xContext, rPath, EConfigurationModes::ReadOnly ), + css::uno::UNO_QUERY_THROW ) + , mbDisposed(false) + { } + + virtual ~ConfigurationListener() override + { + dispose(); + } + + /// Listen for the specific property denoted by the listener + void addListener(ConfigurationListenerPropertyBase *pListener); + + /// Stop listening. + void removeListener(ConfigurationListenerPropertyBase *pListener); + + /// Release various circular references + void dispose(); + + // XPropertyChangeListener implementation + virtual void SAL_CALL disposing(css::lang::EventObject const &) override; + + /// Notify of the property change + virtual void SAL_CALL propertyChange( + css::beans::PropertyChangeEvent const &rEvt ) override; + + bool isDisposed() const { return mbDisposed; } +}; + +template< typename uno_type > ConfigurationListenerProperty< uno_type >::ConfigurationListenerProperty(const rtl::Reference< ConfigurationListener > &xListener, const OUString &rProp ) + : maValue() +{ + maName = rProp; + mxListener = xListener; + mxListener->addListener(this); +} + +template< typename uno_type > ConfigurationListenerProperty< uno_type >::~ConfigurationListenerProperty() +{ + if (mxListener.is()) + mxListener->removeListener(this); +} + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_CONFIGURATIONLISTENER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/container.hxx b/include/comphelper/container.hxx new file mode 100644 index 000000000..84acfc5b0 --- /dev/null +++ b/include/comphelper/container.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_CONTAINER_HXX +#define INCLUDED_COMPHELPER_CONTAINER_HXX + +#include +#include +#include + + +namespace comphelper +{ + + +//= IndexAccessIterator + +/** an iterator that iterates through all elements, starting from an XIndexAccess (pre-order) +*/ +class COMPHELPER_DLLPUBLIC IndexAccessIterator +{ +protected: + css::uno::Reference< css::uno::XInterface> m_xStartingPoint; + + css::uno::Reference< css::uno::XInterface> m_xCurrentObject; + // The current object + ::std::vector m_arrChildIndizies; + + // I'm moving through a tree, but its elements have no GetNextSibling, + // so I have to remember where each child is in relation to its parent. + // That is the path from the root node to m_xCurrentObject + +public: + IndexAccessIterator(css::uno::Reference< css::uno::XInterface> xStartingPoint); + + virtual ~IndexAccessIterator(); + + css::uno::Reference< css::uno::XInterface> const & Next(); + + virtual void Invalidate() { m_xCurrentObject = nullptr; } + +protected: + virtual bool ShouldHandleElement(const css::uno::Reference< css::uno::XInterface>& /*rElement*/) { return true; } + + // This can be used to exclude certain elements; elements for which + // this function returns sal_True will be simply skipped. + // If this element is returned from Next(), then one can get + // here get a little more information on the element. + // That's why this method is not const. + virtual bool ShouldStepInto(const css::uno::Reference< css::uno::XInterface>& /*xContainer*/) const { return true; } +}; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_CONTAINER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/containermultiplexer.hxx b/include/comphelper/containermultiplexer.hxx new file mode 100644 index 000000000..5b40b62ae --- /dev/null +++ b/include/comphelper/containermultiplexer.hxx @@ -0,0 +1,106 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_CONTAINERMULTIPLEXER_HXX +#define INCLUDED_COMPHELPER_CONTAINERMULTIPLEXER_HXX + +#include +#include +#include +#include + +namespace osl { class Mutex; } +namespace com::sun::star::container { class XContainer; } + + +namespace comphelper +{ + + + class OContainerListenerAdapter; + + //= OContainerListener + + /** a non-UNO container listener +

Useful if you have a non-refcountable class which should act as container listener.
+ In this case, derive this class from OContainerListener, and create an adapter + OContainerListenerAdapter which multiplexes the changes.

+ */ + class COMPHELPER_DLLPUBLIC OContainerListener + { + friend class OContainerListenerAdapter; + protected: + rtl::Reference m_xAdapter; + ::osl::Mutex& m_rMutex; + + public: + OContainerListener(::osl::Mutex& _rMutex); + virtual ~OContainerListener(); + + /// @throws css::uno::RuntimeException + virtual void _elementInserted( const css::container::ContainerEvent& _rEvent ); + /// @throws css::uno::RuntimeException + virtual void _elementRemoved( const css::container::ContainerEvent& _rEvent ); + /// @throws css::uno::RuntimeException + virtual void _elementReplaced( const css::container::ContainerEvent& _rEvent ); + /// @throws css::uno::RuntimeException + virtual void _disposing(const css::lang::EventObject& _rSource); + + protected: + void setAdapter(OContainerListenerAdapter* _pAdapter); + }; + + // workaround for incremental linking bugs in MSVC2015 + class SAL_DLLPUBLIC_TEMPLATE OContainerListenerAdapter_Base : public cppu::WeakImplHelper< css::container::XContainerListener > {}; + + class COMPHELPER_DLLPUBLIC OContainerListenerAdapter final : public OContainerListenerAdapter_Base + { + friend class OContainerListener; + + private: + css::uno::Reference< css::container::XContainer > + m_xContainer; + OContainerListener* m_pListener; + + virtual ~OContainerListenerAdapter() override; + + public: + OContainerListenerAdapter(OContainerListener* _pListener, + const css::uno::Reference< css::container::XContainer >& _rxContainer); + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XContainerListener + virtual void SAL_CALL elementInserted( const css::container::ContainerEvent& Event ) override; + virtual void SAL_CALL elementRemoved( const css::container::ContainerEvent& Event ) override; + virtual void SAL_CALL elementReplaced( const css::container::ContainerEvent& Event ) override; + + /// dispose the object. No multiplexing anymore + void dispose(); + + }; + + +} // namespace dbaui + + +#endif // INCLUDED_COMPHELPER_CONTAINERMULTIPLEXER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/crashzone.hxx b/include/comphelper/crashzone.hxx new file mode 100644 index 000000000..f15f848cd --- /dev/null +++ b/include/comphelper/crashzone.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_CRASHZONE_H +#define INCLUDED_COMPHELPER_CRASHZONE_H + +#include + +#include +#include +#include + +struct CrashWatchdogTimingsValues +{ + /// delays to take various actions in 1/4 of a second increments. + int mnDisableEntries; + int const mnAbortAfter; +}; + +/** + * A generic class for detecting if a given crash or a lock-up came from a specific + * area of code (such as OpenGL). + * Use this helper to track that. + * The class is a template so that there can be multiple instances of static variables. + */ +template class CrashZone +{ +// gnEnterCount and gnLeaveCount are accessed both from multiple threads (cf. +// WatchdogThread::execute; so need to be of atomic type) and from signal handlers (cf. +// VCLExceptionSignal_impl; so need to be of lock-free atomic type). sig_atomic_t is chosen as +// the underlying type under the assumption that it is most likely to lead to an atomic type +// that is actually lock-free. However, gnEnterCount and gnLeaveCount are both monotonically +// increasing, so will eventually overflow, so the underlying type better be unsigned, which +// sig_atomic_t is not guaranteed to be: +#if !defined ARM32 || (defined ARM32 && defined __ARM_PCS_VFP) + using AtomicCounter = std::atomic>; + static_assert(AtomicCounter::is_always_lock_free); +#else + using AtomicCounter = volatile std::make_unsigned_t; +#endif + + /// how many times have we entered a zone + static inline AtomicCounter gnEnterCount = 0; + /// how many times have we left a new zone + static inline AtomicCounter gnLeaveCount = 0; + +public: + CrashZone() { enter(); } + ~CrashZone() { leave(); } + static bool isInZone() { return gnEnterCount != gnLeaveCount; } + static const AtomicCounter& enterCount() { return gnEnterCount; } + // prefer creating instances to manually calling enter()/leave() + static void enter() { gnEnterCount++; } + static void leave() { gnLeaveCount++; } + // these should be implemented for each specific zone if needed + // static void hardDisable(); + // static const CrashWatchdogTimingsValues& getCrashWatchdogTimingsValues(); + // static void checkDebug(int nUnchanged, const CrashWatchdogTimingsValues& aTimingValues); + // static const char* name(); +}; + +#endif // INCLUDED_COMPHELPER_CRASHZONE_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/debuggerinfo.hxx b/include/comphelper/debuggerinfo.hxx new file mode 100644 index 000000000..8c4c0a4cb --- /dev/null +++ b/include/comphelper/debuggerinfo.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_DEBUGINFO_HXX +#define INCLUDED_COMPHELPER_DEBUGINFO_HXX + +#include + +namespace comphelper +{ +#if defined DBG_UTIL +/// Returns true if the process is running with a debugger attached. +/// +/// This is useful to disable watchdogs or increase timeouts if they trigger +/// too soon while using a debugger. +COMPHELPER_DLLPUBLIC bool isDebuggerAttached(); +#endif + +// For detecting whether Valgrind is used, add valgrind to gb_Library_use_externals +// and then in code use: +// #if defined HAVE_VALGRIND_HEADERS +// #include +// #endif +// ... +// #if defined HAVE_VALGRIND_HEADERS +// if( RUNNING_ON_VALGRIND ) + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_DEBUGINFO_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/dispatchcommand.hxx b/include/comphelper/dispatchcommand.hxx new file mode 100644 index 000000000..384536952 --- /dev/null +++ b/include/comphelper/dispatchcommand.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_DISPATCHCOMMAND_HXX +#define INCLUDED_COMPHELPER_DISPATCHCOMMAND_HXX + +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::frame { class XDispatchResultListener; class XFrame; } +namespace com::sun::star::uno { template class Sequence; } + +namespace comphelper +{ + +/** Dispatch the given UNO command in the active frame. + + @param rCommand the command to dispatch, like ".uno:Bold". + + @return true on success. +*/ +COMPHELPER_DLLPUBLIC bool dispatchCommand(const OUString& rCommand, + const css::uno::Sequence& rArguments, + const css::uno::Reference& rListener = css::uno::Reference()); + +COMPHELPER_DLLPUBLIC bool dispatchCommand(const OUString& rCommand, + const css::uno::Reference& rFrame, + const css::uno::Sequence& rArguments, + const css::uno::Reference& rListener = css::uno::Reference()); + +} + +#endif // INCLUDED_COMPHELPER_DISPATCHCOMMAND_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/docpasswordhelper.hxx b/include/comphelper/docpasswordhelper.hxx new file mode 100644 index 000000000..64d7ba978 --- /dev/null +++ b/include/comphelper/docpasswordhelper.hxx @@ -0,0 +1,447 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_DOCPASSWORDHELPER_HXX +#define INCLUDED_COMPHELPER_DOCPASSWORDHELPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::beans { struct NamedValue; } + +namespace comphelper { + +enum class DocPasswordVerifierResult +{ + OK, + WrongPassword, + Abort +}; + + +/** Base class for a password verifier used by the DocPasswordHelper class + below. + + Users have to implement the virtual functions and pass an instance of the + verifier to one of the password request functions. + */ +class COMPHELPER_DLLPUBLIC IDocPasswordVerifier +{ +public: + virtual ~IDocPasswordVerifier(); + + /** Will be called every time a password needs to be verified. + + @param rPassword + The password to be verified + + @param o_rEncryptionData + Output parameter, that is filled with the EncryptionData generated + from the password. The data is filled only if the validation was + successful. + + @return The result of the verification. + - DocPasswordVerifierResult_OK, if and only if the passed password + is valid and can be used to process the related document. + - DocPasswordVerifierResult_WRONG_PASSWORD, if the password is + wrong. The user may be asked again for a new password. + - DocPasswordVerifierResult_ABORT, if an unrecoverable error + occurred while password verification. The password request loop + will be aborted. + */ + virtual DocPasswordVerifierResult verifyPassword( const OUString& rPassword, css::uno::Sequence< css::beans::NamedValue >& o_rEncryptionData ) = 0; + + /** Will be called every time an encryption data needs to be verified. + + @param rEncryptionData + The data will be validated + + @return The result of the verification. + - DocPasswordVerifierResult_OK, if and only if the passed encryption data + is valid and can be used to process the related document. + - DocPasswordVerifierResult_WRONG_PASSWORD, if the encryption data is + wrong. + - DocPasswordVerifierResult_ABORT, if an unrecoverable error + occurred while data verification. The password request loop + will be aborted. + */ + virtual DocPasswordVerifierResult verifyEncryptionData( const css::uno::Sequence< css::beans::NamedValue >& o_rEncryptionData ) = 0; + +}; + + +/** Helper that asks for a document password and checks its validity. + */ +class COMPHELPER_DLLPUBLIC DocPasswordHelper +{ +public: + + + /** This helper function generates the information related + to "Password to modify" provided by user. The result + sequence contains the hash and the algorithm-related + info. + + @param aString + The string for which the info should be generated + + @return + The sequence containing the hash and the algorithm-related info + */ + + static css::uno::Sequence< css::beans::PropertyValue > + GenerateNewModifyPasswordInfo( std::u16string_view aPassword ); + + /** This helper function converts a grab-bagged password, e.g. the + trackChanges password which has no complete inner equivalent to + the inner format. The result sequence contains the hash and the + algorithm-related info to use e.g. in IsModifyPasswordCorrect(). + + @param aInfo + The sequence containing the hash and the algorithm-related info + according to the OOXML origin, used by grab-bagging. + + @return + The sequence containing the hash and the algorithm-related info + in the inner format. + */ + + static css::uno::Sequence< css::beans::PropertyValue > ConvertPasswordInfo( + const css::uno::Sequence< css::beans::PropertyValue >& aInfo ); + + static css::uno::Sequence + GenerateNewModifyPasswordInfoOOXML(std::u16string_view aPassword); + + /** This helper function allows to check whether + the "Password to modify" provided by user is the correct one. + + @param aString + The string containing the provided password + + @param aInfo + The sequence containing the hash and the algorithm-info + + @return + if the password is correct one + otherwise + */ + + static bool IsModifyPasswordCorrect( + std::u16string_view aPassword, + const css::uno::Sequence< css::beans::PropertyValue >& aInfo ); + + + /** This helper function generates the hash code based on the algorithm + specified by MS for "Password to modify" feature of Word. + + @param aString + The string for which the hash should be calculated + + @return + The hash represented by sal_uInt32 + */ + + static sal_uInt32 GetWordHashAsUINT32( std::u16string_view aString ); + + + /** This helper function generates the hash code based on the algorithm + specified by MS for "Password to modify" and passwords related to + table protection of Excel. + + @param aString + The string for which the hash should be calculated + + @param nEnc + The encoding that should be used to generate the 8-bit string + before the hash is generated + + @return + The hash represented by sal_uInt16 + */ + + static sal_uInt16 GetXLHashAsUINT16( + std::u16string_view aString, + rtl_TextEncoding nEnc = RTL_TEXTENCODING_UTF8 ); + + + /** This helper function generates the hash code based on the algorithm + specified by MS for "Password to modify" and passwords related to + table protection. + + @param aString + The string for which the hash should be calculated + + @return + The hash represented by sequence of bytes in BigEndian form + */ + + static css::uno::Sequence< sal_Int8 > GetXLHashAsSequence( + std::u16string_view aString ); + + + /** Convenience function to calculate a salted hash with iterations as + specified in https://msdn.microsoft.com/en-us/library/dd920692 for the + OOXML sheetProtection and fileSharing elements, or + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 for Standard and + Agile Encryption. + + @param rPassword + UTF-16 encoded string without leading BOM character + + @param rSaltValue + Base64 encoded salt that will be decoded and prepended to password + data. + + @param nSpinCount + If >0 the number of repeated iterations. + + @param eIterCount + If Hash::IterCount::APPEND, append iteration count as per + https://msdn.microsoft.com/en-us/library/dd920692 + If Hash::IterCount::PREPEND, prepend iteration count as per + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 + If Hash::IterCount::NONE, do not add the iteration count to hash + iterations. + + @param rAlgorithmName + One of "SHA-512", "SHA-256", ... as listed for AlgorithmName in + https://msdn.microsoft.com/en-us/library/dd920692 + or "SHA512", "SHA256", ... as listed for HashAlgorithm in + https://msdn.microsoft.com/en-us/library/dd925810 + that have a valid match in comphelper::HashType. If not, an + empty sequence is returned. Not all algorithm names are + supported. + + @return the raw hash value as sal_Int8 sequence. + */ + static css::uno::Sequence GetOoxHashAsSequence( + const OUString& rPassword, + std::u16string_view rSaltValue, + sal_uInt32 nSpinCount, + comphelper::Hash::IterCount eIterCount, + std::u16string_view rAlgorithmName); + + + /** Convenience function to calculate a salted hash with iterations as + specified in https://msdn.microsoft.com/en-us/library/dd920692 for the + OOXML sheetProtection and fileSharing elements, or + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 for Standard and + Agile Encryption. + + @param rPassword + UTF-16 encoded string without leading BOM character + + @param rSaltValue + Base64 encoded salt that will be decoded and prepended to password + data. + + @param nSpinCount + If >0 the number of repeated iterations. + + @param eIterCount + If Hash::IterCount::APPEND, append iteration count as per + https://msdn.microsoft.com/en-us/library/dd920692 + If Hash::IterCount::PREPEND, prepend iteration count as per + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 + If Hash::IterCount::NONE, do not add the iteration count to hash + iterations. + + @param rAlgorithmName + One of "SHA-512", "SHA-256", ... as listed for AlgorithmName in + https://msdn.microsoft.com/en-us/library/dd920692 + or "SHA512", "SHA256", ... as listed for HashAlgorithm in + https://msdn.microsoft.com/en-us/library/dd925810 + that have a valid match in comphelper::HashType. If not, an + empty sequence is returned. Not all algorithm names are + supported. + + @return the base64 encoded string of the hash value, that can be + compared against a stored base64 encoded hash value. + */ + static OUString GetOoxHashAsBase64( + const OUString& rPassword, + std::u16string_view rSaltValue, + sal_uInt32 nSpinCount, + comphelper::Hash::IterCount eIterCount, + std::u16string_view rAlgorithmName); + + + /** Convenience function to calculate a salted hash with iterations as + specified in https://msdn.microsoft.com/en-us/library/dd920692 for the + OOXML sheetProtection and fileSharing elements, or + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 for Standard and + Agile Encryption. + + @param rPassword + UTF-16 encoded string without leading BOM character + + @param rSaltValue + A raw salt that will be prepended to password data. + + @param nSpinCount + If >0 the number of repeated iterations. + + @param eIterCount + If Hash::IterCount::APPEND, append iteration count as per + https://msdn.microsoft.com/en-us/library/dd920692 + If Hash::IterCount::PREPEND, prepend iteration count as per + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 + If Hash::IterCount::NONE, do not add the iteration count to hash + iterations. + + @param rAlgorithmName + One of "SHA-512", "SHA-256", ... as listed for AlgorithmName in + https://msdn.microsoft.com/en-us/library/dd920692 + or "SHA512", "SHA256", ... as listed for HashAlgorithm in + https://msdn.microsoft.com/en-us/library/dd925810 + that have a valid match in comphelper::HashType. If not, an + empty sequence is returned. Not all algorithm names are + supported. + + @return the raw the hash value. + */ + static std::vector GetOoxHashAsVector( + const OUString& rPassword, + const std::vector& rSaltValue, + sal_uInt32 nSpinCount, + comphelper::Hash::IterCount eIterCount, + std::u16string_view rAlgorithmName); + + + /** This helper function generates a random sequence of bytes of + requested length. + */ + + static css::uno::Sequence< sal_Int8 > GenerateRandomByteSequence( + sal_Int32 nLength ); + + + /** This helper function generates a byte sequence representing the + key digest value used by MSCodec_Std97 codec. + */ + + static css::uno::Sequence< sal_Int8 > GenerateStd97Key( + std::u16string_view aPassword, + const css::uno::Sequence< sal_Int8 >& aDocId ); + + + /** This helper function generates a byte sequence representing the + key digest value used by MSCodec_Std97 codec. + */ + + static css::uno::Sequence< sal_Int8 > GenerateStd97Key( + const sal_uInt16 pPassData[16], + const css::uno::Sequence< sal_Int8 >& aDocId ); + + /** This helper function generates a byte sequence representing the + key digest value used by MSCodec_Std97 codec. + */ + + static css::uno::Sequence< sal_Int8 > GenerateStd97Key( + const sal_uInt16 pPassData[16], + const sal_uInt8 pDocId[16] ); + + + /** This helper function tries to request and verify a password to load a + protected document. + + First, the list of default passwords will be tried if provided. This is + needed by import filters for external file formats that have to check a + predefined password in some cases without asking the user for a + password. Every password is checked using the passed password verifier. + + If not successful, the passed password of a medium is tried, that has + been set e.g. by an API call to load a document. If existing, the + password is checked using the passed password verifier. + + If still not successful, the passed interaction handler is used to + request a password from the user. This will be repeated until the + passed password verifier validates the entered password, or if the user + chooses to cancel password input. + + @param rVerifier + The password verifier used to check every processed password. + + @param rMediaPassword + If not empty, will be passed to the password validator before + requesting a password from the user. This password usually should + be querried from a media descriptor. + + @param rxInteractHandler + The interaction handler that will be used to request a password + from the user, e.g. by showing a password input dialog. + + @param rDocumentUrl + The URL of the related document that will be shown in the password + input dialog. + + @param eRequestType + The password request type that will be passed to the + DocPasswordRequest object created internally. See + docpasswordrequest.hxx for more details. + + @param pDefaultPasswords + If not null, contains default passwords that will be tried before a + password will be requested from the media descriptor or the user. + + @param pbIsDefaultPassword + (output parameter) If not null, the type of the found password will + be returned. True means the password has been found in the passed + list of default passwords. False means the password has been taken + from the rMediaPassword parameter or has been entered by the user. + + @return + If not empty, contains the password that has been validated by the + passed password verifier. If empty, no valid password has been + found, or the user has chosen to cancel password input. + */ + static css::uno::Sequence< css::beans::NamedValue > requestAndVerifyDocPassword( + IDocPasswordVerifier& rVerifier, + const css::uno::Sequence< css::beans::NamedValue >& rMediaEncData, + const OUString& rMediaPassword, + const css::uno::Reference< css::task::XInteractionHandler >& rxInteractHandler, + const OUString& rDocumentUrl, + DocPasswordRequestType eRequestType, + const ::std::vector< OUString >* pDefaultPasswords = nullptr, + bool* pbIsDefaultPassword = nullptr ); + + static css::uno::Sequence< css::beans::NamedValue > decryptGpgSession( + const css::uno::Sequence< css::uno::Sequence< css::beans::NamedValue > >& rGpgProperties); + +private: + ~DocPasswordHelper(); +}; + + +} // namespace comphelper + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/docpasswordrequest.hxx b/include/comphelper/docpasswordrequest.hxx new file mode 100644 index 000000000..a4e8704eb --- /dev/null +++ b/include/comphelper/docpasswordrequest.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_DOCPASSWORDREQUEST_HXX +#define INCLUDED_COMPHELPER_DOCPASSWORDREQUEST_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::task { class XInteractionAbort; } + +namespace comphelper { + +class PasswordContinuation; + + +/** Selects which UNO document password request type to use. */ +enum class DocPasswordRequestType +{ + Standard, /// Uses the standard com.sun.star.task.DocumentPasswordRequest request. + MS /// Uses the com.sun.star.task.DocumentMSPasswordRequest request. +}; + + +class COMPHELPER_DLLPUBLIC SimplePasswordRequest final : + public cppu::WeakImplHelper +{ +public: + explicit SimplePasswordRequest(); + virtual ~SimplePasswordRequest() override; + + bool isPassword() const; + + OUString getPassword() const; + +private: + SimplePasswordRequest(SimplePasswordRequest const&) = delete; + SimplePasswordRequest& operator=(SimplePasswordRequest const&) = delete; + + // XInteractionRequest + virtual css::uno::Any SAL_CALL getRequest() override; + virtual css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > SAL_CALL getContinuations() override; + +private: + css::uno::Any maRequest; + css::uno::Reference mxAbort; + rtl::Reference mxPassword; +}; + + +/** Implements the task.XInteractionRequest interface for requesting a password + string for a document. + */ +class COMPHELPER_DLLPUBLIC DocPasswordRequest final : + public cppu::WeakImplHelper +{ +public: + explicit DocPasswordRequest( + DocPasswordRequestType eType, + css::task::PasswordRequestMode eMode, + const OUString& rDocumentUrl, + bool bPasswordToModify = false ); + virtual ~DocPasswordRequest() override; + + bool isPassword() const; + + OUString getPassword() const; + + OUString getPasswordToModify() const; + bool getRecommendReadOnly() const; + +private: + DocPasswordRequest(DocPasswordRequest const&) = delete; + DocPasswordRequest& operator=(DocPasswordRequest const&) = delete; + + // XInteractionRequest + virtual css::uno::Any SAL_CALL getRequest() override; + virtual css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > SAL_CALL getContinuations() override; + +private: + css::uno::Any maRequest; + css::uno::Reference mxAbort; + rtl::Reference mxPassword; +}; + + +} // namespace comphelper + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/documentconstants.hxx b/include/comphelper/documentconstants.hxx new file mode 100644 index 000000000..aafa84e75 --- /dev/null +++ b/include/comphelper/documentconstants.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_DOCUMENTCONSTANTS_HXX +#define INCLUDED_COMPHELPER_DOCUMENTCONSTANTS_HXX + +#include +#include + +// formats of SO6/7 +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_WRITER_ASCII = u"application/vnd.sun.xml.writer"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_WRITER_WEB_ASCII = u"application/vnd.sun.xml.writer.web"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_WRITER_GLOBAL_ASCII = u"application/vnd.sun.xml.writer.global"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_DRAW_ASCII = u"application/vnd.sun.xml.draw"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_IMPRESS_ASCII = u"application/vnd.sun.xml.impress"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_CALC_ASCII = u"application/vnd.sun.xml.calc"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_CHART_ASCII = u"application/vnd.sun.xml.chart"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_MATH_ASCII = u"application/vnd.sun.xml.math"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_BASE_ASCII = u"application/vnd.sun.xml.base"; + +// template formats of SO6/7 +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_WRITER_TEMPLATE_ASCII = u"application/vnd.sun.xml.writer.template"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_DRAW_TEMPLATE_ASCII = u"application/vnd.sun.xml.draw.template"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_IMPRESS_TEMPLATE_ASCII = u"application/vnd.sun.xml.impress.template"; +inline constexpr OUStringLiteral MIMETYPE_VND_SUN_XML_CALC_TEMPLATE_ASCII = u"application/vnd.sun.xml.calc.template"; + +// formats of SO8 +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII = u"application/vnd.oasis.opendocument.text"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII = u"application/vnd.oasis.opendocument.text-web"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII = u"application/vnd.oasis.opendocument.text-master"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII = u"application/vnd.oasis.opendocument.graphics"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII = u"application/vnd.oasis.opendocument.presentation"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII = u"application/vnd.oasis.opendocument.spreadsheet"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII = u"application/vnd.oasis.opendocument.chart"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII = u"application/vnd.oasis.opendocument.formula"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII = u"application/vnd.oasis.opendocument.base"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_REPORT_ASCII = u"application/vnd.sun.xml.report"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_REPORT_CHART_ASCII = u"application/vnd.sun.xml.report.chart"; + +// template formats of SO8 +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.text-template"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.text-master-template"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.graphics-template"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.presentation-template"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.spreadsheet-template"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.chart-template"; +inline constexpr OUStringLiteral MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII = u"application/vnd.oasis.opendocument.formula-template"; + + +// ODF versions +inline constexpr OUStringLiteral ODFVER_010_TEXT = u"1.0"; +inline constexpr OUStringLiteral ODFVER_011_TEXT = u"1.1"; +inline constexpr OUStringLiteral ODFVER_012_TEXT = u"1.2"; +inline constexpr OUStringLiteral ODFVER_013_TEXT = u"1.3"; + +// filter flags +// TODO/LATER: The flags should be part of the UNO specification +// +// http://www.mail-archive.com/dev@openoffice.org/msg05047.html says: +// +// I can just sum up what comes into my mind, hope I don't miss one: +// +// Import - should be self explaining +// Export - should be self explaining +// Template - deprecated +// TemplatePath - filter for a documenttemplate +// Own - one of the OOo file formats +// Alien - no zip container based format +// Preferred - preferred filter for a particular type +// 3rdPartyFilter - implemented as a UNO component +// Default - default filter for this document type +// Exotic - an unusual/legacy file-format, we don't normally see +// +// (The 3rdPartyFilter flag is here called StarONE) +// +enum class SfxFilterFlags +{ + NONE = 0, + IMPORT = 0x00000001, + EXPORT = 0x00000002, + TEMPLATE = 0x00000004, + INTERNAL = 0x00000008, + TEMPLATEPATH = 0x00000010, + OWN = 0x00000020, + ALIEN = 0x00000040, + + DEFAULT = 0x00000100, + SUPPORTSSELECTION = 0x00000400, + NOTINFILEDLG = 0x00001000, + + OPENREADONLY = 0x00010000, + MUSTINSTALL = 0x00020000, + CONSULTSERVICE = 0x00040000, + STARONEFILTER = 0x00080000, + PACKED = 0x00100000, + EXOTIC = 0x00200000, + COMBINED = 0x00800000, + + ENCRYPTION = 0x01000000, + PASSWORDTOMODIFY = 0x02000000, + GPGENCRYPTION = 0x04000000, + PREFERED = 0x10000000, + STARTPRESENTATION = 0x20000000, + SUPPORTSSIGNING = 0x40000000, +}; + +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +#define SFX_FILTER_NOTINSTALLED (SfxFilterFlags::MUSTINSTALL | SfxFilterFlags::CONSULTSERVICE) + +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/documentinfo.hxx b/include/comphelper/documentinfo.hxx new file mode 100644 index 000000000..a7002120a --- /dev/null +++ b/include/comphelper/documentinfo.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_DOCUMENTINFO_HXX +#define INCLUDED_COMPHELPER_DOCUMENTINFO_HXX + +#include +#include + +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::uno { template class Reference; } + + +namespace comphelper { + + + //= DocumentInfo + + namespace DocumentInfo + { + /** retrieves the UI title of the given document + */ + COMPHELPER_DLLPUBLIC OUString getDocumentTitle( const css::uno::Reference< css::frame::XModel >& _rxDocument ); + + /** notify that this document contains a macro event handler + */ + COMPHELPER_DLLPUBLIC void notifyMacroEventRead( const css::uno::Reference< css::frame::XModel >& _rxDocument ); + } + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_DOCUMENTINFO_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/doublecheckedinit.hxx b/include/comphelper/doublecheckedinit.hxx new file mode 100644 index 000000000..200a9c88c --- /dev/null +++ b/include/comphelper/doublecheckedinit.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_DOUBLECHECKEDINIT_HXX +#define INCLUDED_COMPHELPER_DOUBLECHECKEDINIT_HXX + +#include + +#include +// HACK: includes , which in some Clang versions does '#define bool bool', +// which confuses clang plugins. +#undef bool +#include + +namespace comphelper +{ +/** + * Thread-safe singleton creation. + * + * It is normally sufficient to create singletons using static variables in a function. + * This function is only for use cases that have a more complex lifetime of the object, + * such as when the object may require specific cleanup or may be created more times + * (e.g. when there is a "singleton" per each instance of another object). + */ +template , + typename Guard = osl::MutexGuard, typename GuardCtor = osl::GetGlobalMutex> +static inline Type* doubleCheckedInit(std::atomic& pointer, Function function, + GuardCtor guardCtor = osl::GetGlobalMutex()) +{ + Type* p = pointer.load(std::memory_order_acquire); + if (!p) + { + Guard guard(guardCtor()); + p = pointer.load(std::memory_order_relaxed); + if (!p) + { + p = function(); + pointer.store(p, std::memory_order_release); + } + } + return p; +} + +} // namespace + +#endif // INCLUDED_COMPHELPER_DOUBLECHECKEDINIT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/embeddedobjectcontainer.hxx b/include/comphelper/embeddedobjectcontainer.hxx new file mode 100644 index 000000000..cc040da15 --- /dev/null +++ b/include/comphelper/embeddedobjectcontainer.hxx @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_EMBEDDEDOBJECTCONTAINER_HXX +#define INCLUDED_COMPHELPER_EMBEDDEDOBJECTCONTAINER_HXX + +#include +#include +#include + +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::embed { class XEmbeddedObject; } +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::uno { class XInterface; } + +namespace comphelper +{ + class EmbeddedObjectContainer; + /** Helper interface to give access to some common object which replace the SfxObjectShell + */ + class SAL_NO_VTABLE SAL_DLLPUBLIC_RTTI IEmbeddedHelper + { + public: + virtual EmbeddedObjectContainer& getEmbeddedObjectContainer() const = 0; + virtual css::uno::Reference < css::embed::XStorage > getStorage() const = 0; + virtual css::uno::Reference< css::task::XInteractionHandler > getInteractionHandler() const = 0; + virtual bool isEnableSetModified() const = 0; + virtual OUString getDocumentBaseURL() const = 0; + + protected: + ~IEmbeddedHelper() {} + }; + +struct EmbedImpl; +class COMPHELPER_DLLPUBLIC EmbeddedObjectContainer +{ + std::unique_ptr pImpl; + + css::uno::Reference < css::embed::XEmbeddedObject > Get_Impl( const OUString&, + const css::uno::Reference < css::embed::XEmbeddedObject >& xCopy, + OUString const* pBaseURL); + +public: + // add an embedded object to the container storage + bool StoreEmbeddedObject( + const css::uno::Reference& xObj, OUString& rName, bool bCopy, + const OUString& rSrcShellID, const OUString& rDestShellID ); + + // add an embedded object that has been imported from the container storage - should only be called by filters! + void AddEmbeddedObject( const css::uno::Reference < css::embed::XEmbeddedObject >&, const OUString& ); + + EmbeddedObjectContainer(); + EmbeddedObjectContainer( const css::uno::Reference < css::embed::XStorage >& ); + EmbeddedObjectContainer( const css::uno::Reference < css::embed::XStorage >&, + const css::uno::Reference < css::uno::XInterface >& ); + ~EmbeddedObjectContainer(); + + void SwitchPersistence( const css::uno::Reference < css::embed::XStorage >& ); + bool CommitImageSubStorage(); + void ReleaseImageSubStorage(); + + OUString CreateUniqueObjectName(); + + // get a list of object names that have been added so far + css::uno::Sequence < OUString > GetObjectNames() const; + + // check for existence of objects at all + bool HasEmbeddedObjects() const; + + // check existence of an object - either by identity or by name + bool HasEmbeddedObject( const OUString& ); + bool HasEmbeddedObject( const css::uno::Reference < css::embed::XEmbeddedObject >& ) const; + bool HasInstantiatedEmbeddedObject( const OUString& ); + + // get the object name of an object - this is the persist name if the object has persistence + OUString GetEmbeddedObjectName( const css::uno::Reference < css::embed::XEmbeddedObject >& ) const; + + // retrieve an embedded object by name that either has been added already or is available in the container storage + css::uno::Reference GetEmbeddedObject(const OUString&, OUString const* pBaseURL = nullptr); + + // create an object from a ClassId + css::uno::Reference < css::embed::XEmbeddedObject > + CreateEmbeddedObject( const css::uno::Sequence < sal_Int8 >&, OUString&, + OUString const* pBaseURL = nullptr ); + + css::uno::Reference < css::embed::XEmbeddedObject > + CreateEmbeddedObject( const css::uno::Sequence < sal_Int8 >&, + const css::uno::Sequence < css::beans::PropertyValue >&, OUString&, + OUString const* pBaseURL = nullptr ); + + // insert an embedded object into the container - objects persistent representation will be added to the storage + bool InsertEmbeddedObject( const css::uno::Reference < css::embed::XEmbeddedObject >&, OUString& ); + + // load an embedded object from a MediaDescriptor and insert it into the container + // a new object will be created from the new content and returned + css::uno::Reference < css::embed::XEmbeddedObject > + InsertEmbeddedObject( const css::uno::Sequence < css::beans::PropertyValue >&, OUString& rName, OUString const* pBaseURL = nullptr); + + // create an embedded link based on a MediaDescriptor and insert it into the container + // a new object will be created from the new content and returned + css::uno::Reference < css::embed::XEmbeddedObject > + InsertEmbeddedLink( const css::uno::Sequence < css::beans::PropertyValue >&, OUString& ); + + // create an object from a stream that contains its persistent representation and insert it as usual (usually called from clipboard) + // a new object will be created from the new content and returned + css::uno::Reference < css::embed::XEmbeddedObject > + InsertEmbeddedObject( const css::uno::Reference < css::io::XInputStream >&, OUString& ); + + // copy an embedded object into the storage, open the new copy and return it + css::uno::Reference CopyAndGetEmbeddedObject( + EmbeddedObjectContainer& rSrc, const css::uno::Reference & xObj, OUString& rName, + const OUString& rSrcShellID, const OUString& rDestShellID ); + + // remove an embedded object from the container and from the storage; if object can't be closed + // #i119941, bKeepToTempStorage: use to specify whether store the removed object to temporary storage+ + void RemoveEmbeddedObject( const OUString& rName, bool bKeepToTempStorage = true); + bool RemoveEmbeddedObject( const css::uno::Reference < css::embed::XEmbeddedObject >&, bool bKeepToTempStorage = true); + + // close and remove an embedded object from the container without removing it from the storage + void CloseEmbeddedObject( const css::uno::Reference < css::embed::XEmbeddedObject >& ); + + // move an embedded object to another container (keep the persistent name) + bool MoveEmbeddedObject( const OUString& rName, EmbeddedObjectContainer& ); + + // get the stored graphical representation for the object + css::uno::Reference < css::io::XInputStream > GetGraphicStream( const css::uno::Reference < css::embed::XEmbeddedObject >&, OUString* pMediaType=nullptr ); + + // get the stored graphical representation by the object name + css::uno::Reference < css::io::XInputStream > GetGraphicStream( const OUString& aName, OUString* pMediaType=nullptr ); + + // add a graphical representation for an object + bool InsertGraphicStream( const css::uno::Reference < css::io::XInputStream >& rStream, const OUString& rObjectName, const OUString& rMediaType ); + + // try to add a graphical representation for an object in optimized way ( might fail ) + bool InsertGraphicStreamDirectly( const css::uno::Reference < css::io::XInputStream >& rStream, const OUString& rObjectName, const OUString& rMediaType ); + + // remove a graphical representation for an object + void RemoveGraphicStream( const OUString& rObjectName ); + + // copy the graphical representation from different container + bool TryToCopyGraphReplacement( EmbeddedObjectContainer& rSrc, + const OUString& aOrigName, + const OUString& aTargetName ); + + void CloseEmbeddedObjects(); + bool StoreChildren(bool _bOasisFormat,bool _bObjectsOnly); + bool StoreAsChildren( bool _bOasisFormat + ,bool _bCreateEmbedded + ,bool _bAutoSaveEvent + ,const css::uno::Reference < css::embed::XStorage >& _xStorage); + + static css::uno::Reference< css::io::XInputStream > GetGraphicReplacementStream( + sal_Int64 nViewAspect, + const css::uno::Reference < css::embed::XEmbeddedObject >&, + OUString* pMediaType ); + + /** call setPersistentEntry for each embedded object in the container + * + * \param _xStorage The storage where to store the objects. + * \param _bClearModifiedFlag If then the modified flag will be set to otherwise nothing happen. + * \return if no error occurred, otherwise . + */ + bool SetPersistentEntries(const css::uno::Reference< css::embed::XStorage >& _xStorage,bool _bClearModifiedFlag = true); + + bool getUserAllowsLinkUpdate() const; + void setUserAllowsLinkUpdate(bool bNew); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/enumhelper.hxx b/include/comphelper/enumhelper.hxx new file mode 100644 index 000000000..fb26de489 --- /dev/null +++ b/include/comphelper/enumhelper.hxx @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_ENUMHELPER_HXX +#define INCLUDED_COMPHELPER_ENUMHELPER_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::container { class XIndexAccess; } +namespace com::sun::star::container { class XNameAccess; } + +namespace comphelper +{ + +/** provides a com.sun.star.container::XEnumeration access based + on an object implementing the com.sun.star.container::XNameAccess interface +*/ +class COMPHELPER_DLLPUBLIC OEnumerationByName final : + public ::cppu::WeakImplHelper< css::container::XEnumeration , + css::lang::XEventListener > +{ + std::variant, std::vector> m_aNames; + css::uno::Reference< css::container::XNameAccess > m_xAccess; + sal_Int32 m_nPos; + bool m_bListening; + std::mutex m_aLock; + +public: + OEnumerationByName(const css::uno::Reference< css::container::XNameAccess > _xAccess); + OEnumerationByName(const css::uno::Reference< css::container::XNameAccess > _xAccess, + std::vector _aNames ); + virtual ~OEnumerationByName() override; + + virtual sal_Bool SAL_CALL hasMoreElements( ) override; + virtual css::uno::Any SAL_CALL nextElement( ) override; + + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) override; + +private: + sal_Int32 getLength() const; + const OUString& getElement(sal_Int32 nIndex) const; + COMPHELPER_DLLPRIVATE void impl_startDisposeListening(); + COMPHELPER_DLLPRIVATE void impl_stopDisposeListening(); +}; + +/** provides a com.sun.star.container::XEnumeration access based + on an object implementing the com.sun.star.container::XNameAccess interface +*/ +class COMPHELPER_DLLPUBLIC OEnumerationByIndex final : + public ::cppu::WeakImplHelper< css::container::XEnumeration , + css::lang::XEventListener > +{ + css::uno::Reference< css::container::XIndexAccess > m_xAccess; + sal_Int32 m_nPos; + bool m_bListening; + std::mutex m_aLock; + +public: + OEnumerationByIndex(css::uno::Reference< css::container::XIndexAccess > _xAccess); + virtual ~OEnumerationByIndex() override; + + virtual sal_Bool SAL_CALL hasMoreElements( ) override; + virtual css::uno::Any SAL_CALL nextElement( ) override; + + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) override; + +private: + COMPHELPER_DLLPRIVATE void impl_startDisposeListening(); + COMPHELPER_DLLPRIVATE void impl_stopDisposeListening(); +}; + +// this is the way that works for ENABLE_LTO with MSVC 2013 +class SAL_DLLPUBLIC_TEMPLATE OAnyEnumeration_BASE + : public ::cppu::WeakImplHelper {}; + +/** provides a com.sun.star.container::XEnumeration + for an outside set vector of Any's. + +*/ +class COMPHELPER_DLLPUBLIC OAnyEnumeration final : + public OAnyEnumeration_BASE +{ + sal_Int32 m_nPos; + css::uno::Sequence< css::uno::Any > m_lItems; + std::mutex m_aLock; + +public: + OAnyEnumeration(const css::uno::Sequence< css::uno::Any >& lItems); + virtual ~OAnyEnumeration() override; + + virtual sal_Bool SAL_CALL hasMoreElements( ) override; + virtual css::uno::Any SAL_CALL nextElement( ) override; + +}; + +} + +#endif // INCLUDED_COMPHELPER_ENUMHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/eventattachermgr.hxx b/include/comphelper/eventattachermgr.hxx new file mode 100644 index 000000000..4a2a99909 --- /dev/null +++ b/include/comphelper/eventattachermgr.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_EVENTATTACHERMGR_HXX +#define INCLUDED_COMPHELPER_EVENTATTACHERMGR_HXX + +#include +#include + +namespace com::sun::star { +namespace uno { + class XComponentContext; +} +namespace script { + class XEventAttacherManager; +} +} + + +namespace comphelper +{ + +/// @throws css::uno::Exception +COMPHELPER_DLLPUBLIC css::uno::Reference< css::script::XEventAttacherManager > +createEventAttacherManager( + const css::uno::Reference< css::uno::XComponentContext > & rxContext ); + +} + +#endif // INCLUDED_COMPHELPER_EVENTATTACHERMGR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/evtlistenerhlp.hxx b/include/comphelper/evtlistenerhlp.hxx new file mode 100644 index 000000000..212d94662 --- /dev/null +++ b/include/comphelper/evtlistenerhlp.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_EVTLISTENERHLP_HXX +#define INCLUDED_COMPHELPER_EVTLISTENERHLP_HXX + +#include +#include +#include +#include +#include + + +namespace comphelper +{ + + + //= OCommandsListener + // is helper class to avoid a cycle in refcount between the XEventListener + // and the member XComponent + + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OEventListenerHelper final : public ::cppu::WeakImplHelper< css::lang::XEventListener > + { + css::uno::WeakReference< css::lang::XEventListener> m_xListener; + public: + OEventListenerHelper(const css::uno::Reference< css::lang::XEventListener>& _rxListener); + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + }; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_EVTLISTENERHLP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/evtmethodhelper.hxx b/include/comphelper/evtmethodhelper.hxx new file mode 100644 index 000000000..f420b1869 --- /dev/null +++ b/include/comphelper/evtmethodhelper.hxx @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace comphelper +{ +COMPHELPER_DLLPUBLIC css::uno::Sequence +getEventMethodsForType(const css::uno::Type& type); + +} // namespace comphelper + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/extract.hxx b/include/comphelper/extract.hxx new file mode 100644 index 000000000..c8ab9c6e6 --- /dev/null +++ b/include/comphelper/extract.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_EXTRACT_HXX +#define INCLUDED_COMPHELPER_EXTRACT_HXX + +#include + +#include + +#include +#include +#include +#include + +namespace cppu +{ +/** + * Sets enum from int32 value. This function does NOT check for valid enum values! + * + * @param nEnum int32 enum value + * @param rType enum type + * @return enum or empty any. + */ +inline css::uno::Any int2enum(sal_Int32 nEnum, const css::uno::Type& rType) +{ + assert(rType.getTypeClass() == css::uno::TypeClass_ENUM); + return css::uno::Any(&nEnum, rType); +} + +/** + * Sets int32 from enum or int in any. + * + * @param[out] rnEnum int32 enum value + * @param rAny enum or int + * @retval true if enum or int value was set + * @retval false otherwise + */ +inline bool enum2int(sal_Int32& rnEnum, const css::uno::Any& rAny) +{ + if (rAny.getValueTypeClass() == css::uno::TypeClass_ENUM) + { + rnEnum = *static_cast(rAny.getValue()); + return true; + } + + return rAny >>= rnEnum; +} + +/** + * Sets int32 from enum or int in any with additional typecheck + * + * @param[out] eRet the enum value as int. If there is no enum of the given type + * a css::lang::IllegalArgumentException is thrown + * @param rAny enum or int + * @throws css::lang::IllegalArgumentException + */ +template inline void any2enum(E& eRet, const css::uno::Any& rAny) +{ + // check for typesafe enum + if (!(rAny >>= eRet)) + { + // if not enum, maybe integer? + sal_Int32 nValue = 0; + if (!(rAny >>= nValue)) + throw css::lang::IllegalArgumentException(); + + eRet = static_cast(nValue); + } +} + +/** + * Extracts a boolean either as a bool or an integer from + * an any. If there is no bool or integer inside the any + * a css::lang::IllegalArgumentException is thrown + * + * @throws css::lang::IllegalArgumentException + */ +inline bool any2bool(const css::uno::Any& rAny) +{ + bool b; + if (rAny >>= b) + { + return b; + } + else + { + sal_Int32 nValue = 0; + if (!(rAny >>= nValue)) + throw css::lang::IllegalArgumentException(); + return nValue != 0; + } +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/fileformat.h b/include/comphelper/fileformat.h new file mode 100644 index 000000000..7eabf5829 --- /dev/null +++ b/include/comphelper/fileformat.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_FILEFORMAT_H +#define INCLUDED_COMPHELPER_FILEFORMAT_H + +/* file format versions *************************************************/ + +#define SOFFICE_FILEFORMAT_31 3450 +#define SOFFICE_FILEFORMAT_40 3580 +#define SOFFICE_FILEFORMAT_50 5050 +#define SOFFICE_FILEFORMAT_60 6200 +#define SOFFICE_FILEFORMAT_8 6800 +#define SOFFICE_FILEFORMAT_CURRENT SOFFICE_FILEFORMAT_8 + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/fileurl.hxx b/include/comphelper/fileurl.hxx new file mode 100644 index 000000000..27ac6b576 --- /dev/null +++ b/include/comphelper/fileurl.hxx @@ -0,0 +1,36 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_FILEURL_HXX +#define INCLUDED_COMPHELPER_FILEURL_HXX + +#include + +#include +#include + +namespace comphelper +{ +// Return true iff url is an absolute URL of "file" scheme: +COMPHELPER_DLLPUBLIC bool isFileUrl(OUString const& url); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/flagguard.hxx b/include/comphelper/flagguard.hxx new file mode 100644 index 000000000..14eee07a8 --- /dev/null +++ b/include/comphelper/flagguard.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_FLAGGUARD_HXX +#define INCLUDED_COMPHELPER_FLAGGUARD_HXX + +#include +#include + +namespace comphelper +{ + + //= ValueRestorationGuard + + // note: can't store the originalValue in a ValueRestorationGuard member, + // because it will be used from base class dtor + template struct ValueRestorationGuard_Impl + { + T& rVal; + T const originalValue; + ValueRestorationGuard_Impl(T& i_valRef) + : rVal(i_valRef), originalValue(i_valRef) {} + void operator()() + { + rVal = originalValue; + } + }; + + template + class ValueRestorationGuard : public ScopeGuard> + { + public: + template + ValueRestorationGuard(T& i_valRef, T1&& i_temporaryValue) + : ScopeGuard>(ValueRestorationGuard_Impl(i_valRef)) + { + i_valRef = std::forward(i_temporaryValue); + } + }; + + typedef ValueRestorationGuard FlagRestorationGuard; + + //= FlagGuard + + // Guarantees that the flag is true within the scope of the guard, and is set to false after + // its destruction, regardless of initial flag value + class FlagGuard : public FlagRestorationGuard + { + public: + // Set flag to false before passing its reference to base class ctor, so that it would be + // reset back to false in base class dtor + explicit FlagGuard(bool& i_flagRef) + : FlagRestorationGuard((i_flagRef = false), true) + { + } + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_FLAGGUARD_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/genericpropertyset.hxx b/include/comphelper/genericpropertyset.hxx new file mode 100644 index 000000000..2450ef047 --- /dev/null +++ b/include/comphelper/genericpropertyset.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_GENERICPROPERTYSET_HXX +#define INCLUDED_COMPHELPER_GENERICPROPERTYSET_HXX + +#include +#include + +namespace com::sun::star::beans +{ +class XPropertySet; +} +namespace comphelper +{ +class PropertySetInfo; +} + +namespace comphelper +{ +COMPHELPER_DLLPUBLIC css::uno::Reference +GenericPropertySet_CreateInstance(PropertySetInfo* pInfo); +} + +#endif // INCLUDED_COMPHELPER_GENERICPROPERTYSET_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/getexpandeduri.hxx b/include/comphelper/getexpandeduri.hxx new file mode 100644 index 000000000..5b75c43d4 --- /dev/null +++ b/include/comphelper/getexpandeduri.hxx @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_GETEXPANDEDURI_HXX +#define INCLUDED_COMPHELPER_GETEXPANDEDURI_HXX + +#include + +#include +#include + +namespace com::sun::star::uno +{ +class XComponentContext; +} +namespace com::sun::star::uno +{ +template class Reference; +} + +namespace comphelper +{ +/** + A helper function to expand vnd.sun.star.expand URLs. + + If the given URI is a vnd.sun.star.expand URL, it is expanded (using the + given component context's com.sun.star.util.theMacroExpander); otherwise it + is returned unchanged. +*/ +COMPHELPER_DLLPUBLIC OUString getExpandedUri( + css::uno::Reference const& context, OUString const& uri); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/graphicmimetype.hxx b/include/comphelper/graphicmimetype.hxx new file mode 100644 index 000000000..94a3cd3cd --- /dev/null +++ b/include/comphelper/graphicmimetype.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_GMH_HXX +#define INCLUDED_COMPHELPER_GMH_HXX + +#include + +#include + +#include +#include +#include + +#include + +namespace com::sun::star::graphic +{ +class XGraphic; +} +namespace com::sun::star::io +{ +class XInputStream; +} + +namespace comphelper +{ +class COMPHELPER_DLLPUBLIC GraphicMimeTypeHelper +{ +public: + static OUString GetMimeTypeForExtension(std::string_view rExt); + static OUString + GetMimeTypeForXGraphic(const css::uno::Reference& xGraphic); + static OUString + GetMimeTypeForImageStream(const css::uno::Reference& xInputStream); + static OUString GetMimeTypeForConvertDataFormat(ConvertDataFormat convertDataFormat); + static char const* GetExtensionForConvertDataFormat(ConvertDataFormat nFormat); +}; +} + +#endif // INCLUDED_COMPHELPER_GMH_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/guarding.hxx b/include/comphelper/guarding.hxx new file mode 100644 index 000000000..3bbf4ac71 --- /dev/null +++ b/include/comphelper/guarding.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_GUARDING_HXX +#define INCLUDED_COMPHELPER_GUARDING_HXX + +namespace osl { class Mutex; } + + +namespace comphelper +{ + + +// = class MutexRelease - + + +/** opposite of OGuard :) + (a mutex is released within the constructor and acquired within the destructor) + use only when you're sure the mutex is acquired ! +*/ +template +class ORelease +{ + MUTEX& m_rMutex; + +public: + ORelease(MUTEX& _rMutex) : m_rMutex(_rMutex) { _rMutex.release(); } + ~ORelease() { m_rMutex.acquire(); } +}; + +typedef ORelease< ::osl::Mutex > MutexRelease; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_GUARDING_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/hash.hxx b/include/comphelper/hash.hxx new file mode 100644 index 000000000..54ab3a251 --- /dev/null +++ b/include/comphelper/hash.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_HASH_HXX +#define INCLUDED_COMPHELPER_HASH_HXX + +#include +#include + +#include +#include + +namespace rtl { + class OUString; +} + +namespace comphelper { + +enum class HashType +{ + MD5, + SHA1, + SHA256, + SHA512 +}; + +const sal_uInt32 MD5_HASH_LENGTH = RTL_DIGEST_LENGTH_MD5; +const sal_uInt32 SHA1_HASH_LENGTH = RTL_DIGEST_LENGTH_SHA1; +const sal_uInt32 SHA256_HASH_LENGTH = 32; +const sal_uInt32 SHA512_HASH_LENGTH = 64; + +struct HashImpl; + +class COMPHELPER_DLLPUBLIC Hash +{ +private: + std::unique_ptr mpImpl; + +public: + + enum class IterCount + { + NONE, /// Iteration count not added to hash iterations. + PREPEND, /// Iteration count prepended to hash iterations. + APPEND /// Iteration count appended to hash iterations. + }; + + Hash(HashType eType); + ~Hash(); + + void update(const unsigned char* pInput, size_t length); + + std::vector finalize(); + + static std::vector calculateHash(const unsigned char* pInput, size_t length, HashType eType); + + /** Calculate hash value with salt (pSalt,nSaltLen) prepended to password + (pInput,nLength) and repeated iterations run if nSpinCount>0. + + This implements the algorithms as specified in + https://msdn.microsoft.com/en-us/library/dd920692 or + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 + + @param pSalt + may be nullptr thus no salt prepended + + @param nSpinCount + If >0, repeat nSpinCount iterations. For each iteration, the + previous iteration's result plus a 4 byte value (0-based, + little endian) containing the number of the iteration prepended + or appended to the hash value is the input for the next + iteration. + + @param eIterCount + If IterCount::APPEND, append iteration count as per + https://msdn.microsoft.com/en-us/library/dd920692 + If IterCount::PREPEND, prepend iteration count as per + https://msdn.microsoft.com/en-us/library/dd924776 and + https://msdn.microsoft.com/en-us/library/dd925430 + If IterCount::NONE, do not add the iteration count to hash + iterations. + + @return the raw hash value + */ + static std::vector calculateHash( + const unsigned char* pInput, size_t nLength, + const unsigned char* pSalt, size_t nSaltLen, + sal_uInt32 nSpinCount, + IterCount eIterCount, + HashType eType); + + /** Convenience function to calculate a salted hash with iterations. + + @param rPassword + UTF-16 encoded string, hashed byte-wise as unsigned char. + + @param rSaltValue + Salt that will be prepended to password data. + */ + static std::vector calculateHash( + const rtl::OUString& rPassword, + const std::vector& rSaltValue, + sal_uInt32 nSpinCount, + IterCount eIterCount, + HashType eType); + + size_t getLength() const; +}; + +} + +#endif // INCLUDED_COMPHELPER_HASH_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/indexedpropertyvalues.hxx b/include/comphelper/indexedpropertyvalues.hxx new file mode 100644 index 000000000..5a5f3e8ba --- /dev/null +++ b/include/comphelper/indexedpropertyvalues.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper +{ +typedef std::vector> IndexedPropertyValues; + +class COMPHELPER_DLLPUBLIC IndexedPropertyValuesContainer final + : public cppu::WeakImplHelper +{ +public: + IndexedPropertyValuesContainer() noexcept; + + // XIndexContainer + virtual void SAL_CALL insertByIndex(sal_Int32 nIndex, const css::uno::Any& aElement) override; + virtual void SAL_CALL removeByIndex(sal_Int32 nIndex) override; + + // XIndexReplace + virtual void SAL_CALL replaceByIndex(sal_Int32 nIndex, const css::uno::Any& aElement) override; + + // XIndexAccess + virtual sal_Int32 SAL_CALL getCount() override; + virtual css::uno::Any SAL_CALL getByIndex(sal_Int32 nIndex) override; + + // XElementAccess + virtual css::uno::Type SAL_CALL getElementType() override; + virtual sal_Bool SAL_CALL hasElements() override; + + //XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + virtual css::uno::Sequence SAL_CALL getSupportedServiceNames() override; + +private: + IndexedPropertyValues maProperties; +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/interaction.hxx b/include/comphelper/interaction.hxx new file mode 100644 index 000000000..0f783e946 --- /dev/null +++ b/include/comphelper/interaction.hxx @@ -0,0 +1,119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_INTERACTION_HXX +#define INCLUDED_COMPHELPER_INTERACTION_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace comphelper +{ + + + //= OInteraction + + /** template for instantiating concrete interaction handlers

+ the template argument must be an interface derived from XInteractionContinuation + */ + template + class OInteraction + : public ::cppu::WeakImplHelper< INTERACTION > + { + public: + OInteraction() : m_bSelected(false) {} + + /// determines whether or not this handler was selected + bool wasSelected() const { return m_bSelected; } + + // XInteractionContinuation + virtual void SAL_CALL select() override; + private: + bool m_bSelected : 1; /// indicates if the select event occurred + }; + + + template + void SAL_CALL OInteraction< INTERACTION >::select( ) + { + m_bSelected = true; + } + + + //= OInteractionApprove + + typedef OInteraction< css::task::XInteractionApprove > OInteractionApprove; + + + //= OInteractionDisapprove + + typedef OInteraction< css::task::XInteractionDisapprove > OInteractionDisapprove; + + + //= OInteractionAbort + + typedef OInteraction< css::task::XInteractionAbort > OInteractionAbort; + + + //= OInteractionRetry + + typedef OInteraction< css::task::XInteractionRetry > OInteractionRetry; + + + //= OInteractionRequest + + typedef ::cppu::WeakImplHelper < css::task::XInteractionRequest + > OInteractionRequest_Base; + /** implements an interaction request (com.sun.star.task::XInteractionRequest)

+ at run time, you can freely add any interaction continuation objects + */ + class COMPHELPER_DLLPUBLIC OInteractionRequest final : public OInteractionRequest_Base + { + css::uno::Any const + m_aRequest; /// the request we represent + std::vector< css::uno::Reference< css::task::XInteractionContinuation > > + m_aContinuations; /// all registered continuations + + public: + OInteractionRequest(css::uno::Any aRequestDescription); + OInteractionRequest(css::uno::Any aRequestDescription, + std::vector>&& rContinuations); + + /// add a new continuation + void addContinuation(const css::uno::Reference< css::task::XInteractionContinuation >& _rxContinuation); + + // XInteractionRequest + virtual css::uno::Any SAL_CALL getRequest( ) override; + virtual css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > SAL_CALL getContinuations( ) override; + }; + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_INTERACTION_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/interfacecontainer2.hxx b/include/comphelper/interfacecontainer2.hxx new file mode 100644 index 000000000..3df7c71d4 --- /dev/null +++ b/include/comphelper/interfacecontainer2.hxx @@ -0,0 +1,290 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_INTERFACECONTAINER2_H +#define INCLUDED_COMPHELPER_INTERFACECONTAINER2_H + +#include + +#include + +#include + +#include +#include + +namespace com::sun::star::uno { class XInterface; } +namespace osl { class Mutex; } + +namespace comphelper +{ + +namespace detail { + + /** + This is here to optimise space in the common case that there are zero or one + listeners. + */ + union element_alias2 + { + std::vector< css::uno::Reference< css::uno::XInterface > > *pAsVector; + css::uno::XInterface * pAsInterface; + element_alias2() : pAsInterface(nullptr) {} + }; + +} + + +class OInterfaceContainerHelper2; +/** + This is the iterator of an OInterfaceContainerHelper2. Typically + one constructs an instance on the stack for one firing session. + It is not allowed to assign or copy an instance of this class. + + @see OInterfaceContainerHelper2 + */ +class COMPHELPER_DLLPUBLIC OInterfaceIteratorHelper2 +{ +public: + /** + Create an iterator over the elements of the container. The iterator + copies the elements of the container. A change to the container + during the lifetime of an iterator is allowed and does not + affect the iterator-instance. The iterator and the container take cares + themself for concurrent access, no additional guarding is necessary. + + Remark: The copy is on demand. The iterator copy the elements only if the container + change the contents. It is not allowed to destroy the container as long + as an iterator exist. + + @param rCont the container of the elements. + */ + OInterfaceIteratorHelper2( OInterfaceContainerHelper2 & rCont ); + + /** + Releases the connection to the container. + */ + ~OInterfaceIteratorHelper2(); + + /** Return true, if there are more elements in the iterator. */ + bool hasMoreElements() const + { return nRemain != 0; } + /** Return the next element of the iterator. Calling this method if + hasMoreElements() has returned false, is an error. Cast the + returned pointer to the + */ + css::uno::XInterface * next(); + + /** Removes the current element (the last one returned by next()) + from the underlying container. Calling this method before + next() has been called or calling it twice with no next() + inbetween is an error. + */ + void remove(); + +private: + OInterfaceContainerHelper2 & rCont; + detail::element_alias2 aData; + sal_Int32 nRemain; + bool bIsList; + + OInterfaceIteratorHelper2( const OInterfaceIteratorHelper2 & ) = delete; + OInterfaceIteratorHelper2 & operator = ( const OInterfaceIteratorHelper2 & ) = delete; +}; + + +/** + A container of interfaces. To access the elements use an iterator. + This implementation is thread-safe. + + This is a copy of the code at include/cppuhelper/interfacecontainer.h, + Except that it uses a std::vector instead of a Sequence for the mutable listener + list, which provides far better performance. + + @see OInterfaceIteratorHelper2 + */ +class COMPHELPER_DLLPUBLIC OInterfaceContainerHelper2 +{ +public: + /** + Create an interface container. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + OInterfaceContainerHelper2( ::osl::Mutex & rMutex ); + /** + Release all interfaces. All iterators must be destroyed before + the container is destructed. + */ + ~OInterfaceContainerHelper2(); + /** + Return the number of Elements in the container. Only useful if you have acquired + the mutex. + */ + sal_Int32 getLength() const; + + /** + Return all interfaces added to this container. + **/ + std::vector< css::uno::Reference< css::uno::XInterface > > getElements() const; + + /** Inserts an element into the container. The position is not specified, thus it is not + specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rxIFace + interface to be added; it is allowed to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + sal_Int32 addInterface( const css::uno::Reference< css::uno::XInterface > & rxIFace ); + /** Removes an element from the container. It uses interface equality to remove the interface. + + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + sal_Int32 removeInterface( const css::uno::Reference< css::uno::XInterface > & rxIFace ); + /** Return an interface by index */ + css::uno::Reference< css::uno::XInterface > getInterface(sal_Int32 nIndex) const; + /** + Call disposing on all object in the container that + support XEventListener. Then clear the container. + */ + void disposeAndClear( const css::lang::EventObject & rEvt ); + /** + Clears the container without calling disposing(). + */ + void clear(); + + /** Executes a functor for each contained listener of specified type, e.g. + forEach(.... + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam ListenerT listener type + @tparam FuncT unary functor type, let your compiler deduce this for you + @param func unary functor object expecting an argument of type + css::uno::Reference + */ + template + inline void forEach( FuncT const& func ); + + /** Calls a UNO listener method for each contained listener. + + The listener method must take a single argument of type EventT, + and return void. + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam ListenerT UNO event listener type, let your compiler deduce this for you + @tparam EventT event type, let your compiler deduce this for you + @param NotificationMethod + Pointer to a method of a ListenerT interface. + @param Event + Event to notify to all contained listeners + + Example: +@code + awt::PaintEvent aEvent( static_cast< cppu::OWeakObject* >( this ), ... ); + listeners.notifyEach( &XPaintListener::windowPaint, aEvent ); +@endcode + */ + template< typename ListenerT, typename EventT > + inline void notifyEach( void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& ), const EventT& Event ); + +private: +friend class OInterfaceIteratorHelper2; + /** + bIsList == TRUE -> aData.pAsVector of type vector< XInterfaceSequence >, + otherwise aData.pAsInterface == of type (XEventListener *) + */ + detail::element_alias2 aData; + ::osl::Mutex & rMutex; + /** TRUE -> used by an iterator. */ + bool bInUse; + /** TRUE -> aData.pAsVector is of type Sequence< XInterfaceSequence >. */ + bool bIsList; + + OInterfaceContainerHelper2( const OInterfaceContainerHelper2 & ) = delete; + OInterfaceContainerHelper2 & operator = ( const OInterfaceContainerHelper2 & ) = delete; + + /* + Duplicate content of the container and release the old one without destroying. + The mutex must be locked and the memberbInUse must be true. + */ + void copyAndResetInUse(); + +private: + template< typename ListenerT, typename EventT > + class NotifySingleListener + { + private: + typedef void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& ); + NotificationMethod const m_pMethod; + const EventT& m_rEvent; + public: + NotifySingleListener( NotificationMethod method, const EventT& event ) : m_pMethod( method ), m_rEvent( event ) { } + + void operator()( const css::uno::Reference& listener ) const + { + (listener.get()->*m_pMethod)( m_rEvent ); + } + }; +}; + +template +inline void OInterfaceContainerHelper2::forEach( FuncT const& func ) +{ + OInterfaceIteratorHelper2 iter( *this ); + while (iter.hasMoreElements()) { + css::uno::Reference const xListener( iter.next(), css::uno::UNO_QUERY ); + if (xListener.is()) { + try { + func( xListener ); + } + catch (css::lang::DisposedException const& exc) { + if (exc.Context == xListener) + iter.remove(); + } + } + } +} + +template< typename ListenerT, typename EventT > +inline void OInterfaceContainerHelper2::notifyEach( void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& ), const EventT& Event ) +{ + forEach< ListenerT, NotifySingleListener< ListenerT, EventT > >( NotifySingleListener< ListenerT, EventT >( NotificationMethod, Event ) ); +} + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/interfacecontainer3.hxx b/include/comphelper/interfacecontainer3.hxx new file mode 100644 index 000000000..4b3d44bab --- /dev/null +++ b/include/comphelper/interfacecontainer3.hxx @@ -0,0 +1,379 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include +#include +#include + +namespace com::sun::star::uno +{ +class XInterface; +} +namespace osl +{ +class Mutex; +} + +namespace comphelper +{ +template class OInterfaceContainerHelper3; +/** + This is the iterator of an OInterfaceContainerHelper3. Typically + one constructs an instance on the stack for one firing session. + It is not allowed to assign or copy an instance of this class. + + @tparam ListenerT UNO event listener type + @see OInterfaceContainerHelper3 + */ +template class OInterfaceIteratorHelper3 +{ +public: + /** + Create an iterator over the elements of the container. The iterator + copies the elements of the container. A change to the container + during the lifetime of an iterator is allowed and does not + affect the iterator-instance. The iterator and the container take cares + themself for concurrent access, no additional guarding is necessary. + + Remark: The copy is on demand. The iterator copy the elements only if the container + change the contents... + + @param rCont the container of the elements. + */ + OInterfaceIteratorHelper3(OInterfaceContainerHelper3& rCont_) + : rCont(rCont_) + , maData(rCont.maData) + , nRemain(maData->size()) + { + } + + /** Return true, if there are more elements in the iterator. */ + bool hasMoreElements() const { return nRemain != 0; } + /** Return the next element of the iterator. Calling this method if + hasMoreElements() has returned false, is an error. + */ + css::uno::Reference const& next(); + + /** Removes the current element (the last one returned by next()) + from the underlying container. Calling this method before + next() has been called or calling it twice with no next() + in between is an error. + */ + void remove(); + +private: + OInterfaceContainerHelper3& rCont; + o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy> + maData; + sal_Int32 nRemain; + + OInterfaceIteratorHelper3(const OInterfaceIteratorHelper3&) = delete; + OInterfaceIteratorHelper3& operator=(const OInterfaceIteratorHelper3&) = delete; +}; + +template +const css::uno::Reference& OInterfaceIteratorHelper3::next() +{ + nRemain--; + return (*maData)[nRemain]; +} + +template void OInterfaceIteratorHelper3::remove() +{ + rCont.removeInterface((*maData)[nRemain]); +} + +/** + A container of interfaces. To access the elements use an iterator. + This implementation is thread-safe. + + This is a copy of the code at include/comphelper/interfacecontainer2.hxx, + except that it is templatized on the type of the listener, which allows + some parts of the code to avoid doing an UNO_QUERY that can be expensive + in bulk. + + @tparam ListenerT UNO event listener type + @see OInterfaceIteratorHelper + */ +template class OInterfaceContainerHelper3 +{ +public: + /** + Create an interface container. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + inline OInterfaceContainerHelper3(::osl::Mutex& rMutex_); + + /** + Return the number of Elements in the container. Only useful if you have acquired + the mutex. + */ + sal_Int32 getLength() const; + + /** + Return all interfaces added to this container. + **/ + std::vector> getElements() const; + + /** Inserts an element into the container. The position is not specified, thus it is not + specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rxIFace + interface to be added; it is allowed to insert + the same interface more than once + @return + the new count of elements in the container + */ + sal_Int32 addInterface(const css::uno::Reference& rxIFace); + /** Removes an element from the container. It uses interface equality to remove the interface. + + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + sal_Int32 removeInterface(const css::uno::Reference& rxIFace); + /** Return an interface by index + */ + const css::uno::Reference& getInterface(sal_Int32 nIndex) const; + /** + Call disposing on all object in the container that + support XEventListener. Then clear the container. + */ + void disposeAndClear(const css::lang::EventObject& rEvt); + /** + Clears the container without calling disposing(). + */ + void clear(); + + /** Executes a functor for each contained listener of specified type, e.g. + forEach(.... + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam FuncT unary functor type, let your compiler deduce this for you + @param func unary functor object expecting an argument of type + css::uno::Reference + */ + template inline void forEach(FuncT const& func); + + /** Calls a UNO listener method for each contained listener. + + The listener method must take a single argument of type EventT, + and return void. + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam EventT event type, let your compiler deduce this for you + @param NotificationMethod + Pointer to a method of a ListenerT interface. + @param Event + Event to notify to all contained listeners + + Example: +@code + awt::PaintEvent aEvent( static_cast< cppu::OWeakObject* >( this ), ... ); + listeners.notifyEach( &XPaintListener::windowPaint, aEvent ); +@endcode + */ + template + inline void notifyEach(void (SAL_CALL ListenerT::*NotificationMethod)(const EventT&), + const EventT& Event); + +private: + friend class OInterfaceIteratorHelper3; + o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy> + maData; + ::osl::Mutex& mrMutex; + OInterfaceContainerHelper3(const OInterfaceContainerHelper3&) = delete; + OInterfaceContainerHelper3& operator=(const OInterfaceContainerHelper3&) = delete; + + static o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy>& + DEFAULT() + { + static o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy> + SINGLETON; + return SINGLETON; + } + +private: + template class NotifySingleListener + { + private: + typedef void (SAL_CALL ListenerT::*NotificationMethod)(const EventT&); + NotificationMethod const m_pMethod; + const EventT& m_rEvent; + + public: + NotifySingleListener(NotificationMethod method, const EventT& event) + : m_pMethod(method) + , m_rEvent(event) + { + } + + void operator()(const css::uno::Reference& listener) const + { + (listener.get()->*m_pMethod)(m_rEvent); + } + }; +}; + +template +inline OInterfaceContainerHelper3::OInterfaceContainerHelper3(::osl::Mutex& rMutex_) + : maData(OInterfaceContainerHelper3::DEFAULT()) + , mrMutex(rMutex_) +{ +} + +template +template +inline void OInterfaceContainerHelper3::forEach(FuncT const& func) +{ + OInterfaceIteratorHelper3 iter(*this); + while (iter.hasMoreElements()) + { + auto xListener = iter.next(); + try + { + func(xListener); + } + catch (css::lang::DisposedException const& exc) + { + if (exc.Context == xListener) + iter.remove(); + } + } +} + +template +template +inline void OInterfaceContainerHelper3::notifyEach( + void (SAL_CALL ListenerT::*NotificationMethod)(const EventT&), const EventT& Event) +{ + forEach>(NotifySingleListener(NotificationMethod, Event)); +} + +template sal_Int32 OInterfaceContainerHelper3::getLength() const +{ + osl::MutexGuard aGuard(mrMutex); + return maData->size(); +} + +template +std::vector> +OInterfaceContainerHelper3::getElements() const +{ + std::vector> rVec; + osl::MutexGuard aGuard(mrMutex); + rVec = *maData; + return rVec; +} + +template +sal_Int32 +OInterfaceContainerHelper3::addInterface(const css::uno::Reference& rListener) +{ + assert(rListener.is()); + osl::MutexGuard aGuard(mrMutex); + + maData->push_back(rListener); + return maData->size(); +} + +template +sal_Int32 OInterfaceContainerHelper3::removeInterface( + const css::uno::Reference& rListener) +{ + assert(rListener.is()); + osl::MutexGuard aGuard(mrMutex); + + // It is not valid to compare the pointer directly, but it's faster. + auto it = std::find_if(maData->begin(), maData->end(), + [&rListener](const css::uno::Reference& rItem) { + return rItem.get() == rListener.get(); + }); + + // interface not found, use the correct compare method + if (it == maData->end()) + it = std::find(maData->begin(), maData->end(), rListener); + + if (it != maData->end()) + maData->erase(it); + + return maData->size(); +} + +template +const css::uno::Reference& +OInterfaceContainerHelper3::getInterface(sal_Int32 nIndex) const +{ + osl::MutexGuard aGuard(mrMutex); + + return (*maData)[nIndex]; +} + +template +void OInterfaceContainerHelper3::disposeAndClear(const css::lang::EventObject& rEvt) +{ + osl::ClearableMutexGuard aGuard(mrMutex); + OInterfaceIteratorHelper3 aIt(*this); + maData->clear(); + aGuard.clear(); + while (aIt.hasMoreElements()) + { + try + { + aIt.next()->disposing(rEvt); + } + catch (css::uno::RuntimeException&) + { + // be robust, if e.g. a remote bridge has disposed already. + // there is no way to delegate the error to the caller :o(. + } + } +} + +template void OInterfaceContainerHelper3::clear() +{ + osl::MutexGuard aGuard(mrMutex); + maData->clear(); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/interfacecontainer4.hxx b/include/comphelper/interfacecontainer4.hxx new file mode 100644 index 000000000..bdd6a6b60 --- /dev/null +++ b/include/comphelper/interfacecontainer4.hxx @@ -0,0 +1,401 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star::uno +{ +class XInterface; +} + +namespace comphelper +{ +template class OInterfaceContainerHelper4; +/** + This is the iterator of an OInterfaceContainerHelper4. Typically + one constructs an instance on the stack for one firing session. + It is not allowed to assign or copy an instance of this class. + + @tparam ListenerT UNO event listener type + @see OInterfaceContainerHelper4 + */ +template class OInterfaceIteratorHelper4 +{ +public: + /** + Create an iterator over the elements of the container. The iterator + copies the elements of the container. A change to the container + during the lifetime of an iterator is allowed and does not + affect the iterator-instance. The iterator and the container take cares + themself for concurrent access, no additional guarding is necessary. + + Remark: The copy is on demand. The iterator copy the elements only if the container + change the contents... + + @param rCont the container of the elements. + @param rGuard + this parameter only here to make that this container is accessed while locked + */ + OInterfaceIteratorHelper4(std::unique_lock& /*rGuard*/, + OInterfaceContainerHelper4& rCont_) + : rCont(rCont_) + , maData(rCont.maData) + // const_cast so we don't trigger make_unique via o3tl::cow_wrapper::operator-> + , nRemain(std::as_const(maData)->size()) + { + } + + /** Return true, if there are more elements in the iterator. */ + bool hasMoreElements() const { return nRemain != 0; } + /** Return the next element of the iterator. Calling this method if + hasMoreElements() has returned false, is an error. + */ + css::uno::Reference const& next(); + + /** Removes the current element (the last one returned by next()) + from the underlying container. Calling this method before + next() has been called or calling it twice with no next() + in between is an error. + @param rGuard + this parameter only here to make that this container is accessed while locked + */ + void remove(::std::unique_lock<::std::mutex>& rGuard); + +private: + OInterfaceContainerHelper4& rCont; + o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy> + maData; + sal_Int32 nRemain; + + OInterfaceIteratorHelper4(const OInterfaceIteratorHelper4&) = delete; + OInterfaceIteratorHelper4& operator=(const OInterfaceIteratorHelper4&) = delete; +}; + +template +const css::uno::Reference& OInterfaceIteratorHelper4::next() +{ + nRemain--; + return (*std::as_const(maData))[nRemain]; +} + +template +void OInterfaceIteratorHelper4::remove(::std::unique_lock<::std::mutex>& rGuard) +{ + rCont.removeInterface(rGuard, (*std::as_const(maData))[nRemain]); +} + +/** + A container of interfaces. To access the elements use an iterator. + This implementation is thread-safe. + + This is a copy of the code at include/comphelper/interfacecontainer3.hxx, + except that it (a) uses std::mutex instead of osl::Mutex and (b) does not + store a reference to the mutex, but relies on the calling class to take + a lock around using it. + + @tparam ListenerT UNO event listener type + @see OInterfaceIteratorHelper + */ +template class OInterfaceContainerHelper4 +{ +public: + OInterfaceContainerHelper4(); + + /** + Return the number of Elements in the container. Only useful if you have acquired + the mutex. + @param rGuard + this parameter only here to make that this container is accessed while locked + */ + sal_Int32 getLength(std::unique_lock& rGuard) const; + + /** + Return all interfaces added to this container. + @param rGuard + this parameter only here to make that this container is accessed while locked + **/ + std::vector> + getElements(std::unique_lock& rGuard) const; + + /** Inserts an element into the container. The position is not specified, thus it is not + specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rxIFace + interface to be added; it is allowed to insert + the same interface more than once + @param rGuard + this parameter only here to make that this container is accessed while locked + @return + the new count of elements in the container + */ + sal_Int32 addInterface(std::unique_lock& rGuard, + const css::uno::Reference& rxIFace); + /** Removes an element from the container. It uses interface equality to remove the interface. + + @param rxIFace + interface to be removed + @param rGuard + this parameter only here to make that this container is accessed while locked + @return + the new count of elements in the container + */ + sal_Int32 removeInterface(std::unique_lock& rGuard, + const css::uno::Reference& rxIFace); + /** + Call disposing on all object in the container that + support XEventListener. Then clear the container. + The guard is unlock()'ed before calling the listeners. + */ + void disposeAndClear(::std::unique_lock<::std::mutex>& rGuard, + const css::lang::EventObject& rEvt); + /** + Clears the container without calling disposing(). + @param rGuard + this parameter only here to make that this container is accessed while locked + */ + void clear(::std::unique_lock<::std::mutex>& rGuard); + + /** Executes a functor for each contained listener of specified type, e.g. + forEach(.... + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam FuncT unary functor type, let your compiler deduce this for you + @param func unary functor object expecting an argument of type + css::uno::Reference + @param rGuard + this parameter only here to make that this container is accessed while locked + */ + template + inline void forEach(std::unique_lock& rGuard, FuncT const& func); + + /** Calls a UNO listener method for each contained listener. + + The listener method must take a single argument of type EventT, + and return void. + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam EventT event type, let your compiler deduce this for you + @param NotificationMethod + Pointer to a method of a ListenerT interface. + @param Event + Event to notify to all contained listeners + @param rGuard + this parameter only here to make that this container is accessed while locked + + Example: +@code + awt::PaintEvent aEvent( static_cast< cppu::OWeakObject* >( this ), ... ); + listeners.notifyEach( &XPaintListener::windowPaint, aEvent ); +@endcode + */ + template + inline void notifyEach(std::unique_lock& rGuard, + void (SAL_CALL ListenerT::*NotificationMethod)(const EventT&), + const EventT& Event); + +private: + friend class OInterfaceIteratorHelper4; + o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy> + maData; + OInterfaceContainerHelper4(const OInterfaceContainerHelper4&) = delete; + OInterfaceContainerHelper4& operator=(const OInterfaceContainerHelper4&) = delete; + + static o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy>& + DEFAULT() + { + static o3tl::cow_wrapper>, + o3tl::ThreadSafeRefCountingPolicy> + SINGLETON; + return SINGLETON; + } + +private: + template class NotifySingleListener + { + private: + typedef void (SAL_CALL ListenerT::*NotificationMethod)(const EventT&); + NotificationMethod const m_pMethod; + const EventT& m_rEvent; + + public: + NotifySingleListener(NotificationMethod method, const EventT& event) + : m_pMethod(method) + , m_rEvent(event) + { + } + + void operator()(const css::uno::Reference& listener) const + { + (listener.get()->*m_pMethod)(m_rEvent); + } + }; +}; + +template +inline OInterfaceContainerHelper4::OInterfaceContainerHelper4() + : maData(OInterfaceContainerHelper4::DEFAULT()) +{ +} + +template +template +inline void OInterfaceContainerHelper4::forEach(std::unique_lock& rGuard, + FuncT const& func) +{ + if (std::as_const(maData)->size() == 0) + { + return; + } + maData.make_unique(); // so we can iterate over the data without holding the lock + OInterfaceIteratorHelper4 iter(rGuard, *this); + rGuard.unlock(); + while (iter.hasMoreElements()) + { + auto xListener = iter.next(); + try + { + func(xListener); + } + catch (css::lang::DisposedException const& exc) + { + if (exc.Context == xListener) + { + rGuard.lock(); + iter.remove(rGuard); + rGuard.unlock(); + } + } + } + rGuard.lock(); +} + +template +template +inline void OInterfaceContainerHelper4::notifyEach( + std::unique_lock& rGuard, + void (SAL_CALL ListenerT::*NotificationMethod)(const EventT&), const EventT& Event) +{ + forEach>(rGuard, + NotifySingleListener(NotificationMethod, Event)); +} + +template +sal_Int32 +OInterfaceContainerHelper4::getLength(std::unique_lock& /*rGuard*/) const +{ + return maData->size(); +} + +template +std::vector> +OInterfaceContainerHelper4::getElements(std::unique_lock& /*rGuard*/) const +{ + return *maData; +} + +template +sal_Int32 +OInterfaceContainerHelper4::addInterface(std::unique_lock& /*rGuard*/, + const css::uno::Reference& rListener) +{ + assert(rListener.is()); + maData->push_back(rListener); + return maData->size(); +} + +template +sal_Int32 OInterfaceContainerHelper4::removeInterface( + std::unique_lock& /*rGuard*/, const css::uno::Reference& rListener) +{ + assert(rListener.is()); + + // It is not valid to compare the pointer directly, but it's faster. + auto it = std::find_if(maData->begin(), maData->end(), + [&rListener](const css::uno::Reference& rItem) { + return rItem.get() == rListener.get(); + }); + + // interface not found, use the correct compare method + if (it == maData->end()) + it = std::find(maData->begin(), maData->end(), rListener); + + if (it != maData->end()) + maData->erase(it); + + return maData->size(); +} + +template +void OInterfaceContainerHelper4::disposeAndClear(std::unique_lock& rGuard, + const css::lang::EventObject& rEvt) +{ + { + OInterfaceIteratorHelper4 aIt(rGuard, *this); + maData + = DEFAULT(); // cheaper than calling maData->clear() because it doesn't allocate a new vector + rGuard.unlock(); + // unlock followed by iterating is only safe because we are not going to call remove() on the iterator + while (aIt.hasMoreElements()) + { + try + { + aIt.next()->disposing(rEvt); + } + catch (css::uno::RuntimeException&) + { + // be robust, if e.g. a remote bridge has disposed already. + // there is no way to delegate the error to the caller :o(. + } + } + } + // tdf#152077 need to destruct the OInterfaceIteratorHelper4 before we take the lock again + // because there is a vague chance that destructing it will trigger a call back into something + // that wants to take the lock. + rGuard.lock(); +} + +template +void OInterfaceContainerHelper4::clear(::std::unique_lock<::std::mutex>& /*rGuard*/) +{ + maData->clear(); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/logging.hxx b/include/comphelper/logging.hxx new file mode 100644 index 000000000..f0a599765 --- /dev/null +++ b/include/comphelper/logging.hxx @@ -0,0 +1,460 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_LOGGING_HXX +#define INCLUDED_COMPHELPER_LOGGING_HXX + +#include +#include + +#include +#include + +namespace com::sun::star::uno { template class Reference; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::logging { class XLogger; } + +namespace comphelper +{ + + + //= string conversions, employed by the templatized log* members of + //= EventLogger + + + namespace log::convert + { + inline const OUString& convertLogArgToString( const OUString& _rValue ) + { + return _rValue; + } + + inline OUString convertLogArgToString( const char* _pAsciiValue ) + { + return OUString::createFromAscii( _pAsciiValue ); + } + + inline OUString convertLogArgToString( double _nValue ) { return OUString::number( _nValue ); } + inline OUString convertLogArgToString( float _nValue ) { return OUString::number( _nValue ); } + inline OUString convertLogArgToString( sal_Int64 _nValue ) { return OUString::number( _nValue ); } + inline OUString convertLogArgToString( sal_Int32 _nValue ) { return OUString::number( _nValue ); } + inline OUString convertLogArgToString( sal_Int16 _nValue ) { return OUString::number( _nValue ); } + inline OUString convertLogArgToString( sal_Unicode _nValue ) { return OUString( _nValue ); } + inline OUString convertLogArgToString( bool _bValue ) { return OUString::boolean( _bValue ); } + void convertLogArgToString(sal_Bool) = delete; + + } // namespace log::convert + + + //= EventLogger + + class EventLogger_Impl; + typedef ::std::optional< OUString > OptionalString; + + /** encapsulates a css::logging::XLogger + + The class silences several (unlikely) errors which could potentially happen + when working with a logger. Additionally, it provides some convenience methods + for logging events. + + You can use this class as follows +

+    EventLogger aLogger( xContext, sLoggerName );
+    ...
+    aLogger.log( LogLevel::SEVERE, sSomeMessage );
+    aLogger.logp( LogLevel::CONFIG, "MyClass", "MyMethod", sSomeMessage, SomeParameter1, SomeParameter2, SomeParameter3 );
+
+ + The log and logp calls support up to 6 parameters, which can be of + arbitrary type. For every parameter, there must exist a function convertLogArgToString + which takes an argument of the respective type, and returns a string. + + After a parameter has been converted to a string using the above mentioned + convertLogArgToString function, a placeholder $1$ (resp. $2$ resp. $4$ ...) + in the message will be replaced with this string, and the resulting message will be logged. + */ + class COMPHELPER_DLLPUBLIC EventLogger + { + protected: + std::shared_ptr< EventLogger_Impl > m_pImpl; + + public: + /** creates an EventLogger instance working with a css.logging.XLogger + instance given by ASCII name. + + @param _rxContext + the component context to create services + + @param _rLoggerName + the ASCII name of the logger to create. + */ + EventLogger( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + const char* _pAsciiLoggerName + ); + + public: + /// determines whether an event with the given level would be logged + bool isLoggable( const sal_Int32 _nLogLevel ) const; + + + //- XLogger::log equivalents/wrappers + //- string messages + + /// logs a given message, without any arguments, or source class/method names + void log( const sal_Int32 _nLogLevel, const OUString& rMessage ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log(_nLogLevel, nullptr, nullptr, rMessage); + } + + const css::uno::Reference & getLogger() const; + + /** logs a given message, replacing a placeholder in the message with an argument + + The function takes, additionally to the log level and the message, an arbitrary + argument. This argument is converted to a string using an overloaded function + named convertLogArgToString. Then, a placeholder "$1$" + is searched in the message string, and replaced with the argument string. + */ + template< typename ARGTYPE1 > + void log( const sal_Int32 _nLogLevel, const OUString& _rMessage, ARGTYPE1 _argument1 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ) ); + } + + /// logs a given message, replacing 2 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2 > + void log( const sal_Int32 _nLogLevel, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ) ); + } + + /// logs a given message, replacing 3 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3 > + void log( const sal_Int32 _nLogLevel, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ) ); + } + + /// logs a given message, replacing 4 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4 > + void log( const sal_Int32 _nLogLevel, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ) ); + } + + /// logs a given message, replacing 5 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5 > + void log( const sal_Int32 _nLogLevel, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ) ); + } + + /// logs a given message, replacing 6 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5, typename ARGTYPE6 > + void log( const sal_Int32 _nLogLevel, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5, ARGTYPE6 _argument6 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ), + OptionalString( log::convert::convertLogArgToString( _argument6 ) ) ); + } + + + //- XLogger::log equivalents/wrappers + //- ASCII messages + + /** logs a given message, replacing a placeholder in the message with an argument + + The function takes, additionally to the log level and the message, an arbitrary + argument. This argument is converted to a string using an overloaded function + named convertLogArgToString. Then, a placeholder "$1$" + is searched in the message string, and replaced with the argument string. + */ + template< typename ARGTYPE1 > + void log( const sal_Int32 _nLogLevel, const char* _pMessage, ARGTYPE1 _argument1 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, OUString::createFromAscii( _pMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ) ); + } + + /// logs a given message, replacing 2 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2 > + void log( const sal_Int32 _nLogLevel, const char* _pMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, OUString::createFromAscii( _pMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ) ); + } + + /// logs a given message, replacing 3 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3 > + void log( const sal_Int32 _nLogLevel, const char* _pMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, OUString::createFromAscii( _pMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ) ); + } + + /// logs a given message, replacing 4 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4 > + void log( const sal_Int32 _nLogLevel, const char* _pMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, OUString::createFromAscii( _pMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ) ); + } + + /// logs a given message, replacing 5 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5 > + void log( const sal_Int32 _nLogLevel, const char* _pMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, OUString::createFromAscii( _pMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ) ); + } + + /// logs a given message, replacing 6 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5, typename ARGTYPE6 > + void log( const sal_Int32 _nLogLevel, const char* _pMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5, ARGTYPE6 _argument6 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, nullptr, nullptr, OUString::createFromAscii( _pMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ), + OptionalString( log::convert::convertLogArgToString( _argument6 ) ) ); + } + + + //- XLogger::logp equivalents/wrappers + //- string messages + + /** logs a given message, replacing a placeholder in the message with an argument + + The function takes, additionally to the logp level and the message, an arbitrary + argument. This argument is converted to a string using an overloaded function + named convertLogArgToString. Then, a placeholder "$1$" + is searched in the message string, and replaced with the argument string. + */ + template< typename ARGTYPE1 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const OUString& _rMessage, ARGTYPE1 _argument1 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ) ); + } + + /// logs a given message, replacing 2 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ) ); + } + + /// logs a given message, replacing 3 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ) ); + } + + /// logs a given message, replacing 4 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ) ); + } + + /// logs a given message, replacing 5 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ) ); + } + + /// logs a given message, replacing 6 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5, typename ARGTYPE6 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const OUString& _rMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5, ARGTYPE6 _argument6 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, _rMessage, + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ), + OptionalString( log::convert::convertLogArgToString( _argument6 ) ) ); + } + + + //- XLogger::logp equivalents/wrappers + //- ASCII messages + + /** logs a given ASCII message, replacing a placeholder in the message with an argument + + The function takes, additionally to the logp level and the message, an arbitrary + argument. This argument is converted to a string using an overloaded function + named convertLogArgToString. Then, a placeholder "$1$" + is searched in the message string, and replaced with the argument string. + */ + template< typename ARGTYPE1 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const char* _pAsciiMessage, ARGTYPE1 _argument1 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, OUString::createFromAscii( _pAsciiMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ) ); + } + + /// logs a given ASCII message, replacing 2 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const char* _pAsciiMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, OUString::createFromAscii( _pAsciiMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ) ); + } + + /// logs a given ASCII message, replacing 3 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const char* _pAsciiMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, OUString::createFromAscii( _pAsciiMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ) ); + } + + /// logs a given ASCII message, replacing 4 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const char* _pAsciiMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, OUString::createFromAscii( _pAsciiMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ) ); + } + + /// logs a given ASCII message, replacing 5 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const char* _pAsciiMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, OUString::createFromAscii( _pAsciiMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ) ); + } + + /// logs a given ASCII message, replacing 6 placeholders in the message with respective values + template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5, typename ARGTYPE6 > + void logp( const sal_Int32 _nLogLevel, const char* _pSourceClass, const char* _pSourceMethod, const char* _pAsciiMessage, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5, ARGTYPE6 _argument6 ) const + { + if ( isLoggable( _nLogLevel ) ) + impl_log( _nLogLevel, _pSourceClass, _pSourceMethod, OUString::createFromAscii( _pAsciiMessage ), + OptionalString( log::convert::convertLogArgToString( _argument1 ) ), + OptionalString( log::convert::convertLogArgToString( _argument2 ) ), + OptionalString( log::convert::convertLogArgToString( _argument3 ) ), + OptionalString( log::convert::convertLogArgToString( _argument4 ) ), + OptionalString( log::convert::convertLogArgToString( _argument5 ) ), + OptionalString( log::convert::convertLogArgToString( _argument6 ) ) ); + } + + protected: + void impl_log( + const sal_Int32 _nLogLevel, + const char* _pSourceClass, + const char* _pSourceMethod, + const OUString& _rMessage, + const OptionalString& _rArgument1 = OptionalString(), + const OptionalString& _rArgument2 = OptionalString(), + const OptionalString& _rArgument3 = OptionalString(), + const OptionalString& _rArgument4 = OptionalString(), + const OptionalString& _rArgument5 = OptionalString(), + const OptionalString& _rArgument6 = OptionalString() + ) const; + }; +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_LOGGING_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/lok.hxx b/include/comphelper/lok.hxx new file mode 100644 index 000000000..66784e8e4 --- /dev/null +++ b/include/comphelper/lok.hxx @@ -0,0 +1,117 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_LOK_HXX +#define INCLUDED_COMPHELPER_LOK_HXX + +#include +#include + +class LanguageTag; + +// Interface between the LibreOfficeKit implementation called by LibreOfficeKit clients and other +// LibreOffice code. + +namespace comphelper::LibreOfficeKit +{ +// Functions to be called only from the LibreOfficeKit implementation in desktop, not from other +// places in LibreOffice code. + +COMPHELPER_DLLPUBLIC void setActive(bool bActive = true); + +enum class statusIndicatorCallbackType +{ + Start, + SetValue, + Finish +}; + +COMPHELPER_DLLPUBLIC void setStatusIndicatorCallback( + void (*callback)(void* data, statusIndicatorCallbackType type, int percent, const char* pText), + void* data); + +// Functions that can be called from arbitrary places in LibreOffice. + +// Check whether the code is running as invoked through LibreOfficeKit. +COMPHELPER_DLLPUBLIC bool isActive(); + +/// Shift the coordinates before rendering each bitmap. +/// Used by Calc to render each tile separately. +/// This should be unnecessary (and removed) once Calc +/// moves to using 100MM Unit. +COMPHELPER_DLLPUBLIC void setLocalRendering(bool bLocalRendering = true); +COMPHELPER_DLLPUBLIC bool isLocalRendering(); + +/// Check whether clients want a part number in an invalidation payload. +COMPHELPER_DLLPUBLIC bool isPartInInvalidation(); +/// Set whether clients want a part number in an invalidation payload. +COMPHELPER_DLLPUBLIC void setPartInInvalidation(bool bPartInInvalidation); + +/// Check if we are doing tiled painting. +COMPHELPER_DLLPUBLIC bool isTiledPainting(); +/// Set if we are doing tiled painting. +COMPHELPER_DLLPUBLIC void setTiledPainting(bool bTiledPainting); +/// Check if we are painting the dialog. +COMPHELPER_DLLPUBLIC bool isDialogPainting(); +/// Set if we are painting the dialog. +COMPHELPER_DLLPUBLIC void setDialogPainting(bool bDialogPainting); +/// Set the DPI scale for rendering for HiDPI displays. +COMPHELPER_DLLPUBLIC void setDPIScale(double fDPIScale); +/// Get the DPI scale for rendering for HiDPI displays. +COMPHELPER_DLLPUBLIC double getDPIScale(); +/// Set if we want no annotations rendering +COMPHELPER_DLLPUBLIC void setTiledAnnotations(bool bTiledAnnotations); +/// Check if annotations rendering is turned off +COMPHELPER_DLLPUBLIC bool isTiledAnnotations(); +/// Set if we want range based header data +COMPHELPER_DLLPUBLIC void setRangeHeaders(bool bTiledAnnotations); +/// Check if range based header data is enabled +COMPHELPER_DLLPUBLIC bool isRangeHeaders(); + +enum Compat : sal_uInt32 +{ + none = 0, + scNoGridBackground = 1, + scPrintTwipsMsgs = 2, +}; +/// Set compatibility flags +COMPHELPER_DLLPUBLIC void setCompatFlag(Compat flag); +/// Get compatibility flags +COMPHELPER_DLLPUBLIC bool isCompatFlagSet(Compat flag); + +/// Check whether clients want viewId in visible cursor invalidation payload. +COMPHELPER_DLLPUBLIC bool isViewIdForVisCursorInvalidation(); +/// Set whether clients want viewId in visible cursor invalidation payload. +COMPHELPER_DLLPUBLIC void setViewIdForVisCursorInvalidation(bool bViewIdForVisCursorInvalidation); + +/// Update the current LOK's locale. +COMPHELPER_DLLPUBLIC void setLocale(const LanguageTag& languageTag); +/// Get the current LOK's locale. +COMPHELPER_DLLPUBLIC const LanguageTag& getLocale(); + +/// Update the current LOK's language. +COMPHELPER_DLLPUBLIC void setLanguageTag(const LanguageTag& languageTag); +/// Get the current LOK's language. +COMPHELPER_DLLPUBLIC const LanguageTag& getLanguageTag(); +/// If the language name should be used for this LOK instance. +COMPHELPER_DLLPUBLIC bool isAllowlistedLanguage(const OUString& lang); + +// Status indicator handling. Even if in theory there could be several status indicators active at +// the same time, in practice there is only one at a time, so we don't handle any identification of +// status indicator in this API. +COMPHELPER_DLLPUBLIC void statusIndicatorStart(const OUString& sText); +COMPHELPER_DLLPUBLIC void statusIndicatorSetValue(int percent); +COMPHELPER_DLLPUBLIC void statusIndicatorFinish(); + +COMPHELPER_DLLPUBLIC void setBlockedCommandList(const char* blockedCommandList); +} + +#endif // INCLUDED_COMPHELPER_LOK_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/make_shared_from_uno.hxx b/include/comphelper/make_shared_from_uno.hxx new file mode 100644 index 000000000..7075e3000 --- /dev/null +++ b/include/comphelper/make_shared_from_uno.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_MAKE_SHARED_FROM_UNO_HXX +#define INCLUDED_COMPHELPER_MAKE_SHARED_FROM_UNO_HXX + +#include + +namespace comphelper +{ +/// @internal +namespace detail +{ +/// @internal +template struct ReleaseFunc +{ + void operator()(T* p) const { p->release(); } +}; +} // namespace detail + +/** Makes a std::shared_ptr from a ref-counted UNO object pointer. + This makes sense if the object is used via UNO (implementing some X + interface) and also internally using its implementation class, e.g. + +
+        std::shared_ptr const ptr(
+            comphelper::make_shared_from_UNO( new MyUnoImpl ) );
+        ...
+        xUno->callingUno( uno::Reference( ptr.get() ) );
+        ...
+        takeSharedPtr( ptr );
+        ...
+    
+ + @attention The shared_ptr operates on a separate reference counter, so + weak pointers (std::weak_ptr) are invalidated when the last + shared_ptr is destroyed, although the UNO object may still be + alive. + + @param p object pointer + @return shared_ptr to object +*/ +template inline std::shared_ptr make_shared_from_UNO(T* p) +{ + p->acquire(); + return std::shared_ptr(p, detail::ReleaseFunc()); +} + +} // namespace comphelper + +#endif // ! defined(INCLUDED_COMPHELPER_MAKE_SHARED_FROM_UNO_HXX) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/mimeconfighelper.hxx b/include/comphelper/mimeconfighelper.hxx new file mode 100644 index 000000000..5dd99664a --- /dev/null +++ b/include/comphelper/mimeconfighelper.hxx @@ -0,0 +1,142 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_MIMECONFIGHELPER_HXX +#define INCLUDED_COMPHELPER_MIMECONFIGHELPER_HXX + +#include +#include +#include + +namespace com::sun::star::beans { struct NamedValue; } +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::container { class XContainerQuery; } +namespace com::sun::star::container { class XNameAccess; } +namespace com::sun::star::embed { struct VerbDescriptor; } +namespace com::sun::star::lang { class XMultiServiceFactory; } +namespace com::sun::star::uno { class XComponentContext; } + +enum class SfxFilterFlags; + +namespace comphelper { + +class COMPHELPER_DLLPUBLIC MimeConfigurationHelper +{ + std::mutex m_aMutex; + css::uno::Reference< css::uno::XComponentContext > m_xContext; + css::uno::Reference< css::lang::XMultiServiceFactory > m_xConfigProvider; + + css::uno::Reference< css::container::XNameAccess > m_xObjectConfig; + css::uno::Reference< css::container::XNameAccess > m_xVerbsConfig; + css::uno::Reference< css::container::XNameAccess > m_xMediaTypeConfig; + + css::uno::Reference< css::container::XNameAccess > m_xFilterFactory; + +public: + + MimeConfigurationHelper( css::uno::Reference< css::uno::XComponentContext > xContext ); + + + static OUString GetStringClassIDRepresentation( const css::uno::Sequence< sal_Int8 >& aClassID ); + + static css::uno::Sequence< sal_Int8 > GetSequenceClassIDRepresentation( std::u16string_view aClassID ); + + + css::uno::Reference< css::container::XNameAccess > GetObjConfiguration(); + css::uno::Reference< css::container::XNameAccess > GetVerbsConfiguration(); + css::uno::Reference< css::container::XNameAccess > GetMediaTypeConfiguration(); + + + OUString GetDocServiceNameFromFilter( const OUString& aFilterName ); + + OUString GetDocServiceNameFromMediaType( const OUString& aMediaType ); + + css::uno::Sequence< css::beans::NamedValue > GetObjPropsFromConfigEntry( + const css::uno::Sequence< sal_Int8 >& aClassID, + const css::uno::Reference< css::container::XNameAccess >& xObjectProps ); + + bool GetVerbByShortcut( const OUString& aVerbShortcut, + css::embed::VerbDescriptor& aDescriptor ); + + OUString GetExplicitlyRegisteredObjClassID( const OUString& aMediaType ); + + + // retrieving object description from configuration + css::uno::Sequence< css::beans::NamedValue > GetObjectPropsByStringClassID( + const OUString& aStringClassID ); + + css::uno::Sequence< css::beans::NamedValue > GetObjectPropsByClassID( + const css::uno::Sequence< sal_Int8 >& aClassID ); + + css::uno::Sequence< css::beans::NamedValue > GetObjectPropsByMediaType( + const OUString& aMediaType ); + + css::uno::Sequence< css::beans::NamedValue > GetObjectPropsByFilter( + const OUString& aFilterName ); + + css::uno::Sequence< css::beans::NamedValue > GetObjectPropsByDocumentName( + std::u16string_view aDocumentName ); + + // retrieving object factory from configuration + OUString GetFactoryNameByStringClassID( const OUString& aStringClassID ); + OUString GetFactoryNameByClassID( const css::uno::Sequence< sal_Int8 >& aClassID ); + OUString GetFactoryNameByDocumentName( std::u16string_view aDocName ); + OUString GetFactoryNameByMediaType( const OUString& aMediaType ); + + // typedetection related + css::uno::Reference< css::container::XNameAccess > GetFilterFactory(); + + OUString UpdateMediaDescriptorWithFilterName( + css::uno::Sequence< css::beans::PropertyValue >& aMediaDescr, + bool bIgnoreType ); + OUString UpdateMediaDescriptorWithFilterName( + css::uno::Sequence< css::beans::PropertyValue >& aMediaDescr, + css::uno::Sequence< css::beans::NamedValue >& aObject ); +#ifdef _WIN32 + SfxFilterFlags GetFilterFlags( const OUString& aFilterName ); + + bool AddFilterNameCheckOwnFile( + css::uno::Sequence< css::beans::PropertyValue >& aMediaDescr ); +#endif + + OUString GetDefaultFilterFromServiceName( const OUString& aServName, sal_Int32 nVersion ); + + OUString GetExportFilterFromImportFilter( const OUString& aImportFilterName ); + + static css::uno::Sequence< css::beans::PropertyValue > SearchForFilter( + const css::uno::Reference< css::container::XContainerQuery >& xFilterQuery, + const css::uno::Sequence< css::beans::NamedValue >& aSearchRequest, + SfxFilterFlags nMustFlags, + SfxFilterFlags nDontFlags ); + + static bool ClassIDsEqual( const css::uno::Sequence< sal_Int8 >& aClassID1, + const css::uno::Sequence< sal_Int8 >& aClassID2 ); + static css::uno::Sequence< sal_Int8 > GetSequenceClassID( sal_uInt32 n1, sal_uInt16 n2, sal_uInt16 n3, + sal_uInt8 b8, sal_uInt8 b9, sal_uInt8 b10, sal_uInt8 b11, + sal_uInt8 b12, sal_uInt8 b13, sal_uInt8 b14, sal_uInt8 b15 ); +private: + css::uno::Reference< css::container::XNameAccess > + GetConfigurationByPathImpl( const OUString& aPath ); +}; + +} + +#endif // INCLUDED_COMPHELPER_MIMECONFIGHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/multicontainer2.hxx b/include/comphelper/multicontainer2.hxx new file mode 100644 index 000000000..91875b668 --- /dev/null +++ b/include/comphelper/multicontainer2.hxx @@ -0,0 +1,133 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno +{ +class XInterface; +} + +namespace comphelper +{ +/** This is a copy of cppu::OMultiTypeInterfaceContainerHelper2 in include/cppuhelper/interfacecontainer.h, + except that it uses comphelper::OInterfaceContainerHelper2, which is more efficient. +*/ +class COMPHELPER_DLLPUBLIC OMultiTypeInterfaceContainerHelper2 +{ +public: + /** + Create a container of interface containers. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + OMultiTypeInterfaceContainerHelper2(::osl::Mutex& rMutex); + /** + Delete all containers. + */ + ~OMultiTypeInterfaceContainerHelper2(); + + /** + Return all id's under which at least one interface is added. + */ + std::vector getContainedTypes() const; + + /** + Return the container created under this key. + @return the container created under this key. If the container + was not created, null was returned. + */ + OInterfaceContainerHelper2* getContainer(const css::uno::Type& rKey) const; + + /** Inserts an element into the container with the specified key. + The position is not specified, thus it is not specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rKey + the id of the container + @param r + interface to be added; it is allowed, to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + sal_Int32 addInterface(const css::uno::Type& rKey, + const css::uno::Reference& r); + + /** Removes an element from the container with the specified key. + It uses interface equality to remove the interface. + + @param rKey + the id of the container + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + sal_Int32 removeInterface(const css::uno::Type& rKey, + const css::uno::Reference& rxIFace); + + /** + Call disposing on all object in the container that + support XEventListener. Then clear the container. + */ + void disposeAndClear(const css::lang::EventObject& rEvt); + /** + Remove all elements of all containers. Does not delete the container. + */ + void clear(); + + typedef css::uno::Type keyType; + +private: + typedef std::vector>> + t_type2ptr; + + t_type2ptr::iterator findType(const css::uno::Type& rKey); + t_type2ptr::const_iterator findType(const css::uno::Type& rKey) const; + + t_type2ptr m_aMap; + ::osl::Mutex& rMutex; + + OMultiTypeInterfaceContainerHelper2(const OMultiTypeInterfaceContainerHelper2&) = delete; + OMultiTypeInterfaceContainerHelper2& operator=(const OMultiTypeInterfaceContainerHelper2&) + = delete; +}; + +} // namespace comphelper + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/multiinterfacecontainer3.hxx b/include/comphelper/multiinterfacecontainer3.hxx new file mode 100644 index 000000000..87199885e --- /dev/null +++ b/include/comphelper/multiinterfacecontainer3.hxx @@ -0,0 +1,217 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include +#include +#include + +namespace osl +{ +class Mutex; +} + +namespace comphelper +{ +/** + A helper class to store interface references of different types. + This is a copy of the similar class at include/cppuhelper/interfacecontainer.h, + but now uses the improved comphelper::InterfaceContainer3. + + @see OInterfaceIteratorHelper3 + @see OInterfaceContainerHelper3 + */ +template > +class OMultiTypeInterfaceContainerHelperVar3 +{ +public: + /** + Create a container of interface containers. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + inline OMultiTypeInterfaceContainerHelperVar3(::osl::Mutex& rMutex_) + : rMutex(rMutex_) + { + } + + /** + Return all id's under which at least one interface is added. + */ + inline std::vector getContainedTypes() const + { + ::osl::MutexGuard aGuard(rMutex); + std::vector aInterfaceTypes; + aInterfaceTypes.reserve(m_aMap.size()); + for (const auto& rPair : m_aMap) + // are interfaces added to this container? + if (rPair.second->getLength()) + // yes, put the type in the array + aInterfaceTypes.push_back(rPair.first); + return aInterfaceTypes; + } + + inline bool hasContainedTypes() const + { + ::osl::MutexGuard aGuard(rMutex); + for (const auto& rPair : m_aMap) + // are interfaces added to this container? + if (rPair.second->getLength()) + return true; + return false; + } + + /** + Return the container created under this key. + The InterfaceContainerHelper exists until the whole MultiTypeContainer is destroyed. + @return the container created under this key. If the container + was not created, null was returned. + */ + inline OInterfaceContainerHelper3* getContainer(const key& rKey) const + { + ::osl::MutexGuard aGuard(rMutex); + + auto iter = find(rKey); + if (iter != m_aMap.end()) + return (*iter).second.get(); + return nullptr; + } + + /** Inserts an element into the container with the specified key. + The position is not specified, thus it is not specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rKey + the id of the container + @param r + interface to be added; it is allowed, to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + inline sal_Int32 addInterface(const key& rKey, const css::uno::Reference& rListener) + { + ::osl::MutexGuard aGuard(rMutex); + auto iter = find(rKey); + if (iter == m_aMap.end()) + { + auto pLC = new OInterfaceContainerHelper3(rMutex); + m_aMap.emplace_back(rKey, pLC); + return pLC->addInterface(rListener); + } + else + return (*iter).second->addInterface(rListener); + } + + /** Removes an element from the container with the specified key. + It uses interface equality to remove the interface. + + @param rKey + the id of the container + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + inline sal_Int32 removeInterface(const key& rKey, + const css::uno::Reference& rListener) + { + ::osl::MutexGuard aGuard(rMutex); + + // search container with id nUik + auto iter = find(rKey); + // container found? + if (iter != m_aMap.end()) + return (*iter).second->removeInterface(rListener); + + // no container with this id. Always return 0 + return 0; + } + + /** + Call disposing on all references in the container, that + support XEventListener. Then clears the container. + @param rEvt the event object which is passed during disposing() call + */ + inline void disposeAndClear(const css::lang::EventObject& rEvt) + { + // create a copy, because do not fire event in a guarded section + InterfaceMap tempMap; + { + ::osl::MutexGuard aGuard(rMutex); + tempMap = std::move(m_aMap); + } + + for (auto& rPair : tempMap) + rPair.second->disposeAndClear(rEvt); + } + + /** + Remove all elements of all containers. Does not delete the container. + */ + inline void clear() + { + ::osl::MutexGuard aGuard(rMutex); + + for (const auto& rPair : m_aMap) + rPair.second->clear(); + } + + typedef key keyType; + +private: + typedef ::std::vector>>> + InterfaceMap; + InterfaceMap m_aMap; + ::osl::Mutex& rMutex; + + typename InterfaceMap::const_iterator find(const key& rKey) const + { + auto iter = m_aMap.begin(); + auto end = m_aMap.end(); + + while (iter != end) + { + equalImpl equal; + if (equal(iter->first, rKey)) + break; + ++iter; + } + return iter; + } + + OMultiTypeInterfaceContainerHelperVar3(const OMultiTypeInterfaceContainerHelperVar3&) = delete; + OMultiTypeInterfaceContainerHelperVar3& operator=(const OMultiTypeInterfaceContainerHelperVar3&) + = delete; +}; + +} // namespace comphelper + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/multiinterfacecontainer4.hxx b/include/comphelper/multiinterfacecontainer4.hxx new file mode 100644 index 000000000..eeccd2092 --- /dev/null +++ b/include/comphelper/multiinterfacecontainer4.hxx @@ -0,0 +1,190 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once +#include +#include +#include +#include +#include +#include +/** */ //for docpp +namespace comphelper +{ +/** + A helper class to store interface references of different types. + This is a copy of the code at include/comphelper/multiinterfacecontainer3.hxx, + except that it (a) uses std::mutex instead of osl::Mutex and (b) does not + store a reference to the mutex, but relies on the calling class to take + a lock around using it. + @see OInterfaceIteratorHelper3 + @see OInterfaceContainerHelper3 + */ +template > +class OMultiTypeInterfaceContainerHelperVar4 +{ +public: + OMultiTypeInterfaceContainerHelperVar4() {} + /** + Return all id's under which at least one interface is added. + */ + inline std::vector getContainedTypes(std::unique_lock& rGuard) const + { + std::vector aInterfaceTypes; + aInterfaceTypes.reserve(m_aMap.size()); + for (const auto& rPair : m_aMap) + // are interfaces added to this container? + if (rPair.second->getLength(rGuard)) + // yes, put the type in the array + aInterfaceTypes.push_back(rPair.first); + return aInterfaceTypes; + } + inline bool hasContainedTypes() const + { + for (const auto& rPair : m_aMap) + // are interfaces added to this container? + if (rPair.second->getLength()) + return true; + return false; + } + /** + Return the container created under this key. + The InterfaceContainerHelper exists until the whole MultiTypeContainer is destroyed. + @return the container created under this key. If the container + was not created, null was returned. + */ + inline OInterfaceContainerHelper4* getContainer(const key& rKey) const + { + auto iter = find(rKey); + if (iter != m_aMap.end()) + return (*iter).second.get(); + return nullptr; + } + /** Inserts an element into the container with the specified key. + The position is not specified, thus it is not specified in which order events are fired. + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + @param rKey + the id of the container + @param r + interface to be added; it is allowed, to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + inline sal_Int32 addInterface(::std::unique_lock<::std::mutex>& rGuard, const key& rKey, + const css::uno::Reference& rListener) + { + auto iter = find(rKey); + if (iter == m_aMap.end()) + { + auto pLC = new OInterfaceContainerHelper4(); + m_aMap.emplace_back(rKey, pLC); + return pLC->addInterface(rGuard, rListener); + } + else + return (*iter).second->addInterface(rGuard, rListener); + } + /** Removes an element from the container with the specified key. + It uses interface equality to remove the interface. + @param rKey + the id of the container + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + inline sal_Int32 removeInterface(::std::unique_lock<::std::mutex>& rGuard, const key& rKey, + const css::uno::Reference& rListener) + { + // search container with id nUik + auto iter = find(rKey); + // container found? + if (iter != m_aMap.end()) + return (*iter).second->removeInterface(rGuard, rListener); + // no container with this id. Always return 0 + return 0; + } + /** + Call disposing on all references in the container, that + support XEventListener. Then clears the container. + @param rEvt the event object which is passed during disposing() call + */ + inline void disposeAndClear(std::unique_lock& rGuard, + const css::lang::EventObject& rEvt) + { + // create a copy, because do not fire event in a guarded section + InterfaceMap tempMap; + { + tempMap = std::move(m_aMap); + } + rGuard.unlock(); + for (auto& rPair : tempMap) + { + OInterfaceIteratorHelper4 aIt(rGuard, *rPair.second); + while (aIt.hasMoreElements()) + { + try + { + aIt.next()->disposing(rEvt); + } + catch (css::uno::RuntimeException&) + { + // be robust, if e.g. a remote bridge has disposed already. + // there is no way to delegate the error to the caller :o(. + } + } + } + } + /** + Remove all elements of all containers. Does not delete the container. + */ + inline void clear() + { + for (const auto& rPair : m_aMap) + rPair.second->clear(); + } + typedef key keyType; + +private: + typedef ::std::vector>>> + InterfaceMap; + InterfaceMap m_aMap; + typename InterfaceMap::const_iterator find(const key& rKey) const + { + auto iter = m_aMap.begin(); + auto end = m_aMap.end(); + while (iter != end) + { + equalImpl equal; + if (equal(iter->first, rKey)) + break; + ++iter; + } + return iter; + } + OMultiTypeInterfaceContainerHelperVar4(const OMultiTypeInterfaceContainerHelperVar4&) = delete; + OMultiTypeInterfaceContainerHelperVar4& operator=(const OMultiTypeInterfaceContainerHelperVar4&) + = delete; +}; +} // namespace comphelper +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/namecontainer.hxx b/include/comphelper/namecontainer.hxx new file mode 100644 index 000000000..616b07f1a --- /dev/null +++ b/include/comphelper/namecontainer.hxx @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_NAMECONTAINER_HXX +#define INCLUDED_COMPHELPER_NAMECONTAINER_HXX + +#include +#include +#include + +namespace com::sun::star::container +{ +class XNameContainer; +} + +namespace comphelper +{ +COMPHELPER_DLLPUBLIC css::uno::Reference +NameContainer_createInstance(const css::uno::Type& aType); +} + +#endif // INCLUDED_COMPHELPER_NAMECONTAINER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/namedvaluecollection.hxx b/include/comphelper/namedvaluecollection.hxx new file mode 100644 index 000000000..b92646e40 --- /dev/null +++ b/include/comphelper/namedvaluecollection.hxx @@ -0,0 +1,322 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_NAMEDVALUECOLLECTION_HXX +#define INCLUDED_COMPHELPER_NAMEDVALUECOLLECTION_HXX + +#include + +#include +#include +#include +#include + +#include +#include + +namespace comphelper +{ + + + // = NamedValueCollection + + /** a collection of named values, packed in various formats. + */ + class COMPHELPER_DLLPUBLIC NamedValueCollection + { + std::unordered_map< OUString, css::uno::Any > maValues; + public: + NamedValueCollection() = default; + + NamedValueCollection( const NamedValueCollection& _rCopySource ) = default; + NamedValueCollection(NamedValueCollection&& _rCopySource) noexcept = default; + + NamedValueCollection& operator=( const NamedValueCollection& i_rCopySource ) = default; + NamedValueCollection& operator=(NamedValueCollection&& i_rCopySource) noexcept = default; + + /** constructs a collection + @param _rElements + the wrapped elements of the collection. The @c Any might contain a sequence of + property values, a sequence of named values, or directly a property value or named value. + All other cases are worth an assertion in non-product builds. + */ + NamedValueCollection( const css::uno::Any& _rElements ); + + /** constructs a collection + @param _rArguments + a sequence of Any's containing either PropertyValue's or NamedValue's. + */ + NamedValueCollection( const css::uno::Sequence< css::uno::Any >& _rArguments ); + + /** constructs a collection + @param _rArguments + a sequence of PropertyValues's + */ + NamedValueCollection( const css::uno::Sequence< css::beans::PropertyValue >& _rArguments ); + + /** constructs a collection + @param _rArguments + a sequence of NamedValue's + */ + NamedValueCollection( const css::uno::Sequence< css::beans::NamedValue >& _rArguments ); + + void assign( const css::uno::Sequence< css::uno::Any >& _rArguments ) + { + impl_assign( _rArguments ); + } + + void clear() + { + impl_assign( css::uno::Sequence< css::beans::NamedValue >() ); + } + + /** determines whether or not named values can be extracted from the given value + + @return + true if and only if the given @c Any contains a @c NamedValue, a + @c PropertyValue, or a sequence thereof. + */ + static bool canExtractFrom( css::uno::Any const & i_value ); + + /// returns the number of elements in the collection + size_t size() const; + + /// determines whether the collection is empty + bool empty() const; + + /** returns the names of all elements in the collection + */ + ::std::vector< OUString > + getNames() const; + + /** merges the content of another collection into @c this + @param _rAdditionalValues + the collection whose values are to be merged + @param _bOverwriteExisting + defines whether or not elements which are already present in @c this + should be overwritten (true) or preserved (false). + @return @c *this + */ + NamedValueCollection& + merge( + const NamedValueCollection& _rAdditionalValues, + bool _bOverwriteExisting + ); + + /** retrieves a value with a given name from the collection, if it is present + + @param _pAsciiValueName + the ASCII name of the value to retrieve + + @param _out_rValue + is the output parameter taking the desired value upon successful return. If + a value with the given name is not present in the collection, or if a wrong-typed + value is present, then this parameter will not be touched. + + @retval + true if there is a value with the given name, which could successfully + be extracted. In this case, @c _out_rValue will contain the requested + value. + @retval + false, if there is no value with the given name. + + @throws IllegalArgumentException + in case there is a value with the given name, but it cannot legally assigned to + _out_rValue. + */ + template < typename VALUE_TYPE > + bool get_ensureType( const OUString& _rValueName, VALUE_TYPE& _out_rValue ) const + { + return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() ); + } + + /** retrieves a value with a given name, or defaults it to a given value, if it's not present + in the collection + */ + template < typename VALUE_TYPE > + VALUE_TYPE getOrDefault( const OUString& _rValueName, const VALUE_TYPE& _rDefault ) const + { + VALUE_TYPE retVal( _rDefault ); + get_ensureType( _rValueName, retVal ); + return retVal; + } + + /** Retrieves a value with a given name, or defaults it to a given value, if it's not present + in the collection. + For when you only need a single value from a Sequence. + */ + template < typename VALUE_TYPE > + static VALUE_TYPE getOrDefault( const css::uno::Sequence & rPropSeq, + std::u16string_view _rValueName, const VALUE_TYPE& _rDefault ) + { + VALUE_TYPE retVal( _rDefault ); + get_ensureType( rPropSeq, _rValueName, &retVal, ::cppu::UnoType< VALUE_TYPE >::get() ); + return retVal; + } + + /** retrieves a (untyped) value with a given name + + If the collection does not contain a value with the given name, an empty + Any is returned. + */ + const css::uno::Any& get( const OUString& _rValueName ) const + { + return impl_get( _rValueName ); + } + + /** retrieves a (untyped) value with a given name. For when you only need a single value from a Sequence. + + If the collection does not contain a value with the given name, an empty + Any is returned. + */ + static const css::uno::Any& get( const css::uno::Sequence& rPropSeq, std::u16string_view _rValueName ); + + /// determines whether a value with a given name is present in the collection + bool has( const OUString& _rValueName ) const + { + return impl_has( _rValueName ); + } + + /** puts a value into the collection + + @return true if and only if a value was already present previously, in + which case it has been overwritten. + */ + template < typename VALUE_TYPE > + bool put( const OUString& _rValueName, const VALUE_TYPE& _rValue ) + { + return impl_put( _rValueName, css::uno::Any( _rValue ) ); + } + + bool put( const OUString& _rValueName, const css::uno::Any& _rValue ) + { + return impl_put( _rValueName, _rValue ); + } + + /** removes the value with the given name from the collection + + @return true if and only if a value with the given name existed in the collection. + */ + bool remove( const OUString& _rValueName ) + { + return impl_remove( _rValueName ); + } + + /** transforms the collection to a sequence of PropertyValues + + @return + the number of elements in the sequence + */ + sal_Int32 operator >>= ( css::uno::Sequence< css::beans::PropertyValue >& _out_rValues ) const; + + /** transforms the collection to a sequence of NamedValues + + @return + the number of elements in the sequence + */ + sal_Int32 operator >>= ( css::uno::Sequence< css::beans::NamedValue >& _out_rValues ) const; + + /** transforms the collection into a sequence of PropertyValues + */ + css::uno::Sequence< css::beans::PropertyValue > + getPropertyValues() const + { + css::uno::Sequence< css::beans::PropertyValue > aValues; + *this >>= aValues; + return aValues; + } + + /** returns a Sequence< Any >, containing PropertyValues + */ + css::uno::Sequence< css::uno::Any > + getWrappedPropertyValues() const + { + return impl_wrap< css::beans::PropertyValue >(); + } + + /** returns a Sequence< Any >, containing NamedValues + */ + css::uno::Sequence< css::uno::Any > + getWrappedNamedValues() const + { + return impl_wrap< css::beans::NamedValue >(); + } + + /** transforms the collection into a sequence of NamedValues + */ + css::uno::Sequence< css::beans::NamedValue > + getNamedValues() const + { + css::uno::Sequence< css::beans::NamedValue > aValues; + *this >>= aValues; + return aValues; + } + + private: + void impl_assign( const css::uno::Any& i_rWrappedElements ); + void impl_assign( const css::uno::Sequence< css::uno::Any >& _rArguments ); + void impl_assign( const css::uno::Sequence< css::beans::PropertyValue >& _rArguments ); + void impl_assign( const css::uno::Sequence< css::beans::NamedValue >& _rArguments ); + + bool get_ensureType( + const OUString& _rValueName, + void* _pValueLocation, + const css::uno::Type& _rExpectedValueType + ) const; + + static bool get_ensureType( + const css::uno::Sequence & rPropSeq, + std::u16string_view _rValueName, + void* _pValueLocation, + const css::uno::Type& _rExpectedValueType + ); + + const css::uno::Any& + impl_get( const OUString& _rValueName ) const; + + bool impl_has( const OUString& _rValueName ) const; + + bool impl_put( const OUString& _rValueName, const css::uno::Any& _rValue ); + + bool impl_remove( const OUString& _rValueName ); + + template< class VALUE_TYPE > + css::uno::Sequence< css::uno::Any > impl_wrap() const + { + css::uno::Sequence< VALUE_TYPE > aValues; + *this >>= aValues; + css::uno::Sequence< css::uno::Any > aWrappedValues( aValues.getLength() ); + + css::uno::Any* pO = aWrappedValues.getArray(); + const VALUE_TYPE* pV = aValues.getConstArray(); + const sal_Int32 nLen = aValues.getLength(); + for( sal_Int32 i = 0; i < nLen; ++i ) + *(pO++) = css::uno::Any( *(pV++) ); + + return aWrappedValues; + } + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_NAMEDVALUECOLLECTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/newarray.hxx b/include/comphelper/newarray.hxx new file mode 100644 index 000000000..d3eaccd77 --- /dev/null +++ b/include/comphelper/newarray.hxx @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_NEWARRAY_HXX +#define INCLUDED_COMPHELPER_NEWARRAY_HXX + +#include +#include +#include + +namespace comphelper { + +template T * +newArray_null(size_t const n) noexcept +{ + if ((::std::numeric_limits::max() / sizeof(T)) <= n) { + return nullptr; + } + return new (::std::nothrow) T[n]; +} + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_NEWARRAY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/numberedcollection.hxx b/include/comphelper/numberedcollection.hxx new file mode 100644 index 000000000..3dbb1f534 --- /dev/null +++ b/include/comphelper/numberedcollection.hxx @@ -0,0 +1,168 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_NUMBEREDCOLLECTION_HXX +#define INCLUDED_COMPHELPER_NUMBEREDCOLLECTION_HXX + +#include + +#include +#include + +#include +#include + +#include +#include +#include + +namespace com::sun::star::uno { class XInterface; } + +namespace comphelper{ + +/** @short defines a collection of UNO components, where every component will get its own unique number. + + @descr Such number will be unique at runtime only... but it supports fragmentation. + Note: This collection uses weak references only to know her components. + So lifetime of these components must be controlled outside. + + @threadsafe + */ +class COMPHELPER_DLLPUBLIC NumberedCollection final : + public ::cppu::WeakImplHelper< css::frame::XUntitledNumbers > +{ + + // types, const + private: + + struct TNumberedItem + { + css::uno::WeakReference< css::uno::XInterface > xItem; + ::sal_Int32 nNumber; + }; + + typedef std::unordered_map< + sal_IntPtr, + TNumberedItem > TNumberedItemHash; + + typedef ::std::vector< sal_IntPtr > TDeadItemList; + + + // interface + public: + + + /** @short lightweight constructor. + */ + NumberedCollection(); + + + /** @short free all internally used resources. + */ + virtual ~NumberedCollection() override; + + + /** set an outside component which uses this container and must be set + as source of all broadcasted messages, exceptions. + + It's holded weak only so we do not need any complex dispose sessions. + + Note: Passing NULL as parameter will be allowed. It will reset the internal + member reference only. + + @param xOwner + the new owner of this collection. + */ + void setOwner (const css::uno::Reference< css::uno::XInterface >& xOwner); + + + /** set the localized prefix to be used for untitled components. + + Localization has to be done outside. This container will return + those value then. There are no further checks. Its up to you to define + a suitable string here :-) + + @param sPrefix + the new prefix for untitled components. + */ + void setUntitledPrefix(const OUString& sPrefix); + + + /** @see css.frame.XUntitledNumbers */ + virtual ::sal_Int32 SAL_CALL leaseNumber(const css::uno::Reference< css::uno::XInterface >& xComponent) override; + + + /** @see css.frame.XUntitledNumbers */ + virtual void SAL_CALL releaseNumber(::sal_Int32 nNumber) override; + + + /** @see css.frame.XUntitledNumbers */ + virtual void SAL_CALL releaseNumberForComponent(const css::uno::Reference< css::uno::XInterface >& xComponent) override; + + + /** @see css.frame.XUntitledNumbers */ + virtual OUString SAL_CALL getUntitledPrefix() override; + + + // internal + private: + + + /** @short tries to find a unique number not already used within this collection. + + @descr It reuses the smallest number which isn't used by any component + of this collection. (fragmentation!) If collection is full (means there + is no free number) the special value INVALID_NUMBER will be returned. + + @note Those method can't be called within a multithreaded environment. + Because such number won't be "reserved" for the call of these method + it can happen that two calls returns the same number (reasoned by the fact that first call + doesn't used the returned number already. + + So the outside code has to make sure that retrieving and using of those numbers + will be an atomic operation. + + @return a unique number or special value INVALID_NUMBER if collection is full. + */ + ::sal_Int32 impl_searchFreeNumber (); + + static void impl_cleanUpDeadItems ( TNumberedItemHash& lItems , + const TDeadItemList& lDeadItems); + + + // member + private: + + /// localized string to be used for untitled components + OUString m_sUntitledPrefix; + + /// cache of all "leased numbers" and its bound components + TNumberedItemHash m_lComponents; + + /// used as source of broadcasted messages or exceptions (can be null !) + css::uno::WeakReference< css::uno::XInterface > m_xOwner; + + std::mutex m_aMutex; +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_NUMBEREDCOLLECTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/numbers.hxx b/include/comphelper/numbers.hxx new file mode 100644 index 000000000..e486bac0b --- /dev/null +++ b/include/comphelper/numbers.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_NUMBERS_HXX +#define INCLUDED_COMPHELPER_NUMBERS_HXX + +#include +#include +#include + +namespace com::sun::star::util { class XNumberFormats; } +namespace com::sun::star::util { class XNumberFormatter; } + +namespace comphelper +{ + + /// returns the css::util::NumberFormat of the given key under the given formats + COMPHELPER_DLLPUBLIC sal_Int16 getNumberFormatType(const css::uno::Reference& xFormats, sal_Int32 nKey); + + /// returns the css::util::NumberFormat of the given key under the given formatter + COMPHELPER_DLLPUBLIC sal_Int16 getNumberFormatType(const css::uno::Reference& xFormatter, sal_Int32 nKey); + + /// returns the decimals of the given numeric number formatunder the given formats + COMPHELPER_DLLPUBLIC css::uno::Any getNumberFormatDecimals(const css::uno::Reference& xFormats, sal_Int32 nKey); + + /** retrieves the value of a given property for a given format key, relating to a given formatter + */ + COMPHELPER_DLLPUBLIC css::uno::Any getNumberFormatProperty( + const css::uno::Reference< css::util::XNumberFormatter >& _rxFormatter, + sal_Int32 _nKey, + const OUString& _rPropertyName + ); + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_NUMBERS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/ofopxmlhelper.hxx b/include/comphelper/ofopxmlhelper.hxx new file mode 100644 index 000000000..fe778bf1e --- /dev/null +++ b/include/comphelper/ofopxmlhelper.hxx @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_OFOPXMLHELPER_HXX +#define INCLUDED_COMPHELPER_OFOPXMLHELPER_HXX + +#include + +#include + +#include + +#include + +namespace com::sun::star::beans { struct StringPair; } +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::io { class XOutputStream; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { template class Reference; } + +namespace comphelper::OFOPXMLHelper { + + // returns sequence of elements, where each element is described by sequence of tags, + // where each tag is described by StringPair ( First - name, Second - value ) + // the first tag of each element sequence must be "Id" + /// @throws css::uno::Exception + COMPHELPER_DLLPUBLIC + css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > + ReadRelationsInfoSequence( + const css::uno::Reference< css::io::XInputStream >& xInStream, + std::u16string_view aStreamName, + const css::uno::Reference< css::uno::XComponentContext >& rContext ); + + // returns sequence containing two entries of type sequence + // the first sequence describes "Default" elements, where each element is described + // by StringPair object ( First - Extension, Second - ContentType ) + // the second sequence describes "Override" elements, where each element is described + // by StringPair object ( First - PartName, Second - ContentType ) + /// @throws css::uno::Exception + COMPHELPER_DLLPUBLIC + css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > + ReadContentTypeSequence( + const css::uno::Reference< css::io::XInputStream >& xInStream, + const css::uno::Reference< css::uno::XComponentContext >& rContext ); + + // returns the ContentType for the given name, or empty when not found. + // rContentTypes is a sequence containing two entries of type sequence + // the first sequence describes "Default" elements, where each element is described + // by StringPair object ( First - Extension, Second - ContentType ) + // the second sequence describes "Override" elements, where each element is described + // by StringPair object ( First - PartName, Second - ContentType ) + // The "Override" sequence is searched first before falling back on "Default". + COMPHELPER_DLLPUBLIC + OUString + GetContentTypeByName(const css::uno::Sequence>& rContentTypes, + const OUString& rFilename); + + // writes sequence of elements, where each element is described by sequence of tags, + // where each tag is described by StringPair ( First - name, Second - value ) + // the first tag of each element sequence must be "Id" + /// @throws css::uno::Exception + COMPHELPER_DLLPUBLIC + void WriteRelationsInfoSequence( + const css::uno::Reference< css::io::XOutputStream >& xOutStream, + const css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > >& aSequence, + const css::uno::Reference< css::uno::XComponentContext >& rContext ); + + // writes two entries of type sequence + // the first sequence describes "Default" elements, where each element is described + // by StringPair object ( First - Extension, Second - ContentType ) + // the second sequence describes "Override" elements, where each element is described + // by StringPair object ( First - PartName, Second - ContentType ) + /// @throws css::uno::Exception + COMPHELPER_DLLPUBLIC + void WriteContentSequence( + const css::uno::Reference< css::io::XOutputStream >& xOutStream, + const css::uno::Sequence< css::beans::StringPair >& aDefaultsSequence, + const css::uno::Sequence< css::beans::StringPair >& aOverridesSequence, + const css::uno::Reference< css::uno::XComponentContext >& rContext ); + +} // namespace comphelper::OFOPXMLHelper + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/oslfile2streamwrap.hxx b/include/comphelper/oslfile2streamwrap.hxx new file mode 100644 index 000000000..c80c7b344 --- /dev/null +++ b/include/comphelper/oslfile2streamwrap.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_OSLFILE2STREAMWRAP_HXX +#define INCLUDED_COMPHELPER_OSLFILE2STREAMWRAP_HXX + +#include +#include +#include +#include +#include + +namespace osl { class File; } + +namespace comphelper +{ + +// Stream to read and write data, based on File + +class OSLInputStreamWrapper final : public ::cppu::WeakImplHelper +{ +public: + COMPHELPER_DLLPUBLIC OSLInputStreamWrapper(::osl::File& _rStream); + +private: + virtual ~OSLInputStreamWrapper() override; + +// css::io::XInputStream + virtual sal_Int32 SAL_CALL readBytes(css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead) override; + virtual sal_Int32 SAL_CALL readSomeBytes(css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) override; + virtual void SAL_CALL skipBytes(sal_Int32 nBytesToSkip) override; + virtual sal_Int32 SAL_CALL available() override; + virtual void SAL_CALL closeInput() override; + + std::mutex m_aMutex; + ::osl::File* m_pFile; +}; + + +// data sink for the files + +class OSLOutputStreamWrapper final : public ::cppu::WeakImplHelper +{ +public: + COMPHELPER_DLLPUBLIC OSLOutputStreamWrapper(::osl::File& _rFile); + +private: + virtual ~OSLOutputStreamWrapper() override; + +// css::io::XOutputStream + virtual void SAL_CALL writeBytes(const css::uno::Sequence< sal_Int8 >& aData) override; + virtual void SAL_CALL flush() override; + virtual void SAL_CALL closeOutput() override; + + ::osl::File& rFile; +}; + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_OSLFILE2STREAMWRAP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/parallelsort.hxx b/include/comphelper/parallelsort.hxx new file mode 100644 index 000000000..94d86e0d1 --- /dev/null +++ b/include/comphelper/parallelsort.hxx @@ -0,0 +1,373 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_PARALLELSORT_HXX +#define INCLUDED_COMPHELPER_PARALLELSORT_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper +{ +const size_t nThreadCountGlobal = std::thread::hardware_concurrency(); +const bool bHyperThreadingActive = cpuid::hasHyperThreading(); +static comphelper::ThreadPool& rTPool(comphelper::ThreadPool::getSharedOptimalPool()); + +static thread_local std::mt19937 aGenerator{ std::random_device{}() }; + +#define PARALLELSORT_ENABLEPZ 0 + +namespace +{ +class ProfileZone +{ +public: +#if PARALLELSORT_ENABLEPZ + ProfileZone(const char* pTag) + : maTag(pTag) + , maStart(std::chrono::steady_clock::now()) + , mbFinished(false) + { + } + + ~ProfileZone() + { + if (!mbFinished) + showTimeElapsed(); + } + + void stop() + { + showTimeElapsed(); + mbFinished = true; + } +#else + ProfileZone(const char* /*pTag*/) + : mbDummy(true) + { + } + + void stop() + { + // Avoid loplugin:staticmethods, loplugin:staticaccess errors + (void)mbDummy; + } +#endif + +private: +#if PARALLELSORT_ENABLEPZ + + void showTimeElapsed() + { + auto end = std::chrono::steady_clock::now(); + size_t elapsed + = std::chrono::duration_cast(end - maStart).count(); + std::cout << maTag << " : " << elapsed << " ms" << std::endl << std::flush; + } + + std::string maTag; + std::chrono::steady_clock::time_point maStart; + bool mbFinished; +#else + bool mbDummy; + +#endif +}; + +class ParallelRunner +{ + class Executor final : public comphelper::ThreadTask + { + public: + Executor(const std::shared_ptr& rTag, + std::function aFunc) + : comphelper::ThreadTask(rTag) + , maFunc(std::move(aFunc)) + { + } + + virtual void doWork() override { maFunc(); } + + private: + const std::function maFunc; + }; + +public: + ParallelRunner() { maTag = comphelper::ThreadPool::createThreadTaskTag(); } + + void enqueue(std::function aFunc) + { + rTPool.pushTask(std::make_unique(maTag, aFunc)); + } + + void wait() { rTPool.waitUntilDone(maTag, false); } + +private: + std::shared_ptr maTag; +}; + +constexpr size_t nMaxTreeArraySize = 64; + +size_t lcl_round_down_pow2(size_t nNum) +{ + size_t nPow2; + for (nPow2 = 1; nPow2 <= nNum; nPow2 <<= 1) + ; + return std::min((nPow2 >> 1), nMaxTreeArraySize); +} + +template struct Sampler +{ + using ValueType = typename std::iterator_traits::value_type; + + static void sample(RandItr aBegin, RandItr aEnd, ValueType* pSamples, size_t nSamples, + size_t /*nParallelism*/) + { + ProfileZone aZone("\tsample()"); + assert(aBegin <= aEnd); + size_t nLen = static_cast(aEnd - aBegin); + assert(std::mt19937::max() >= nLen); + + for (size_t nIdx = 0; nIdx < nSamples; ++nIdx) + { + size_t nSel = aGenerator() % nLen--; + using namespace std; + swap(*(aBegin + nSel), *(aBegin + nLen)); + pSamples[nIdx] = *(aBegin + nLen); + } + } +}; + +template class Binner +{ + using ValueType = typename std::iterator_traits::value_type; + + const size_t mnTreeArraySize; + const size_t mnDividers; + constexpr static size_t mnMaxStaticSize = 1024 * 50; + uint8_t maLabels[mnMaxStaticSize]; + ValueType maDividers[nMaxTreeArraySize]; + std::unique_ptr pLabels; + size_t maSepBinEnds[nMaxTreeArraySize * nMaxTreeArraySize]; + bool mbThreaded; + +public: + size_t maBinEnds[nMaxTreeArraySize]; + + Binner(const ValueType* pSamples, size_t nSamples, size_t nBins, bool bThreaded) + : mnTreeArraySize(lcl_round_down_pow2(nBins)) + , mnDividers(mnTreeArraySize - 1) + , mbThreaded(bThreaded) + { + assert((nSamples % mnTreeArraySize) == 0); + assert(mnTreeArraySize <= nMaxTreeArraySize); + std::fill(maBinEnds, maBinEnds + mnTreeArraySize, 0); + std::fill(maSepBinEnds, maSepBinEnds + mnTreeArraySize * mnTreeArraySize, 0); + fillTreeArray(1, pSamples, pSamples + nSamples); + } + + void fillTreeArray(size_t nPos, const ValueType* pLow, const ValueType* pHigh) + { + assert(pLow <= pHigh); + const ValueType* pMid = pLow + (pHigh - pLow) / 2; + maDividers[nPos] = *pMid; + + if (2 * nPos < mnDividers) // So that 2*nPos < mnTreeArraySize + { + fillTreeArray(2 * nPos, pLow, pMid); + fillTreeArray(2 * nPos + 1, pMid + 1, pHigh); + } + } + + constexpr inline size_t findBin(const ValueType& rVal, Compare& aComp) + { + size_t nIdx = 1; + while (nIdx <= mnDividers) + nIdx = ((nIdx << 1) + aComp(maDividers[nIdx], rVal)); + return (nIdx - mnTreeArraySize); + } + + void label(const RandItr aBegin, const RandItr aEnd, Compare& aComp) + { + ProfileZone aZoneSetup("\tlabel():setup"); + size_t nLen = static_cast(aEnd - aBegin); + if (nLen > mnMaxStaticSize) + pLabels = std::make_unique(nLen); + uint8_t* pLabelsRaw = (nLen > mnMaxStaticSize) ? pLabels.get() : maLabels; + aZoneSetup.stop(); + ProfileZone aZoneFindBins("\tFindBins()"); + if (mbThreaded) + { + ParallelRunner aPRunner; + const size_t nBins = mnTreeArraySize; + for (size_t nTIdx = 0; nTIdx < nBins; ++nTIdx) + { + aPRunner.enqueue([this, nTIdx, nBins, nLen, aBegin, pLabelsRaw, &aComp] { + ProfileZone aZoneIn("\t\tFindBinsThreaded()"); + size_t nBinEndsStartIdx = nTIdx * mnTreeArraySize; + size_t* pBinEnds = maSepBinEnds + nBinEndsStartIdx; + size_t aBinEndsF[nMaxTreeArraySize] = { 0 }; + for (size_t nIdx = nTIdx; nIdx < nLen; nIdx += nBins) + { + size_t nBinIdx = findBin(*(aBegin + nIdx), aComp); + pLabelsRaw[nIdx] = static_cast(nBinIdx); + ++aBinEndsF[nBinIdx]; + } + + for (size_t nIdx = 0; nIdx < mnTreeArraySize; ++nIdx) + pBinEnds[nIdx] = aBinEndsF[nIdx]; + }); + } + + aPRunner.wait(); + + // Populate maBinEnds from maSepBinEnds + for (size_t nTIdx = 0; nTIdx < mnTreeArraySize; ++nTIdx) + { + for (size_t nSepIdx = 0; nSepIdx < mnTreeArraySize; ++nSepIdx) + maBinEnds[nTIdx] += maSepBinEnds[nSepIdx * mnTreeArraySize + nTIdx]; + } + } + else + { + uint8_t* pLabel = pLabelsRaw; + for (RandItr aItr = aBegin; aItr != aEnd; ++aItr) + { + size_t nBinIdx = findBin(*aItr, aComp); + *pLabel++ = nBinIdx; + ++maBinEnds[nBinIdx]; + } + } + + aZoneFindBins.stop(); + + size_t nSum = 0; + // Store each bin's starting position in maBinEnds array for now. + for (size_t nIdx = 0; nIdx < mnTreeArraySize; ++nIdx) + { + size_t nSize = maBinEnds[nIdx]; + maBinEnds[nIdx] = nSum; + nSum += nSize; + } + + // Now maBinEnds has end positions of each bin. + } + + void bin(const RandItr aBegin, const RandItr aEnd, ValueType* pOut) + { + ProfileZone aZone("\tbin()"); + const size_t nLen = static_cast(aEnd - aBegin); + uint8_t* pLabelsRaw = (nLen > mnMaxStaticSize) ? pLabels.get() : maLabels; + size_t nIdx; + for (nIdx = 0; nIdx < nLen; ++nIdx) + { + pOut[maBinEnds[pLabelsRaw[nIdx]]++] = *(aBegin + nIdx); + } + } +}; + +template > +void s3sort(const RandItr aBegin, const RandItr aEnd, Compare aComp = Compare(), + bool bThreaded = true) +{ + static size_t nThreadCount = nThreadCountGlobal; + + constexpr size_t nBaseCaseSize = 1024; + const std::size_t nLen = static_cast(aEnd - aBegin); + if (nLen < nBaseCaseSize) + { + std::sort(aBegin, aEnd, aComp); + return; + } + + using ValueType = typename std::iterator_traits::value_type; + auto pOut = std::make_unique(nLen); + + const size_t nBins = lcl_round_down_pow2(nThreadCount); + const size_t nOverSamplingFactor = std::max(1.0, std::sqrt(static_cast(nLen) / 64)); + const size_t nSamples = nOverSamplingFactor * nBins; + auto aSamples = std::make_unique(nSamples); + ProfileZone aZoneSampleAnsSort("SampleAndSort"); + // Select samples and sort them + Sampler::sample(aBegin, aEnd, aSamples.get(), nSamples, nBins); + std::sort(aSamples.get(), aSamples.get() + nSamples, aComp); + aZoneSampleAnsSort.stop(); + + if (!aComp(aSamples[0], aSamples[nSamples - 1])) + { + // All samples are equal, fallback to standard sort. + std::sort(aBegin, aEnd, aComp); + return; + } + + ProfileZone aZoneBinner("Binner"); + // Create and populate bins using pOut from input iterators. + Binner aBinner(aSamples.get(), nSamples, nBins, bThreaded); + aBinner.label(aBegin, aEnd, aComp); + aBinner.bin(aBegin, aEnd, pOut.get()); + aZoneBinner.stop(); + + ProfileZone aZoneSortBins("SortBins"); + ValueType* pOutRaw = pOut.get(); + if (bThreaded) + { + ParallelRunner aPRunner; + // Sort the bins separately. + for (size_t nBinIdx = 0, nBinStart = 0; nBinIdx < nBins; ++nBinIdx) + { + size_t nBinEnd = aBinner.maBinEnds[nBinIdx]; + aPRunner.enqueue([pOutRaw, nBinStart, nBinEnd, &aComp] { + std::sort(pOutRaw + nBinStart, pOutRaw + nBinEnd, aComp); + }); + + nBinStart = nBinEnd; + } + + aPRunner.wait(); + } + else + { + for (size_t nBinIdx = 0, nBinStart = 0; nBinIdx < nBins; ++nBinIdx) + { + auto nBinEnd = aBinner.maBinEnds[nBinIdx]; + std::sort(pOutRaw + nBinStart, pOutRaw + nBinEnd, aComp); + nBinStart = nBinEnd; + } + } + + aZoneSortBins.stop(); + + // Move the sorted array to the array specified by input iterators. + std::move(pOutRaw, pOutRaw + nLen, aBegin); +} + +} // anonymous namespace + +template > +void parallelSort(const RandItr aBegin, const RandItr aEnd, Compare aComp = Compare()) +{ + assert(aBegin <= aEnd); + s3sort(aBegin, aEnd, aComp); +} + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_PARALLELSORT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/processfactory.hxx b/include/comphelper/processfactory.hxx new file mode 100644 index 000000000..0f74e5b13 --- /dev/null +++ b/include/comphelper/processfactory.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROCESSFACTORY_HXX +#define INCLUDED_COMPHELPER_PROCESSFACTORY_HXX + +#include +#include + +namespace com::sun::star::lang { + class XMultiServiceFactory; +} +namespace com::sun::star::uno { class XComponentContext; } + +namespace comphelper +{ + +/** + * This function set the process service factory. + */ +COMPHELPER_DLLPUBLIC void setProcessServiceFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMgr); + +/** + * This function gets the process service factory. + * + * If no service factory is set the function throws a RuntimeException. + */ +COMPHELPER_DLLPUBLIC css::uno::Reference< css::lang::XMultiServiceFactory > getProcessServiceFactory(); + +/** Obtains a component context from a service factory. + + Throws a RuntimeException if no component context can be obtained. + + @param factory may be null + @return may be null + */ +COMPHELPER_DLLPUBLIC +css::uno::Reference< css::uno::XComponentContext > +getComponentContext( + css::uno::Reference< css::lang::XMultiServiceFactory > + const & factory); + +/** + * This function gets the process service factory's default component context. + * + * Throws a RuntimeException if no component context can be obtained. + */ +COMPHELPER_DLLPUBLIC +css::uno::Reference< css::uno::XComponentContext > +getProcessComponentContext(); + +} + +#endif // INCLUDED_COMPHELPER_PROCESSFACTORY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/profilezone.hxx b/include/comphelper/profilezone.hxx new file mode 100644 index 000000000..71f9fa30b --- /dev/null +++ b/include/comphelper/profilezone.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef INCLUDED_COMPHELPER_PROFILEZONE_HXX +#define INCLUDED_COMPHELPER_PROFILEZONE_HXX + +#include + +#include + +#include + +// implementation of XToolkitExperimental profiling API + +namespace comphelper +{ +class COMPHELPER_DLLPUBLIC ProfileZone : public NamedEvent +{ + long long m_nCreateTime; + int m_nNesting; + + void addRecording(); + + static void setNestingLevel(int nNestingLevel); + static int getNestingLevel(); + + ProfileZone(const char* sName, const OUString& sArgs) + : NamedEvent(sName, sArgs) + , m_nNesting(-1) + { + if (s_bRecording) + { + m_nCreateTime = getNow(); + + m_nNesting = getNestingLevel(); + setNestingLevel(getNestingLevel() + 1); + } + else + m_nCreateTime = 0; + } + +public: + /** + * Starts measuring the cost of a C++ scope. + * + * Note that the char pointer is stored as such in the ProfileZone object and used in the + * destructor, so be sure to pass a pointer that stays valid for the duration of the object's + * lifetime. + */ + ProfileZone(const char* sName, const std::map& aArgs) + : ProfileZone(sName, createArgsString(aArgs)) + { + } + + ProfileZone(const char* sName) + : ProfileZone(sName, OUString()) + { + } + + ~ProfileZone() + { + if (m_nCreateTime > 0) + { + setNestingLevel(getNestingLevel() - 1); + + if (m_nNesting != getNestingLevel()) + { + SAL_WARN("comphelper.traceevent", "Incorrect ProfileZone nesting for " << m_sName); + } + else + { + if (s_bRecording) + addRecording(); + } + } + } + + ProfileZone(const ProfileZone&) = delete; + void operator=(const ProfileZone&) = delete; +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_PROFILEZONE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propagg.hxx b/include/comphelper/propagg.hxx new file mode 100644 index 000000000..949251892 --- /dev/null +++ b/include/comphelper/propagg.hxx @@ -0,0 +1,325 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPAGG_HXX +#define INCLUDED_COMPHELPER_PROPAGG_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +//= property helper classes + + +namespace comphelper +{ + + +//= OPropertyAccessor +//= internal helper class for OPropertyArrayAggregationHelper + +namespace internal +{ + struct OPropertyAccessor + { + sal_Int32 nOriginalHandle; + std::size_t nPos; + bool bAggregate; + + OPropertyAccessor(sal_Int32 _nOriginalHandle, std::size_t _nPos, bool _bAggregate) + :nOriginalHandle(_nOriginalHandle) ,nPos(_nPos) ,bAggregate(_bAggregate) { } + + bool operator==(const OPropertyAccessor& rOb) const { return nPos == rOb.nPos; } + bool operator <(const OPropertyAccessor& rOb) const { return nPos < rOb.nPos; } + }; +} + + +/** + * used as callback for an OPropertyArrayAggregationHelper + */ +class IPropertyInfoService +{ +public: + /** get the preferred handle for the given property + @param _rName the property name + @return the handle the property should be referred by, or -1 if there are no + preferences for the given property + */ + virtual sal_Int32 getPreferredPropertyId(const OUString& _rName) = 0; + +protected: + ~IPropertyInfoService() {} +}; + +/** + * used for implementing a cppu::IPropertyArrayHelper for classes + * aggregating property sets + */ + +#define DEFAULT_AGGREGATE_PROPERTY_ID 10000 + +class COMPHELPER_DLLPUBLIC OPropertyArrayAggregationHelper final : public ::cppu::IPropertyArrayHelper +{ + friend class OPropertySetAggregationHelper; + + std::vector m_aProperties; + std::map< sal_Int32, internal::OPropertyAccessor > m_aPropertyAccessors; + +public: + /** construct the object. + @param _rProperties the properties of the object doing the aggregation. These properties + are used without any checks, so the caller has to ensure that the names and + handles are valid. + @param _rAggProperties the properties of the aggregate, usually got via a call to getProperties on the + XPropertySetInfo of the aggregate. + The names of the properties are used without any checks, so the caller has to ensure + that there are no doubles. + The handles are stored for later quick access, but the outside-handles the + aggregate properties get depend from the following two parameters. + @param _pInfoService + If not NULL, the object pointed to is used to calc handles which should be used + for referring the aggregate's properties from outside. + If one of the properties returned from the info service conflict with other handles + already present (e.g. through _rProperties), the property is handled as if -1 was returned. + If NULL (or, for a special property, a call to getPreferredPropertyId returns -1), + the aggregate property(ies) get a new handle which they can be referred by from outside. + @param _nFirstAggregateId + if the object is about to create new handles for the aggregate properties, it uses + id's ascending from this given id. + No checks are made if the handle range determined by _nFirstAggregateId conflicts with other + handles within _rProperties. + */ + OPropertyArrayAggregationHelper(const css::uno::Sequence< css::beans::Property>& _rProperties, + const css::uno::Sequence< css::beans::Property>& _rAggProperties, + IPropertyInfoService* _pInfoService = nullptr, + sal_Int32 _nFirstAggregateId = DEFAULT_AGGREGATE_PROPERTY_ID); + + + /// inherited from IPropertyArrayHelper + virtual sal_Bool SAL_CALL fillPropertyMembersByHandle( OUString* _pPropName, sal_Int16* _pAttributes, + sal_Int32 _nHandle) override ; + + /// inherited from IPropertyArrayHelper + virtual css::uno::Sequence< css::beans::Property> SAL_CALL getProperties() override; + /// inherited from IPropertyArrayHelper + virtual css::beans::Property SAL_CALL getPropertyByName(const OUString& _rPropertyName) override; + + /// inherited from IPropertyArrayHelper + virtual sal_Bool SAL_CALL hasPropertyByName(const OUString& _rPropertyName) override ; + /// inherited from IPropertyArrayHelper + virtual sal_Int32 SAL_CALL getHandleByName(const OUString & _rPropertyName) override; + /// inherited from IPropertyArrayHelper + virtual sal_Int32 SAL_CALL fillHandles( /*out*/sal_Int32* _pHandles, const css::uno::Sequence< OUString >& _rPropNames ) override; + + /** returns information about a property of the aggregate. + @param _pPropName points to a string to receive the property name. No name is returned if this is NULL. + @param _pOriginalHandle points to a sal_Int32 to receive the original property handle. No original handle is returned + if this is NULL. + @param _nHandle the handle of the property as got by, for instance, fillHandles + + @return sal_True, if _nHandle marks an aggregate property, otherwise sal_False + */ + bool fillAggregatePropertyInfoByHandle(OUString* _pPropName, sal_Int32* _pOriginalHandle, + sal_Int32 _nHandle) const; + + /** returns information about a property given by handle + */ + bool getPropertyByHandle( sal_Int32 _nHandle, css::beans::Property& _rProperty ) const; + + + enum class PropertyOrigin + { + Aggregate, + Delegator, + Unknown + }; + /** prefer this one over the XPropertySetInfo of the aggregate! + +

The reason is that OPropertyArrayAggregationHelper is the only instance which really knows + which properties of the aggregate are to be exposed.
+ + For instance, some derivee of OPropertySetAggregationHelper may decide to create an + OPropertyArrayAggregationHelper which contains only a subset of the aggregate properties. This way, + some of the aggregate properties may be hidden to the public.
+ + When using the XPropertySetInfo of the aggregate set to determine the existence of a property, then this + would return false positives.

+ */ + PropertyOrigin classifyProperty( const OUString& _rName ); + +private: + const css::beans::Property* findPropertyByName(const OUString& _rName) const; +}; + + +namespace internal +{ + class PropertyForwarder; +} + +/** + * helper class for implementing the property-set-related interfaces + * for an object doin' aggregation + * supports at least XPropertySet and XMultiPropertySet + * + */ +class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OPropertySetAggregationHelper :public OPropertyStateHelper + ,public css::beans::XPropertiesChangeListener + ,public css::beans::XVetoableChangeListener +{ + friend class internal::PropertyForwarder; + +protected: + css::uno::Reference< css::beans::XPropertyState> m_xAggregateState; + css::uno::Reference< css::beans::XPropertySet> m_xAggregateSet; + css::uno::Reference< css::beans::XMultiPropertySet> m_xAggregateMultiSet; + css::uno::Reference< css::beans::XFastPropertySet> m_xAggregateFastSet; + + std::unique_ptr m_pForwarder; + bool m_bListening : 1; + +public: + OPropertySetAggregationHelper( ::cppu::OBroadcastHelper& rBHelper ); + + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type& aType) override; + +// XEventListener + virtual void SAL_CALL disposing(const css::lang::EventObject& Source) override; + +// XFastPropertySet + virtual void SAL_CALL setFastPropertyValue(sal_Int32 nHandle, const css::uno::Any& aValue) override; + virtual css::uno::Any SAL_CALL getFastPropertyValue(sal_Int32 nHandle) override; + +// XPropertySet + virtual void SAL_CALL addPropertyChangeListener(const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener) override; + virtual void SAL_CALL addVetoableChangeListener(const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener) override; + +// XPropertiesChangeListener + virtual void SAL_CALL propertiesChange(const css::uno::Sequence< css::beans::PropertyChangeEvent >& evt) override; + +// XVetoableChangeListener + virtual void SAL_CALL vetoableChange(const css::beans::PropertyChangeEvent& aEvent) override; + +// XMultiPropertySet + virtual void SAL_CALL setPropertyValues(const css::uno::Sequence< OUString >& PropertyNames, const css::uno::Sequence< css::uno::Any >& Values) override; + virtual void SAL_CALL addPropertiesChangeListener(const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener) override; + +// XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState(const OUString& PropertyName) override; + virtual void SAL_CALL setPropertyToDefault(const OUString& PropertyName) override; + virtual css::uno::Any SAL_CALL getPropertyDefault(const OUString& aPropertyName) override; + +// OPropertySetHelper + /** still waiting to be overwritten ... + you must use an OPropertyArrayAggregationHelper here, as the implementation strongly relies on this. + */ + virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() override = 0; + + /** only implemented for "forwarded" properties, every other property must be handled + in the derivee, and will assert if passed herein + */ + virtual sal_Bool SAL_CALL convertFastPropertyValue( css::uno::Any& _rConvertedValue, css::uno::Any& _rOldValue, sal_Int32 _nHandle, const css::uno::Any& _rValue ) override; + + /** only implemented for "forwarded" properties, every other property must be handled + in the derivee, and will assert if passed herein + */ + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const css::uno::Any& _rValue ) override; + +protected: + virtual ~OPropertySetAggregationHelper() override; + + virtual void SAL_CALL getFastPropertyValue(css::uno::Any& rValue, sal_Int32 nHandle) const override; + void disposing(); + + sal_Int32 getOriginalHandle( sal_Int32 _nHandle ) const; + OUString getPropertyName( sal_Int32 _nHandle ) const; + + /** declares the property with the given (public) handle as one to be forwarded to the aggregate + + Sometimes, you might want to overwrite properties at the aggregate. That is, + though the aggregate implements this property, and still is to hold the property value, + you want to do additional handling upon setting the property, but then forward the value + to the aggregate. + + Use this method to declare such properties. + + When a "forwarded property" is set from outside, the class first calls + forwardingPropertyValue for any preprocessing, then forwards the property + value to the aggregate, and then calls forwardedPropertyValue. + + When you declare a property as "forwarded", the class takes care for some multi-threading + issues, for instance, it won't fire any property change notifications which result from + forwarding a property value, unless it's safe to do so (i.e. unless our mutex is + released). + + @see forwardingPropertyValue + @see forwardedPropertyValue + */ + void declareForwardedProperty( sal_Int32 _nHandle ); + + /** checks whether we're actually forwarding a property value to our aggregate + + @see declareForwardedProperty + @see forwardingPropertyValue + @see forwardedPropertyValue + */ + bool isCurrentlyForwardingProperty( sal_Int32 _nHandle ) const; + + /** called immediately before a property value which is overwritten in this instance + is forwarded to the aggregate + + @see declareForwardedProperty + @see forwardedPropertyValue + */ + virtual void forwardingPropertyValue( sal_Int32 _nHandle ); + + /** called immediately after a property value which is overwritten in this instance + has been forwarded to the aggregate + + @see declareForwardedProperty + @see forwardingPropertyValue + */ + virtual void forwardedPropertyValue( sal_Int32 _nHandle ); + + /// must be called before aggregation, if aggregation is used + /// + /// @throws css::lang::IllegalArgumentException + void setAggregation(const css::uno::Reference< css::uno::XInterface >&); + void startListening(); +}; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPAGG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/proparrhlp.hxx b/include/comphelper/proparrhlp.hxx new file mode 100644 index 000000000..5db95972f --- /dev/null +++ b/include/comphelper/proparrhlp.hxx @@ -0,0 +1,141 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPARRHLP_HXX +#define INCLUDED_COMPHELPER_PROPARRHLP_HXX + +#include +#include +#include +#include + +namespace comphelper +{ + +template +class OPropertyArrayUsageHelper +{ +protected: + static sal_Int32 s_nRefCount; + static ::cppu::IPropertyArrayHelper* s_pProps; + static std::mutex& theMutex() + { + static std::mutex SINGLETON; + return SINGLETON; + } +public: + OPropertyArrayUsageHelper(); + virtual ~OPropertyArrayUsageHelper(); + + /** call this in the getInfoHelper method of your derived class. The method returns the array helper of the + class, which is created if necessary. + */ + ::cppu::IPropertyArrayHelper* getArrayHelper(); + +protected: + /** used to implement the creation of the array helper which is shared amongst all instances of the class. + This method needs to be implemented in derived classes. +
+ The method gets called with Mutex acquired. + @return a pointer to the newly created array helper. Must not be NULL. + */ + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const = 0; +}; + +/** an OPropertyArrayUsageHelper which will create an OPropertyArrayAggregationHelper +*/ +template +class OAggregationArrayUsageHelper: public OPropertyArrayUsageHelper +{ +protected: + /** overwrite this in your derived class. initialize the two sequences with your and your aggregate's + properties. +
+ The method gets called with Mutex acquired. + @param _rProps out parameter to be filled with the property descriptions of your own class + @param _rAggregateProps out parameter to be filled with the properties of your aggregate. + */ + virtual void fillProperties( + css::uno::Sequence< css::beans::Property >& /* [out] */ _rProps, + css::uno::Sequence< css::beans::Property >& /* [out] */ _rAggregateProps + ) const = 0; + + /** creates an OPropertyArrayAggregationHelper filled with properties for which's initialization + fillProperties is called. getInfoService and getFirstAggregateId may be overwritten to determine + the additional parameters of the OPropertyArrayAggregationHelper. + */ + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; +}; + +template +sal_Int32 OPropertyArrayUsageHelper< TYPE >::s_nRefCount = 0; + +template +::cppu::IPropertyArrayHelper* OPropertyArrayUsageHelper< TYPE >::s_pProps = nullptr; + +template +OPropertyArrayUsageHelper::OPropertyArrayUsageHelper() +{ + std::unique_lock aGuard(theMutex()); + ++s_nRefCount; +} + +template +OPropertyArrayUsageHelper::~OPropertyArrayUsageHelper() +{ + std::unique_lock aGuard(theMutex()); + OSL_ENSURE(s_nRefCount > 0, "OPropertyArrayUsageHelper::~OPropertyArrayUsageHelper : suspicious call : have a refcount of 0 !"); + if (!--s_nRefCount) + { + delete s_pProps; + s_pProps = nullptr; + } +} + +template +::cppu::IPropertyArrayHelper* OPropertyArrayUsageHelper::getArrayHelper() +{ + OSL_ENSURE(s_nRefCount, "OPropertyArrayUsageHelper::getArrayHelper : suspicious call : have a refcount of 0 !"); + if (!s_pProps) + { + std::unique_lock aGuard(theMutex()); + if (!s_pProps) + { + s_pProps = createArrayHelper(); + OSL_ENSURE(s_pProps, "OPropertyArrayUsageHelper::getArrayHelper : createArrayHelper returned nonsense !"); + } + } + return s_pProps; +} + +template inline +::cppu::IPropertyArrayHelper* OAggregationArrayUsageHelper::createArrayHelper() const +{ + css::uno::Sequence< css::beans::Property > aProps; + css::uno::Sequence< css::beans::Property > aAggregateProps; + fillProperties(aProps, aAggregateProps); + OSL_ENSURE(aProps.hasElements(), "OAggregationArrayUsageHelper::createArrayHelper : fillProperties returned nonsense !"); + return new OPropertyArrayAggregationHelper(aProps, aAggregateProps, nullptr, DEFAULT_AGGREGATE_PROPERTY_ID); +} + +} + +#endif // INCLUDED_COMPHELPER_PROPARRHLP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/property.hxx b/include/comphelper/property.hxx new file mode 100644 index 000000000..b9787f130 --- /dev/null +++ b/include/comphelper/property.hxx @@ -0,0 +1,131 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTY_HXX +#define INCLUDED_COMPHELPER_PROPERTY_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySet; } + +namespace comphelper +{ + + // comparing two property instances + struct PropertyCompareByName + { + bool operator() (const css::beans::Property& x, const css::beans::Property& y) const + { + return x.Name.compareTo(y.Name) < 0; + } + }; + +/// remove the property with the given name from the given sequence +COMPHELPER_DLLPUBLIC void RemoveProperty(css::uno::Sequence& seqProps, const OUString& _rPropName); + +/** within the given property sequence, modify attributes of a special property + @param _rProps the sequence of properties to search in + @param _sPropName the name of the property which's attributes should be modified + @param _nAddAttrib the attributes which should be added + @param _nRemoveAttrib the attributes which should be removed +*/ +COMPHELPER_DLLPUBLIC void ModifyPropertyAttributes(css::uno::Sequence& _rProps, const OUString& _sPropName, sal_Int16 _nAddAttrib, sal_Int16 _nRemoveAttrib); + +/** check if the given set has the given property. +*/ +COMPHELPER_DLLPUBLIC bool hasProperty(const OUString& _rName, const css::uno::Reference& _rxSet); + +/** copy properties between property sets, in compliance with the property + attributes of the target object +*/ +COMPHELPER_DLLPUBLIC void copyProperties(const css::uno::Reference& _rxSource, + const css::uno::Reference& _rxDest); + +/** helper for implementing ::cppu::OPropertySetHelper::convertFastPropertyValue + @param _rConvertedValue the conversion result (if successful) + @param _rOldValue the old value of the property, calculated from _rCurrentValue + @param _rValueToSet the new value which is about to be set + @param _rCurrentValue the current value of the property + @return sal_True, if the value could be converted and has changed + sal_False, if the value could be converted and has not changed + @exception InvalidArgumentException thrown if the value could not be converted to the requested type (which is the template argument) +*/ +template +bool tryPropertyValue(css::uno::Any& /*out*/_rConvertedValue, css::uno::Any& /*out*/_rOldValue, const css::uno::Any& _rValueToSet, const T& _rCurrentValue) +{ + bool bModified(false); + T aNewValue = T(); + ::cppu::convertPropertyValue(aNewValue, _rValueToSet); + if (aNewValue != _rCurrentValue) + { + _rConvertedValue <<= aNewValue; + _rOldValue <<= _rCurrentValue; + bModified = true; + } + return bModified; +} + +/** helper for implementing ::cppu::OPropertySetHelper::convertFastPropertyValue for enum values + @param _rConvertedValue the conversion result (if successful) + @param _rOldValue the old value of the property, calculated from _rCurrentValue + @param _rValueToSet the new value which is about to be set + @param _rCurrentValue the current value of the property + @return sal_True, if the value could be converted and has changed + sal_False, if the value could be converted and has not changed + @exception InvalidArgumentException thrown if the value could not be converted to the requested type (which is the template argument) +*/ +template +typename std::enable_if::value, bool>::type +tryPropertyValueEnum(css::uno::Any& /*out*/_rConvertedValue, css::uno::Any& /*out*/_rOldValue, const css::uno::Any& _rValueToSet, const ENUMTYPE& _rCurrentValue) +{ + bool bModified(false); + ENUMTYPE aNewValue; + ::cppu::any2enum(aNewValue, _rValueToSet); + // will throw an exception if not convertible + + if (aNewValue != _rCurrentValue) + { + _rConvertedValue <<= aNewValue; + _rOldValue <<= _rCurrentValue; + bModified = true; + } + return bModified; +} + +/** helper for implementing ::cppu::OPropertySetHelper::convertFastPropertyValue + @param _rConvertedValue the conversion result (if successful) + @param _rOldValue the old value of the property, calculated from _rCurrentValue + @param _rValueToSet the new value which is about to be set + @param _rCurrentValue the current value of the property + @param _rExpectedType the type which the property should have (if not void) + @return sal_True, if the value could be converted and has changed + sal_False, if the value could be converted and has not changed + @exception InvalidArgumentException thrown if the value could not be converted to the requested type (which is the template argument) +*/ +COMPHELPER_DLLPUBLIC bool tryPropertyValue(css::uno::Any& _rConvertedValue, css::uno::Any& _rOldValue, const css::uno::Any& _rValueToSet, const css::uno::Any& _rCurrentValue, const css::uno::Type& _rExpectedType); + +} + +#endif // INCLUDED_COMPHELPER_PROPERTY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertybag.hxx b/include/comphelper/propertybag.hxx new file mode 100644 index 000000000..3cf9de9ff --- /dev/null +++ b/include/comphelper/propertybag.hxx @@ -0,0 +1,226 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYBAG_HXX +#define INCLUDED_COMPHELPER_PROPERTYBAG_HXX + +#include +#include +#include +#include + +#include + + +namespace comphelper +{ + + + //= PropertyBag + + /** provides a bag of properties associated with their values + + This class can, for instance, be used for components which need to implement + the com.sun.star.beans.PropertyBag service. + */ + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) PropertyBag final : protected OPropertyContainerHelper + { + std::map< sal_Int32, css::uno::Any > aDefaults; + bool m_bAllowEmptyPropertyName; + public: + PropertyBag(); + virtual ~PropertyBag(); + + /** allow adding property with empty string as name + (by default, such names are rejected with IllegalActionException). + @param i_isAllowed + iff true, empty property name will be allowed + */ + void setAllowEmptyPropertyName(bool i_isAllowed); + + /** adds a property to the bag + + The type of the property is determined from its initial value (_rInitialValue). + + @param _rName + the name of the new property. Must not be empty unless + explicitly allowed with setAllowEmptyPropertyName. + @param _nHandle + the handle of the new property + @param _nAttributes + the attributes of the property + @param _rInitialValue + the initial value of the property. Must not be , to allow + determining the property type. + + @throws css::beans::IllegalTypeException + if the initial value is + @throws css::beans::PropertyExistException + if the name or the handle are already used + @throws css::beans::IllegalArgumentException + if the name is empty + */ + void addProperty( + const OUString& _rName, + sal_Int32 _nHandle, + sal_Int32 _nAttributes, + const css::uno::Any& _rInitialValue + ); + + /** adds a property to the bag + + The initial value of the property is . + + @param _rName + the name of the new property. Must not be empty unless + explicitly allowed with setAllowEmptyPropertyName. + @param _rType + the type of the new property + @param _nHandle + the handle of the new property + @param _nAttributes + the attributes of the property + + @throws css::beans::IllegalTypeException + if the initial value is + @throws css::beans::PropertyExistException + if the name or the handle are already used + @throws css::beans::IllegalArgumentException + if the name is empty + */ + void addVoidProperty( + const OUString& _rName, + const css::uno::Type& _rType, + sal_Int32 _nHandle, + sal_Int32 _nAttributes + ); + + /** removes a property from the bag + @param _rName + the name of the to-be-removed property. + @throws UnknownPropertyException + if the bag does not contain a property with the given name + @throws NotRemoveableException + if the property with the given name is not removable, as indicated + by the property attributes used in a previous addProperty + call. + */ + void removeProperty( + const OUString& _rName + ); + + /** describes all properties in the bag + @param _out_rProps + takes, upon return, the descriptions of all properties in the bag + */ + void describeProperties( + css::uno::Sequence< css::beans::Property >& _out_rProps + ) const + { + OPropertyContainerHelper::describeProperties( _out_rProps ); + } + + /** retrieves the value of a property given by handle + @param _nHandle + the handle of the property whose value is to be retrieved + @param _out_rValue + output parameter taking the property value + @throws UnknownPropertyException + if the given handle does not denote a property in the bag + */ + void getFastPropertyValue( + sal_Int32 _nHandle, + css::uno::Any& _out_rValue + ) const; + + /** converts a to-be-set value of a property (given by handle) so that it can + be used in subsequent calls to setFastPropertyValue + @param _nHandle + the handle of the property + @param _rNewValue + the new value, which should be converted + @param _out_rConvertedValue + output parameter taking the converted value + @param _out_rCurrentValue + output parameter taking the current value of the + property + @throws UnknownPropertyException + if the given handle does not denote a property in the bag + @throws IllegalArgumentException + if the given value cannot be lossless converted into a value + for the given property. + */ + bool convertFastPropertyValue( + sal_Int32 _nHandle, + const css::uno::Any& _rNewValue, + css::uno::Any& _out_rConvertedValue, + css::uno::Any& _out_rCurrentValue + ) const; + + /** sets a new value for a property given by handle + @throws UnknownPropertyException + if the given handle does not denote a property in the bag + */ + void setFastPropertyValue( + sal_Int32 _nHandle, + const css::uno::Any& _rValue + ); + + /** returns the default value for a property given by handle + + The default value of a property is its initial value, as passed + to ->addProperty. + + @param _nHandle + handle of the property whose default value is to be obtained + @param _out_rValue + the default value + @throws UnknownPropertyException + if the given handle does not denote a property in the bag + */ + void getPropertyDefaultByHandle( + sal_Int32 _nHandle, + css::uno::Any& _out_rValue + ) const; + + /** determines whether a property with a given name is part of the bag + */ + bool hasPropertyByName( const OUString& _rName ) const + { + return isRegisteredProperty( _rName ); + } + + /** determines whether a property with a given handle is part of the bag + */ + bool hasPropertyByHandle( sal_Int32 _nHandle ) const + { + return isRegisteredProperty( _nHandle ); + } + protected: + using OPropertyContainerHelper::convertFastPropertyValue; + using OPropertyContainerHelper::getFastPropertyValue; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPERTYBAG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertycontainer.hxx b/include/comphelper/propertycontainer.hxx new file mode 100644 index 000000000..2c64b2cdf --- /dev/null +++ b/include/comphelper/propertycontainer.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYCONTAINER_HXX +#define INCLUDED_COMPHELPER_PROPERTYCONTAINER_HXX + +#include +#include +#include + + +namespace com::sun::star::uno { class Any; } +namespace com::sun::star::uno { class Type; } + +namespace comphelper +{ + + +/** an OPropertySetHelper implementation which is just a simple container for properties represented + by class members, usually in a derived class. +
+ A restriction of this class is that no value conversions are made on a setPropertyValue call. Though + the base class supports this with the convertFastPropertyValue method, the OPropertyContainer accepts only + values which already have the correct type, it's unable to convert, for instance, a long to a short. +*/ +class COMPHELPER_DLLPUBLIC OPropertyContainer + :public cppu::OPropertySetHelper + ,public OPropertyContainerHelper +{ +public: + // this dtor is needed otherwise we can get a wrong delete operator + virtual ~OPropertyContainer(); + +protected: + OPropertyContainer(::cppu::OBroadcastHelper& _rBHelper); + + /// for scripting : the types of the interfaces supported by this class + /// + /// @throws css::uno::RuntimeException + static css::uno::Sequence< css::uno::Type > getBaseTypes(); + +// OPropertySetHelper overridables + virtual sal_Bool SAL_CALL convertFastPropertyValue( + css::uno::Any & rConvertedValue, + css::uno::Any & rOldValue, + sal_Int32 nHandle, + const css::uno::Any& rValue ) override; + + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const css::uno::Any& rValue + ) override; + + using OPropertySetHelper::getFastPropertyValue; + virtual void SAL_CALL getFastPropertyValue( + css::uno::Any& rValue, + sal_Int32 nHandle + ) const override; + + // disambiguate a base class method (XFastPropertySet) + using OPropertySetHelper::setFastPropertyValue; +}; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPERTYCONTAINER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertycontainerhelper.hxx b/include/comphelper/propertycontainerhelper.hxx new file mode 100644 index 000000000..73a0ce513 --- /dev/null +++ b/include/comphelper/propertycontainerhelper.hxx @@ -0,0 +1,197 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYCONTAINERHELPER_HXX +#define INCLUDED_COMPHELPER_PROPERTYCONTAINERHELPER_HXX + +#include +#include +#include +#include +#include +#include + + +namespace comphelper +{ + + +// infos about one single property +struct COMPHELPER_DLLPUBLIC PropertyDescription +{ + // the possibilities where a property holding object may be located + enum class LocationType + { + DerivedClassRealType, // within the derived class, it's a "real" (non-Any) type + DerivedClassAnyType, // within the derived class, it's a com.sun.star.uno::Any + HoldMyself // within m_aHoldProperties + }; + // the location of an object holding a property value : + union LocationAccess + { + void* pDerivedClassMember; // a pointer to a member of an object of a derived class + std::size_t nOwnClassVectorIndex; // an index within m_aHoldProperties + }; + + css::beans::Property aProperty; + LocationType eLocated; // where is the object containing the value located ? + LocationAccess aLocation; // access to the property value + + PropertyDescription() + :aProperty( OUString(), -1, css::uno::Type(), 0 ) + ,eLocated( LocationType::HoldMyself ) + { + aLocation.nOwnClassVectorIndex = std::numeric_limits::max(); + } +}; + + +//= OPropertyContainerHelper + +/** helper class for managing property values, and implementing most of the X*Property* interfaces + + The property values are usually held in derived classes, but can also be given to the + responsibility of this class here. + + For more information, see http://wiki.openoffice.org/wiki/Development/Cpp/Helper/PropertyContainerHelper. +*/ +class COMPHELPER_DLLPUBLIC OPropertyContainerHelper +{ + typedef ::std::vector< css::uno::Any > PropertyContainer; + PropertyContainer m_aHoldProperties; + // the properties which are hold by this class' instance, not the derived one's + +private: + typedef ::std::vector< PropertyDescription > Properties; + typedef Properties::iterator PropertiesIterator; + typedef Properties::const_iterator ConstPropertiesIterator; + Properties m_aProperties; + +protected: + OPropertyContainerHelper(); + ~OPropertyContainerHelper(); + + /** register a property. The property is represented through a member of the derived class which calls + this method. + @param _rName the name of the property + @param _nHandle the handle of the property + @param _nAttributes the attributes of the property + @param _pPointerToMember the pointer to the member representing the property + within the derived class. + @param _rMemberType the cppu type of the property represented by the object + to which _pPointerToMember points. + */ + void registerProperty(const OUString& _rName, sal_Int32 _nHandle, sal_Int32 _nAttributes, + void* _pPointerToMember, const css::uno::Type& _rMemberType); + + + /** register a property. The property is represented through a css::uno::Any member of the + derived class which calls this method. + @param _rName the name of the property + @param _nHandle the handle of the property + @param _nAttributes the attributes of the property + @param _pPointerToMember the pointer to the member representing the property + within the derived class, which has to be a css::uno::Any. + @param _rExpectedType the expected type of the property. NOT the type of the object to which + _pPointerToMember points (this is always an Any). + */ + void registerMayBeVoidProperty(const OUString& _rName, sal_Int32 _nHandle, sal_Int32 _nAttributes, + css::uno::Any* _pPointerToMember, const css::uno::Type& _rExpectedType); + + /** register a property. The repository will create an own object holding this property, so there is no + need to declare an extra member in your derived class + @param _rName the name of the property + @param _nHandle the handle of the property + @param _nAttributes the attributes of the property + @param _rType the type of the property + @param _pInitialValue the initial value of the property. May be void if _nAttributes includes + the css::beans::PropertyAttribute::MAYBEVOID flag. + Else it must contain a value compatible with the type described by _rType. + */ + void registerPropertyNoMember(const OUString& _rName, sal_Int32 _nHandle, sal_Int32 _nAttributes, + const css::uno::Type& _rType, css::uno::Any const & _pInitialValue); + + /** revokes a previously registered property + @throw css::beans::UnknownPropertyException + if no property with the given handle is registered + */ + void revokeProperty( sal_Int32 _nHandle ); + + + /// checks whether a property with the given handle has been registered + bool isRegisteredProperty( sal_Int32 _nHandle ) const; + + /// checks whether a property with the given name has been registered + bool isRegisteredProperty( const OUString& _rName ) const; + + + // helper for implementing OPropertySetHelper overridables + bool convertFastPropertyValue( + css::uno::Any & rConvertedValue, + css::uno::Any & rOldValue, + sal_Int32 nHandle, + const css::uno::Any& rValue + ); + + void setFastPropertyValue( + sal_Int32 nHandle, + const css::uno::Any& rValue + ); + + void getFastPropertyValue( + css::uno::Any& rValue, + sal_Int32 nHandle + ) const; + +// helper + /** appends the descriptions of all properties which were registered 'til that moment to the given sequence, + keeping the array sorted (by name) + @precond + the given sequence is already sorted by name + @param _rProps + initial property sequence which is to be extended + */ + void describeProperties(css::uno::Sequence< css::beans::Property >& /* [out] */ _rProps) const; + + /** retrieves the description for a registered property + @throw css::beans::UnknownPropertyException + if no property with the given name is registered + */ + const css::beans::Property& + getProperty( const OUString& _rName ) const; + +private: + /// insertion of _rProp into m_aProperties, keeping the sort order + COMPHELPER_DLLPRIVATE void implPushBackProperty(const PropertyDescription& _rProp); + + /// search the PropertyDescription for the given handle (within m_aProperties) + COMPHELPER_DLLPRIVATE PropertiesIterator searchHandle(sal_Int32 _nHandle); + +private: + OPropertyContainerHelper( const OPropertyContainerHelper& ) = delete; + OPropertyContainerHelper& operator=( const OPropertyContainerHelper& ) = delete; +}; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPERTYCONTAINERHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertysequence.hxx b/include/comphelper/propertysequence.hxx new file mode 100644 index 000000000..e788f56f4 --- /dev/null +++ b/include/comphelper/propertysequence.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYSEQUENCE_HXX +#define INCLUDED_COMPHELPER_PROPERTYSEQUENCE_HXX + +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace comphelper +{ + /// Init list for property sequences. + inline css::uno::Sequence< css::beans::PropertyValue > InitPropertySequence( + ::std::initializer_list< ::std::pair< OUString, css::uno::Any > > vInit) + { + css::uno::Sequence< css::beans::PropertyValue> vResult{static_cast(vInit.size())}; + std::transform(vInit.begin(), vInit.end(), vResult.getArray(), + [](const std::pair& rInit) { + return css::beans::PropertyValue(rInit.first, -1, rInit.second, + css::beans::PropertyState_DIRECT_VALUE); + }); + return vResult; + } + + /// Init list for property sequences that wrap the PropertyValues in Anys. + /// + /// This is particularly useful for creation of sequences that are later + /// unwrapped using comphelper::SequenceAsHashMap. + inline css::uno::Sequence< css::uno::Any > InitAnyPropertySequence( + ::std::initializer_list< ::std::pair< OUString, css::uno::Any > > vInit) + { + css::uno::Sequence vResult{static_cast(vInit.size())}; + std::transform(vInit.begin(), vInit.end(), vResult.getArray(), + [](const std::pair& rInit) { + return css::uno::Any( + css::beans::PropertyValue(rInit.first, -1, rInit.second, + css::beans::PropertyState_DIRECT_VALUE)); + }); + return vResult; + } + + COMPHELPER_DLLPUBLIC std::vector JsonToPropertyValues(const OString& rJson); +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPERTYSEQUENCE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertysethelper.hxx b/include/comphelper/propertysethelper.hxx new file mode 100644 index 000000000..a4746a02f --- /dev/null +++ b/include/comphelper/propertysethelper.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYSETHELPER_HXX +#define INCLUDED_COMPHELPER_PROPERTYSETHELPER_HXX + +#include +#include +#include +#include +#include + +namespace comphelper +{ +class PropertySetInfo; +struct PropertyMapEntry; + +class COMPHELPER_DLLPUBLIC PropertySetHelper : public css::beans::XPropertySet, + public css::beans::XPropertyState, + public css::beans::XMultiPropertySet +{ +private: + rtl::Reference mxInfo; + +protected: + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const css::uno::Any* pValues ) = 0; + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, css::uno::Any* pValue ) = 0; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + virtual void _getPropertyStates( const comphelper::PropertyMapEntry** ppEntries, css::beans::PropertyState* pStates ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + virtual void _setPropertyToDefault( const comphelper::PropertyMapEntry* pEntry ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + virtual css::uno::Any _getPropertyDefault( const comphelper::PropertyMapEntry* pEntry ); + +public: + PropertySetHelper( rtl::Reference xInfo ) noexcept; + virtual ~PropertySetHelper() noexcept; + + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; + virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; + virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; + virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + + // XMultiPropertySet +// virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(css::uno::RuntimeException); + virtual void SAL_CALL setPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Sequence< css::uno::Any >& aValues ) override; + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames ) override; + virtual void SAL_CALL addPropertiesChangeListener( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertiesChangeListener( const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL firePropertiesChangeEvent( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + + // XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState( const OUString& PropertyName ) override; + virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) override; + virtual void SAL_CALL setPropertyToDefault( const OUString& PropertyName ) override; + virtual css::uno::Any SAL_CALL getPropertyDefault( const OUString& aPropertyName ) override; +}; + +} + +#endif // _UTL_PROPERTYSETHELPER_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertysetinfo.hxx b/include/comphelper/propertysetinfo.hxx new file mode 100644 index 000000000..ee26d8698 --- /dev/null +++ b/include/comphelper/propertysetinfo.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYSETINFO_HXX +#define INCLUDED_COMPHELPER_PROPERTYSETINFO_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include + +enum class PropertyMoreFlags : sal_uInt8 { + NONE = 0x00, + METRIC_ITEM = 0x01, +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +namespace comphelper +{ + +struct PropertyMapEntry +{ + OUString maName; + css::uno::Type maType; + sal_Int32 mnHandle; + /// flag bitmap, @see css::beans::PropertyAttribute + sal_Int16 mnAttributes; + sal_uInt8 mnMemberId; + PropertyMoreFlags mnMoreFlags; + + PropertyMapEntry(OUString _aName, sal_Int32 _nHandle, css::uno::Type const & _rType, + sal_Int16 _nAttributes, sal_uInt8 _nMemberId, PropertyMoreFlags _nMoreFlags = PropertyMoreFlags::NONE) + : maName(std::move( _aName )) + , maType( _rType ) + , mnHandle( _nHandle ) + , mnAttributes( _nAttributes ) + , mnMemberId( _nMemberId ) + , mnMoreFlags( _nMoreFlags ) + { + assert(mnAttributes <= 0x1ff ); + assert( (_nMemberId & 0x40) == 0 ); + // Verify that if METRIC_ITEM is set, we are one of the types supported by + // SvxUnoConvertToMM. + assert(!(_nMoreFlags & PropertyMoreFlags::METRIC_ITEM) || + ( (maType.getTypeClass() == css::uno::TypeClass_BYTE) + || (maType.getTypeClass() == css::uno::TypeClass_SHORT) + || (maType.getTypeClass() == css::uno::TypeClass_UNSIGNED_SHORT) + || (maType.getTypeClass() == css::uno::TypeClass_LONG) + || (maType.getTypeClass() == css::uno::TypeClass_UNSIGNED_LONG) + ) ); + } + PropertyMapEntry() = default; +}; + +typedef std::unordered_map PropertyMap; + +// don't export to avoid duplicate WeakImplHelper definitions with MSVC +class SAL_DLLPUBLIC_TEMPLATE PropertySetInfo_BASE + : public ::cppu::WeakImplHelper< css::beans::XPropertySetInfo > +{}; + +/** this class implements a XPropertySetInfo that is initialized with arrays of PropertyMapEntry. + It is used by the class PropertySetHelper. +*/ +class COMPHELPER_DLLPUBLIC PropertySetInfo final + : public PropertySetInfo_BASE +{ +public: + PropertySetInfo() noexcept; + PropertySetInfo( o3tl::span pMap ) noexcept; + virtual ~PropertySetInfo() noexcept override; + + /** returns a stl map with all PropertyMapEntry pointer.

+ The key is the property name. + */ + const PropertyMap& getPropertyMap() const noexcept { return maPropertyMap; } + + /** adds an array of PropertyMapEntry to this instance.

+ The end is marked with a PropertyMapEntry where mpName equals NULL

+ */ + void add( o3tl::span pMap ) noexcept; + + /** removes an already added PropertyMapEntry which string in mpName equals to aName */ + void remove( const OUString& aName ) noexcept; + + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() override; + virtual css::beans::Property SAL_CALL getPropertyByName( const OUString& aName ) override; + virtual sal_Bool SAL_CALL hasPropertyByName( const OUString& Name ) override; + +private: + PropertyMap maPropertyMap; + /// Cache the value we return in getProperties because it is expensive to construct + css::uno::Sequence< css::beans::Property > maProperties; +}; + +} + +#endif // _UTL_PROPERTSETINFO_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertystatecontainer.hxx b/include/comphelper/propertystatecontainer.hxx new file mode 100644 index 000000000..966e2cb99 --- /dev/null +++ b/include/comphelper/propertystatecontainer.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYSTATECONTAINER_HXX +#define INCLUDED_COMPHELPER_PROPERTYSTATECONTAINER_HXX + +#include +#include +#include +#include +#include + + +namespace comphelper +{ + + + //= OPropertyStateContainer + + typedef ::cppu::ImplHelper1 < css::beans::XPropertyState + > OPropertyStateContainer_TBase; + + /** helper implementation for components which have properties with a default + +

This class is not intended for direct use, you need to derive from it.

+ + @see com.sun.star.beans.XPropertyState + */ + class COMPHELPER_DLLPUBLIC OPropertyStateContainer + :public OPropertyContainer + ,public OPropertyStateContainer_TBase + { + protected: + /** ctor + @param _rBHelper + help to be used for broadcasting events + */ + OPropertyStateContainer( ::cppu::OBroadcastHelper& _rBHelper ); + + + // XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState( const OUString& PropertyName ) override; + virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) override; + virtual void SAL_CALL setPropertyToDefault( const OUString& PropertyName ) override; + virtual css::uno::Any SAL_CALL getPropertyDefault( const OUString& aPropertyName ) override; + + + // own overridables + // these are the impl-methods for the XPropertyState members - they are implemented already by this class, + // but you may want to override them for whatever reasons (for instance, if your derived class + // supports the AMBIGUOUS state for properties) + + /** get the PropertyState of the property denoted by the given handle + +

Already implemented by this base class, no need to override

+ @precond _nHandle is a valid property handle + */ + css::beans::PropertyState getPropertyStateByHandle( sal_Int32 _nHandle ) const; + + /** set the property denoted by the given handle to its default value + +

Already implemented by this base class, no need to override

+ @precond _nHandle is a valid property handle + */ + void setPropertyToDefaultByHandle( sal_Int32 _nHandle ); + + /** get the default value for the property denoted by the given handle + + @precond + _nHandle is a valid property handle + */ + virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, css::uno::Any& _rDefault ) const = 0; + + protected: + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& _rType ) override; + // XTypeProvider + DECLARE_XTYPEPROVIDER( ) + + protected: + /** returns the handle for the given name + + @throw UnknownPropertyException if the given name is not a registered property + */ + sal_Int32 getHandleForName( const OUString& _rPropertyName ); + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPERTYSTATECONTAINER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propertyvalue.hxx b/include/comphelper/propertyvalue.hxx new file mode 100644 index 000000000..de7179110 --- /dev/null +++ b/include/comphelper/propertyvalue.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_PROPERTYVALUE_HXX +#define INCLUDED_COMPHELPER_PROPERTYVALUE_HXX + +#include + +#include +#include + +#include + +namespace comphelper +{ +/** + * Creates a beans::PropertyValue easily, i.e. you can write: + * + * function(comphelper::makePropertyValue("Foo", nBar)); + * + * instead of writing 3 extra lines to set the name and value of the beans::PropertyValue. + */ +template >, int> = 0> +css::beans::PropertyValue makePropertyValue(const OUString& rName, T&& rValue) +{ + return { rName, 0, css::uno::toAny(std::forward(rValue)), + css::beans::PropertyState_DIRECT_VALUE }; +} +// Allows to pass e.g. bit fields +template , int> = 0> +css::beans::PropertyValue makePropertyValue(const OUString& rName, T aValue) +{ + return makePropertyValue(rName, css::uno::toAny(aValue)); +} +} + +#endif // INCLUDED_COMPHELPER_PROPERTYVALUE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propmultiplex.hxx b/include/comphelper/propmultiplex.hxx new file mode 100644 index 000000000..41d456d43 --- /dev/null +++ b/include/comphelper/propmultiplex.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPMULTIPLEX_HXX +#define INCLUDED_COMPHELPER_PROPMULTIPLEX_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySet; } + +//= property helper classes + + +namespace comphelper +{ + + + class OPropertyChangeMultiplexer; + + + //= OPropertyChangeListener + + /// simple listener adapter for property sets + class COMPHELPER_DLLPUBLIC OPropertyChangeListener + { + friend class OPropertyChangeMultiplexer; + + rtl::Reference m_xAdapter; + ::osl::Mutex& m_rMutex; + + public: + OPropertyChangeListener(::osl::Mutex& _rMutex) + : m_rMutex(_rMutex) { } + virtual ~OPropertyChangeListener(); + + /// @throws css::uno::RuntimeException + virtual void _propertyChanged(const css::beans::PropertyChangeEvent& _rEvent) = 0; + /// @throws css::uno::RuntimeException + virtual void _disposing(const css::lang::EventObject& _rSource); + + protected: + /** If the derivee also owns the mutex which we know as reference, then call this within your + derivee's dtor. + */ + void disposeAdapter(); + + // pseudo-private. Making it private now could break compatibility + void setAdapter( OPropertyChangeMultiplexer* _pAdapter ); + }; + + + //= OPropertyChangeMultiplexer + + /// multiplexer for property changes + // workaround for incremental linking bugs in MSVC2019 + class SAL_DLLPUBLIC_TEMPLATE OPropertyChangeMultiplexer_Base : public cppu::WeakImplHelper< css::beans::XPropertyChangeListener > {}; + class COMPHELPER_DLLPUBLIC OPropertyChangeMultiplexer final : public OPropertyChangeMultiplexer_Base + { + friend class OPropertyChangeListener; + std::vector< OUString > m_aProperties; + css::uno::Reference< css::beans::XPropertySet> m_xSet; + OPropertyChangeListener* m_pListener; + sal_Int32 m_nLockCount; + bool m_bListening : 1; + bool const m_bAutoSetRelease : 1; + + + virtual ~OPropertyChangeMultiplexer() override; + public: + OPropertyChangeMultiplexer(OPropertyChangeListener* _pListener, const css::uno::Reference< css::beans::XPropertySet>& _rxSet, bool _bAutoReleaseSet = true); + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XPropertyChangeListener + virtual void SAL_CALL propertyChange( const css::beans::PropertyChangeEvent& evt ) override; + + /// incremental lock + void lock(); + /// incremental unlock + void unlock(); + /// get the lock count + sal_Int32 locked() const { return m_nLockCount; } + + void addProperty(const OUString& aPropertyName); + void dispose(); + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPMULTIPLEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/propstate.hxx b/include/comphelper/propstate.hxx new file mode 100644 index 000000000..7729aaa9b --- /dev/null +++ b/include/comphelper/propstate.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROPSTATE_HXX +#define INCLUDED_COMPHELPER_PROPSTATE_HXX + +#include +#include +#include + + +#include +#include +#include +#include +#include +#include + + +//= property helper classes + + +namespace comphelper +{ + + + //= OPropertyStateHelper + + /// helper class for implementing property states + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OPropertyStateHelper :public ::cppu::OPropertySetHelper2 + ,public css::beans::XPropertyState + { + public: + OPropertyStateHelper(::cppu::OBroadcastHelper& rBHlp):OPropertySetHelper2(rBHlp) { } + OPropertyStateHelper(::cppu::OBroadcastHelper& rBHlp, + ::cppu::IEventNotificationHook *i_pFireEvents); + + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type& aType) override; + + // XPropertyState + virtual css::beans::PropertyState SAL_CALL + getPropertyState(const OUString& PropertyName) override; + virtual css::uno::Sequence< css::beans::PropertyState> SAL_CALL + getPropertyStates(const css::uno::Sequence< OUString >& aPropertyName) override; + virtual void SAL_CALL + setPropertyToDefault(const OUString& PropertyName) override; + virtual css::uno::Any SAL_CALL + getPropertyDefault(const OUString& aPropertyName) override; + + // access via handle + virtual css::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle); + virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle); + virtual css::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const; + + protected: + virtual ~OPropertyStateHelper() override; + + void firePropertyChange(sal_Int32 nHandle, const css::uno::Any& aNewValue, const css::uno::Any& aOldValue); + + static css::uno::Sequence getTypes(); + }; + + + //= OPropertyStateHelper + + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OStatefulPropertySet :public ::cppu::OWeakObject + ,public css::lang::XTypeProvider + ,public OMutexAndBroadcastHelper // order matters: before OPropertyStateHelper/OPropertySetHelper + ,public OPropertyStateHelper + { + protected: + OStatefulPropertySet(); + virtual ~OStatefulPropertySet() override; + + protected: + DECLARE_XINTERFACE() + DECLARE_XTYPEPROVIDER() + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROPSTATE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/proxyaggregation.hxx b/include/comphelper/proxyaggregation.hxx new file mode 100644 index 000000000..48444355c --- /dev/null +++ b/include/comphelper/proxyaggregation.hxx @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_PROXYAGGREGATION_HXX +#define INCLUDED_COMPHELPER_PROXYAGGREGATION_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { + class XComponentContext; +} +namespace com::sun::star::uno { class XAggregation; } +namespace com::sun::star::lang { class XComponent; } + +/* class hierarchy herein: + + +-------------------+ helper class for aggregating the proxy to another object + | OProxyAggregation | - not ref counted + +-------------------+ - no UNO implementation, i.e. not derived from XInterface + ^ (neither direct nor indirect) + | + | + +----------------------------------+ helper class for aggregating a proxy to an XComponent + | OComponentProxyAggregationHelper | - life time coupling: if the inner component (the "aggregate") + +----------------------------------+ is disposed, the outer (the delegator) is disposed, too, and + ^ vice versa + | - UNO based, implementing XEventListener + | + +----------------------------+ component aggregating another XComponent + | OComponentProxyAggregation | - life time coupling as above + +----------------------------+ - ref-counted + - implements an XComponent itself + + If you need to + + - wrap a foreign object which is a XComponent + => use OComponentProxyAggregation + - call componentAggregateProxyFor in your ctor + - call implEnsureDisposeInDtor in your dtor + + - wrap a foreign object which is a XComponent, but already have ref-counting mechanisms + inherited from somewhere else + => use OComponentProxyAggregationHelper + - override dispose - don't forget to call the base class' dispose! + - call componentAggregateProxyFor in your ctor + + - wrap a foreign object which is no XComponent + => use OProxyAggregation + - call baseAggregateProxyFor in your ctor +*/ + + +namespace comphelper +{ + + + //= OProxyAggregation + + /** helper class for aggregating a proxy for a foreign object + */ + class OProxyAggregation + { + private: + css::uno::Reference< css::uno::XAggregation > m_xProxyAggregate; + css::uno::Reference< css::lang::XTypeProvider > m_xProxyTypeAccess; + css::uno::Reference< css::uno::XComponentContext > m_xContext; + + protected: + const css::uno::Reference< css::uno::XComponentContext >& getComponentContext() const + { + return m_xContext; + } + + protected: + OProxyAggregation( const css::uno::Reference< css::uno::XComponentContext >& _rxContext ); + ~OProxyAggregation(); + + /// to be called from within your ctor + void baseAggregateProxyFor( + const css::uno::Reference< css::uno::XInterface >& _rxComponent, + oslInterlockedCount& _rRefCount, + ::cppu::OWeakObject& _rDelegator + ); + + // XInterface and XTypeProvider + /// @throws css::uno::RuntimeException + css::uno::Any SAL_CALL queryAggregation( const css::uno::Type& _rType ); + /// @throws css::uno::RuntimeException + css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ); + + private: + OProxyAggregation( const OProxyAggregation& ) = delete; + OProxyAggregation& operator=( const OProxyAggregation& ) = delete; + }; + + + //= OComponentProxyAggregationHelper + + /** a helper class for aggregating a proxy to an XComponent + +

The object couples the life time of itself and the component: if one of the both + dies (in a sense of being disposed), the other one dies, too.

+ +

The class itself does not implement XComponent so you need to forward any XComponent::dispose + calls which your derived class gets to the dispose method of this class.

+ */ + + class OComponentProxyAggregationHelper :public ::cppu::ImplHelper1 < css::lang::XEventListener + > + ,private OProxyAggregation + { + private: + typedef ::cppu::ImplHelper1 < css::lang::XEventListener + > BASE; // prevents some MSVC problems + + protected: + css::uno::Reference< css::lang::XComponent > + m_xInner; + ::cppu::OBroadcastHelper& m_rBHelper; + + protected: + // OProxyAggregation + using OProxyAggregation::getComponentContext; + + // XInterface + css::uno::Any SAL_CALL queryInterface( const css::uno::Type& _rType ) override; + + // XTypeProvider + DECLARE_XTYPEPROVIDER( ) + + protected: + OComponentProxyAggregationHelper( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + ::cppu::OBroadcastHelper& _rBHelper + ); + virtual ~OComponentProxyAggregationHelper( ); + + /// to be called from within your ctor + void componentAggregateProxyFor( + const css::uno::Reference< css::lang::XComponent >& _rxComponent, + oslInterlockedCount& _rRefCount, + ::cppu::OWeakObject& _rDelegator + ); + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XComponent + /// @throws css::uno::RuntimeException + virtual void SAL_CALL dispose() = 0; + + private: + OComponentProxyAggregationHelper( const OComponentProxyAggregationHelper& ) = delete; + OComponentProxyAggregationHelper& operator=( const OComponentProxyAggregationHelper& ) = delete; + }; + + + //= OComponentProxyAggregation + + class COMPHELPER_DLLPUBLIC OComponentProxyAggregation : public cppu::BaseMutex + ,public cppu::WeakComponentImplHelperBase + ,public OComponentProxyAggregationHelper + { + protected: + OComponentProxyAggregation( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + const css::uno::Reference< css::lang::XComponent >& _rxComponent + ); + + virtual ~OComponentProxyAggregation() override; + + // XInterface + DECLARE_XINTERFACE() + // XTypeProvider + DECLARE_XTYPEPROVIDER() + + // OComponentHelper + virtual void SAL_CALL disposing() override; + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& _rSource ) override; + + // XComponent/OComponentProxyAggregationHelper + virtual void SAL_CALL dispose() override; + + private: + OComponentProxyAggregation( const OComponentProxyAggregation& ) = delete; + OComponentProxyAggregation& operator=( const OComponentProxyAggregation& ) = delete; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_PROXYAGGREGATION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/random.hxx b/include/comphelper/random.hxx new file mode 100644 index 000000000..345d57c71 --- /dev/null +++ b/include/comphelper/random.hxx @@ -0,0 +1,39 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_RANDOM_HXX +#define INCLUDED_COMPHELPER_RANDOM_HXX + +#include + +namespace comphelper::rng +{ +// These functions obey the SAL_RAND_REPEATABLE environment +// variable: If it is set, use a fixed seed. + +// note that uniform_int_distribution is inclusive of b, i.e. [a,b] while +// uniform_real_distribution is exclusive of b, i.e. [a,b), std::nextafter may be your friend there + +/// uniform distribution in [a,b) +COMPHELPER_DLLPUBLIC double uniform_real_distribution(double a = 0.0, double b = 1.0); + +/// uniform distribution in [a,b] +COMPHELPER_DLLPUBLIC int uniform_int_distribution(int a, int b); + +/// uniform distribution in [a,b] +COMPHELPER_DLLPUBLIC unsigned int uniform_uint_distribution(unsigned int a, unsigned int b); + +/// uniform distribution in [a,b] +COMPHELPER_DLLPUBLIC size_t uniform_size_distribution(size_t a, size_t b); + +} // namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/refcountedmutex.hxx b/include/comphelper/refcountedmutex.hxx new file mode 100644 index 000000000..fcda72097 --- /dev/null +++ b/include/comphelper/refcountedmutex.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_REFCOUNTEDMUTEX_HXX +#define INCLUDED_COMPHELPER_REFCOUNTEDMUTEX_HXX + +#include +#include +#include + +namespace comphelper +{ +class COMPHELPER_DLLPUBLIC RefCountedMutex final : public salhelper::SimpleReferenceObject +{ + osl::Mutex m_aMutex; + +public: + ~RefCountedMutex() override; + + ::osl::Mutex& GetMutex() { return m_aMutex; } +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_REFCOUNTEDMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/scopeguard.hxx b/include/comphelper/scopeguard.hxx new file mode 100644 index 000000000..95832c505 --- /dev/null +++ b/include/comphelper/scopeguard.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SCOPEGUARD_HXX +#define INCLUDED_COMPHELPER_SCOPEGUARD_HXX + +#include + +#include + +#include + +// For some reason, Android buildbot issues -Werror like this: +// In file included from +// /home/android/lo/master-android-arm/filter/source/xmlfilteradaptor/XmlFilterAdaptor.cxx:50: +// /home/android/lo/master-android-arm/include/comphelper/scopeguard.hxx:36:14: +// error: function 'comphelper::<(lambda at +// /home/android/lo/master-android-arm/filter/source/xmlfilteradaptor/XmlFilterAdaptor.cxx:146:34)>' +// has internal linkage but is not defined [-Werror,-Wundefined-internal] +// explicit ScopeGuard( Func && func ) : m_func( std::move(func) ) {} +// ^ +// /home/android/lo/master-android-arm/filter/source/xmlfilteradaptor/XmlFilterAdaptor.cxx:146:28: +// note: used here +// comphelper::ScopeGuard guard([&]() { +// ^ +#ifdef ANDROID +#if defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundefined-internal" +#endif +#endif + + +namespace comphelper { + +/** ScopeGuard to ease writing exception-safe code. + */ +template class ScopeGuard +{ +public: + /** @param func function object to be executed in dtor + */ + explicit ScopeGuard( Func && func ) : m_func( std::move(func) ) {} + + ~ScopeGuard() + { + if (m_bDismissed) + return; + suppress_fun_call_w_exception(m_func()); + } + + /** Dismisses the scope guard, i.e. the function won't + be executed. + */ + void dismiss() { m_bDismissed = true; } + +private: + // noncopyable until we have good reasons... + ScopeGuard(const ScopeGuard&) = delete; + ScopeGuard& operator=(const ScopeGuard&) = delete; + + Func m_func; + bool m_bDismissed = false; +}; + +} // namespace comphelper + +#ifdef ANDROID +#if defined __clang__ +#pragma clang diagnostic pop +#endif +#endif + +#endif // ! defined(INCLUDED_COMPHELPER_SCOPEGUARD_HXX) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/seekableinput.hxx b/include/comphelper/seekableinput.hxx new file mode 100644 index 000000000..0c2092f7b --- /dev/null +++ b/include/comphelper/seekableinput.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_SEEKABLEINPUT_HXX +#define INCLUDED_COMPHELPER_SEEKABLEINPUT_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { class XComponentContext; } + +namespace comphelper +{ + +class SAL_DLLPUBLIC_TEMPLATE OSeekableInputWrapper_BASE + : public ::cppu::WeakImplHelper< css::io::XInputStream, + css::io::XSeekable > +{}; + +class COMPHELPER_DLLPUBLIC OSeekableInputWrapper final + : public OSeekableInputWrapper_BASE +{ + std::mutex m_aMutex; + + css::uno::Reference< css::uno::XComponentContext > m_xContext; + + css::uno::Reference< css::io::XInputStream > m_xOriginalStream; + + css::uno::Reference< css::io::XInputStream > m_xCopyInput; + css::uno::Reference< css::io::XSeekable > m_xCopySeek; + +private: + COMPHELPER_DLLPRIVATE void PrepareCopy_Impl(); + +public: + OSeekableInputWrapper( + css::uno::Reference< css::io::XInputStream > xInStream, + css::uno::Reference< css::uno::XComponentContext > xContext ); + + virtual ~OSeekableInputWrapper() override; + + static css::uno::Reference< css::io::XInputStream > CheckSeekableCanWrap( + const css::uno::Reference< css::io::XInputStream >& xInStream, + const css::uno::Reference< css::uno::XComponentContext >& rxContext ); + +// XInputStream + virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override; + virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override; + virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override; + virtual sal_Int32 SAL_CALL available() override; + virtual void SAL_CALL closeInput() override; + +// XSeekable + virtual void SAL_CALL seek( sal_Int64 location ) override; + virtual sal_Int64 SAL_CALL getPosition() override; + virtual sal_Int64 SAL_CALL getLength() override; + +}; + +} // namespace comphelper + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/seqstream.hxx b/include/comphelper/seqstream.hxx new file mode 100644 index 000000000..c2ba39134 --- /dev/null +++ b/include/comphelper/seqstream.hxx @@ -0,0 +1,135 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_SEQSTREAM_HXX +#define INCLUDED_COMPHELPER_SEQSTREAM_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper +{ + + +// SequenceInputStream +// stream for reading data from a sequence of bytes + + +class COMPHELPER_DLLPUBLIC SequenceInputStream final + : public ::cppu::WeakImplHelper< css::io::XInputStream, css::io::XSeekable, css::lang::XUnoTunnel >, + public comphelper::ByteReader +{ + std::mutex m_aMutex; + css::uno::Sequence const m_aData; + sal_Int32 m_nPos; + +public: + SequenceInputStream(css::uno::Sequence const & rData); + +// css::io::XInputStream + virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence& aData, sal_Int32 nBytesToRead ) override; + + virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence& aData, sal_Int32 nMaxBytesToRead ) override; + + virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override; + + virtual sal_Int32 SAL_CALL available( ) override; + + virtual void SAL_CALL closeInput( ) override; + + virtual void SAL_CALL seek( sal_Int64 location ) override; + virtual sal_Int64 SAL_CALL getPosition( ) override; + virtual sal_Int64 SAL_CALL getLength( ) override; + +// css::lang::XUnoTunnel + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + +// comphelper::ByteReader + virtual sal_Int32 readSomeBytes( sal_Int8* pData, sal_Int32 nBytesToRead ) override; + +private: + sal_Int32 avail(); +}; + +// don't export to avoid duplicate WeakImplHelper definitions with MSVC +class SAL_DLLPUBLIC_TEMPLATE OSequenceOutputStream_Base + : public ::cppu::WeakImplHelper< css::io::XOutputStream > +{}; + +class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OSequenceOutputStream final : public OSequenceOutputStream_Base +{ +private: + css::uno::Sequence< sal_Int8 >& m_rSequence; + double m_nResizeFactor; + sal_Int32 const m_nMinimumResize; + sal_Int32 m_nSize; + // the size of the virtual stream. This is not the size of the sequence, but the number of bytes written + // into the stream at a given moment. + + bool m_bConnected; + // closeOutput has been called ? + + std::mutex m_aMutex; + + void finalizeOutput(); + virtual ~OSequenceOutputStream() override { if (m_bConnected) finalizeOutput(); } + +public: + /** constructs the object. Everything written into the stream through the XOutputStream methods will be forwarded + to the sequence, reallocating it if necessary. Writing will start at offset 0 within the sequence. + @param _rSeq a reference to the sequence which will be used for output. + The caller is responsible for taking care of the lifetime of the stream + object and the sequence. If you're in doubt about this, use closeOutput + before destroying the sequence + @param _nResizeFactor the factor which is used for resizing the sequence when necessary. In every + resize step, the new sequence size will be calculated by multiplying the current + size with this factor, rounded off to the next multiple of 4. + @param _nMinimumResize the minimal number of bytes which is additionally allocated on resizing + @see closeOutput + */ + OSequenceOutputStream( + css::uno::Sequence< sal_Int8 >& _rSeq, + double _nResizeFactor = 1.3, + sal_Int32 _nMinimumResize = 128 + ); + + /// same as XOutputStream::writeBytes (as expected :) + virtual void SAL_CALL writeBytes( const css::uno::Sequence< sal_Int8 >& aData ) override; + /// this is a dummy in this implementation, no buffering is used + virtual void SAL_CALL flush( ) override; + /** closes the output stream. In the case of this class, this means that the sequence used for writing is + resized to the really used size and not used any further, every subsequent call to one of the XOutputStream + methods will throw a NotConnectedException. + */ + virtual void SAL_CALL closeOutput( ) override; +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_SEQSTREAM_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/sequence.hxx b/include/comphelper/sequence.hxx new file mode 100644 index 000000000..bc67559df --- /dev/null +++ b/include/comphelper/sequence.hxx @@ -0,0 +1,322 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SEQUENCE_HXX +#define INCLUDED_COMPHELPER_SEQUENCE_HXX + +#include +#include + +#include +#include + +namespace comphelper +{ + /** Search the given value within the given sequence, return the position of the first occurrence. + Returns -1 if nothing found. + */ + template + inline sal_Int32 findValue(const css::uno::Sequence& _rList, const T2& _rValue) + { + // at which position do I find the value? + for (sal_Int32 i = 0; i < _rList.getLength(); ++i) + { + if (_rList[i] == _rValue) + return i; + } + + return -1; + } + + /// concat several sequences + template + inline css::uno::Sequence concatSequences(const css::uno::Sequence& rS1, const Ss&... rSn) + { + // unary fold to disallow empty parameter pack: at least have one sequence in rSn + css::uno::Sequence aReturn(std::size(rS1) + (... + std::size(rSn))); + T* pReturn = std::copy(std::begin(rS1), std::end(rS1), aReturn.getArray()); + (..., (pReturn = std::copy(std::begin(rSn), std::end(rSn), pReturn))); + return aReturn; + } + + /// concat additional elements from right sequence to left sequence + /// + /// be aware that this takes time O(|left| * |right|) + template inline css::uno::Sequence combineSequences( + css::uno::Sequence const & left, css::uno::Sequence const & right) + { + sal_Int32 n1 = left.getLength(); + css::uno::Sequence ret(n1 + right.getLength()); + //TODO: check for overflow + auto pRet = ret.getArray(); + std::copy_n(left.getConstArray(), n1, pRet); + sal_Int32 n2 = n1; + for (sal_Int32 i = 0; i != right.getLength(); ++i) { + bool found = false; + for (sal_Int32 j = 0; j != n1; ++j) { + if (right[i] == left[j]) { + found = true; + break; + } + } + if (!found) { + pRet[n2++] = right[i]; + } + } + ret.realloc(n2); + return ret; + } + + /// remove a specified element from a sequences + template + inline void removeElementAt(css::uno::Sequence& _rSeq, sal_Int32 _nPos) + { + sal_Int32 nLength = _rSeq.getLength(); + + OSL_ENSURE(0 <= _nPos && _nPos < nLength, "invalid index"); + + T* pPos = _rSeq.getArray() + _nPos; + std::move(pPos + 1, pPos + nLength - _nPos, pPos); + + _rSeq.realloc(nLength-1); + } + + /** Copy from a plain C/C++ array into a Sequence. + + @tpl SrcType + Array element type. Must be assignable to DstType + + @tpl DstType + Sequence element type. Must be assignable from SrcType + + @param i_pArray + Valid pointer to at least num elements of type SrcType + + @param nNum + Number of array elements to copy + + @return the resulting Sequence + + @attention when copying from e.g. a double array to a + Sequence, no proper rounding will be performed, but the + values will be truncated. There's currently no measure to + prevent or detect precision loss, overflow or truncation. + */ + template < typename DstType, typename SrcType > + inline css::uno::Sequence< DstType > arrayToSequence( const SrcType* i_pArray, sal_Int32 nNum ) + { + if constexpr (std::is_same_v< DstType, SrcType >) + { + return css::uno::Sequence< DstType >( i_pArray, nNum ); + } + else + { + css::uno::Sequence< DstType > result( nNum ); + ::std::copy( i_pArray, i_pArray+nNum, result.getArray() ); + return result; + } + } + + + /** Copy from a Sequence into a plain C/C++ array + + @tpl SrcType + Sequence element type. Must be assignable to DstType + + @tpl DstType + Array element type. Must be assignable from SrcType + + @param io_pArray + Valid pointer to at least i_Sequence.getLength() elements of + type DstType + + @param i_Sequence + Reference to a Sequence of SrcType elements + + @return a pointer to the array + + @attention when copying from e.g. a Sequence to an int + array, no proper rounding will be performed, but the values + will be truncated. There's currently no measure to prevent or + detect precision loss, overflow or truncation. + */ + template < typename DstType, typename SrcType > + inline DstType* sequenceToArray( DstType* io_pArray, const css::uno::Sequence< SrcType >& i_Sequence ) + { + ::std::copy( i_Sequence.begin(), i_Sequence.end(), io_pArray ); + return io_pArray; + } + + + /** Copy from a container into a Sequence + + @tpl SrcType + Container type. This type must fulfill the STL container + concept, in particular, the size(), begin() and end() methods + must be available and have the usual semantics. + + @tpl DstType + Sequence element type. Must be assignable from SrcType's + elements + + @param i_Container + Reference to the input contain with elements of type SrcType + + @return the generated Sequence + + @attention this function always performs a copy. Furthermore, + when copying from e.g. a vector to a Sequence, no + proper rounding will be performed, but the values will be + truncated. There's currently no measure to prevent or detect + precision loss, overflow or truncation. + */ + template < typename DstElementType, typename SrcType > + inline css::uno::Sequence< DstElementType > containerToSequence( const SrcType& i_Container ) + { + using ::std::size, ::std::begin, ::std::end; + css::uno::Sequence< DstElementType > result( size(i_Container) ); + ::std::copy( begin(i_Container), end(i_Container), result.getArray() ); + return result; + } + + // this one does better type deduction, but does not allow us to copy into a different element type + template < typename SrcType > + inline css::uno::Sequence< typename SrcType::value_type > containerToSequence( const SrcType& i_Container ) + { + return containerToSequence(i_Container); + } + + // handle arrays + template + inline css::uno::Sequence< ElementType > containerToSequence( ElementType const (&i_Array)[ SrcSize ] ) + { + return css::uno::Sequence< ElementType >( i_Array, SrcSize ); + } + + template + inline css::uno::Sequence containerToSequence( + ::std::vector const& v ) + { + return css::uno::Sequence( + v.data(), static_cast(v.size()) ); + } + + + /** Copy from a Sequence into a container + + @tpl SrcType + Sequence element type. Must be assignable to SrcType's + elements + + @tpl DstType + Container type. This type must have a constructor taking a pair + of iterators defining a range to copy from + + @param i_Sequence + Reference to a Sequence of SrcType elements + + @return the generated container. C++17 copy elision rules apply + + @attention this function always performs a copy. Furthermore, + when copying from e.g. a Sequence to a vector, no + proper rounding will be performed, but the values will be + truncated. There's currently no measure to prevent or detect + precision loss, overflow or truncation. + */ + template < typename DstType, typename SrcType > + inline DstType sequenceToContainer( const css::uno::Sequence< SrcType >& i_Sequence ) + { + return DstType(i_Sequence.begin(), i_Sequence.end()); + } + + // this one does better type deduction, but does not allow us to copy into a different element type + template < typename DstType > + inline DstType sequenceToContainer( const css::uno::Sequence< typename DstType::value_type >& i_Sequence ) + { + return DstType(i_Sequence.begin(), i_Sequence.end()); + } + + /** Copy from a Sequence into an existing container + + This potentially saves a needless extra copy operation over + the whole container, as it passes the target object by + reference. + + @tpl SrcType + Sequence element type. Must be assignable to SrcType's + elements + + @tpl DstType + Container type. This type must fulfill the STL container and + sequence concepts, in particular, the begin(), end() and + resize(int) methods must be available and have the usual + semantics. + + @param o_Output + Reference to the target container + + @param i_Sequence + Reference to a Sequence of SrcType elements + + @return a non-const reference to the given container + + @attention this function always performs a copy. Furthermore, + when copying from e.g. a Sequence to a vector, no + proper rounding will be performed, but the values will be + truncated. There's currently no measure to prevent or detect + precision loss, overflow or truncation. + */ + template < typename DstType, typename SrcType > + inline DstType& sequenceToContainer( DstType& o_Output, const css::uno::Sequence< SrcType >& i_Sequence ) + { + o_Output.resize( i_Sequence.getLength() ); + ::std::copy( i_Sequence.begin(), i_Sequence.end(), o_Output.begin() ); + return o_Output; + } + + /** Copy (keys or values) from an associate container into a Sequence + + @tpl M map container type eg. std::map/std::unordered_map + + @return the generated Sequence + */ + template < typename M > + inline css::uno::Sequence< typename M::key_type > mapKeysToSequence( M const& map ) + { + css::uno::Sequence< typename M::key_type > ret( static_cast(map.size()) ); + std::transform(map.begin(), map.end(), ret.getArray(), + [](const auto& i) { return i.first; }); + return ret; + } + + template < typename M > + inline css::uno::Sequence< typename M::mapped_type > mapValuesToSequence( M const& map ) + { + css::uno::Sequence< typename M::mapped_type > ret( static_cast(map.size()) ); + std::transform(map.begin(), map.end(), ret.getArray(), + [](const auto& i) { return i.second; }); + return ret; + } + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_SEQUENCE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/sequenceashashmap.hxx b/include/comphelper/sequenceashashmap.hxx new file mode 100644 index 000000000..59ab4c298 --- /dev/null +++ b/include/comphelper/sequenceashashmap.hxx @@ -0,0 +1,426 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SEQUENCEASHASHMAP_HXX +#define INCLUDED_COMPHELPER_SEQUENCEASHASHMAP_HXX + +#include +#include + +#include + +namespace com::sun::star::beans { struct NamedValue; } +namespace com::sun::star::beans { struct PropertyValue; } + +namespace comphelper{ + + +/** @short Implements a stl hash map on top of some + specialized sequence from type PropertyValue + or NamedValue. + + @descr That provides the possibility to modify + such name sequences very easy ... + */ + +/** Cache the hash code since calculating it for every comparison adds up */ +struct OUStringAndHashCode +{ + OUString maString; + sal_Int32 mnHashCode; + + OUStringAndHashCode(OUString s) : maString(s), mnHashCode(maString.hashCode()) {} +}; +struct OUStringAndHashCodeEqual +{ + bool operator()(const OUStringAndHashCode & lhs, const OUStringAndHashCode & rhs) const + { + return lhs.mnHashCode == rhs.mnHashCode && lhs.maString == rhs.maString; + } +}; +struct OUStringAndHashCodeHash +{ + size_t operator()(const OUStringAndHashCode & i) const + { + return i.mnHashCode; + } +}; +using SequenceAsHashMapBase = std::unordered_map; + +class SAL_WARN_UNUSED COMPHELPER_DLLPUBLIC SequenceAsHashMap +{ + + public: + + + /** @short creates an empty hash map. + */ + SequenceAsHashMap(); + + + /** @see operator<<(const css::uno::Any&) + */ + SequenceAsHashMap(const css::uno::Any& aSource); + + + /** @see operator<<(const css::uno::Sequence< css::uno::Any >&) + */ + SequenceAsHashMap(const css::uno::Sequence< css::uno::Any >& lSource); + + + /** @see operator<<(const css::uno::Sequence< css::beans::PropertyValue >&) + */ + SequenceAsHashMap(const css::uno::Sequence< css::beans::PropertyValue >& lSource); + + + /** @see operator<<(const css::uno::Sequence< css::beans::NamedValue >&) + */ + SequenceAsHashMap(const css::uno::Sequence< css::beans::NamedValue >& lSource); + + + /** @short fill this map from the given + Any, which of course must contain + a suitable sequence of element types + "css.beans.PropertyValue" or "css.beans.NamedValue". + + @attention If the given Any is an empty one + (if it's set to VOID), no exception + is thrown. In such case this instance will + be created as an empty one too! + + @param aSource + contains the new items for this map. + + @throw A css::lang::IllegalArgumentException + is thrown, if the given Any does not contain a suitable sequence ... + but not if it's a VOID Any! + */ + void operator<<(const css::uno::Any& aSource); + + + /** @short fill this map from the given + sequence, where every Any must contain + an item from type "css.beans.PropertyValue" + "css.beans.NamedValue". + + @param lSource + contains the new items for this map. + + @throw A css::lang::IllegalArgumentException + is thrown, if the given Any sequence + uses wrong types for its items. VOID Any will be ignored! + */ + void operator<<(const css::uno::Sequence< css::uno::Any >& lSource); + + + /** @short fill this map from the given + PropertyValue sequence. + + @param lSource + contains the new items for this map. + */ + void operator<<(const css::uno::Sequence< css::beans::PropertyValue >& lSource); + + + /** @short fill this map from the given + NamedValue sequence. + + @param lSource + contains the new items for this map. + */ + void operator<<(const css::uno::Sequence< css::beans::NamedValue >& lSource); + + + /** @short converts this map instance to an + PropertyValue sequence. + + @param lDestination + target sequence for converting. + */ + void operator>>(css::uno::Sequence< css::beans::PropertyValue >& lDestination) const; + + + /** @short converts this map instance to an + NamedValue sequence. + + @param lDestination + target sequence for converting. + */ + void operator>>(css::uno::Sequence< css::beans::NamedValue >& lDestination) const; + + + /** @short return this map instance as an + Any, which can be + used in const environments only. + + @descr It's made const to prevent using of the + return value directly as an in/out parameter! + usage: myMethod(stlDequeAdapter.getAsAnyList()); + + @param bAsPropertyValue + switch between using of PropertyValue or NamedValue as + value type. + + @return A const Any, which + contains all items of this map. + */ + css::uno::Any getAsConstAny(bool bAsPropertyValue) const; + + + /** @short return this map instance to as a + NamedValue sequence, which can be + used in const environments only. + + @descr It's made const to prevent using of the + return value directly as an in/out parameter! + usage: myMethod(stlDequeAdapter.getAsNamedValueList()); + + @return A const sequence of type NamedValue, which + contains all items of this map. + */ + css::uno::Sequence< css::beans::NamedValue > getAsConstNamedValueList() const; + + + /** @short return this map instance to as a + PropertyValue sequence, which can be + used in const environments only. + + @descr It's made const to prevent using of the + return value directly as an in/out parameter! + usage: myMethod(stlDequeAdapter.getAsPropertyValueList()); + + @return A const sequence of type PropertyValue, which + contains all items of this map. + */ + css::uno::Sequence< css::beans::PropertyValue > getAsConstPropertyValueList() const; + + + /** @short check if the specified item exists + and return its (unpacked!) value or it returns the + specified default value otherwise. + + @descr If a value should be extracted only in case + the requested property exists really (without creating + of new items as it the index operator of a + hash map does!) this method can be used. + + @param sKey + key name of the item. + + @param aDefault + the default value, which is returned + if the specified item could not + be found. + + @return The (unpacked!) value of the specified property or + the given default value otherwise. + + @attention "unpacked" means the Any content of every iterator->second! + */ + template< class TValueType > + TValueType getUnpackedValueOrDefault(const OUString& sKey , + const TValueType& aDefault) const + { + auto pIt = m_aMap.find(sKey); + if (pIt == m_aMap.end()) + return aDefault; + + TValueType aValue = TValueType(); + if (!(pIt->second >>= aValue)) + return aDefault; + + return aValue; + } + + /** @short check if the specified item exists + and return its value or it returns + an empty css::uno::Any. + + @descr If a value should be extracted only in case + the requested property exists really (without creating + of new items as the index operator of a + hash map does!) this method can be used. + + @param sKey + key name of the item. + + @return The value of the specified property or + an empty css::uno::Any. + */ + css::uno::Any getValue(const OUString& sKey) const + { + auto pIt = m_aMap.find(sKey); + if (pIt == m_aMap.end()) + return css::uno::Any(); + + return pIt->second; + } + + + /** @short creates a new item with the specified + name and value only in case such item name + does not already exist. + + @descr To check if the property already exists only + its name is used for compare. Its value isn't + checked! + + @param sKey + key name of the property. + + @param aValue + the new (unpacked!) value. + Note: This value will be transformed to an Any + internally, because only Any values can be + part of a PropertyValue or NamedValue structure. + + @return TRUE if this property was added as new item; + FALSE if it already exists. + */ + template< class TValueType > + bool createItemIfMissing(const OUString& sKey , + const TValueType& aValue) + { + if (m_aMap.find(sKey) == m_aMap.end()) + { + (*this)[sKey] = css::uno::toAny(aValue); + return true; + } + + return false; + } + + + /** @short check if all items of given map + exists in these called map also. + + @descr Every item of the given map must exists + with same name and value inside these map. + But these map can contain additional items + which are not part of the search-map. + + @param rCheck + the map containing all items for checking. + + @return + TRUE if all items of Rcheck could be found + in these map; FALSE otherwise. + */ + bool match(const SequenceAsHashMap& rCheck) const; + + + /** @short merge all values from the given map into + this one. + + @descr Existing items will be overwritten ... + missing items will be created new ... + but non specified items will stay alive ! + + @param rSource + the map containing all items for the update. + */ + void update(const SequenceAsHashMap& rSource); + + css::uno::Any& operator[](const OUString& rKey) + { + return m_aMap[rKey]; + } + + css::uno::Any& operator[](const OUStringAndHashCode& rKey) + { + return m_aMap[rKey]; + } + + using iterator = SequenceAsHashMapBase::iterator; + using const_iterator = SequenceAsHashMapBase::const_iterator; + + void clear() + { + m_aMap.clear(); + } + + size_t size() const + { + return m_aMap.size(); + } + + bool empty() const + { + return m_aMap.empty(); + } + + iterator begin() + { + return m_aMap.begin(); + } + + const_iterator begin() const + { + return m_aMap.begin(); + } + + iterator end() + { + return m_aMap.end(); + } + + const_iterator end() const + { + return m_aMap.end(); + } + + iterator find(const OUString& rKey) + { + return m_aMap.find(rKey); + } + + const_iterator find(const OUString& rKey) const + { + return m_aMap.find(rKey); + } + + iterator find(const OUStringAndHashCode& rKey) + { + return m_aMap.find(rKey); + } + + const_iterator find(const OUStringAndHashCode& rKey) const + { + return m_aMap.find(rKey); + } + + iterator erase(iterator it) + { + return m_aMap.erase(it); + } + + size_t erase(const OUString& rKey) + { + return m_aMap.erase(rKey); + } + +private: + SequenceAsHashMapBase m_aMap; +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_SEQUENCEASHASHMAP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/servicedecl.hxx b/include/comphelper/servicedecl.hxx new file mode 100644 index 000000000..57da446e6 --- /dev/null +++ b/include/comphelper/servicedecl.hxx @@ -0,0 +1,155 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_SERVICEDECL_HXX +#define INCLUDED_COMPHELPER_SERVICEDECL_HXX + +#include +#include +#include + +#include +#include + +namespace comphelper::service_decl { + +class ServiceDecl; + +namespace detail { +typedef ::std::function< + css::uno::Reference /* return */ + (ServiceDecl const&, + css::uno::Sequence const&, + css::uno::Reference const&)> CreateFuncF; +} + +/** Class to declare a service implementation. There is no need to implement + lang::XServiceInfo nor lang::XInitialization anymore. + The declaration can be done in various ways, the (simplest) form is + +
+    class MyClass : public cppu::WeakImplHelper {
+    public:
+        MyClass( uno::Reference const& xContext )
+        [...]
+    };
+    [...]
+    namespace sdecl = comphelper::service_decl;
+    sdecl::ServiceDecl const myDecl(
+        sdecl::class_(),
+        "my.unique.implementation.name",
+        "MyServiceSpec1;MyServiceSpec2" );
+    
+ + If the service demands initialization by arguments, the implementation + class has to define a constructor taking both arguments and component + context: + +
+    class MyClass : public cppu::WeakImplHelper {
+    public:
+        MyClass( uno::Sequence const& args,
+                 uno::Reference const& xContext )
+        [...]
+    };
+    [...]
+    namespace sdecl = comphelper::service_decl;
+    sdecl::ServiceDecl const myDecl(
+        sdecl::class_ >(),
+        "my.unique.implementation.name",
+        "MyServiceSpec1;MyServiceSpec2" );
+    
+ + Additionally, there is the possibility to process some code after creation, + e.g. to add the newly created object as a listener or perform aggregation + (C++-UNO only): + +
+    uno::Reference somePostProcCode( MyClass * p );
+    [...]
+    namespace sdecl = comphelper::service_decl;
+    sdecl::ServiceDecl const myDecl(
+        sdecl::class_(&somePostProcCode),
+        "my.unique.implementation.name",
+        "MyServiceSpec1;MyServiceSpec2" );
+    
+ + In the latter case, somePostProcCode gets the yet unacquired "raw" pointer. +*/ +class COMPHELPER_DLLPUBLIC ServiceDecl +{ +public: + /** Ctor for multiple supported service names. + + @param implClass implementation class description + @param pImplName implementation name + @param pSupportedServiceNames supported service names + @param cDelim delimiter for supported service names + */ + ServiceDecl( const ServiceDecl& ) = delete; + ServiceDecl& operator=( const ServiceDecl& ) = delete; + template + ServiceDecl( ImplClassT const& implClass, + char const* pImplName, + char const* pSupportedServiceNames ) + : m_createFunc(implClass.m_createFunc), + m_pImplName(pImplName), + m_pServiceNames(pSupportedServiceNames) {} + + /// @internal gets called by component_getFactoryHelper() + void * getFactory( char const* pImplName ) const; + + /// @return supported service names + css::uno::Sequence< OUString> getSupportedServiceNames() const; + + /// @return whether name is in set of supported service names + bool supportsService( std::u16string_view name ) const; + + /// @return implementation name + OUString getImplementationName() const; + +private: + class Factory; + friend class Factory; + + detail::CreateFuncF const m_createFunc; + char const* const m_pImplName; + char const* const m_pServiceNames; +}; + +/** To specify whether the implementation class expects arguments + (uno::Sequence). +*/ +template struct with_args; + +/// @internal +namespace detail { + +} // namespace detail + + +COMPHELPER_DLLPUBLIC +void* component_getFactoryHelper( const char* pImplName, + std::initializer_list args ); + +} // namespace comphelper::service_decl + + +#endif // ! defined( INCLUDED_COMPHELPER_SERVICEDECL_HXX) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/servicehelper.hxx b/include/comphelper/servicehelper.hxx new file mode 100644 index 000000000..c225494cc --- /dev/null +++ b/include/comphelper/servicehelper.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SERVICEHELPER_HXX +#define INCLUDED_COMPHELPER_SERVICEHELPER_HXX + +#include +#include +#include + +namespace comphelper { + + // Class incapsulating UIDs used as e.g. tunnel IDs for css::lang::XUnoTunnel, + // or implementation IDs for css::lang::XTypeProvider + class UnoIdInit + { + private: + css::uno::Sequence< sal_Int8 > m_aSeq; + public: + UnoIdInit() : m_aSeq(16) + { + rtl_createUuid(reinterpret_cast(m_aSeq.getArray()), nullptr, true); + } + const css::uno::Sequence< sal_Int8 >& getSeq() const { return m_aSeq; } + }; + + inline sal_Int64 getSomething_cast(void* p) + { + return sal::static_int_cast(reinterpret_cast(p)); + } + + template inline T* getSomething_cast(sal_Int64 n) + { + return reinterpret_cast(sal::static_int_cast(n)); + } + + template T* getFromUnoTunnel(const css::uno::Reference& xUT) + { + if (!xUT.is()) + return nullptr; + + return getSomething_cast(xUT->getSomething(T::getUnoTunnelId())); + } + + // Takes an interface + template T* getFromUnoTunnel(const css::uno::Reference& xIface) + { + return getFromUnoTunnel( + css::uno::Reference{ xIface, css::uno::UNO_QUERY }); + } + + // Takes an Any + template T* getFromUnoTunnel(const css::uno::Any& rAny) + { + // For unclear reason, using a Reference ctor taking an Any + // gives different results compared to use of operator >>=. + css::uno::Reference xUnoTunnel; + rAny >>= xUnoTunnel; + return getFromUnoTunnel(xUnoTunnel); + } + + template + inline bool isUnoTunnelId(const css::uno::Sequence< sal_Int8 >& rId) + { + return rId.getLength() == 16 + && memcmp(T::getUnoTunnelId().getConstArray(), rId.getConstArray(), 16) == 0; + } + + template struct FallbackToGetSomethingOf + { + static sal_Int64 get(const css::uno::Sequence& rId, Base* p) + { + return p->Base::getSomething(rId); + } + }; + + template <> struct FallbackToGetSomethingOf + { + static sal_Int64 get(const css::uno::Sequence&, void*) { return 0; } + }; + + template + sal_Int64 getSomethingImpl(const css::uno::Sequence& rId, T* pThis, + FallbackToGetSomethingOf = {}) + { + if (isUnoTunnelId(rId)) + return getSomething_cast(pThis); + + return FallbackToGetSomethingOf::get(rId, pThis); + } + +} + +/** the UNO3_GETIMPLEMENTATION_* macros implement a static helper function + that gives access to your implementation for a given interface reference, + if possible. + + Example: + MyClass* pClass = comphelper::getFromUnoTunnel( xRef ); + + Usage: + Put a UNO3_GETIMPLEMENTATION_DECL( classname ) inside your class + definition and UNO3_GETIMPLEMENTATION_IMPL( classname ) inside + your cxx file. Your class must inherit css::lang::XUnoTunnel + and export it with queryInterface. Implementation of XUnoTunnel is + done by this macro. +*/ +#define UNO3_GETIMPLEMENTATION_DECL( classname ) \ + static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId() noexcept; \ + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + +#define UNO3_GETIMPLEMENTATION_BASE_IMPL( classname ) \ +const css::uno::Sequence< sal_Int8 > & classname::getUnoTunnelId() noexcept \ +{ \ + static const comphelper::UnoIdInit aId; \ + return aId.getSeq(); \ +} + +#define UNO3_GETIMPLEMENTATION_IMPL( classname )\ +UNO3_GETIMPLEMENTATION_BASE_IMPL(classname)\ +sal_Int64 SAL_CALL classname::getSomething( const css::uno::Sequence< sal_Int8 >& rId ) \ +{ \ + return comphelper::getSomethingImpl(rId, this); \ +} + +#define UNO3_GETIMPLEMENTATION2_IMPL( classname, baseclass )\ +UNO3_GETIMPLEMENTATION_BASE_IMPL(classname)\ +sal_Int64 SAL_CALL classname::getSomething( const css::uno::Sequence< sal_Int8 >& rId ) \ +{ \ + return comphelper::getSomethingImpl(rId, this, comphelper::FallbackToGetSomethingOf{}); \ +} + + +#endif // INCLUDED_COMPHELPER_SERVICEHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/sharedmutex.hxx b/include/comphelper/sharedmutex.hxx new file mode 100644 index 000000000..a92c7ccb3 --- /dev/null +++ b/include/comphelper/sharedmutex.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SHAREDMUTEX_HXX +#define INCLUDED_COMPHELPER_SHAREDMUTEX_HXX + +#include +#include + +namespace osl { class Mutex; } + +namespace comphelper +{ + + + //= SharedMutex + + class COMPHELPER_DLLPUBLIC SharedMutex + { + public: + SharedMutex(); + + operator ::osl::Mutex& () { return *m_pMutexImpl; } + + private: + std::shared_ptr< ::osl::Mutex > m_pMutexImpl; + }; + + + //= SharedMutexBase + + /** sometimes, it's necessary to have an initialized ::osl::Mutex to pass + to some ctor call of your base class. In this case, you can't hold the + SharedMutex as member, but you need to move it into another base class, + which is initialized before the mutex-requiring class is. + */ + class COMPHELPER_DLLPUBLIC SharedMutexBase + { + protected: + SharedMutexBase() + { + } + ~SharedMutexBase() + { + } + + protected: + ::osl::Mutex& getMutex() const { return m_aMutex; } + SharedMutex& getSharedMutex() const { return m_aMutex; } + + private: + mutable SharedMutex m_aMutex; + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_SHAREDMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/simplefileaccessinteraction.hxx b/include/comphelper/simplefileaccessinteraction.hxx new file mode 100644 index 000000000..e9295d4d7 --- /dev/null +++ b/include/comphelper/simplefileaccessinteraction.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_SIMPLEFILEACCESSINTERACTION_HXX +#define INCLUDED_COMPHELPER_SIMPLEFILEACCESSINTERACTION_HXX + +#include +#include +#include + +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::task { class XInteractionRequest; } + +namespace comphelper { +/** An interaction handler wrapper for simple file access. + + This wrapper is to be used together with XSimpleFileAccess when + you want to avoid the error messages displayed when accessing a file (the messages activated + by ucphelper::cancelCommandExecution). + + This wrapper is especially useful when you need to access a Web/DAV connection + enabling https certificate validation and optionally enabling the authentication + dialog that may be needed in these operations. + + @param xHandler + Used handler, always needed. + It will be used for Certificate Validation dialog or authentication dialog. + The authentication is used in Web/DAV access when the server requests credentials to be accessed. +*/ +class COMPHELPER_DLLPUBLIC SimpleFileAccessInteraction final : public ::ucbhelper::InterceptedInteraction +{ + +public: + SimpleFileAccessInteraction(const css::uno::Reference< css::task::XInteractionHandler >& xHandler); + virtual ~SimpleFileAccessInteraction() override; + +private: + + virtual ucbhelper::InterceptedInteraction::EInterceptionState intercepted(const ::ucbhelper::InterceptedInteraction::InterceptedRequest& aRequest, + const css::uno::Reference< css::task::XInteractionRequest >& xRequest) override; + +}; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/solarmutex.hxx b/include/comphelper/solarmutex.hxx new file mode 100644 index 000000000..4094e08ee --- /dev/null +++ b/include/comphelper/solarmutex.hxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SOLARMUTEX_HXX +#define INCLUDED_COMPHELPER_SOLARMUTEX_HXX + +#include + +#include +#include + +#include +#include +#include + +namespace comphelper { + + +/** + * SolarMutex, needed for VCL's Application::GetSolarMutex(). + * + * The SolarMutex is the one big recursive code lock used + * to protect the vast majority of the LibreOffice code-base, + * in particular anything that is graphical and the cores of + * the applications. + * + * Treat this as a singleton, as its constructor sets a global + * pointing at itself. + */ +class COMPHELPER_DLLPUBLIC SolarMutex { +public: + typedef void (*BeforeReleaseHandler) (); + + SolarMutex(); + virtual ~SolarMutex(); + + void SetBeforeReleaseHandler( const BeforeReleaseHandler& rLink ) + { m_aBeforeReleaseHandler = rLink; } + + void acquire( sal_uInt32 nLockCount = 1 ); + sal_uInt32 release( bool bUnlockAll = false ); + + virtual bool tryToAcquire(); + + // returns true, if the mutex is owned by the current thread + virtual bool IsCurrentThread() const; + + /// Help components to get the SolarMutex easily. + static SolarMutex *get(); + +protected: + virtual sal_uInt32 doRelease( bool bUnlockAll ); + virtual void doAcquire( sal_uInt32 nLockCount ); + + osl::Mutex m_aMutex; + sal_uInt32 m_nCount; + +private: + std::atomic m_nThreadId; + + SolarMutex(const SolarMutex&) = delete; + SolarMutex& operator=(const SolarMutex&) = delete; + + BeforeReleaseHandler m_aBeforeReleaseHandler; +}; + +inline void SolarMutex::acquire( sal_uInt32 nLockCount ) +{ + assert( nLockCount > 0 ); + doAcquire( nLockCount ); +} + +inline sal_uInt32 SolarMutex::release( bool bUnlockAll ) +{ + return doRelease( bUnlockAll ); +} + +} + +#endif // INCLUDED_COMPHELPER_SOLARMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/stillreadwriteinteraction.hxx b/include/comphelper/stillreadwriteinteraction.hxx new file mode 100644 index 000000000..fb03a7ad1 --- /dev/null +++ b/include/comphelper/stillreadwriteinteraction.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_STILLREADWRITEINTERACTION_HXX +#define INCLUDED_COMPHELPER_STILLREADWRITEINTERACTION_HXX + +#include +#include + +#include + +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::task { class XInteractionRequest; } + + +namespace comphelper{ +class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) StillReadWriteInteraction final : public ::ucbhelper::InterceptedInteraction +{ +private: + static const sal_Int32 HANDLE_INTERACTIVEIOEXCEPTION = 0; + static const sal_Int32 HANDLE_UNSUPPORTEDDATASINKEXCEPTION = 1; + static const sal_Int32 HANDLE_AUTHENTICATIONREQUESTEXCEPTION = 2; + static const sal_Int32 HANDLE_CERTIFICATEVALIDATIONREQUESTEXCEPTION = 3; + + bool m_bUsed; + bool m_bHandledByMySelf; + +public: + StillReadWriteInteraction(const css::uno::Reference< css::task::XInteractionHandler >& xHandler, + css::uno::Reference< css::task::XInteractionHandler > xAuxiliaryHandler); + + void resetInterceptions(); + void resetErrorStates(); + bool wasWriteError() const { return (m_bUsed && m_bHandledByMySelf);} + +private: + css::uno::Reference< css::task::XInteractionHandler > m_xAuxiliaryHandler; + + virtual ucbhelper::InterceptedInteraction::EInterceptionState intercepted(const ::ucbhelper::InterceptedInteraction::InterceptedRequest& aRequest, + const css::uno::Reference< css::task::XInteractionRequest >& xRequest) override; + +}; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/stl_types.hxx b/include/comphelper/stl_types.hxx new file mode 100644 index 000000000..6b21dd77d --- /dev/null +++ b/include/comphelper/stl_types.hxx @@ -0,0 +1,176 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_STL_TYPES_HXX +#define INCLUDED_COMPHELPER_STL_TYPES_HXX + +#include + +#include +#include +#include + +#include +#include +#include + +namespace com::sun::star::uno { template class Reference; } + +namespace comphelper +{ + +// comparison functors + +struct UStringMixLess +{ + bool m_bCaseSensitive; +public: + UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){} + bool operator() (std::u16string_view x, std::u16string_view y) const + { + if (m_bCaseSensitive) + return x < y; + else + return o3tl::compareToIgnoreAsciiCase(x, y) < 0; + } + + bool isCaseSensitive() const {return m_bCaseSensitive;} +}; + +class UStringMixEqual +{ + bool const m_bCaseSensitive; + +public: + UStringMixEqual(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){} + bool operator() (std::u16string_view lhs, std::u16string_view rhs) const + { + return m_bCaseSensitive ? lhs == rhs : o3tl::equalsIgnoreAsciiCase( lhs, rhs ); + } + bool isCaseSensitive() const {return m_bCaseSensitive;} +}; + +/// by-value less functor for std::set> +template struct UniquePtrValueLess +{ + bool operator()(std::unique_ptr const& lhs, + std::unique_ptr const& rhs) const + { + assert(lhs.get()); + assert(rhs.get()); + return (*lhs) < (*rhs); + } + // The following are so we can search in std::set without allocating a temporary entry on the heap + typedef bool is_transparent; + bool operator()(T const& lhs, + std::unique_ptr const& rhs) const + { + assert(rhs.get()); + return lhs < (*rhs); + } + bool operator()(std::unique_ptr const& lhs, + T const& rhs) const + { + assert(lhs.get()); + return (*lhs) < rhs; + } +}; + +/// by-value implementation of std::foo>::operator== +template class C, typename T, typename... Etc> +bool ContainerUniquePtrEquals( + C, Etc...> const& lhs, + C, Etc...> const& rhs) +{ + return lhs.size() == rhs.size() + && std::equal(lhs.begin(), lhs.end(), rhs.begin(), + [](const auto& p1, const auto& p2) { return *p1 == *p2; }); +}; + + +template +class mem_fun1_t +{ + typedef void (Tp::*_fun_type)(Arg); +public: + explicit mem_fun1_t(_fun_type pf) : M_f(pf) {} + void operator()(Tp* p, Arg x) const { (p->*M_f)(x); } +private: + _fun_type const M_f; +}; + +template +inline mem_fun1_t mem_fun(void (Tp::*f)(Arg)) +{ + return mem_fun1_t(f); +} + +/** output iterator that appends OUStrings into an OUStringBuffer. + */ +class OUStringBufferAppender +{ +public: + typedef OUStringBufferAppender Self; + typedef ::std::output_iterator_tag iterator_category; + typedef void value_type; + typedef void reference; + typedef void pointer; + typedef size_t difference_type; + + OUStringBufferAppender(OUStringBuffer & i_rBuffer) + : m_rBuffer(&i_rBuffer) { } + Self & operator=(std::u16string_view i_rStr) + { + m_rBuffer->append( i_rStr ); + return *this; + } + Self & operator*() { return *this; } // so operator= works + Self & operator++() { return *this; } + +private: + OUStringBuffer * m_rBuffer; +}; + +/** algorithm similar to std::copy, but inserts a separator between elements. + */ +template< typename ForwardIter, typename OutputIter, typename T > +OutputIter intersperse( + ForwardIter start, ForwardIter end, OutputIter out, T const & separator) +{ + if (start != end) { + *out = *start; + ++start; + ++out; + } + + while (start != end) { + *out = separator; + ++out; + *out = *start; + ++start; + ++out; + } + + return out; +} + +} + +#endif // INCLUDED_COMPHELPER_STL_TYPES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/storagehelper.hxx b/include/comphelper/storagehelper.hxx new file mode 100644 index 000000000..c6c47c1a5 --- /dev/null +++ b/include/comphelper/storagehelper.hxx @@ -0,0 +1,206 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_STORAGEHELPER_HXX +#define INCLUDED_COMPHELPER_STORAGEHELPER_HXX + +#include +#include +#include +#include +#include +#include + +inline constexpr OUStringLiteral PACKAGE_STORAGE_FORMAT_STRING = u"PackageFormat"; +inline constexpr OUStringLiteral ZIP_STORAGE_FORMAT_STRING = u"ZipFormat"; +inline constexpr OUStringLiteral OFOPXML_STORAGE_FORMAT_STRING = u"OFOPXMLFormat"; + +inline constexpr OUStringLiteral PACKAGE_ENCRYPTIONDATA_SHA256UTF8 = u"PackageSHA256UTF8EncryptionKey"; +inline constexpr OUStringLiteral PACKAGE_ENCRYPTIONDATA_SHA1UTF8 = u"PackageSHA1UTF8EncryptionKey"; +inline constexpr OUStringLiteral PACKAGE_ENCRYPTIONDATA_SHA1MS1252 = u"PackageSHA1MS1252EncryptionKey"; +inline constexpr OUStringLiteral PACKAGE_ENCRYPTIONDATA_SHA1CORRECT = u"PackageSHA1CorrectEncryptionKey"; + +namespace com::sun::star { + namespace beans { struct NamedValue; } + namespace embed { class XStorage; } + namespace io { + class XInputStream; + class XOutputStream; + class XStream; + } + namespace lang { class XSingleServiceFactory; } + namespace uno { class XComponentContext; } +} + +namespace comphelper { + +// Unfortunately - the impl.s of XStorage like to invalidate all +// their sub streams and storages when you release references, so +// it is necessary to keep references to all storages down the +// path - this is 'beautiful' (TM). So we need this ugly hack: +class COMPHELPER_DLLPUBLIC LifecycleProxy +{ +private: + class Impl; +public: + std::unique_ptr m_xBadness; + LifecycleProxy(); + ~LifecycleProxy(); + // commit the storages: necessary for writes to streams to take effect! + void commitStorages(); +}; + +class COMPHELPER_DLLPUBLIC OStorageHelper +{ +public: + /// @throws css::uno::Exception + static css::uno::Reference< css::lang::XSingleServiceFactory > + GetStorageFactory( + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::lang::XSingleServiceFactory > + GetFileSystemStorageFactory( + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetTemporaryStorage( + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// this one will only return Storage + /// + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageFromURL( + const OUString& aURL, + sal_Int32 nStorageMode, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// this one will return either Storage or FileSystemStorage + /// + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageFromURL2( + const OUString& aURL, + sal_Int32 nStorageMode, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageFromInputStream( + const css::uno::Reference < css::io::XInputStream >& xStream, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageFromStream( + const css::uno::Reference < css::io::XStream >& xStream, + sal_Int32 nStorageMode = css::embed::ElementModes::READWRITE, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// @throws css::uno::Exception + static void CopyInputToOutput( + const css::uno::Reference< css::io::XInputStream >& xInput, + const css::uno::Reference< css::io::XOutputStream >& xOutput ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::io::XInputStream > + GetInputStreamFromURL( + const OUString& aURL, + const css::uno::Reference< css::uno::XComponentContext >& context ); + + /// @throws css::uno::Exception + static void SetCommonStorageEncryptionData( + const css::uno::Reference< css::embed::XStorage >& xStorage, + const css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ); + + // the following method supports only storages of OOo formats + /// @throws css::uno::Exception + static sal_Int32 GetXStorageFormat( + const css::uno::Reference< css::embed::XStorage >& xStorage ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageOfFormatFromURL( + const OUString& aFormat, + const OUString& aURL, + sal_Int32 nStorageMode, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >() ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageOfFormatFromInputStream( + const OUString& aFormat, + const css::uno::Reference < css::io::XInputStream >& xStream, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >(), + bool bRepairStorage = false ); + + /// @throws css::uno::Exception + static css::uno::Reference< css::embed::XStorage > + GetStorageOfFormatFromStream( + const OUString& aFormat, + const css::uno::Reference < css::io::XStream >& xStream, + sal_Int32 nStorageMode = css::embed::ElementModes::READWRITE, + const css::uno::Reference< css::uno::XComponentContext >& rxContext + = css::uno::Reference< css::uno::XComponentContext >(), + bool bRepairStorage = false ); + + static css::uno::Sequence< css::beans::NamedValue > + CreatePackageEncryptionData( + std::u16string_view aPassword ); + + static css::uno::Sequence< css::beans::NamedValue > + CreateGpgPackageEncryptionData(); + + static bool IsValidZipEntryFileName( std::u16string_view aName, bool bSlashAllowed ); + static bool IsValidZipEntryFileName( const sal_Unicode *pChar, sal_Int32 nLength, bool bSlashAllowed ); + + static bool PathHasSegment( std::u16string_view aPath, std::u16string_view aSegment ); + + // Methods to allow easy use of hierarchical names inside storages + + static css::uno::Reference< css::embed::XStorage > GetStorageAtPath( + const css::uno::Reference< css::embed::XStorage > &xStorage, + std::u16string_view aPath, sal_uInt32 nOpenMode, LifecycleProxy const &rNastiness ); + static css::uno::Reference< css::io::XStream > GetStreamAtPath( + const css::uno::Reference< css::embed::XStorage > &xStorage, + std::u16string_view aPath, sal_uInt32 nOpenMode, LifecycleProxy const &rNastiness ); + static css::uno::Reference< css::io::XStream > GetStreamAtPackageURL( + const css::uno::Reference< css::embed::XStorage > &xStorage, + const OUString& rURL, sal_uInt32 const nOpenMode, + LifecycleProxy const & rNastiness ); + + static OUString + GetODFVersionFromStorage(const css::uno::Reference& xStorage); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/streamsection.hxx b/include/comphelper/streamsection.hxx new file mode 100644 index 000000000..fa1fe8ac9 --- /dev/null +++ b/include/comphelper/streamsection.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_STREAMSECTION_HXX +#define INCLUDED_COMPHELPER_STREAMSECTION_HXX + +#include +#include +#include + +namespace com::sun::star::io +{ +class XDataInputStream; +} +namespace com::sun::star::io +{ +class XDataOutputStream; +} +namespace com::sun::star::io +{ +class XMarkableStream; +} + +namespace comphelper +{ +/** implements handling for compatibly reading/writing data from/into an input/output stream. + data written in a block secured by this class should be readable by older versions which + use the same mechanism. +*/ + +class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OStreamSection +{ + css::uno::Reference m_xMarkStream; + css::uno::Reference m_xInStream; + css::uno::Reference m_xOutStream; + + sal_Int32 m_nBlockStart; + sal_Int32 m_nBlockLen; + +public: + /** starts reading of a "skippable" section of data within the given input stream
+ @param _rxInput the stream to read from. Must support the + css::io::XMarkableStream interface + */ + OStreamSection(const css::uno::Reference& _rxInput); + + /** starts writing of a "skippable" section of data into the given output stream + @param _rxOutput the stream the stream to write to. Must support the + css::io::XMarkableStream interface + */ + OStreamSection(const css::uno::Reference& _rxOutput); + + /** dtor.
If constructed for writing, the section "opened" by this object will be "closed".
+ If constructed for reading, any remaining bytes 'til the end of the section will be skipped. + */ + ~OStreamSection(); +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_STREAMSECTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/string.hxx b/include/comphelper/string.hxx new file mode 100644 index 000000000..a722e2cc4 --- /dev/null +++ b/include/comphelper/string.hxx @@ -0,0 +1,386 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::i18n { class XBreakIterator; } +namespace com::sun::star::i18n { class XCollator; } +namespace com::sun::star::uno { class XComponentContext; } + +// OUString helper functions that are not widespread or mature enough to +// go into the stable URE API: +namespace comphelper::string { + +/** Removes all occurrences of a character from within the source string + + @param rIn The input OUStringBuffer + @param c The character to be removed + + @return The resulting OUStringBuffer + */ +inline OUStringBuffer& remove(OUStringBuffer &rIn, + sal_Unicode c) +{ + sal_Int32 index = 0; + while (true) + { + if (index >= rIn.getLength()) + break; + index = rIn.indexOf(c, index); + if (index == -1) + break; + rIn.remove(index, 1); + } + return rIn; +} + +/** Strips occurrences of a character from the start of the source string + + @param rIn The input OString + @param c The character to be stripped from the start + + @return The resulting OString + */ +COMPHELPER_DLLPUBLIC OString stripStart(const OString& rIn, + char c); +COMPHELPER_DLLPUBLIC std::string_view stripStart(std::string_view rIn, + char c); + +/** Strips occurrences of a character from the start of the source string + + @param rIn The input OUString + @param c The character to be stripped from the start + + @return The resulting OUString + */ +COMPHELPER_DLLPUBLIC OUString stripStart(const OUString& rIn, + sal_Unicode c); +COMPHELPER_DLLPUBLIC std::u16string_view stripStart(std::u16string_view rIn, + sal_Unicode c); + +/** Strips occurrences of a character from the end of the source string + + @param rIn The input OString + @param c The character to be stripped from the end + + @return The resulting OString + */ +COMPHELPER_DLLPUBLIC OString stripEnd(const OString& rIn, + char c); +COMPHELPER_DLLPUBLIC std::string_view stripEnd(std::string_view rIn, + char c); + +/** Strips occurrences of a character from the end of the source string + + @param rIn The input OUString + @param c The character to be stripped from the end + + @return The resulting OUString + */ +COMPHELPER_DLLPUBLIC OUString stripEnd(const OUString& rIn, + sal_Unicode c); +COMPHELPER_DLLPUBLIC std::u16string_view stripEnd(std::u16string_view rIn, + sal_Unicode c); + +/** Strips occurrences of a character from the start and end of the source string + + @param rIn The input OString + @param c The character to be stripped from the start and end + + @return The resulting OString + */ +COMPHELPER_DLLPUBLIC OString strip(const OString& rIn, + char c); +COMPHELPER_DLLPUBLIC std::string_view strip(std::string_view rIn, + char c); + +/** Strips occurrences of a character from the start and end of the source string + + @param rIn The input OUString + @param c The character to be stripped from the start and end + + @return The resulting OUString + */ +COMPHELPER_DLLPUBLIC OUString strip(const OUString& rIn, + sal_Unicode c); +COMPHELPER_DLLPUBLIC std::u16string_view strip(std::u16string_view rIn, + sal_Unicode c); + +/** Returns number of tokens in an OUString + + @param rIn the input OString + @param cTok the character which separate the tokens. + @return the number of tokens +*/ +COMPHELPER_DLLPUBLIC sal_Int32 getTokenCount(std::string_view rIn, char cTok); + +/** Returns number of tokens in an OUString + + @param rIn the input OUString + @param cTok the character which separate the tokens. + @return the number of tokens +*/ +COMPHELPER_DLLPUBLIC sal_Int32 getTokenCount(std::u16string_view rIn, sal_Unicode cTok); + +/** Reverse an OUString's UTF-16 code units. + + @param rIn the input OUString + @return the reversed input +*/ +COMPHELPER_DLLPUBLIC OUString reverseString(std::u16string_view rStr); + +/** Reverse an OString + + @param rIn the input OString + @return the reversed input +*/ +COMPHELPER_DLLPUBLIC OString reverseString(std::string_view rStr); + +/** Reverse an OUString's Unicode code points. +*/ +COMPHELPER_DLLPUBLIC OUString reverseCodePoints(OUString const & str); + +namespace detail +{ + template B& truncateToLength(B& rBuffer, sal_Int32 nLen) + { + if (nLen < rBuffer.getLength()) + rBuffer.setLength(nLen); + return rBuffer; + } +} + +/** Truncate a buffer to a given length. + + If the StringBuffer has more characters than nLength it will be truncated + on the right to nLength characters. + + Has no effect if the StringBuffer is <= nLength + + @param rBuf StringBuffer to operate on + @param nLength Length to truncate the buffer to + + @return rBuf; + */ +inline OUStringBuffer& truncateToLength( + OUStringBuffer& rBuffer, sal_Int32 nLength) +{ + return detail::truncateToLength(rBuffer, nLength); +} + +namespace detail +{ + template B& padToLength(B& rBuffer, sal_Int32 nLen, U cFill) + { + const sal_Int32 nPadLen = nLen - rBuffer.getLength(); + if (nPadLen > 0) + std::fill_n(rBuffer.appendUninitialized(nPadLen), nPadLen, cFill); + return rBuffer; + } +} + +/** Pad a buffer to a given length using a given char. + + If the StringBuffer has less characters than nLength it will be expanded on + the right to nLength characters, with the expansion filled using cFill. + + Has no effect if the StringBuffer is >= nLength + + @param rBuf StringBuffer to operate on + @param nLength Length to pad the buffer to + @param cFill character to fill expansion with + + @return rBuf; + */ +inline OStringBuffer& padToLength( + OStringBuffer& rBuffer, sal_Int32 nLength, + char cFill = '\0') +{ + return detail::padToLength(rBuffer, nLength, cFill); +} + +inline OUStringBuffer& padToLength( + OUStringBuffer& rBuffer, sal_Int32 nLength, + sal_Unicode cFill = '\0') +{ + return detail::padToLength(rBuffer, nLength, cFill); +} + +/** Similar to OUString::replaceAt, but for an OUStringBuffer. + + Replace n = count characters + from position index in this string with newStr. + */ +COMPHELPER_DLLPUBLIC void replaceAt(OUStringBuffer& rIn, sal_Int32 index, sal_Int32 count, std::u16string_view newStr ); + +/** Replace a token in a string + @param rIn OUString in which the token is to be replaced + @param nToken which nToken to replace + @param cTok token delimiter + @param rNewToken replacement token + + @return original string with token nToken replaced by rNewToken + */ +COMPHELPER_DLLPUBLIC OUString setToken(const OUString& rIn, sal_Int32 nToken, sal_Unicode cTok, + std::u16string_view rNewToken); + +/** Find any of a list of code units in the string. + @param rIn OUString to search + @param pChars 0-terminated array of sal_Unicode code units to search for + @param nPos start position + + @return position of first occurrence of any of the elements of pChars + or -1 if none of the code units occur in the string + */ +COMPHELPER_DLLPUBLIC sal_Int32 indexOfAny(std::u16string_view rIn, + sal_Unicode const*const pChars, sal_Int32 const nPos); + +/** Remove any of a list of code units in the string. + @param rIn OUString to search + @param pChars 0-terminated array of sal_Unicode code units to search for + + @return OUString that has all of the pChars code units removed + */ +COMPHELPER_DLLPUBLIC OUString removeAny(std::u16string_view rIn, + sal_Unicode const*const pChars); + +/** Convert a sequence of strings to a single comma separated string. + + Note that no escaping of commas or anything fancy is done. + + @param i_rSeq A list of strings to be concatenated. + + @return A single string containing the concatenation of the given + list, interspersed with the string ", ". + */ +COMPHELPER_DLLPUBLIC OUString convertCommaSeparated( + css::uno::Sequence< OUString > const & i_rSeq); + +/// Return a string which is the concatenation of the strings in the sequence. +COMPHELPER_DLLPUBLIC OString join(std::string_view rSeparator, const std::vector& rSequence); + +/** Convert a decimal string to a number. + + The string must be base-10, no sign but can contain any + codepoint listed in the "Number, Decimal Digit" Unicode + category. + + No verification is made about the validity of the string, + passing string not containing decimal digit code points + gives unspecified results + + If your string is guaranteed to contain only ASCII digit + use OUString::toInt32 instead. + + @param str The string to convert containing only decimal + digit codepoints. + + @return The value of the string as an int32. + */ +COMPHELPER_DLLPUBLIC sal_uInt32 decimalStringToNumber( + OUString const & str ); + +COMPHELPER_DLLPUBLIC std::vector + split(std::u16string_view rString, const sal_Unicode cSeparator); + +/** Convert a single comma separated string to a sequence of strings. + + Note that no escaping of commas or anything fancy is done. + + @param i_rString A string containing comma-separated words. + + @return A sequence of strings resulting from splitting the given + string at ',' tokens and stripping whitespace. + */ +COMPHELPER_DLLPUBLIC css::uno::Sequence< OUString > + convertCommaSeparated( std::u16string_view i_rString ); + +/** + Compares two strings using natural order. + + For non digit characters, the comparison use the same algorithm as + rtl_str_compare. When a number is encountered during the comparison, + natural order is used. Thus, Heading 10 will be considered as greater + than Heading 2. Numerical comparison is done using decimal representation. + + Beware that "MyString 001" and "MyString 1" will be considered as equal + since leading 0 are meaningless. + + @param str the object to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument +*/ +COMPHELPER_DLLPUBLIC sal_Int32 compareNatural( const OUString &rLHS, const OUString &rRHS, + const css::uno::Reference< css::i18n::XCollator > &rCollator, + const css::uno::Reference< css::i18n::XBreakIterator > &rBI, + const css::lang::Locale &rLocale ); + +class COMPHELPER_DLLPUBLIC NaturalStringSorter +{ +private: + css::lang::Locale const m_aLocale; + css::uno::Reference< css::i18n::XCollator > m_xCollator; + css::uno::Reference< css::i18n::XBreakIterator > m_xBI; +public: + NaturalStringSorter( + const css::uno::Reference< css::uno::XComponentContext > &rContext, + css::lang::Locale aLocale); + sal_Int32 compare(const OUString &rLHS, const OUString &rRHS) const + { + return compareNatural(rLHS, rRHS, m_xCollator, m_xBI, m_aLocale); + } + const css::lang::Locale& getLocale() const { return m_aLocale; } +}; + +/** Determine if an OString contains solely ASCII numeric digits + + @param rString An OString + + @return false if string contains any characters outside + the ASCII '0'-'9' range + true otherwise, including for empty string + */ +COMPHELPER_DLLPUBLIC bool isdigitAsciiString(std::string_view rString); + +/** Determine if an OUString contains solely ASCII numeric digits + + @param rString An OUString + + @return false if string contains any characters outside + the ASCII '0'-'9' range + true otherwise, including for empty string + */ +COMPHELPER_DLLPUBLIC bool isdigitAsciiString(std::u16string_view rString); + +} // namespace comphelper::string + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/synchronousdispatch.hxx b/include/comphelper/synchronousdispatch.hxx new file mode 100644 index 000000000..8503b2a43 --- /dev/null +++ b/include/comphelper/synchronousdispatch.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_SYNCHRONOUSDISPATCH_HXX +#define INCLUDED_COMPHELPER_SYNCHRONOUSDISPATCH_HXX + +#include + +#include +#include + +namespace com::sun::star { + namespace uno { + class XInterface; } + namespace lang { + class XComponent; } +} + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::uno { template class Sequence; } + + +namespace comphelper +{ + + + //= SynchronousDispatch + + /** a helper class for working with the dispatch interface replacing + loadComponentFromURL + */ + class SynchronousDispatch + { + public: + static COMPHELPER_DLLPUBLIC css::uno::Reference< css::lang::XComponent > dispatch( + const css::uno::Reference< css::uno::XInterface > &xStartPoint, + const OUString &sURL, + const OUString &sTarget, + const css::uno::Sequence< css::beans::PropertyValue > &lArguments ); + }; + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_SYNCHRONOUSDISPATCH_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/syntaxhighlight.hxx b/include/comphelper/syntaxhighlight.hxx new file mode 100644 index 000000000..c8bc100d3 --- /dev/null +++ b/include/comphelper/syntaxhighlight.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_SYNTAXHIGHLIGHT_HXX +#define INCLUDED_COMPHELPER_SYNTAXHIGHLIGHT_HXX + +#include + +#include + +#include +#include + +enum class TokenType +{ + Unknown, + Identifier, + Whitespace, + Number, + String, + EOL, + Comment, + Error, + Operator, + Keywords, + Parameter, + LAST = Parameter +}; + +struct HighlightPortion { + sal_Int32 nBegin; + sal_Int32 nEnd; + TokenType tokenType; + + HighlightPortion( + sal_Int32 theBegin, sal_Int32 theEnd, TokenType theTokenType): + nBegin(theBegin), nEnd(theEnd), tokenType(theTokenType) + {} +}; + +// Language mode of the Highlighter (possibly to be refined later with keyword +// lists, C comment flags) +enum class HighlighterLanguage +{ + Basic, + SQL +}; + +class COMPHELPER_DLLPUBLIC SyntaxHighlighter +{ + class Tokenizer; + + std::unique_ptr m_tokenizer; + + SyntaxHighlighter(const SyntaxHighlighter&) = delete; + SyntaxHighlighter& operator=(const SyntaxHighlighter&) = delete; +public: + SyntaxHighlighter(HighlighterLanguage language); + ~SyntaxHighlighter(); + + void getHighlightPortions( std::u16string_view rLine, + std::vector& pPortions ) const; + + HighlighterLanguage GetLanguage() const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/threadpool.hxx b/include/comphelper/threadpool.hxx new file mode 100644 index 000000000..84f9dc928 --- /dev/null +++ b/include/comphelper/threadpool.hxx @@ -0,0 +1,114 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_THREADPOOL_HXX +#define INCLUDED_COMPHELPER_THREADPOOL_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace comphelper +{ +class ThreadTaskTag; + +class COMPHELPER_DLLPUBLIC ThreadTask +{ +friend class ThreadPool; +friend struct std::default_delete; + std::shared_ptr mpTag; + + /// execute this task + void exec(); +protected: + /// override to get your task performed by the pool + virtual void doWork() = 0; + /// once pushed ThreadTasks are destroyed by the pool + virtual ~ThreadTask() {} +public: + ThreadTask(std::shared_ptr pTag); +}; + +/// A very basic thread-safe thread pool implementation +class COMPHELPER_DLLPUBLIC ThreadPool final +{ +public: + /// returns a pointer to a shared pool with optimal thread + /// count for the CPU + static ThreadPool& getSharedOptimalPool(); + + static std::shared_ptr createThreadTaskTag(); + + static bool isTaskTagDone(const std::shared_ptr&); + + /// returns a configurable max-concurrency + /// limit to avoid spawning an unnecessarily + /// large number of threads on high-core boxes. + /// MAX_CONCURRENCY env. var. controls the cap. + static std::size_t getPreferredConcurrency(); + + ThreadPool( std::size_t nWorkers ); + ~ThreadPool(); + + /// push a new task onto the work queue + void pushTask( std::unique_ptr pTask); + + /** Wait until all queued tasks associated with the tag are completed + @param bJoin - if set call joinThreadsIfIdle() at the end + */ + void waitUntilDone(const std::shared_ptr&, bool bJoin = true); + + /// join all threads if there are no tasks presently. + void joinThreadsIfIdle(); + + /// return true if there are no queued or worked-on tasks + bool isIdle() const { return maTasks.empty() && mnBusyWorkers == 0; }; + + /// return the number of live worker threads + sal_Int32 getWorkerCount() const { return mnMaxWorkers; } + + /// wait until all work is completed, then join all threads + void shutdown(); + +private: + ThreadPool(const ThreadPool&) = delete; + ThreadPool& operator=(const ThreadPool&) = delete; + + class ThreadWorker; + friend class ThreadWorker; + + /** Pop a work task + @param bWait - if set wait until task present or termination + @return a new task to perform, or NULL if list empty or terminated + */ + std::unique_ptr popWorkLocked( std::unique_lock< std::mutex > & rGuard, bool bWait ); + void shutdownLocked(std::unique_lock&); + void incBusyWorker(); + void decBusyWorker(); + + /// signalled when all in-progress tasks are complete + std::mutex maMutex; + std::condition_variable maTasksChanged; + bool mbTerminate; + std::size_t const mnMaxWorkers; + std::size_t mnBusyWorkers; + std::vector< std::unique_ptr > maTasks; + std::vector< rtl::Reference< ThreadWorker > > maWorkers; +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_THREADPOOL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/traceevent.hxx b/include/comphelper/traceevent.hxx new file mode 100644 index 000000000..a0fe9cae1 --- /dev/null +++ b/include/comphelper/traceevent.hxx @@ -0,0 +1,222 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef INCLUDED_COMPHELPER_TRACEEVENT_HXX +#define INCLUDED_COMPHELPER_TRACEEVENT_HXX + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +// implementation of XToolkitExperimental profiling API + +namespace comphelper +{ +class COMPHELPER_DLLPUBLIC TraceEvent +{ +private: + static int getPid() + { + oslProcessInfo aProcessInfo; + aProcessInfo.Size = sizeof(oslProcessInfo); + if (osl_getProcessInfo(nullptr, osl_Process_IDENTIFIER, &aProcessInfo) + == osl_Process_E_None) + return aProcessInfo.Ident; + return -1; + } + + static std::size_t s_nBufferSize; + static void (*s_pBufferFullCallback)(); + +protected: + static std::atomic s_bRecording; // true during recording + + static void addRecording(const OUString& sObject); + + static long long getNow() + { + TimeValue systemTime; + osl_getSystemTime(&systemTime); + return static_cast(systemTime.Seconds) * 1000000 + systemTime.Nanosec / 1000; + } + + static OUString createArgsString(const std::map& args) + { + if (args.size() == 0) + return ""; + + OUStringBuffer sResult; + sResult.append(",\"args\":{"); + bool first = true; + for (auto& i : args) + { + if (!first) + sResult.append(','); + sResult.append('"'); + sResult.append(i.first); + sResult.append("\":\""); + sResult.append(i.second); + sResult.append('"'); + first = false; + } + sResult.append('}'); + + return sResult.makeStringAndClear(); + } + + const int m_nPid; + const OUString m_sArgs; + + TraceEvent(OUString sArgs) + : m_nPid(s_bRecording ? getPid() : 1) + , m_sArgs(std::move(sArgs)) + { + } + + TraceEvent(const std::map& aArgs) + : TraceEvent(createArgsString(aArgs)) + { + } + +public: + static void addInstantEvent(const char* sName, const std::map& args + = std::map()); + + static void startRecording(); + static void stopRecording(); + static void setBufferSizeAndCallback(std::size_t bufferSize, void (*bufferFullCallback)()); + + static std::vector getEventVectorAndClear(); + + static css::uno::Sequence getRecordingAndClear(); +}; + +class COMPHELPER_DLLPUBLIC NamedEvent : public TraceEvent +{ +protected: + const char* m_sName; + + NamedEvent(const char* sName, const OUString& sArgs) + : TraceEvent(sArgs) + , m_sName(sName ? sName : "(null)") + { + } + + NamedEvent(const char* sName, const std::map& aArgs) + : TraceEvent(aArgs) + , m_sName(sName ? sName : "(null)") + { + } +}; + +// An AsyncEvent generates an 'S' (start) event when constructed and a 'F' (finish) event when it +// is destructed. + +// The Trace Event specification claims that these event types are deprecated and replaces by +// nestable 'b' (begin) and 'e' (end) events, but Chrome does not seem to support those. + +// To generate a pair of 'S' and 'F' events, create an AsyncEvent object using the AsyncEvent(const +// char* sName) constructor when you want the 'S' event to be generated, and destroy it when you +// want the corresponding 'F' event to be generated. + +class COMPHELPER_DLLPUBLIC AsyncEvent : public NamedEvent, + public std::enable_shared_from_this +{ + static int s_nIdCounter; + int m_nId; + bool m_bBeginRecorded; + + AsyncEvent(const char* sName, int nId, const std::map& args) + : NamedEvent(sName, args) + , m_nId(nId) + , m_bBeginRecorded(false) + { + if (!s_bRecording) + return; + + long long nNow = getNow(); + + // Generate a "Start" (type S) event + TraceEvent::addRecording("{" + "\"name\":\"" + + OUString(m_sName, strlen(m_sName), RTL_TEXTENCODING_UTF8) + + "\"," + "\"ph\":\"S\"" + "," + "\"id\":" + + OUString::number(m_nId) + m_sArgs + + "," + "\"ts\":" + + OUString::number(nNow) + + "," + "\"pid\":" + + OUString::number(m_nPid) + + "," + "\"tid\":" + + OUString::number(osl_getThreadIdentifier(nullptr)) + "},"); + m_bBeginRecorded = true; + } + + void generateEnd() + { + if (!m_bBeginRecorded) + return; + + m_bBeginRecorded = false; + + long long nNow = getNow(); + // Generate a "Finish" (type F) event + TraceEvent::addRecording("{" + "\"name\":\"" + + OUString(m_sName, strlen(m_sName), RTL_TEXTENCODING_UTF8) + + "\"," + "\"ph\":\"F\"" + "," + "\"id\":" + + OUString::number(m_nId) + m_sArgs + + "," + "\"ts\":" + + OUString::number(nNow) + + "," + "\"pid\":" + + OUString::number(m_nPid) + + "," + "\"tid\":" + + OUString::number(osl_getThreadIdentifier(nullptr)) + "},"); + } + +public: + AsyncEvent(const char* sName, + const std::map& args = std::map()) + : AsyncEvent(sName, s_nIdCounter++, args) + { + } + + ~AsyncEvent() { generateEnd(); } + + void finish() { generateEnd(); } +}; + +} // namespace comphelper + +#endif // INCLUDED_COMPHELPER_TRACEEVENT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/types.hxx b/include/comphelper/types.hxx new file mode 100644 index 000000000..203bbbe02 --- /dev/null +++ b/include/comphelper/types.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_TYPES_HXX +#define INCLUDED_COMPHELPER_TYPES_HXX + +#include +#include +#include + +namespace com::sun::star::awt { + struct FontDescriptor; +} + +namespace com::sun::star::uno { class Any; } +namespace com::sun::star::uno { class XInterface; } + + +namespace comphelper +{ + /// returns sal_True if objects of the types given are "compatible" + COMPHELPER_DLLPUBLIC bool isAssignableFrom(const css::uno::Type& _rAssignable, const css::uno::Type& _rFrom); + + /** ask the given object for an XComponent interface and dispose on it + */ + template + void disposeComponent(css::uno::Reference& _rxComp) + { + css::uno::Reference xComp(_rxComp, css::uno::UNO_QUERY); + if (xComp.is()) + { + xComp->dispose(); + _rxComp = nullptr; + } + } + + + /** get a css::awt::FontDescriptor that is fully initialized with + the XXX_DONTKNOW enum values (which isn't the case if you instantiate it + via the default constructor) + */ + COMPHELPER_DLLPUBLIC css::awt::FontDescriptor getDefaultFont(); + + /** examine a sequence for the com.sun.star.uno::Type of its elements. + */ + COMPHELPER_DLLPUBLIC css::uno::Type getSequenceElementType(const css::uno::Type& _rSequenceType); + + +//= replacement of the former UsrAny.getXXX methods + + // may be used if you need the return value just as temporary, else it's may be too inefficient... + + // no, we don't use templates here. This would lead to a lot of implicit uses of the conversion methods, + // which would be difficult to trace... + + COMPHELPER_DLLPUBLIC sal_Int64 getINT64(const css::uno::Any& _rAny); + COMPHELPER_DLLPUBLIC sal_Int32 getINT32(const css::uno::Any& _rAny); + COMPHELPER_DLLPUBLIC sal_Int16 getINT16(const css::uno::Any& _rAny); + COMPHELPER_DLLPUBLIC double getDouble(const css::uno::Any& _rAny); + COMPHELPER_DLLPUBLIC float getFloat(const css::uno::Any& _rAny); + COMPHELPER_DLLPUBLIC OUString getString(const css::uno::Any& _rAny); + COMPHELPER_DLLPUBLIC bool getBOOL(const css::uno::Any& _rAny); + + /// @throws css::lang::IllegalArgumentException + COMPHELPER_DLLPUBLIC sal_Int32 getEnumAsINT32(const css::uno::Any& _rAny); + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_TYPES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/unique_disposing_ptr.hxx b/include/comphelper/unique_disposing_ptr.hxx new file mode 100644 index 000000000..5994799fc --- /dev/null +++ b/include/comphelper/unique_disposing_ptr.hxx @@ -0,0 +1,187 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_UNIQUE_DISPOSING_PTR_HXX +#define INCLUDED_COMPHELPER_UNIQUE_DISPOSING_PTR_HXX + +#include +#include + +#include +#include +#include + +#include +#include +#include + +namespace comphelper +{ +//Similar to std::unique_ptr, except additionally releases the ptr on XComponent::disposing and/or XTerminateListener::notifyTermination if supported +template class unique_disposing_ptr +{ +private: + std::unique_ptr> m_xItem; + css::uno::Reference< css::frame::XTerminateListener> m_xTerminateListener; + + unique_disposing_ptr(const unique_disposing_ptr&) = delete; + unique_disposing_ptr& operator=(const unique_disposing_ptr&) = delete; +public: + unique_disposing_ptr( const css::uno::Reference< css::lang::XComponent > &rComponent, T * p = nullptr, bool bComponent = false) + : m_xItem(p) + { + m_xTerminateListener = new TerminateListener(rComponent, *this, bComponent); + } + + virtual void reset(T * p = nullptr) + { + m_xItem.reset(p); + } + + T & operator*() const + { + return *m_xItem; + } + + T * get() const + { + return m_xItem.get(); + } + + T * operator->() const + { + return m_xItem.get(); + } + + operator bool () const + { + return static_cast< bool >(m_xItem); + } + + virtual ~unique_disposing_ptr() COVERITY_NOEXCEPT_FALSE + { + reset(); + } +private: + class TerminateListener final : public ::cppu::WeakImplHelper< css::frame::XTerminateListener, + css::lang::XServiceInfo> + { + private: + css::uno::Reference< css::lang::XComponent > m_xComponent; + unique_disposing_ptr& m_rItem; + bool const mbComponentDLL; + public: + TerminateListener(css::uno::Reference< css::lang::XComponent > xComponent, + unique_disposing_ptr& rItem, bool bComponentDLL) : + m_xComponent(std::move(xComponent)), + m_rItem(rItem), + mbComponentDLL(bComponentDLL) + { + if (m_xComponent.is()) + { + css::uno::Reference< css::frame::XDesktop> xDesktop(m_xComponent, css::uno::UNO_QUERY); + if (xDesktop.is()) + xDesktop->addTerminateListener(this); + else + m_xComponent->addEventListener(this); + } + } + + virtual ~TerminateListener() override + { + if ( m_xComponent.is() ) + { + css::uno::Reference< css::frame::XDesktop> xDesktop(m_xComponent, css::uno::UNO_QUERY); + if (xDesktop.is()) + xDesktop->removeTerminateListener(this); + else + m_xComponent->removeEventListener(this); + } + } + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& rEvt ) override + { + bool shutDown = (rEvt.Source == m_xComponent); + + if (shutDown && m_xComponent.is()) + { + css::uno::Reference< css::frame::XDesktop> xDesktop(m_xComponent, css::uno::UNO_QUERY); + if (xDesktop.is()) + xDesktop->removeTerminateListener(this); + else + m_xComponent->removeEventListener(this); + m_xComponent.clear(); + } + + if (shutDown) + m_rItem.reset(); + } + + // XTerminateListener + virtual void SAL_CALL queryTermination( const css::lang::EventObject& ) override + { + } + + virtual void SAL_CALL notifyTermination( const css::lang::EventObject& rEvt ) override + { + disposing(rEvt); + } + + virtual OUString SAL_CALL getImplementationName() override + { + if (mbComponentDLL) + return "com.sun.star.comp.ComponentDLLListener"; + else + return "com.sun.star.comp.DisposingTerminateListener"; + } + + virtual sal_Bool SAL_CALL supportsService(const OUString& /*rName*/) override + { + return false; + } + + virtual css::uno::Sequence SAL_CALL getSupportedServiceNames() override + { + return css::uno::Sequence(); + } + }; +}; + +//Something like an OutputDevice requires the SolarMutex to be taken before use +//for threadsafety. The user can ensure this, except in the case of its dtor +//being called from reset due to a terminate on the XComponent being called +//from an arbitrary thread +template class unique_disposing_solar_mutex_reset_ptr + : public unique_disposing_ptr +{ +public: + unique_disposing_solar_mutex_reset_ptr( const css::uno::Reference< css::lang::XComponent > &rComponent, T * p = nullptr, bool bComponent = false) + : unique_disposing_ptr(rComponent, p, bComponent) + { + } + + virtual void reset(T * p = nullptr) override + { + SolarMutexGuard aGuard; + unique_disposing_ptr::reset(p); + } + + virtual ~unique_disposing_solar_mutex_reset_ptr() override + { + if (unique_disposing_ptr::get() && comphelper::SolarMutex::get()) + reset(); + } +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/uno3.hxx b/include/comphelper/uno3.hxx new file mode 100644 index 000000000..517398fd7 --- /dev/null +++ b/include/comphelper/uno3.hxx @@ -0,0 +1,169 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_UNO3_HXX +#define INCLUDED_COMPHELPER_UNO3_HXX + +#include +#include + + +namespace comphelper +{ + /** used for declaring UNO3-Defaults, i.e. acquire/release + */ + #define DECLARE_UNO3_DEFAULTS(classname, baseclass) \ + virtual void SAL_CALL acquire() noexcept override { baseclass::acquire(); } \ + virtual void SAL_CALL release() noexcept override { baseclass::release(); } + + /** used for declaring UNO3-Defaults, i.e. acquire/release if you want to forward all queryInterfaces to the base class, + (e.g. if you override queryAggregation) + */ + #define DECLARE_UNO3_AGG_DEFAULTS(classname, baseclass) \ + virtual void SAL_CALL acquire() noexcept override { baseclass::acquire(); } \ + virtual void SAL_CALL release() noexcept override { baseclass::release(); } \ + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type& _rType) override \ + { return baseclass::queryInterface(_rType); } + + /** Use this macro to forward XComponent methods to base class + + When using the ::cppu::WeakComponentImplHelper base classes to + implement a UNO interface, a problem occurs when the interface + itself already derives from XComponent (like e.g. awt::XWindow + or awt::XControl): ::cppu::WeakComponentImplHelper is then + still abstract. Using this macro in the most derived class + definition provides overrides for the XComponent methods, + forwarding them to the given baseclass. + + @param classname + Name of the class this macro is issued within + + @param baseclass + Name of the baseclass that should have the XInterface methods + forwarded to - that's usually the WeakComponentImplHelperN base + + @param implhelper + Name of the baseclass that should have the XComponent methods + forwarded to - in the case of the WeakComponentImplHelper, + that would be ::cppu::WeakComponentImplHelperBase + */ + #define DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS(classname, baseclass, implhelper) \ + virtual void SAL_CALL acquire() noexcept override { baseclass::acquire(); } \ + virtual void SAL_CALL release() noexcept override { baseclass::release(); } \ + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type& _rType) override \ + { return baseclass::queryInterface(_rType); } \ + virtual void SAL_CALL dispose() override \ + { \ + implhelper::dispose(); \ + } \ + virtual void SAL_CALL addEventListener( \ + css::uno::Reference< css::lang::XEventListener > const & xListener ) override \ + { \ + implhelper::addEventListener(xListener); \ + } \ + virtual void SAL_CALL removeEventListener( \ + css::uno::Reference< css::lang::XEventListener > const & xListener ) override \ + { \ + implhelper::removeEventListener(xListener); \ + } + + //= deriving from multiple XInterface-derived classes + + //= forwarding/merging XInterface functionality + + #define DECLARE_XINTERFACE( ) \ + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& aType ) override; \ + virtual void SAL_CALL acquire() noexcept override; \ + virtual void SAL_CALL release() noexcept override; + + #define IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \ + void SAL_CALL classname::acquire() noexcept { refcountbase::acquire(); } \ + void SAL_CALL classname::release() noexcept { refcountbase::release(); } + + #define IMPLEMENT_FORWARD_XINTERFACE2( classname, refcountbase, baseclass2 ) \ + IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \ + css::uno::Any SAL_CALL classname::queryInterface( const css::uno::Type& _rType ) \ + { \ + css::uno::Any aReturn = refcountbase::queryInterface( _rType ); \ + if ( !aReturn.hasValue() ) \ + aReturn = baseclass2::queryInterface( _rType ); \ + return aReturn; \ + } + + #define IMPLEMENT_FORWARD_XINTERFACE3( classname, refcountbase, baseclass2, baseclass3 ) \ + IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \ + css::uno::Any SAL_CALL classname::queryInterface( const css::uno::Type& _rType ) \ + { \ + css::uno::Any aReturn = refcountbase::queryInterface( _rType ); \ + if ( !aReturn.hasValue() ) \ + { \ + aReturn = baseclass2::queryInterface( _rType ); \ + if ( !aReturn.hasValue() ) \ + aReturn = baseclass3::queryInterface( _rType ); \ + } \ + return aReturn; \ + } + + + //= forwarding/merging XTypeProvider functionality + + #define DECLARE_XTYPEPROVIDER( ) \ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; \ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; + + #define IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) \ + css::uno::Sequence< sal_Int8 > SAL_CALL classname::getImplementationId( ) \ + { \ + return css::uno::Sequence(); \ + } + + #define IMPLEMENT_FORWARD_XTYPEPROVIDER2( classname, baseclass1, baseclass2 ) \ + css::uno::Sequence< css::uno::Type > SAL_CALL classname::getTypes( ) \ + { \ + return ::comphelper::concatSequences( \ + baseclass1::getTypes(), \ + baseclass2::getTypes() \ + ); \ + } \ + \ + IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) + + /** ask for an iface of an aggregated object + usage:
+ Reference xFoo;
+ if (query_aggregation(xAggregatedObject, xFoo))
+ ... + */ + template + bool query_aggregation(const css::uno::Reference< css::uno::XAggregation >& _rxAggregate, css::uno::Reference& _rxOut) + { + _rxOut.clear(); + if (_rxAggregate.is()) + { + _rxAggregate->queryAggregation(cppu::UnoType::get()) + >>= _rxOut; + } + return _rxOut.is(); + } +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_UNO3_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/unwrapargs.hxx b/include/comphelper/unwrapargs.hxx new file mode 100644 index 000000000..76eb8b838 --- /dev/null +++ b/include/comphelper/unwrapargs.hxx @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_UNWRAPARGS_HXX +#define INCLUDED_COMPHELPER_UNWRAPARGS_HXX + +#include + +#include + +#include +#include +#include +#include + +namespace comphelper { + +/// @internal +namespace detail { + inline void unwrapArgsError( + const OUString& str, sal_Int32 nArg, + const css::uno::Reference< css::uno::XInterface >& xErrorContext = + css::uno::Reference< css::uno::XInterface >() ) + { + throw css::lang::IllegalArgumentException( + str, xErrorContext, static_cast< sal_Int16 >( nArg ) ); + } + + template< typename T, typename... Args > + inline void unwrapArgsError( const OUString& str, sal_Int32 nArg, T&, Args&... args ) + { + return unwrapArgsError( str, nArg, args... ); + } + + inline void unwrapArgs( + const css::uno::Sequence< css::uno::Any >&, + sal_Int32, + const css::uno::Reference< css::uno::XInterface >& ) + { + return; + } + + inline void unwrapArgs( + const css::uno::Sequence< css::uno::Any >&, + sal_Int32 ) + { + return; + } + + template< typename T, typename... Args > + inline void unwrapArgs( + const css::uno::Sequence< css::uno::Any >& seq, + sal_Int32 nArg, ::std::optional< T >& v, Args&... args ); + + template< typename T, typename... Args > + inline void unwrapArgs( + const css::uno::Sequence< css::uno::Any >& seq, + sal_Int32 nArg, T& v, Args&... args ) + { + if( seq.getLength() <= nArg ) + { + return unwrapArgsError( OUString( "No such argument available!"), + nArg, args... ); + } + if( !fromAny( seq[nArg], &v ) ) + { + OUString msg = + "Cannot extract ANY { " + + seq[nArg].getValueType().getTypeName() + + " } to " + + ::cppu::UnoType::get().getTypeName() + + "!"; + return unwrapArgsError( msg, nArg, args... ); + } + return unwrapArgs( seq, ++nArg, args... ); + } + + template< typename T, typename... Args > + inline void unwrapArgs( + const css::uno::Sequence< css::uno::Any >& seq, + sal_Int32 nArg, ::std::optional< T >& v, Args&... args ) + { + if( nArg < seq.getLength() ) + { + T t; + unwrapArgs( seq, nArg, t, args... ); + v = t; + } else { + unwrapArgs( seq, ++nArg, args... ); + } + } +} + +template< typename... Args > +inline void unwrapArgs( + const css::uno::Sequence< css::uno::Any >& seq, + Args&... args ) +{ + return detail::unwrapArgs( seq, 0, args... ); +} + +} // namespace comphelper + +#endif // ! defined( INCLUDED_COMPHELPER_UNWRAPARGS_HXX) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/weak.hxx b/include/comphelper/weak.hxx new file mode 100644 index 000000000..28a23445d --- /dev/null +++ b/include/comphelper/weak.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_COMPHELPER_WEAK_HXX +#define INCLUDED_COMPHELPER_WEAK_HXX + +#include + +#include +#include + +namespace comphelper +{ +/** Base class to implement a UNO object supporting types and weak references, i.e. the object can be held + weakly (by a css::uno::WeakReference). + This implementation copes with reference counting. Upon last release(), the virtual dtor + is called. + + In addition to the features from cppu::OWeakObject, derivations from this class can + also used as a base class for ::cppu::ImplInheritanceHelper? +*/ +class COMPHELPER_DLLPUBLIC OWeakTypeObject : public ::cppu::OWeakObject, public css::lang::XTypeProvider +{ +public: + OWeakTypeObject(); + virtual ~OWeakTypeObject() override; + + OWeakTypeObject(OWeakTypeObject const &) = default; + OWeakTypeObject(OWeakTypeObject &&) = default; + OWeakTypeObject & operator =(OWeakTypeObject const &) = default; + OWeakTypeObject & operator =(OWeakTypeObject &&) = default; + + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override + { ::cppu::OWeakObject::acquire(); } + virtual void SAL_CALL release() noexcept override + { ::cppu::OWeakObject::release(); } + + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< ::sal_Int8 > SAL_CALL getImplementationId( ) override; + +}; + +} + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/weakbag.hxx b/include/comphelper/weakbag.hxx new file mode 100644 index 000000000..c52defab2 --- /dev/null +++ b/include/comphelper/weakbag.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_WEAKBAG_HXX +#define INCLUDED_COMPHELPER_WEAKBAG_HXX + +#include + +#include +#include +#include +#include + +namespace comphelper { + +/** + A bag of UNO weak references. +*/ +template< typename T > class WeakBag { +public: + /** + Add a new weak reference. + + The implementation keeps the amount of memory consumed linear in the + number of living references added, not linear in the number of total + references added. + + @param e + a non-null reference. + */ + void add(css::uno::Reference< T > const & e) { + OSL_ASSERT(e.is()); + for (auto i = m_list.begin(); i != m_list.end();) { + if (css::uno::Reference< T >(*i).is()) { + ++i; + } else { + i = m_list.erase(i); + } + } + m_list.push_back(css::uno::WeakReference< T >(e)); + } + + /** + Remove a living reference. + + @return + a living reference, or null if there are none. + */ + css::uno::Reference< T > remove() { + while (!m_list.empty()) { + css::uno::Reference< T > r(m_list.back()); + m_list.pop_back(); + if (r.is()) { + return r; + } + } + return css::uno::Reference< T >(); + } + +private: + std::vector< css::uno::WeakReference< T > > m_list; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/weakeventlistener.hxx b/include/comphelper/weakeventlistener.hxx new file mode 100644 index 000000000..d64f302d8 --- /dev/null +++ b/include/comphelper/weakeventlistener.hxx @@ -0,0 +1,183 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_WEAKEVENTLISTENER_HXX +#define INCLUDED_COMPHELPER_WEAKEVENTLISTENER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { class XWeak; } + +namespace comphelper +{ + + + //= OWeakListenerAdapterBase + + /** (the base for) an adapter which allows to add as listener to a foreign component, without + being held hard. + +

The idea is that this adapter is added as listener to a foreign component, which usually + holds it's listener hard. The adapter itself knows the real listener as weak reference, + thus not affecting its life time.

+ */ + class OWeakListenerAdapterBase : public cppu::BaseMutex + { + private: + css::uno::WeakReference< css::uno::XInterface > + m_aListener; + css::uno::Reference< css::uno::XInterface > + m_xBroadcaster; + + protected: + css::uno::Reference< css::uno::XInterface > + getListener( ) const + { + return m_aListener.get(); + } + + const css::uno::Reference< css::uno::XInterface >& + getBroadcaster( ) const + { + return m_xBroadcaster; + } + + void resetListener( ) + { + m_aListener.clear(); + } + + + protected: + OWeakListenerAdapterBase( + const css::uno::Reference< css::uno::XWeak >& _rxListener, + css::uno::Reference< css::uno::XInterface > _xBroadcaster + ) + :m_aListener ( _rxListener ) + ,m_xBroadcaster (std::move( _xBroadcaster )) + { + } + + protected: + virtual ~OWeakListenerAdapterBase(); + }; + + + //= OWeakListenerAdapter + + template< class BROADCASTER, class LISTENER > + /** yet another base for weak listener adapters, this time with some type safety + +

Note that derived classes need to overwrite all virtual methods of their interface + except XEventListener::disposing, and forward it to their master listener.

+ +

Additionally, derived classes need to add themself as listener to the broadcaster, + as this can't be done in a generic way

+ */ + class OWeakListenerAdapter + :public ::cppu::WeakComponentImplHelper< LISTENER > + ,public OWeakListenerAdapterBase + { + protected: + /** ctor +

Note that derived classes still need to add themself as listener to the broadcaster, + as this can't be done in a generic way

+ */ + OWeakListenerAdapter( + const css::uno::Reference< css::uno::XWeak >& _rxListener, + const css::uno::Reference< BROADCASTER >& _rxBroadcaster + ); + + protected: + css::uno::Reference< LISTENER > getListener( ) const + { + return css::uno::Reference< LISTENER >( OWeakListenerAdapterBase::getListener(), css::uno::UNO_QUERY ); + } + + // XEventListener overridables + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + protected: + // OComponentHelper overridables + // to be overridden, again - the derived class should revoke the listener from the broadcaster + virtual void SAL_CALL disposing( ) override = 0; + }; + + + //= OWeakEventListenerAdapter + + typedef OWeakListenerAdapter < css::lang::XComponent + , css::lang::XEventListener + > OWeakEventListenerAdapter_Base; + /** the most simple listener adapter: for XEventListeners at XComponents + */ + class UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OWeakEventListenerAdapter final : public OWeakEventListenerAdapter_Base + { + public: + OWeakEventListenerAdapter( + css::uno::Reference< css::uno::XWeak > const & _rxListener, + css::uno::Reference< css::lang::XComponent > const & _rxBroadcaster + ); + + // nothing to do except an own ctor - the forwarding of the "disposing" is already done + // in the base class + + private: + using OWeakEventListenerAdapter_Base::disposing; + virtual void SAL_CALL disposing( ) override; + }; + + + //= OWeakListenerAdapter + + + template< class BROADCASTER, class LISTENER > + OWeakListenerAdapter< BROADCASTER, LISTENER >::OWeakListenerAdapter( + const css::uno::Reference< css::uno::XWeak >& _rxListener, + const css::uno::Reference< BROADCASTER >& _rxBroadcaster + ) + : ::cppu::WeakComponentImplHelper< LISTENER >( m_aMutex ) + , OWeakListenerAdapterBase( _rxListener, _rxBroadcaster ) + { + } + + + template< class BROADCASTER, class LISTENER > + void SAL_CALL OWeakListenerAdapter< BROADCASTER, LISTENER >::disposing( const css::lang::EventObject& _rSource ) + { + css::uno::Reference< LISTENER > xListener( getListener() ); + if ( xListener.is() ) + xListener->disposing( _rSource ); + } + + +} // namespace comphelper + + +#endif // INCLUDED_COMPHELPER_WEAKEVENTLISTENER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/windowsStart.hxx b/include/comphelper/windowsStart.hxx new file mode 100644 index 000000000..a727733d9 --- /dev/null +++ b/include/comphelper/windowsStart.hxx @@ -0,0 +1,27 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef INCLUDED_COMPHELPER_WINSTART_HXX +#define INCLUDED_COMPHELPER_WINSTART_HXX + +#ifdef _WIN32 +#if !defined WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + +/** + * Launch a child process with the specified arguments. + * @note argv[0] is ignored + */ +BOOL +WinLaunchChild(const wchar_t *exePath, int argc, + wchar_t **argv, HANDLE userToken = nullptr, + HANDLE *hProcess = nullptr); + +wchar_t* MakeCommandLine(int argc, wchar_t **argv); + +#endif diff --git a/include/comphelper/windowsdebugoutput.hxx b/include/comphelper/windowsdebugoutput.hxx new file mode 100644 index 000000000..0315933c7 --- /dev/null +++ b/include/comphelper/windowsdebugoutput.hxx @@ -0,0 +1,796 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* Debug output operators for Windows-specific types. For use in SAL_INFO(), SAL_WARN(), and + * friends. The exact format of the generated output is not guaranteed to be stable or contain + * complete information. + */ + +#ifndef INCLUDED_COMPHELPER_WINDOWSDEBUGOUTPUT_HXX +#define INCLUDED_COMPHELPER_WINDOWSDEBUGOUTPUT_HXX + +#include +#include +#include +#include +#include + +#ifdef LIBO_INTERNAL_ONLY +#include +#include +#else +#include +#endif +#include + +namespace +{ +DEFINE_GUID(IID_IdentityUnmarshal, 0x0000001B, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x46); +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& stream, + const IID& rIid) +{ + LPOLESTR pRiid; + if (StringFromIID(rIid, &pRiid) != S_OK) + return stream << "?"; + + stream << std::wstring_convert, wchar_t>().to_bytes( + std::wstring(pRiid)); + + DWORD nSize; + if (RegGetValueW(HKEY_CLASSES_ROOT, std::wstring(L"CLSID\\").append(pRiid).data(), nullptr, + RRF_RT_REG_SZ, nullptr, nullptr, &nSize) + == ERROR_SUCCESS) + { + std::vector sValue(nSize / 2); + if (RegGetValueW(HKEY_CLASSES_ROOT, std::wstring(L"CLSID\\").append(pRiid).data(), nullptr, + RRF_RT_REG_SZ, nullptr, sValue.data(), &nSize) + == ERROR_SUCCESS) + { + stream << "=\"" + << std::wstring_convert, wchar_t>().to_bytes( + std::wstring(sValue.data())) + << "\""; + } + } + else if (RegGetValueW(HKEY_CLASSES_ROOT, std::wstring(L"Interface\\").append(pRiid).data(), + nullptr, RRF_RT_REG_SZ, nullptr, nullptr, &nSize) + == ERROR_SUCCESS) + { + std::vector sValue(nSize / 2); + if (RegGetValueW(HKEY_CLASSES_ROOT, std::wstring(L"Interface\\").append(pRiid).data(), + nullptr, RRF_RT_REG_SZ, nullptr, sValue.data(), &nSize) + == ERROR_SUCCESS) + { + stream << "=\"" + << std::wstring_convert, wchar_t>().to_bytes( + std::wstring(sValue.data())) + << "\""; + } + } + else + { + // Special case well-known interfaces that pop up a lot, but which don't have their name in + // the Registry. + + if (IsEqualIID(rIid, IID_IMarshal)) + stream << "=\"IMarshal\""; + else if (IsEqualIID(rIid, IID_IMarshal2)) + stream << "=\"IMarshal2\""; + else if (IsEqualIID(rIid, IID_INoMarshal)) + stream << "=\"INoMarshal\""; + else if (IsEqualIID(rIid, IID_IdentityUnmarshal)) + stream << "=\"IdentityUnmarshal\""; + else if (IsEqualIID(rIid, IID_IFastRundown)) + stream << "=\"IFastRundown\""; + else if (IsEqualIID(rIid, IID_IStdMarshalInfo)) + stream << "=\"IStdMarshalInfo\""; + else if (IsEqualIID(rIid, IID_IAgileObject)) + stream << "=\"IAgileObject\""; + else if (IsEqualIID(rIid, IID_IExternalConnection)) + stream << "=\"IExternalConnection\""; + else if (IsEqualIID(rIid, IID_ICallFactory)) + stream << "=\"ICallFactory\""; + } + + CoTaskMemFree(pRiid); + return stream; +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& stream, + const VARIANT& rVariant) +{ + if (rVariant.vt & VT_VECTOR) + stream << "VECTOR:"; + if (rVariant.vt & VT_ARRAY) + stream << "ARRAY:"; + if (rVariant.vt & VT_BYREF) + stream << "BYREF:"; + + switch (rVariant.vt & ~(VT_VECTOR | VT_ARRAY | VT_BYREF)) + { + case VT_EMPTY: + stream << "EMPTY"; + break; + case VT_NULL: + stream << "NULL"; + break; + case VT_I2: + stream << "I2"; + break; + case VT_I4: + stream << "I4"; + break; + case VT_R4: + stream << "R4"; + break; + case VT_R8: + stream << "R8"; + break; + case VT_CY: + stream << "CY"; + break; + case VT_DATE: + stream << "DATE"; + break; + case VT_BSTR: + stream << "BSTR"; + break; + case VT_DISPATCH: + stream << "DISPATCH"; + break; + case VT_ERROR: + stream << "ERROR"; + break; + case VT_BOOL: + stream << "BOOL"; + break; + case VT_VARIANT: + stream << "VARIANT"; + break; + case VT_UNKNOWN: + stream << "UNKNOWN"; + break; + case VT_DECIMAL: + stream << "DECIMAL"; + break; + case VT_I1: + stream << "I1"; + break; + case VT_UI1: + stream << "UI1"; + break; + case VT_UI2: + stream << "UI2"; + break; + case VT_UI4: + stream << "UI4"; + break; + case VT_I8: + stream << "I8"; + break; + case VT_UI8: + stream << "UI8"; + break; + case VT_INT: + stream << "INT"; + break; + case VT_UINT: + stream << "UINT"; + break; + case VT_VOID: + stream << "VOID"; + break; + case VT_HRESULT: + stream << "HRESULT"; + break; + case VT_PTR: + stream << "PTR"; + break; + case VT_SAFEARRAY: + stream << "SAFEARRAY"; + break; + case VT_CARRAY: + stream << "CARRAY"; + break; + case VT_USERDEFINED: + stream << "USERDEFINED"; + break; + case VT_LPSTR: + stream << "LPSTR"; + break; + case VT_LPWSTR: + stream << "LPWSTR"; + break; + case VT_RECORD: + stream << "RECORD"; + break; + case VT_INT_PTR: + stream << "INT_PTR"; + break; + case VT_UINT_PTR: + stream << "UINT_PTR"; + break; + case VT_FILETIME: + stream << "FILETIME"; + break; + case VT_BLOB: + stream << "BLOB"; + break; + case VT_STREAM: + stream << "STREAM"; + break; + case VT_STORAGE: + stream << "STORAGE"; + break; + case VT_STREAMED_OBJECT: + stream << "STREAMED_OBJECT"; + break; + case VT_STORED_OBJECT: + stream << "STORED_OBJECT"; + break; + case VT_BLOB_OBJECT: + stream << "BLOB_OBJECT"; + break; + case VT_CF: + stream << "CF"; + break; + case VT_CLSID: + stream << "CLSID"; + break; + case VT_VERSIONED_STREAM: + stream << "VERSIONED_STREAM"; + break; + case VT_BSTR_BLOB: + stream << "BSTR_BLOB"; + break; + default: + stream << rVariant.vt; + break; + } + if (rVariant.vt == VT_EMPTY || rVariant.vt == VT_NULL || rVariant.vt == VT_VOID) + return stream; + stream << ":"; + + std::ios_base::fmtflags flags; + std::streamsize width; + charT fill; + + if (rVariant.vt & VT_BYREF) + { + stream << rVariant.byref << ":"; + if (rVariant.byref == nullptr) + return stream; + if ((rVariant.vt & VT_TYPEMASK) == VT_VOID || (rVariant.vt & VT_TYPEMASK) == VT_USERDEFINED) + return stream; + stream << ":"; + switch (rVariant.vt & VT_TYPEMASK) + { + case VT_I2: + stream << *static_cast(rVariant.byref); + break; + case VT_I4: + stream << *static_cast(rVariant.byref); + break; + case VT_R4: + stream << *static_cast(rVariant.byref); + break; + case VT_R8: + stream << *static_cast(rVariant.byref); + break; + case VT_CY: + stream << static_cast(rVariant.byref)->int64; + break; + case VT_DATE: + stream << *static_cast(rVariant.byref); + break; // FIXME + case VT_BSTR: + stream << std::wstring_convert, wchar_t>().to_bytes( + *static_cast(rVariant.byref)); + break; + case VT_DISPATCH: + stream << rVariant.byref; + break; + case VT_ERROR: + case VT_HRESULT: + flags = stream.flags(); + stream << std::hex << *static_cast(rVariant.byref); + stream.setf(flags); + break; + case VT_BOOL: + stream << (*static_cast(rVariant.byref) ? "YES" : "NO"); + break; + case VT_VARIANT: + stream << *static_cast(rVariant.byref); + break; + case VT_UNKNOWN: + stream << *static_cast(rVariant.byref); + break; + case VT_DECIMAL: + flags = stream.flags(); + width = stream.width(); + fill = stream.fill(); + stream << std::hex << std::setw(8) << std::setfill('0') + << static_cast(rVariant.byref)->Hi32; + stream << std::setw(16) << static_cast(rVariant.byref)->Lo64; + stream.setf(flags); + stream << std::setw(width) << std::setfill(fill); + break; + case VT_I1: + stream << static_cast(*static_cast(rVariant.byref)); + break; + case VT_UI1: + stream << static_cast(*static_cast(rVariant.byref)); + break; + case VT_UI2: + stream << *static_cast(rVariant.byref); + break; + case VT_UI4: + stream << *static_cast(rVariant.byref); + break; + case VT_I8: + stream << *static_cast(rVariant.byref); + break; + case VT_UI8: + stream << *static_cast(rVariant.byref); + break; + case VT_INT: + stream << *static_cast(rVariant.byref); + break; + case VT_UINT: + stream << *static_cast(rVariant.byref); + break; + case VT_INT_PTR: + stream << *static_cast(rVariant.byref); + break; + case VT_UINT_PTR: + stream << *static_cast(rVariant.byref); + break; + case VT_PTR: + case VT_CARRAY: + stream << *static_cast(rVariant.byref); + break; + case VT_SAFEARRAY: + break; // FIXME + case VT_LPSTR: + stream << *static_cast(rVariant.byref); + break; + case VT_LPWSTR: + stream << std::wstring_convert, wchar_t>().to_bytes( + std::wstring(*static_cast(rVariant.byref))); + break; + case VT_FILETIME: + break; // FIXME + case VT_BLOB: + break; // FIXME + case VT_STREAM: + break; // FIXME + case VT_STORAGE: + break; // FIXME + case VT_STREAMED_OBJECT: + break; // FIXME + case VT_STORED_OBJECT: + break; // FIXME + case VT_BLOB_OBJECT: + break; // FIXME + case VT_CF: + break; // FIXME + case VT_CLSID: + stream << *static_cast(rVariant.byref); + break; + case VT_VERSIONED_STREAM: + break; // FIXME + case VT_BSTR_BLOB: + break; // FIXME + default: + stream << "?(" << (rVariant.vt & VT_TYPEMASK) << ")"; + break; + } + return stream; + } + + switch (rVariant.vt & VT_TYPEMASK) + { + case VT_I2: + stream << rVariant.iVal; + break; + case VT_I4: + stream << rVariant.lVal; + break; + case VT_R4: + stream << rVariant.fltVal; + break; + case VT_R8: + stream << rVariant.dblVal; + break; + case VT_CY: + stream << rVariant.cyVal.int64; + break; + case VT_DATE: + stream << static_cast(rVariant.date); + break; // FIXME + case VT_BSTR: + if (rVariant.bstrVal == nullptr) + stream << "(null)"; + else + stream << std::wstring_convert, wchar_t>().to_bytes( + rVariant.bstrVal); + break; + case VT_DISPATCH: + stream << rVariant.pdispVal; + break; + case VT_ERROR: + case VT_HRESULT: + flags = stream.flags(); + stream << std::hex << rVariant.lVal; + stream.setf(flags); + break; + case VT_BOOL: + stream << (rVariant.boolVal ? "YES" : "NO"); + break; + case VT_UNKNOWN: + stream << rVariant.punkVal; + break; + case VT_DECIMAL: + flags = stream.flags(); + width = stream.width(); + fill = stream.fill(); + stream << std::hex << std::setw(8) << std::setfill('0') << rVariant.decVal.Hi32; + stream << std::setw(16) << rVariant.decVal.Lo64; + stream.setf(flags); + stream << std::setw(width) << std::setfill(fill); + break; + case VT_I1: + stream << static_cast(rVariant.bVal); + break; + case VT_UI1: + stream << static_cast(rVariant.bVal); + break; + case VT_UI2: + stream << static_cast(rVariant.iVal); + break; + case VT_UI4: + stream << static_cast(rVariant.lVal); + break; + case VT_I8: + stream << rVariant.llVal; + break; + case VT_UI8: + stream << static_cast(rVariant.llVal); + break; + case VT_INT: + stream << rVariant.lVal; + break; + case VT_UINT: + stream << static_cast(rVariant.lVal); + break; + case VT_INT_PTR: + stream << reinterpret_cast(rVariant.plVal); + break; + case VT_UINT_PTR: + stream << reinterpret_cast(rVariant.plVal); + break; + case VT_PTR: + case VT_CARRAY: + stream << rVariant.byref; + break; + case VT_SAFEARRAY: + break; // FIXME + case VT_LPSTR: + stream << std::wstring_convert, wchar_t>().to_bytes( + rVariant.bstrVal); + break; + case VT_LPWSTR: + stream << std::wstring_convert, wchar_t>().to_bytes( + std::wstring(static_cast(rVariant.byref))); + break; + case VT_FILETIME: + break; // FIXME + case VT_BLOB: + break; // FIXME + case VT_STREAM: + break; // FIXME + case VT_STORAGE: + break; // FIXME + case VT_STREAMED_OBJECT: + break; // FIXME + case VT_STORED_OBJECT: + break; // FIXME + case VT_BLOB_OBJECT: + break; // FIXME + case VT_CF: + break; // FIXME + case VT_VERSIONED_STREAM: + break; // FIXME + case VT_BSTR_BLOB: + break; // FIXME + default: + stream << "?(" << (rVariant.vt & VT_TYPEMASK) << ")"; + break; + } + return stream; +} + +inline std::string DMPAPER_to_string(int dmpaper) +{ + switch (dmpaper) + { + case DMPAPER_LETTER: + return "LETTER"; + case DMPAPER_LETTERSMALL: + return "LETTERSMALL"; + case DMPAPER_TABLOID: + return "TABLOID"; + case DMPAPER_LEDGER: + return "LEDGER"; + case DMPAPER_LEGAL: + return "LEGAL"; + case DMPAPER_STATEMENT: + return "STATEMENT"; + case DMPAPER_EXECUTIVE: + return "EXECUTIVE"; + case DMPAPER_A3: + return "A3"; + case DMPAPER_A4: + return "A4"; + case DMPAPER_A4SMALL: + return "A4SMALL"; + case DMPAPER_A5: + return "A5"; + case DMPAPER_B4: + return "B4"; + case DMPAPER_B5: + return "B5"; + case DMPAPER_FOLIO: + return "FOLIO"; + case DMPAPER_QUARTO: + return "QUARTO"; + case DMPAPER_10X14: + return "10X14"; + case DMPAPER_11X17: + return "11X17"; + case DMPAPER_NOTE: + return "NOTE"; + case DMPAPER_ENV_9: + return "ENV_9"; + case DMPAPER_ENV_10: + return "ENV_10"; + case DMPAPER_ENV_11: + return "ENV_11"; + case DMPAPER_ENV_12: + return "ENV_12"; + case DMPAPER_ENV_14: + return "ENV_14"; + case DMPAPER_CSHEET: + return "CSHEET"; + case DMPAPER_DSHEET: + return "DSHEET"; + case DMPAPER_ESHEET: + return "ESHEET"; + case DMPAPER_ENV_DL: + return "ENV_DL"; + case DMPAPER_ENV_C5: + return "ENV_C5"; + case DMPAPER_ENV_C3: + return "ENV_C3"; + case DMPAPER_ENV_C4: + return "ENV_C4"; + case DMPAPER_ENV_C6: + return "ENV_C6"; + case DMPAPER_ENV_C65: + return "ENV_C65"; + case DMPAPER_ENV_B4: + return "ENV_B4"; + case DMPAPER_ENV_B5: + return "ENV_B5"; + case DMPAPER_ENV_B6: + return "ENV_B6"; + case DMPAPER_ENV_ITALY: + return "ENV_ITALY"; + case DMPAPER_ENV_MONARCH: + return "ENV_MONARCH"; + case DMPAPER_ENV_PERSONAL: + return "ENV_PERSONAL"; + case DMPAPER_FANFOLD_US: + return "FANFOLD_US"; + case DMPAPER_FANFOLD_STD_GERMAN: + return "FANFOLD_STD_GERMAN"; + case DMPAPER_FANFOLD_LGL_GERMAN: + return "FANFOLD_LGL_GERMAN"; + case DMPAPER_ISO_B4: + return "ISO_B4"; + case DMPAPER_JAPANESE_POSTCARD: + return "JAPANESE_POSTCARD"; + case DMPAPER_9X11: + return "9X11"; + case DMPAPER_10X11: + return "10X11"; + case DMPAPER_15X11: + return "15X11"; + case DMPAPER_ENV_INVITE: + return "ENV_INVITE"; + case DMPAPER_RESERVED_48: + return "RESERVED_48"; + case DMPAPER_RESERVED_49: + return "RESERVED_49"; + case DMPAPER_LETTER_EXTRA: + return "LETTER_EXTRA"; + case DMPAPER_LEGAL_EXTRA: + return "LEGAL_EXTRA"; + case DMPAPER_TABLOID_EXTRA: + return "TABLOID_EXTRA"; + case DMPAPER_A4_EXTRA: + return "A4_EXTRA"; + case DMPAPER_LETTER_TRANSVERSE: + return "LETTER_TRANSVERSE"; + case DMPAPER_A4_TRANSVERSE: + return "A4_TRANSVERSE"; + case DMPAPER_LETTER_EXTRA_TRANSVERSE: + return "LETTER_EXTRA_TRANSVERSE"; + case DMPAPER_A_PLUS: + return "A_PLUS"; + case DMPAPER_B_PLUS: + return "B_PLUS"; + case DMPAPER_LETTER_PLUS: + return "LETTER_PLUS"; + case DMPAPER_A4_PLUS: + return "A4_PLUS"; + case DMPAPER_A5_TRANSVERSE: + return "A5_TRANSVERSE"; + case DMPAPER_B5_TRANSVERSE: + return "B5_TRANSVERSE"; + case DMPAPER_A3_EXTRA: + return "A3_EXTRA"; + case DMPAPER_A5_EXTRA: + return "A5_EXTRA"; + case DMPAPER_B5_EXTRA: + return "B5_EXTRA"; + case DMPAPER_A2: + return "A2"; + case DMPAPER_A3_TRANSVERSE: + return "A3_TRANSVERSE"; + case DMPAPER_A3_EXTRA_TRANSVERSE: + return "A3_EXTRA_TRANSVERSE"; + case DMPAPER_DBL_JAPANESE_POSTCARD: + return "DBL_JAPANESE_POSTCARD"; + case DMPAPER_A6: + return "A6"; + case DMPAPER_JENV_KAKU2: + return "JENV_KAKU2"; + case DMPAPER_JENV_KAKU3: + return "JENV_KAKU3"; + case DMPAPER_JENV_CHOU3: + return "JENV_CHOU3"; + case DMPAPER_JENV_CHOU4: + return "JENV_CHOU4"; + case DMPAPER_LETTER_ROTATED: + return "LETTER_ROTATED"; + case DMPAPER_A3_ROTATED: + return "A3_ROTATED"; + case DMPAPER_A4_ROTATED: + return "A4_ROTATED"; + case DMPAPER_A5_ROTATED: + return "A5_ROTATED"; + case DMPAPER_B4_JIS_ROTATED: + return "B4_JIS_ROTATED"; + case DMPAPER_B5_JIS_ROTATED: + return "B5_JIS_ROTATED"; + case DMPAPER_JAPANESE_POSTCARD_ROTATED: + return "JAPANESE_POSTCARD_ROTATED"; + case DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED: + return "DBL_JAPANESE_POSTCARD_ROTATED"; + case DMPAPER_A6_ROTATED: + return "A6_ROTATED"; + case DMPAPER_JENV_KAKU2_ROTATED: + return "JENV_KAKU2_ROTATED"; + case DMPAPER_JENV_KAKU3_ROTATED: + return "JENV_KAKU3_ROTATED"; + case DMPAPER_JENV_CHOU3_ROTATED: + return "JENV_CHOU3_ROTATED"; + case DMPAPER_JENV_CHOU4_ROTATED: + return "JENV_CHOU4_ROTATED"; + case DMPAPER_B6_JIS: + return "B6_JIS"; + case DMPAPER_B6_JIS_ROTATED: + return "B6_JIS_ROTATED"; + case DMPAPER_12X11: + return "12X11"; + case DMPAPER_JENV_YOU4: + return "JENV_YOU4"; + case DMPAPER_JENV_YOU4_ROTATED: + return "JENV_YOU4_ROTATED"; + case DMPAPER_P16K: + return "P16K"; + case DMPAPER_P32K: + return "P32K"; + case DMPAPER_P32KBIG: + return "P32KBIG"; + case DMPAPER_PENV_1: + return "PENV_1"; + case DMPAPER_PENV_2: + return "PENV_2"; + case DMPAPER_PENV_3: + return "PENV_3"; + case DMPAPER_PENV_4: + return "PENV_4"; + case DMPAPER_PENV_5: + return "PENV_5"; + case DMPAPER_PENV_6: + return "PENV_6"; + case DMPAPER_PENV_7: + return "PENV_7"; + case DMPAPER_PENV_8: + return "PENV_8"; + case DMPAPER_PENV_9: + return "PENV_9"; + case DMPAPER_PENV_10: + return "PENV_10"; + case DMPAPER_P16K_ROTATED: + return "P16K_ROTATED"; + case DMPAPER_P32K_ROTATED: + return "P32K_ROTATED"; + case DMPAPER_P32KBIG_ROTATED: + return "P32KBIG_ROTATED"; + case DMPAPER_PENV_1_ROTATED: + return "PENV_1_ROTATED"; + case DMPAPER_PENV_2_ROTATED: + return "PENV_2_ROTATED"; + case DMPAPER_PENV_3_ROTATED: + return "PENV_3_ROTATED"; + case DMPAPER_PENV_4_ROTATED: + return "PENV_4_ROTATED"; + case DMPAPER_PENV_5_ROTATED: + return "PENV_5_ROTATED"; + case DMPAPER_PENV_6_ROTATED: + return "PENV_6_ROTATED"; + case DMPAPER_PENV_7_ROTATED: + return "PENV_7_ROTATED"; + case DMPAPER_PENV_8_ROTATED: + return "PENV_8_ROTATED"; + case DMPAPER_PENV_9_ROTATED: + return "PENV_9_ROTATED"; + case DMPAPER_PENV_10_ROTATED: + return "PENV_10_ROTATED"; + default: + return "?" + std::to_string(dmpaper); + } +} + +inline std::string DC_PAPERSIZE_array_to_string(POINT* pPaperSizes, DWORD nCount) +{ + std::string result; + + for (DWORD i = 0; i < nCount; i++) + { + if (i > 0) + result += ", "; + + result += std::to_string(std::lround(pPaperSizes[i].x / 10.0)) + "x" + + std::to_string(std::lround(pPaperSizes[i].y / 10.0)); + +#if 0 + // WIP. Printer::GetPaperName() should really be inline in or + // something, so that it can be used anywhere. We can't depend on vcl in this file as we + // might be included in modules that precede vcl. + PaperInfo paperInfo(pPaperSizes[i].x * 10, pPaperSizes[i].y * 10); + paperInfo.doSloppyFit(true); + if (paperInfo.getPaper() != PAPER_USER) + result += "(" + std::string(Printer::GetPaperName(paperInfo.getPaper()).toUtf8().getStr()) + ")"; +#endif + } + return result; +} + +#endif // INCLUDED_COMPHELPER_WINDOWSDEBUGOUTPUT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/windowserrorstring.hxx b/include/comphelper/windowserrorstring.hxx new file mode 100644 index 000000000..1b50f1ead --- /dev/null +++ b/include/comphelper/windowserrorstring.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX +#define INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX + +#include +#include +#include +#include + +namespace { + +inline OUString WindowsErrorString(DWORD nErrorCode) +{ + LPWSTR pMsgBuf; + + if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + nErrorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&pMsgBuf), + 0, + nullptr) == 0) + return OUString::number(nErrorCode, 16); + + OUString result(o3tl::toU(pMsgBuf)); + result.endsWith("\r\n", &result); + + HeapFree(GetProcessHeap(), 0, pMsgBuf); + + return result; +} + +inline OUString WindowsErrorStringFromHRESULT(HRESULT hr) +{ + // See https://blogs.msdn.microsoft.com/oldnewthing/20061103-07/?p=29133 + // Also https://social.msdn.microsoft.com/Forums/vstudio/en-US/c33d9a4a-1077-4efd-99e8-0c222743d2f8 + // (which refers to https://msdn.microsoft.com/en-us/library/aa382475) + // explains why can't we just reinterpret_cast HRESULT to DWORD Win32 error: + // we might actually have a Win32 error code converted using HRESULT_FROM_WIN32 macro + + DWORD nErrorCode = DWORD(hr); + if (HRESULT(hr & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0) || hr == S_OK) + { + nErrorCode = HRESULT_CODE(hr); + // https://msdn.microsoft.com/en-us/library/ms679360 mentions that the codes might have + // high word bits set (e.g., bit 29 could be set if error comes from a 3rd-party library). + // So try to restore the original error code to avoid wrong error messages + DWORD nLastError = GetLastError(); + if ((nLastError & 0xFFFF) == nErrorCode) + nErrorCode = nLastError; + } + + return WindowsErrorString(nErrorCode); +} + +} // anonymous namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/xmlsechelper.hxx b/include/comphelper/xmlsechelper.hxx new file mode 100644 index 000000000..9a245877f --- /dev/null +++ b/include/comphelper/xmlsechelper.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_COMPHELPER_XMLSECHELPER_HXX +#define INCLUDED_COMPHELPER_XMLSECHELPER_HXX + +#include + +#include +#include + +#include + +namespace comphelper::xmlsec +{ +COMPHELPER_DLLPUBLIC OUString GetCertificateKind(const css::security::CertificateKind& rKind); + +COMPHELPER_DLLPUBLIC std::vector> +parseDN(std::u16string_view rRawString); +COMPHELPER_DLLPUBLIC std::pair +GetDNForCertDetailsView(std::u16string_view rRawString); +COMPHELPER_DLLPUBLIC OUString GetContentPart(const OUString& _rRawString, + const css::security::CertificateKind& rKind); + +COMPHELPER_DLLPUBLIC OUString GetHexString(const css::uno::Sequence& _rSeq, + const char* _pSep, sal_uInt16 _nLineBreak = 0xFFFF); +} + +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/comphelper/xmltools.hxx b/include/comphelper/xmltools.hxx new file mode 100644 index 000000000..9ef64b17d --- /dev/null +++ b/include/comphelper/xmltools.hxx @@ -0,0 +1,24 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_XMLTOOLS_HXX +#define INCLUDED_COMPHELPER_XMLTOOLS_HXX + +#include +#include + +namespace comphelper::xml +{ + COMPHELPER_DLLPUBLIC OString makeXMLChaff(); + COMPHELPER_DLLPUBLIC OString generateGUIDString(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/BlobHelper.hxx b/include/connectivity/BlobHelper.hxx new file mode 100644 index 000000000..95b5892dc --- /dev/null +++ b/include/connectivity/BlobHelper.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +namespace connectivity +{ + class OOO_DLLPUBLIC_DBTOOLS BlobHelper final : public ::cppu::WeakImplHelper< css::sdbc::XBlob > + { + css::uno::Sequence< sal_Int8 > m_aValue; + public: + BlobHelper(const css::uno::Sequence< sal_Int8 >& _val); + private: + virtual ::sal_Int64 SAL_CALL length( ) override; + virtual css::uno::Sequence< ::sal_Int8 > SAL_CALL getBytes( ::sal_Int64 pos, ::sal_Int32 length ) override; + virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getBinaryStream( ) override; + virtual ::sal_Int64 SAL_CALL position( const css::uno::Sequence< ::sal_Int8 >& pattern, ::sal_Int64 start ) override; + virtual ::sal_Int64 SAL_CALL positionOfBlob( const css::uno::Reference< css::sdbc::XBlob >& pattern, ::sal_Int64 start ) override; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/CommonTools.hxx b/include/connectivity/CommonTools.hxx new file mode 100644 index 000000000..a5279024e --- /dev/null +++ b/include/connectivity/CommonTools.hxx @@ -0,0 +1,167 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_COMMONTOOLS_HXX +#define INCLUDED_CONNECTIVITY_COMMONTOOLS_HXX + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { class XComponentContext; } + +#if HAVE_FEATURE_JAVA +namespace jvmaccess { class VirtualMachine; } +#endif + +namespace connectivity +{ + OOO_DLLPUBLIC_DBTOOLS bool match(const sal_Unicode* pWild, const sal_Unicode* pStr, const sal_Unicode cEscape); + inline bool match(const OUString &rWild, const OUString &rStr, const sal_Unicode cEscape) + { + return match(rWild.getStr(), rStr.getStr(), cEscape); + } + // typedefs + typedef std::vector< css::uno::WeakReferenceHelper > OWeakRefArray; + typedef css::uno::Reference< css::sdbcx::XColumnsSupplier> OSQLTable; + + typedef std::map OSQLTables; + + // class ORefVector allows reference counting on a std::vector + template< class VectorVal > class ORefVector : public salhelper::SimpleReferenceObject, + public std::vector< VectorVal > + { + protected: + virtual ~ORefVector() override {} + public: + typedef std::vector< VectorVal > Vector; + + ORefVector() {} + ORefVector(size_t _st) : std::vector< VectorVal >(_st) {} + ORefVector(const ORefVector& rOther) + : salhelper::SimpleReferenceObject() + , std::vector< VectorVal >(rOther) + {} + + ORefVector& operator=(const ORefVector& _rRH) + { + if ( &_rRH != this ) + { + std::vector< VectorVal >::operator=(_rRH); + } + return *this; + } + }; + + // class ORowVector includes refcounting and initialize himself + // with at least one element. This first element is reserved for + // the bookmark + template< class VectorVal > class ORowVector : public ORefVector< VectorVal > + { + public: + ORowVector() : ORefVector< VectorVal >(1){} + ORowVector(size_t _st) : ORefVector< VectorVal >(_st+1) + {} + }; + + typedef ORefVector< css::uno::Reference< css::beans::XPropertySet> > OSQLColumns; + + // search from first to last the column with the name _rVal + // when no such column exist last is returned + OOO_DLLPUBLIC_DBTOOLS + OSQLColumns::const_iterator find( const OSQLColumns::const_iterator& first, + const OSQLColumns::const_iterator& last, + std::u16string_view _rVal, + const ::comphelper::UStringMixEqual& _rCase); + + // search from first to last the column with the realname _rVal + // when no such column exist last is returned + OOO_DLLPUBLIC_DBTOOLS + OSQLColumns::const_iterator findRealName( const OSQLColumns::const_iterator& first, + const OSQLColumns::const_iterator& last, + std::u16string_view _rVal, + const ::comphelper::UStringMixEqual& _rCase); + + // the first two find methods are much faster than the one below + // search from first to last the column with the property _rProp equals the value _rVal + // when no such column exist last is returned + OOO_DLLPUBLIC_DBTOOLS + OSQLColumns::const_iterator find( OSQLColumns::const_iterator first, + const OSQLColumns::const_iterator& last, + const OUString& _rProp, + std::u16string_view _rVal, + const ::comphelper::UStringMixEqual& _rCase); + + /// @throws css::lang::DisposedException + OOO_DLLPUBLIC_DBTOOLS void checkDisposed(bool _bThrow); + +#if HAVE_FEATURE_JAVA + /** creates a java virtual machine + @param _rxContext + The ORB. + @return + The JavaVM. + */ + OOO_DLLPUBLIC_DBTOOLS ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const css::uno::Reference< css::uno::XComponentContext >& _rxContext); + + /** return if the java class exists, otherwise . + @param _pJVM + The JavaVM. + @param _sClassName + The class name to look for. + */ + OOO_DLLPUBLIC_DBTOOLS bool existsJavaClassByName( const ::rtl::Reference< jvmaccess::VirtualMachine >& _pJVM,std::u16string_view _sClassName ); +#endif +} + +#define DECLARE_SERVICE_INFO() \ + virtual OUString SAL_CALL getImplementationName( ) override; \ + virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) override; \ + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override \ + +#define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname) \ + OUString SAL_CALL classname::getImplementationName( ) \ + { \ + return implasciiname; \ + } \ + css::uno::Sequence< OUString > SAL_CALL classname::getSupportedServiceNames( ) \ + { \ + css::uno::Sequence< OUString > aSupported { serviceasciiname }; \ + return aSupported; \ + } \ + sal_Bool SAL_CALL classname::supportsService( const OUString& rServiceName ) \ + { \ + return cppu::supportsService(this, rServiceName); \ + } \ + +#endif // INCLUDED_CONNECTIVITY_COMMONTOOLS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/ConnectionWrapper.hxx b/include/connectivity/ConnectionWrapper.hxx new file mode 100644 index 000000000..8eac6a7b9 --- /dev/null +++ b/include/connectivity/ConnectionWrapper.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_CONNECTIONWRAPPER_HXX +#define INCLUDED_CONNECTIVITY_CONNECTIONWRAPPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::uno { class XComponentContext; } + +namespace connectivity +{ + + + //= OConnectionWrapper - wraps all methods to the real connection from the driver + //= but when disposed it doesn't dispose the real connection + + typedef ::cppu::ImplHelper2< css::lang::XServiceInfo, + css::lang::XUnoTunnel + > OConnection_BASE; + + class OOO_DLLPUBLIC_DBTOOLS OConnectionWrapper : public OConnection_BASE + { + protected: + css::uno::Reference< css::uno::XAggregation > m_xProxyConnection; + css::uno::Reference< css::sdbc::XConnection > m_xConnection; + css::uno::Reference< css::lang::XTypeProvider > m_xTypeProvider; + css::uno::Reference< css::lang::XUnoTunnel > m_xUnoTunnel; + css::uno::Reference< css::lang::XServiceInfo > m_xServiceInfo; + + virtual ~OConnectionWrapper(); + void setDelegation(css::uno::Reference< css::uno::XAggregation >& _rxProxyConnection,oslInterlockedCount& _rRefCount); + void setDelegation(const css::uno::Reference< css::sdbc::XConnection >& _xConnection + ,const css::uno::Reference< css::uno::XComponentContext>& _rxContext + ,oslInterlockedCount& _rRefCount); + // must be called from derived classes + void disposing(); + public: + OConnectionWrapper( ); + + // XServiceInfo + DECLARE_SERVICE_INFO(); + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& _rType ) override; + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + + // css::lang::XUnoTunnel + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId(); + /** method to create unique ids + @param _rURL + The URL. + @param _rInfo + The info property of the datasource. It will be resorted if needed. + @param _pBuffer + Here we store the digest. Must not NULL. + @param _rUserName + The user name. + @param _rPassword + The password. + */ + static void createUniqueId( const OUString& _rURL + ,css::uno::Sequence< css::beans::PropertyValue >& _rInfo + ,sal_uInt8* _pBuffer + ,const OUString& _rUserName = OUString() + ,const OUString& _rPassword = OUString()); + }; +} +#endif // INCLUDED_CONNECTIVITY_CONNECTIONWRAPPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/DriversConfig.hxx b/include/connectivity/DriversConfig.hxx new file mode 100644 index 000000000..ceb15bedd --- /dev/null +++ b/include/connectivity/DriversConfig.hxx @@ -0,0 +1,82 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_DRIVERSCONFIG_HXX +#define INCLUDED_CONNECTIVITY_DRIVERSCONFIG_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace connectivity +{ + struct TInstalledDriver + { + ::comphelper::NamedValueCollection aProperties; + ::comphelper::NamedValueCollection aFeatures; + ::comphelper::NamedValueCollection aMetaData; + OUString sDriverFactory; + OUString sDriverTypeDisplayName; + }; + typedef std::map TInstalledDrivers; + + class DriversConfigImpl + { + mutable ::utl::OConfigurationTreeRoot m_aInstalled; + mutable TInstalledDrivers m_aDrivers; + public: + DriversConfigImpl(); + + const TInstalledDrivers& getInstalledDrivers(const css::uno::Reference< css::uno::XComponentContext >& _rxORB) const; + }; + + // Allows to access all driver which are located in the configuration + + class OOO_DLLPUBLIC_DBTOOLS DriversConfig + { + typedef salhelper::SingletonRef OSharedConfigNode; + + const ::comphelper::NamedValueCollection& impl_get(std::u16string_view _sURL,sal_Int32 _nProps) const; + public: + DriversConfig(const css::uno::Reference< css::uno::XComponentContext >& _rxORB); + ~DriversConfig(); + + DriversConfig( const DriversConfig& ); + DriversConfig& operator=( const DriversConfig& ); + + OUString getDriverFactoryName(std::u16string_view _sUrl) const; + OUString getDriverTypeDisplayName(std::u16string_view _sUrl) const; + const ::comphelper::NamedValueCollection& getProperties(std::u16string_view _sURL) const; + const ::comphelper::NamedValueCollection& getFeatures(std::u16string_view _sURL) const; + const ::comphelper::NamedValueCollection& getMetaData(std::u16string_view _sURL) const; + css::uno::Sequence< OUString > getURLs() const; + private: + OSharedConfigNode m_aNode; + css::uno::Reference< css::uno::XComponentContext > m_xORB; + }; +} +#endif // INCLUDED_CONNECTIVITY_DRIVERSCONFIG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/FValue.hxx b/include/connectivity/FValue.hxx new file mode 100644 index 000000000..1fe2b9d5f --- /dev/null +++ b/include/connectivity/FValue.hxx @@ -0,0 +1,490 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_FVALUE_HXX +#define INCLUDED_CONNECTIVITY_FVALUE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::sdb { class XColumn; } +namespace com::sun::star::sdbc { class XRow; } + +namespace connectivity +{ + namespace detail + { + class IValueSource; + } + + class OOO_DLLPUBLIC_DBTOOLS ORowSetValue + { + union + { + bool m_bBool; + + sal_Int8 m_nInt8; + sal_uInt8 m_uInt8; + + sal_Int16 m_nInt16; + sal_uInt16 m_uInt16; + + sal_Int32 m_nInt32; + sal_uInt32 m_uInt32; + + sal_Int64 m_nInt64; + sal_uInt64 m_uInt64; + + float m_nFloat; + double m_nDouble; + + rtl_uString* m_pString; + + void* m_pValue; // date/time/timestamp/sequence + } m_aValue; + + sal_Int32 m_eTypeKind; // the database type + bool m_bNull : 1; // value is null + bool m_bBound : 1; // is bound + bool m_bModified : 1; // value was changed + bool m_bSigned : 1; // value is signed + + void free() noexcept; + + public: + ORowSetValue() + :m_eTypeKind(css::sdbc::DataType::VARCHAR) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + } + + ORowSetValue(const ORowSetValue& _rRH) + :m_eTypeKind(css::sdbc::DataType::VARCHAR) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(ORowSetValue&& _rRH) noexcept + :m_eTypeKind(css::sdbc::DataType::VARCHAR) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(std::move(_rRH)); + } + + ORowSetValue(const OUString& _rRH) + :m_eTypeKind(css::sdbc::DataType::VARCHAR) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(const double& _rRH) + :m_eTypeKind(css::sdbc::DataType::DOUBLE) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(float _rRH) + :m_eTypeKind(css::sdbc::DataType::FLOAT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(sal_Int8 _rRH) + :m_eTypeKind(css::sdbc::DataType::TINYINT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(sal_Int16 _rRH) + :m_eTypeKind(css::sdbc::DataType::SMALLINT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + ORowSetValue(sal_uInt16 _rRH) + :m_eTypeKind(css::sdbc::DataType::SMALLINT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(false) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + ORowSetValue(sal_Int32 _rRH) + :m_eTypeKind(css::sdbc::DataType::INTEGER) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + ORowSetValue(sal_uInt32 _rRH) + :m_eTypeKind(css::sdbc::DataType::INTEGER) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(false) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + ORowSetValue(sal_Int64 _rRH) + :m_eTypeKind(css::sdbc::DataType::BIGINT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + ORowSetValue(sal_uInt64 _rRH) + :m_eTypeKind(css::sdbc::DataType::BIGINT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(false) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(bool _rRH) + :m_eTypeKind(css::sdbc::DataType::BIT) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + ORowSetValue(sal_Bool) = delete; // aka sal_uInt8 + + ORowSetValue(const css::util::Date& _rRH) + :m_eTypeKind(css::sdbc::DataType::DATE) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(const css::util::Time& _rRH) + :m_eTypeKind(css::sdbc::DataType::TIME) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(const css::util::DateTime& _rRH) + :m_eTypeKind(css::sdbc::DataType::TIMESTAMP) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + ORowSetValue(const css::uno::Sequence& _rRH) + :m_eTypeKind(css::sdbc::DataType::LONGVARBINARY) + ,m_bNull(true) + ,m_bBound(true) + ,m_bModified(false) + ,m_bSigned(true) + { + m_aValue.m_pString = nullptr; + operator=(_rRH); + } + + // Avoid accidental uses of ORowSetValue(bool const &): + template ORowSetValue(T const *) = delete; + + ~ORowSetValue() + { + free(); + } + + ORowSetValue& operator=(const ORowSetValue& _rRH); + ORowSetValue& operator=(ORowSetValue&& _rRH) noexcept; + + // simple types + ORowSetValue& operator=(bool _rRH); + void operator =(sal_Bool) = delete; // aka sal_uInt8 + + ORowSetValue& operator=(sal_Int8 _rRH); + + ORowSetValue& operator=(sal_Int16 _rRH); + ORowSetValue& operator=(sal_uInt16 _rRH); + + ORowSetValue& operator=(sal_Int32 _rRH); + ORowSetValue& operator=(sal_uInt32 _rRH); + + ORowSetValue& operator=(sal_Int64 _rRH); + ORowSetValue& operator=(sal_uInt64 _rRH); + + ORowSetValue& operator=(double _rRH); + ORowSetValue& operator=(float _rRH); + + // ADT's + ORowSetValue& operator=(const css::util::Date& _rRH); + ORowSetValue& operator=(const css::util::Time& _rRH); + ORowSetValue& operator=(const css::util::DateTime& _rRH); + + ORowSetValue& operator=(const OUString& _rRH); + // the type isn't set it will be set to VARCHAR if the type is different change it + ORowSetValue& operator=(const css::uno::Sequence& _rRH); + // with the possibility to save an any for bookmarks + ORowSetValue& operator=(const css::uno::Any& _rAny); + + bool operator==(const ORowSetValue& _rRH) const; + bool operator!=(const ORowSetValue& _rRH) const + { + return !( *this == _rRH ); + } + + bool isNull() const + { + return m_bNull; + } + void setNull() + { + free(); + m_bNull = true; + m_aValue.m_pString = nullptr; + } + + bool isBound() const { return m_bBound; } + void setBound(bool _bBound) { m_bBound = _bBound; } + + bool isModified() const { return m_bModified; } + void setModified(bool _bMod) { m_bModified = _bMod; } + + bool isSigned() const { return m_bSigned; } + void setSigned(bool _bSig); + + sal_Int32 getTypeKind() const { return m_eTypeKind; } + void setTypeKind(sal_Int32 _eType); + + bool getBool() const; + + sal_Int8 getInt8() const; + sal_uInt8 getUInt8() const; + + sal_Int16 getInt16() const; + sal_uInt16 getUInt16() const; + + sal_Int32 getInt32() const; + sal_uInt32 getUInt32() const; + + sal_Int64 getLong() const; + sal_uInt64 getULong() const; + + double getDouble() const; + float getFloat() const; + + OUString getString() const; // makes an automatic conversion if type isn't a string + css::util::Date getDate() const; + css::util::Time getTime() const; + css::util::DateTime getDateTime() const; + css::uno::Sequence getSequence() const; + // only use for anys + const css::uno::Any& getAny() const { return *static_cast(m_aValue.m_pValue); } + css::uno::Any makeAny() const; + + /** + fetches a single value out of the row + @param _nPos the current column position + @param _nType the type of the current column + @param _xRow the row where to fetch the data from + */ + void fill(sal_Int32 _nPos, + sal_Int32 _nType, + const css::uno::Reference< css::sdbc::XRow>& _xRow); + + /** + fetches a single value out of the row + @param _nPos the current column position + @param _nType the type of the current column + @param _bNullable if true then it will be checked if the result could be NULL, otherwise not. + @param _xRow the row where to fetch the data from + */ + void fill(sal_Int32 _nPos, + sal_Int32 _nType, + bool _bNullable, + const css::uno::Reference< css::sdbc::XRow>& _xRow); + + void fill(const css::uno::Any& _rValue); + + void fill( const sal_Int32 _nType, + const css::uno::Reference< css::sdb::XColumn >& _rxColumn ); + + private: + void impl_fill( const sal_Int32 _nType, bool _bNullable, const detail::IValueSource& _rValueSource ); + }; + + /// ORowSetValueDecorator decorates an ORowSetValue so the value is "refcounted" + class OOO_DLLPUBLIC_DBTOOLS ORowSetValueDecorator final : public ::salhelper::SimpleReferenceObject + { + ORowSetValue m_aValue; // my own value + public: + ORowSetValueDecorator(){m_aValue.setBound(true);} + ORowSetValueDecorator(const ORowSetValue& _aValue) : m_aValue(_aValue){m_aValue.setBound(true);} + ORowSetValueDecorator& operator=(const ORowSetValue& _aValue); + + operator const ORowSetValue&() const { return m_aValue; } + bool operator ==( const ORowSetValue & _rRH ) { return m_aValue == _rRH; } + const ORowSetValue& getValue() const { return m_aValue; } + ORowSetValue& get() { return m_aValue; } + void setValue(const ORowSetValue& _aValue) { m_aValue = _aValue; } + void setNull() { m_aValue.setNull(); } + void setBound(bool _bBound ) { m_aValue.setBound(_bBound);} + bool isBound( ) const { return m_aValue.isBound();} + void setTypeKind(sal_Int32 _nType) { m_aValue.setTypeKind(_nType); } + void setModified(bool _bModified) { m_aValue.setModified(_bModified); } + + }; + typedef ::rtl::Reference ORowSetValueDecoratorRef; + + + /// TSetBound is a functor to set the bound value with e.q. for_each call + struct OOO_DLLPUBLIC_DBTOOLS TSetBound + { + bool m_bBound; + TSetBound(bool _bBound) : m_bBound(_bBound){} + void operator()(ORowSetValue& _rValue) const { _rValue.setBound(m_bBound); } + + }; + + + /// TSetBound is a functor to set the bound value with e.q. for_each call + struct OOO_DLLPUBLIC_DBTOOLS TSetRefBound + { + bool m_bBound; + TSetRefBound(bool _bBound) : m_bBound(_bBound){} + void operator()(ORowSetValueDecoratorRef const & _rValue) const { _rValue->setBound(m_bBound); } + + }; + + + // Vector for file based rows + + template< class VectorVal > class ODeleteVector : public connectivity::ORowVector< VectorVal > + { + bool m_bDeleted; + public: + ODeleteVector() : connectivity::ORowVector< VectorVal >() ,m_bDeleted(false) {} + ODeleteVector(size_t _st) : connectivity::ORowVector< VectorVal >(_st) ,m_bDeleted(false) {} + + bool isDeleted() const { return m_bDeleted; } + void setDeleted(bool _bDeleted) { m_bDeleted = _bDeleted; } + }; + + typedef ODeleteVector< ORowSetValue > OValueVector; + + class OOO_DLLPUBLIC_DBTOOLS OValueRefVector : public ODeleteVector< ORowSetValueDecoratorRef > + { + public: + OValueRefVector(){} + OValueRefVector(size_t _st) : ODeleteVector< ORowSetValueDecoratorRef >(_st) + { + for (auto & elem : *this) + elem = new ORowSetValueDecorator; + } + }; + +#define SQL_NO_PARAMETER (SAL_MAX_UINT32) + class OAssignValues final : public OValueRefVector + { + ::std::vector m_nParameterIndexes; + public: + OAssignValues(size_type n) : OValueRefVector(n),m_nParameterIndexes(n+1,SQL_NO_PARAMETER){} + + void setParameterIndex(sal_Int32 _nId,sal_Int32 _nParameterIndex) { m_nParameterIndexes[_nId] = _nParameterIndex;} + sal_Int32 getParameterIndex(sal_Int32 _nId) const { return m_nParameterIndexes[_nId]; } + }; + + typedef ::rtl::Reference< OAssignValues > ORefAssignValues; + + + typedef ::rtl::Reference< OValueVector > OValueRow; + typedef ::rtl::Reference< OValueRefVector > OValueRefRow; +} + +#endif // INCLUDED_CONNECTIVITY_FVALUE_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/IParseContext.hxx b/include/connectivity/IParseContext.hxx new file mode 100644 index 000000000..51171281d --- /dev/null +++ b/include/connectivity/IParseContext.hxx @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_IPARSECONTEXT_HXX +#define INCLUDED_CONNECTIVITY_IPARSECONTEXT_HXX + +#include +#include + +namespace connectivity +{ + + //= IParseContext + + class IParseContext + { + public: + enum class ErrorCode + { + General, // "Syntax error in SQL expression" + ValueNoLike, // "The value #1 can not be used with LIKE." + FieldNoLike, // "LIKE can not be used with this field." + InvalidCompare, // "The entered criterion can not be compared with this field." + InvalidIntCompare, // "The field can not be compared with a number." + InvalidDateCompare, // "The field can not be compared with a date." + InvalidRealCompare, // "The field can not be compared with a floating point number." + InvalidTableNosuch, // "The database does not contain a table named \"#\"." + // Named like this to avoid conflict with a #define in the Windows system ODBC headers. + InvalidTableOrQuery, // "The database does contain neither a table nor a query named \"#\"." + InvalidColumn, // "The column \"#1\" is unknown in the table \"#2\"." + InvalidTableExist, // "The database already contains a table or view with name \"#\"." + InvalidQueryExist // "The database already contains a query with name \"#\"."; + }; + + enum class InternationalKeyCode + { + None = 0, + Like, + Not, + Null, + True, + False, + Is, + Between, + Or, + And, + Avg, + Count, + Max, + Min, + Sum, + Every, + Any, + Some, + StdDevPop, + StdDevSamp, + VarSamp, + VarPop, + Collect, + Fusion, + Intersection + }; + + public: + // retrieves language specific error messages + virtual OUString getErrorMessage(ErrorCode _eCodes) const = 0; + + // retrieves language specific keyword strings (only ASCII allowed) + virtual OString getIntlKeywordAscii(InternationalKeyCode _eKey) const = 0; + + // finds out, if we have an international keyword (only ASCII allowed) + virtual InternationalKeyCode getIntlKeyCode(const OString& rToken) const = 0; + + /** gets a locale instance which should be used when parsing in the context specified by this instance +

if this is not overridden by derived classes, it returns the static default locale.

+ */ + virtual css::lang::Locale getPreferredLocale( ) const = 0; + + protected: + ~IParseContext() {} + }; +} + +#endif // INCLUDED_CONNECTIVITY_IPARSECONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/PColumn.hxx b/include/connectivity/PColumn.hxx new file mode 100644 index 000000000..46ceaa1bb --- /dev/null +++ b/include/connectivity/PColumn.hxx @@ -0,0 +1,148 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_PCOLUMN_HXX +#define INCLUDED_CONNECTIVITY_PCOLUMN_HXX + +#include + +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star::container { class XNameAccess; } +namespace com::sun::star::sdbc { class XDatabaseMetaData; } +namespace com::sun::star::sdbc { class XResultSetMetaData; } + +namespace connectivity::parse + { + class OParseColumn; + + typedef sdbcx::OColumn OParseColumn_BASE; + typedef ::comphelper::OPropertyArrayUsageHelper OParseColumn_PROP; + + class OOO_DLLPUBLIC_DBTOOLS OParseColumn final : + public OParseColumn_BASE, public OParseColumn_PROP + { + OUString m_aRealName; + OUString m_sLabel; + bool m_bFunction; + bool m_bDbasePrecisionChanged; + bool m_bAggregateFunction; + bool m_bIsSearchable; + + virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const override; + virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper() override; + + virtual ~OParseColumn() override; + public: + OParseColumn(const css::uno::Reference< css::beans::XPropertySet>& _xColumn, bool _bCase); + OParseColumn(const OUString& Name, + const OUString& TypeName, + const OUString& DefaultValue, + const OUString& Description, + sal_Int32 IsNullable, + sal_Int32 Precision, + sal_Int32 Scale, + sal_Int32 Type, + bool IsAutoIncrement, + bool IsCurrency, + bool _bCase, + const OUString& CatalogName, + const OUString& SchemaName, + const OUString& TableName); + + virtual void construct() override; + + void setRealName(const OUString& _rName) { m_aRealName = _rName; } + void setLabel(const OUString& i_sLabel) { m_sLabel = i_sLabel; } + void setTableName(const OUString& _rName) { m_TableName = _rName; } + void setFunction(bool _bFunction) { m_bFunction = _bFunction; } + void setAggregateFunction(bool _bFunction) { m_bAggregateFunction = _bFunction; } + void setIsSearchable( bool _bIsSearchable ) { m_bIsSearchable = _bIsSearchable; } + const OUString& getRealName() const { return m_aRealName; } + + /** creates a collection of OParseColumn, as described by a result set meta data instance. + */ + static ::rtl::Reference< OSQLColumns > + createColumnsForResultSet( + const css::uno::Reference< css::sdbc::XResultSetMetaData >& _rxResMetaData, + const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _rxDBMetaData, + const css::uno::Reference< css::container::XNameAccess>& i_xQueryColumns + ); + + typedef std::map StringMap; + /** creates a single OParseColumn, as described by a result set meta data instance. + The column names are unique. + */ + static rtl::Reference + createColumnForResultSet( + const css::uno::Reference< css::sdbc::XResultSetMetaData >& _rxResMetaData, + const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _rxDBMetaData, + sal_Int32 _nColumnPos, + StringMap& _rColumns + ); + + private: + using OParseColumn_BASE::createArrayHelper; + }; + + class OOrderColumn; + + typedef sdbcx::OColumn OOrderColumn_BASE; + typedef ::comphelper::OPropertyArrayUsageHelper OOrderColumn_PROP; + + class OOrderColumn final : + public OOrderColumn_BASE, public OOrderColumn_PROP + { + const bool m_bAscending; + + virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const override; + virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper() override; + + virtual ~OOrderColumn() override; + public: + OOrderColumn( + const css::uno::Reference< css::beans::XPropertySet>& _xColumn, + const OUString& i_rOriginatingTableName, + bool _bCase, + bool _bAscending + ); + + OOrderColumn( + const css::uno::Reference< css::beans::XPropertySet>& _xColumn, + bool _bCase, + bool _bAscending + ); + + virtual void construct() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; + private: + using OOrderColumn_BASE::createArrayHelper; + }; + +} + +#endif // INCLUDED_CONNECTIVITY_PCOLUMN_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/TColumnsHelper.hxx b/include/connectivity/TColumnsHelper.hxx new file mode 100644 index 000000000..c50aefb27 --- /dev/null +++ b/include/connectivity/TColumnsHelper.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_TCOLUMNSHELPER_HXX +#define INCLUDED_CONNECTIVITY_TCOLUMNSHELPER_HXX + +#include +#include +#include + +namespace connectivity +{ + class OTableHelper; + class OColumnsHelperImpl; + /** contains general column handling to create default columns and default sql statements. + */ + class OOO_DLLPUBLIC_DBTOOLS OColumnsHelper : public sdbcx::OCollection + { + std::unique_ptr m_pImpl; + protected: + OTableHelper* m_pTable; + + virtual sdbcx::ObjectType createObject(const OUString& _rName) override; + virtual void impl_refresh() override; + virtual css::uno::Reference< css::beans::XPropertySet > createDescriptor() override; + virtual sdbcx::ObjectType appendObject( const OUString& _rForName, const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + virtual void dropObject(sal_Int32 _nPos, const OUString& _sElementName) override; + public: + OColumnsHelper( ::cppu::OWeakObject& _rParent + ,bool _bCase + ,::osl::Mutex& _rMutex + ,const ::std::vector< OUString> &_rVector + ,bool _bUseHardRef + ); + virtual ~OColumnsHelper() override; + + /** set the parent of the columns. Can also be . + @param _pTable + The parent. + */ + void setParent(OTableHelper* _pTable) { m_pTable = _pTable;} + }; +} +#endif // INCLUDED_CONNECTIVITY_TCOLUMNSHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/TIndexes.hxx b/include/connectivity/TIndexes.hxx new file mode 100644 index 000000000..4f3a09305 --- /dev/null +++ b/include/connectivity/TIndexes.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_TINDEXES_HXX +#define INCLUDED_CONNECTIVITY_TINDEXES_HXX + +#include +#include + +namespace connectivity +{ + class OTableHelper; + class OOO_DLLPUBLIC_DBTOOLS OIndexesHelper : public sdbcx::OCollection + { + OTableHelper* m_pTable; + protected: + virtual sdbcx::ObjectType createObject(const OUString& _rName) override; + virtual void impl_refresh() override; + virtual css::uno::Reference< css::beans::XPropertySet > createDescriptor() override; + virtual sdbcx::ObjectType appendObject( const OUString& _rForName, const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + virtual void dropObject(sal_Int32 _nPos,const OUString& _sElementName) override; + public: + OIndexesHelper(OTableHelper* _pTable, + ::osl::Mutex& _rMutex, + const ::std::vector< OUString> &_rVector + ); + + }; +} + +#endif // INCLUDED_CONNECTIVITY_TINDEXES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/TKeys.hxx b/include/connectivity/TKeys.hxx new file mode 100644 index 000000000..ae226b874 --- /dev/null +++ b/include/connectivity/TKeys.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_TKEYS_HXX +#define INCLUDED_CONNECTIVITY_TKEYS_HXX + +#include +#include + +namespace connectivity +{ + class OTableHelper; + typedef sdbcx::OCollection OKeys_BASE; + class OOO_DLLPUBLIC_DBTOOLS OKeysHelper : public OKeys_BASE + { + OTableHelper* m_pTable; + protected: + virtual sdbcx::ObjectType createObject(const OUString& _rName) override; + virtual void impl_refresh() override; + virtual css::uno::Reference< css::beans::XPropertySet > createDescriptor() override; + virtual sdbcx::ObjectType appendObject( const OUString& _rForName, const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + virtual void dropObject(sal_Int32 _nPos, const OUString& _sElementName) override; + + virtual OUString getDropForeignKey() const; + + public: + OKeysHelper( OTableHelper* _pTable, + ::osl::Mutex& _rMutex, + const ::std::vector< OUString>& _rVector + ); + + static void cloneDescriptorColumns( + const sdbcx::ObjectType& _rSourceDescriptor, + const sdbcx::ObjectType& _rDestDescriptor + ); + }; +} + +#endif // INCLUDED_CONNECTIVITY_TKEYS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/TTableHelper.hxx b/include/connectivity/TTableHelper.hxx new file mode 100644 index 000000000..e987241a6 --- /dev/null +++ b/include/connectivity/TTableHelper.hxx @@ -0,0 +1,168 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_TTABLEHELPER_HXX +#define INCLUDED_CONNECTIVITY_TTABLEHELPER_HXX + +#include +#include + +#include + +#include +#include + +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::sdb::tools { class XIndexAlteration; } +namespace com::sun::star::sdb::tools { class XKeyAlteration; } +namespace com::sun::star::sdb::tools { class XTableAlteration; } +namespace com::sun::star::sdb::tools { class XTableRename; } +namespace connectivity::sdbcx { struct KeyProperties; } + +namespace connectivity +{ + typedef sal_Int32 OrdinalPosition; + struct ColumnDesc + { + OUString sName; + OUString aField6; + OUString sField12; // REMARKS + OUString sField13; + sal_Int32 nField5 + , nField7 + , nField9 + , nField11; + + OrdinalPosition nOrdinalPosition; + + ColumnDesc( const OUString& _rName + , sal_Int32 _nField5 + , const OUString& _aField6 + , sal_Int32 _nField7 + , sal_Int32 _nField9 + , sal_Int32 _nField11 + , const OUString& _sField12 + , const OUString& _sField13 + ,OrdinalPosition _nPosition ) + :sName( _rName ) + ,aField6(_aField6) + ,sField12(_sField12) + ,sField13(_sField13) + ,nField5(_nField5) + ,nField7(_nField7) + ,nField9(_nField9) + ,nField11(_nField11) + ,nOrdinalPosition( _nPosition ) + { + } + }; + typedef connectivity::sdbcx::OTable OTable_TYPEDEF; + + typedef std::map> TKeyMap; + + struct OTableHelperImpl; + + class OOO_DLLPUBLIC_DBTOOLS OTableHelper : public OTable_TYPEDEF + { + ::std::unique_ptr m_pImpl; + + void refreshPrimaryKeys(::std::vector< OUString>& _rKeys); + void refreshForeignKeys(::std::vector< OUString>& _rKeys); + + protected: + /** creates the column collection for the table + @param _rNames + The column names. + */ + virtual sdbcx::OCollection* createColumns(const ::std::vector< OUString>& _rNames) = 0; + + /** creates the key collection for the table + @param _rNames + The key names. + */ + virtual sdbcx::OCollection* createKeys(const ::std::vector< OUString>& _rNames) = 0; + + /** creates the index collection for the table + @param _rNames + The index names. + */ + virtual sdbcx::OCollection* createIndexes(const ::std::vector< OUString>& _rNames) = 0; + + /** this function is called upon disposing the component + */ + virtual void SAL_CALL disposing() override; + + /** The default returns "RENAME TABLE " or "RENAME VIEW " depending on the type. + * + * \return The start of the rename statement. + */ + virtual OUString getRenameStart() const; + + virtual ~OTableHelper() override; + + public: + virtual void refreshColumns() override; + virtual void refreshKeys() override; + virtual void refreshIndexes() override; + + const ColumnDesc* getColumnDescription(const OUString& _sName) const; + + public: + OTableHelper( sdbcx::OCollection* _pTables, + const css::uno::Reference< css::sdbc::XConnection >& _xConnection, + bool _bCase); + OTableHelper( sdbcx::OCollection* _pTables, + const css::uno::Reference< css::sdbc::XConnection >& _xConnection, + bool _bCase, + const OUString& Name, + const OUString& Type, + const OUString& Description = OUString(), + const OUString& SchemaName = OUString(), + const OUString& CatalogName = OUString() + ); + + virtual css::uno::Reference< css::sdbc::XDatabaseMetaData> getMetaData() const override; + css::uno::Reference< css::sdbc::XConnection> const & getConnection() const; + + // XRename + virtual void SAL_CALL rename( const OUString& newName ) override; + + // XAlterTable + virtual void SAL_CALL alterColumnByIndex( sal_Int32 index, const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + // XNamed + virtual OUString SAL_CALL getName() override; + + // To retrieve the table name only without the schema + const OUString & getTableName(); + + // helper method to get key properties + std::shared_ptr getKeyProperties(const OUString& _sName) const; + void addKey(const OUString& _sName,const std::shared_ptr& _aKeyProperties); + + virtual OUString getTypeCreatePattern() const; + + css::uno::Reference< css::sdb::tools::XTableRename> const & getRenameService() const; + css::uno::Reference< css::sdb::tools::XTableAlteration> const & getAlterService() const; + css::uno::Reference< css::sdb::tools::XKeyAlteration> const & getKeyService() const; + css::uno::Reference< css::sdb::tools::XIndexAlteration> const & getIndexService() const; + }; +} +#endif // INCLUDED_CONNECTIVITY_TTABLEHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/conncleanup.hxx b/include/connectivity/conncleanup.hxx new file mode 100644 index 000000000..d243e3842 --- /dev/null +++ b/include/connectivity/conncleanup.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_CONNCLEANUP_HXX +#define INCLUDED_CONNECTIVITY_CONNCLEANUP_HXX + +#include +#include +#include +#include + + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::sdbc { class XRowSet; } +namespace com::sun::star::sdbc { class XConnection; } + +namespace dbtools +{ + + + //= OAutoConnectionDisposer + + typedef ::cppu::WeakImplHelper < css::beans::XPropertyChangeListener, + css::sdbc::XRowSetListener + > OAutoConnectionDisposer_Base; + + class OOO_DLLPUBLIC_DBTOOLS OAutoConnectionDisposer final : public OAutoConnectionDisposer_Base + { + css::uno::Reference< css::sdbc::XConnection > + m_xOriginalConnection; + css::uno::Reference< css::sdbc::XRowSet > m_xRowSet; // needed to add as listener + bool m_bRSListening : 1; // true when we're listening on rowset + bool m_bPropertyListening : 1; // true when we're listening for property changes + + public: + /** constructs an object +

The connection given will be set on the rowset (as ActiveConnection), and the object adds itself as property + change listener for the connection. Once somebody sets a new ActiveConnection, the old one (the one given + here) will be disposed.

+ */ + OAutoConnectionDisposer( + const css::uno::Reference< css::sdbc::XRowSet >& _rxRowSet, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection + ); + + private: + // XPropertyChangeListener + virtual void SAL_CALL propertyChange( const css::beans::PropertyChangeEvent& _rEvent ) override; + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& _rSource ) override; + + // XRowSetListener + virtual void SAL_CALL cursorMoved( const css::lang::EventObject& event ) override; + virtual void SAL_CALL rowChanged( const css::lang::EventObject& event ) override; + virtual void SAL_CALL rowSetChanged( const css::lang::EventObject& event ) override; + + void clearConnection(); + + void startRowSetListening(); + void stopRowSetListening(); + bool isRowSetListening() const { return m_bRSListening; } + + void startPropertyListening( const css::uno::Reference< css::beans::XPropertySet >& _rxProps ); + void stopPropertyListening( const css::uno::Reference< css::beans::XPropertySet >& _rxEventSource ); + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_CONNCLEANUP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/dbcharset.hxx b/include/connectivity/dbcharset.hxx new file mode 100644 index 000000000..3ee993243 --- /dev/null +++ b/include/connectivity/dbcharset.hxx @@ -0,0 +1,149 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_DBCHARSET_HXX +#define INCLUDED_CONNECTIVITY_DBCHARSET_HXX + +#include + +#include + +#include +#include +#include +#include + + +namespace dbtools +{ + + + //= OCharsetMap + + /** is a class which translates between different charset representations. + +

The set of recognized charsets is very limited: only the ones which are database relevant are + implemented at the moment

+ +

Possible representations are: +

    +
  • IANA names. + Have a look at this document for + more details
  • +
  • rtl_TextEncoding
  • +
+

+ */ + class OOO_DLLPUBLIC_DBTOOLS OCharsetMap + { + protected: + typedef std::set TextEncBag; + + TextEncBag m_aEncodings; + + public: + class CharsetIterator; + friend class OCharsetMap::CharsetIterator; + typedef CharsetIterator iterator; + typedef CharsetIterator const_iterator; + + OCharsetMap(); + virtual ~OCharsetMap(); + + /** find the given text encoding in the map. + @return the end iterator if the encoding could not be found. + */ + CharsetIterator find(const rtl_TextEncoding _eEncoding) const; + /** find the given IANA name in the map. + @return the end iterator if the IANA name could not be found. + */ + CharsetIterator findIanaName(const OUString& _rIanaName) const; + + /// get access to the first element of the charset collection + CharsetIterator begin() const; + /// get access to the (last + 1st) element of the charset collection + CharsetIterator end() const; + + protected: + // needed because we want to call a virtual method during construction + void lateConstruct(); + void ensureConstructed( ) const { if ( m_aEncodings.empty() ) const_cast< OCharsetMap* >( this )->lateConstruct(); } + + virtual bool approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const; + }; + + + //- CharsetIteratorDerefHelper + + class OOO_DLLPUBLIC_DBTOOLS CharsetIteratorDerefHelper + { + friend class OCharsetMap::CharsetIterator; + + rtl_TextEncoding m_eEncoding; + OUString m_aIanaName; + + public: + CharsetIteratorDerefHelper(const CharsetIteratorDerefHelper& _rSource); + + rtl_TextEncoding getEncoding() const { return m_eEncoding; } + const OUString& getIanaName() const { return m_aIanaName; } + + protected: + CharsetIteratorDerefHelper( const rtl_TextEncoding _eEncoding, const OUString& _rIanaName ); + + }; + + + //- OCharsetMap::CharsetIterator + + class OOO_DLLPUBLIC_DBTOOLS OCharsetMap::CharsetIterator + { + friend class OCharsetMap; + + friend OOO_DLLPUBLIC_DBTOOLS bool operator==(const CharsetIterator& lhs, const CharsetIterator& rhs); + friend bool operator!=(const CharsetIterator& lhs, const CharsetIterator& rhs) { return !(lhs == rhs); } + +// friend sal_Int32 operator-(const CharsetIterator& lhs, const CharsetIterator& rhs); + + const OCharsetMap* m_pContainer; + OCharsetMap::TextEncBag::const_iterator m_aPos; + + public: + CharsetIteratorDerefHelper operator*() const; + // no -> operator + // this would require us to a) store CharsetIteratorDerefHelper instances ourself so that we + // can return a pointer or b) introduce a -> operator on the CharsetIteratorDerefHelper, too. + + /// prefix increment + const CharsetIterator& operator++(); + + /// prefix decrement + const CharsetIterator& operator--(); + + protected: + CharsetIterator(const OCharsetMap* _pContainer, OCharsetMap::TextEncBag::const_iterator const & _aPos ); + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_DBCHARSET_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/dbconversion.hxx b/include/connectivity/dbconversion.hxx new file mode 100644 index 000000000..e9471344c --- /dev/null +++ b/include/connectivity/dbconversion.hxx @@ -0,0 +1,185 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_DBCONVERSION_HXX +#define INCLUDED_CONNECTIVITY_DBCONVERSION_HXX + +#include +#include + +namespace com::sun::star::uno { template class Reference; } + +namespace com::sun::star +{ + namespace lang + { + struct Locale; + } + namespace sdb + { + class XColumn; + class XColumnUpdate; + } + namespace beans + { + class XPropertySet; + } + namespace util + { + class XNumberFormatter; + class XNumberFormatsSupplier; + struct Time; + struct DateTime; + } + namespace script + { + class XTypeConverter; + } +} + +namespace dbtools::DBTypeConversion +{ + OOO_DLLPUBLIC_DBTOOLS css::util::Date const & getStandardDate(); + /// @throws css::lang::IllegalArgumentException + OOO_DLLPUBLIC_DBTOOLS void setValue(const css::uno::Reference< css::sdb::XColumnUpdate>& xVariant, + const css::uno::Reference< css::util::XNumberFormatter>& xFormatter, + const css::util::Date& rNullDate, + const OUString& rString, + sal_Int32 nKey, + sal_Int16 nFieldType, + sal_Int16 nKeyType); + + /// @throws css::lang::IllegalArgumentException + OOO_DLLPUBLIC_DBTOOLS void setValue(const css::uno::Reference< css::sdb::XColumnUpdate>& xVariant, + const css::util::Date& rNullDate, + const double& rValue, + sal_Int16 nKeyType); + + OOO_DLLPUBLIC_DBTOOLS double getValue( const css::uno::Reference< css::sdb::XColumn>& xVariant, const css::util::Date& rNullDate ); + + // get the columnvalue as string with a default format given by the column or a default format + // for the type + OOO_DLLPUBLIC_DBTOOLS OUString getFormattedValue( + const css::uno::Reference< css::beans::XPropertySet>& _xColumn, + const css::uno::Reference< css::util::XNumberFormatter>& xFormatter, + const css::lang::Locale& _rLocale, + const css::util::Date& rNullDate); + + OOO_DLLPUBLIC_DBTOOLS OUString getFormattedValue( + const css::uno::Reference< css::sdb::XColumn>& _xColumn, + const css::uno::Reference< css::util::XNumberFormatter>& xFormatter, + const css::util::Date& rNullDate, + sal_Int32 nKey, + sal_Int16 nKeyType); + + OOO_DLLPUBLIC_DBTOOLS css::util::Date toDate(double dVal, const css::util::Date& _rNullDate = getStandardDate()); + OOO_DLLPUBLIC_DBTOOLS css::util::Date toDate(std::u16string_view _sSQLDate); + OOO_DLLPUBLIC_DBTOOLS css::util::Time toTime(double dVal, short nDigits = 9); + OOO_DLLPUBLIC_DBTOOLS css::util::Time toTime(std::u16string_view _sSQLDate); + OOO_DLLPUBLIC_DBTOOLS css::util::DateTime toDateTime(double dVal, const css::util::Date& _rNullDate = getStandardDate()); + OOO_DLLPUBLIC_DBTOOLS css::util::DateTime toDateTime(const OUString& _sSQLDate); + + OOO_DLLPUBLIC_DBTOOLS sal_Int64 getNsFromTime(const css::util::Time& rVal); + + OOO_DLLPUBLIC_DBTOOLS sal_Int32 toDays(const css::util::Date& _rVal, const css::util::Date& _rNullDate = getStandardDate()); + + OOO_DLLPUBLIC_DBTOOLS double toDouble(const css::util::Date& rVal, const css::util::Date& _rNullDate = getStandardDate()); + OOO_DLLPUBLIC_DBTOOLS double toDouble(const css::util::Time& rVal); + OOO_DLLPUBLIC_DBTOOLS double toDouble(const css::util::DateTime& rVal, const css::util::Date& _rNullDate = getStandardDate()); + + OOO_DLLPUBLIC_DBTOOLS css::util::Date toDate(sal_Int32 _nVal); + OOO_DLLPUBLIC_DBTOOLS css::util::Time toTime(sal_Int64 _nVal); + + /** convert a double which is a date value relative to the standard db null date into a date value relative + to a given fixed date. + */ + inline double toNullDate(const css::util::Date& _rNullDate, double _rVal) { return _rVal - toDays(_rNullDate); } + + // return the date from the numberformatsupplier or the STANDARD_DATE (1900,1,1) + OOO_DLLPUBLIC_DBTOOLS css::util::Date getNULLDate(const css::uno::Reference< css::util::XNumberFormatsSupplier > &xSupplier); + + // return the date in the format %04d-%02d-%02d + OOO_DLLPUBLIC_DBTOOLS OUString toDateString(const css::util::Date& rDate); + // return the time in the format %02d:%02d:%02d + OOO_DLLPUBLIC_DBTOOLS OUString toTimeStringS(const css::util::Time& rTime); + // return the time in the format %02d:%02d:%02d.%09d + OOO_DLLPUBLIC_DBTOOLS OUString toTimeString(const css::util::Time& rTime); + // return the DateTime in the format %04d-%02d-%02d %02d:%02d:%02d.%09d + OOO_DLLPUBLIC_DBTOOLS OUString toDateTimeString(const css::util::DateTime& _rDateTime); + // return the any in an sql standard format + OOO_DLLPUBLIC_DBTOOLS OUString toSQLString(sal_Int32 eType, const css::uno::Any& _rVal, + const css::uno::Reference< css::script::XTypeConverter >& _rxTypeConverter); + + /** converts a Unicode string into a 8-bit string, using the given encoding + + @param _rSource + the source string to convert + @param _rDest + the destination string + @param _eEncoding + the encoding to use for the conversion + + @throws css::sdbc::SQLException + if the given string contains characters which are not convertible using the given encoding + The SQLState of the exception will be set to 22018 ("Invalid character value for cast specification") + + @return + the length of the converted string + */ + OOO_DLLPUBLIC_DBTOOLS sal_Int32 convertUnicodeString( + const OUString& _rSource, + OString& _rDest, + rtl_TextEncoding _eEncoding + ); + + /** converts a Unicode string into a 8-bit string, using the given encoding + + @param _rSource + the source string to convert + + @param _rDest + the destination string + + @param _nMaxLen + the maximum length of the destination string + + @param _eEncoding + the encoding to use for the conversion + + @throws css::sdbc::SQLException + if convertUnicodeString, which is called internally, throws such an exception + + @throws css::sdbc::SQLException + if the conversion results in a string which is longer than _nMaxLen + + @return + the length of the converted string + */ + OOO_DLLPUBLIC_DBTOOLS sal_Int32 convertUnicodeStringToLength( + const OUString& _rSource, + OString& _rDest, + sal_Int32 _nMaxLen, + rtl_TextEncoding _eEncoding + ); + +} // namespace dbtools::DBTypeConversion + +#endif // INCLUDED_CONNECTIVITY_DBCONVERSION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/dbexception.hxx b/include/connectivity/dbexception.hxx new file mode 100644 index 000000000..8c9dfad33 --- /dev/null +++ b/include/connectivity/dbexception.hxx @@ -0,0 +1,332 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_DBEXCEPTION_HXX +#define INCLUDED_CONNECTIVITY_DBEXCEPTION_HXX + +#include +#include +#include + +namespace com::sun::star +{ + namespace sdb + { + class SQLContext; + struct SQLErrorEvent; + } + namespace sdbc + { + class SQLWarning; + class SQLException; + } +} + +namespace dbtools +{ + + +//= Special exception if cancel is pressed in DBA UI + +enum OOoBaseErrorCode +{ + ParameterInteractionCancelled = 1 +}; + + +//= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class + + +class OOO_DLLPUBLIC_DBTOOLS SQLExceptionInfo final +{ +public: + enum class TYPE { SQLException, SQLWarning, SQLContext, Undefined }; + +private: + css::uno::Any m_aContent; + TYPE m_eType; // redundant (could be derived from m_aContent.getValueType()) + +public: + SQLExceptionInfo(); + SQLExceptionInfo(const css::sdbc::SQLException& _rError); + SQLExceptionInfo(const css::sdbc::SQLWarning& _rError); + SQLExceptionInfo(const css::sdb::SQLContext& _rError); + + /** convenience constructor + + If your error processing relies on SQLExceptions, and SQLExceptionInfos, you still may + need to display an error which consists of a simple message string only. + In those cases, you can use this constructor, which behaves as if you would have used + an SQLException containing exactly the given error message. + */ + SQLExceptionInfo( const OUString& _rSimpleErrorMessage ); + + // use for events got via XSQLErrorListener::errorOccured + SQLExceptionInfo(const css::uno::Any& _rError); + // use with the Reason member of an SQLErrorEvent or with NextElement of an SQLException + + /** prepends a plain error message to the chain of exceptions + @param _rSimpleErrorMessage + the error message to prepend + */ + void prepend( const OUString& _rErrorMessage ); + + /** appends a plain message to the chain of exceptions + @param _eType + the type of exception to append. Must be SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, for all other + values, the behavior is undefined. + @param _rErrorMessage + the message to append + @param _rSQLState + the SQLState of the exception to append + @param _nErrorCode + the error code of the exception to append + */ + void append( TYPE _eType, const OUString& _rErrorMessage, const OUString& _rSQLState = OUString(), const sal_Int32 _nErrorCode = 0 ); + + /** throws (properly typed) the exception contained in the object + @precond + isValid() returns + @throws SQLException + @throws RuntimeException + if the instance does not contain an SQLException + */ + void doThrow(); + + SQLExceptionInfo& operator=(const css::sdbc::SQLException& _rError); + SQLExceptionInfo& operator=(const css::sdbc::SQLWarning& _rError); + SQLExceptionInfo& operator=(const css::sdb::SQLContext& _rError); + SQLExceptionInfo& operator=(const css::sdb::SQLErrorEvent& _rErrorEvent); + SQLExceptionInfo& operator=(const css::uno::Any& _rCaughtSQLException); + + bool isKindOf(TYPE _eType) const; + // not just a simple comparison ! e.g. getType() == SQL_CONTEXT implies isKindOf(SQL_EXCEPTION) == sal_True ! + bool isValid() const { return m_eType != TYPE::Undefined; } + TYPE getType() const { return m_eType; } + + operator const css::sdbc::SQLException* () const; + operator const css::sdb::SQLContext* () const; + + const css::uno::Any& get() const { return m_aContent; } + + void clear() + { + m_aContent.clear(); + m_eType = TYPE::Undefined; + } + + // create an exception + static css::uno::Any createException(TYPE eType, const OUString& rErrorMessage, const OUString& rSQLState, const sal_Int32 nErrorCode); + + // find the end of the exception chain + static css::sdbc::SQLException* getLastException(css::sdbc::SQLException* pLastException); + +private: + void implDetermineType(); +}; + + +//= SQLExceptionIteratorHelper - iterating through an SQLException chain + + +class OOO_DLLPUBLIC_DBTOOLS SQLExceptionIteratorHelper final +{ + const css::sdbc::SQLException* m_pCurrent; + SQLExceptionInfo::TYPE m_eCurrentType; + +public: + /** constructs an iterator instance from an SQLException + + @param _rChainStart + the start of the exception chain to iterate. Must live as long as the iterator + instances lives, at least. + */ + SQLExceptionIteratorHelper( const css::sdbc::SQLException& _rChainStart ); + + /** constructs an iterator instance from an SQLExceptionInfo + + @param _rErrorInfo + the start of the exception chain to iterate. Must live as long as the iterator + instances lives, at least. + */ + SQLExceptionIteratorHelper( const SQLExceptionInfo& _rErrorInfo ); + + /** determines whether there are more elements in the exception chain + */ + bool hasMoreElements() const { return ( m_pCurrent != nullptr ); } + + /** retrieves the current element in the chain, or if the chain has been completely + traveled. + + In opposite to the second current, this version allows typed access to + the respective SQLException. + */ + void current( SQLExceptionInfo& _out_rInfo ) const; + + /** proceeds to the next element in the chain + + @return the current element in the chain, as before the chain move. + */ + const css::sdbc::SQLException* next(); + + /** proceeds to the next element in the chain + + In opposite to the second current, this version allows typed access to + the respective SQLException. + */ + void next( SQLExceptionInfo& _out_rInfo ); +}; + + +//= StandardExceptions + + +/** returns a standard error string for a given SQLState + + @param _eState + describes the state whose description is to retrieve. Must not be SQL_ERROR_UNSPECIFIED. + @throws RuntimeException + in case of an internal error +*/ +OOO_DLLPUBLIC_DBTOOLS OUString getStandardSQLState( StandardSQLState _eState ); + + +/** throws an exception with SQL state IM001, saying that a certain function is not supported + + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwFunctionNotSupportedSQLException( + const OUString& _rFunctionName, + const css::uno::Reference< css::uno::XInterface >& _rxContext + ); + +/// @throws css::uno::RuntimeException +OOO_DLLPUBLIC_DBTOOLS void throwFunctionNotSupportedRuntimeException( + const OUString& _rFunctionName, + const css::uno::Reference< css::uno::XInterface >& _rxContext + ); + +/** throws a function sequence (HY010) exception + + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwFunctionSequenceException( + const css::uno::Reference< css::uno::XInterface >& Context, + const css::uno::Any& Next = css::uno::Any() + ); + + +/** throw an invalid index sqlexception + + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwInvalidIndexException( + const css::uno::Reference< css::uno::XInterface >& Context, + const css::uno::Any& Next = css::uno::Any() + ); + + +/** throw a generic SQLException, i.e. one with an SQLState of HY000, an ErrorCode of 0 and no NextException + + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwGenericSQLException( + const OUString& _rMsg, + const css::uno::Reference< css::uno::XInterface >& _rxSource + ); + + +/** throw a generic SQLException, i.e. one with an SQLState of HY000, an ErrorCode of 0 and no NextException + + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwGenericSQLException( + const OUString& _rMsg, + const css::uno::Reference< css::uno::XInterface >& _rxSource, + const css::uno::Any& _rNextException + ); + + +/** throw a SQLException with SQLState HYC00 (Optional feature not implemented) + @param _rFeatureName + a description of the feature which is not implemented. It's recommended that the feature + name is built from the name of the interface plus its method, for instance "XParameters::updateBinaryStream" + @param _rxContext + the context of the exception + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwFeatureNotImplementedSQLException( + const OUString& _rFeatureName, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const css::uno::Any& _rNextException = css::uno::Any() + ); + +/** throw a RuntimeException (Optional feature not implemented) + @param _rFeatureName + a description of the feature which is not implemented. It's recommended that the feature + name is built from the name of the interface plus its method, for instance "XParameters::updateBinaryStream" + @param _rxContext + the context of the exception + @throws css::uno::RuntimeException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwFeatureNotImplementedRuntimeException( + const OUString& _rFeatureName, + const css::uno::Reference< css::uno::XInterface >& _rxContext + ); + +/** throw a SQLException with SQLState 42S22 (Column Not Found) + @param _rColumnNameName + The column that couldn't be found. + @param _rxContext + the context of the exception + @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwInvalidColumnException( + const OUString& _rColumnName, + const css::uno::Reference< css::uno::XInterface >& _rxContext + ); + + +/** @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwSQLException( + const OUString& _rMessage, + const OUString& _rSQLState, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const sal_Int32 _nErrorCode + ); + + +/** @throws css::sdbc::SQLException +*/ +OOO_DLLPUBLIC_DBTOOLS void throwSQLException( + const OUString& _rMessage, + StandardSQLState _eSQLState, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const sal_Int32 _nErrorCode = 0 + ); + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_DBEXCEPTION_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/dbmetadata.hxx b/include/connectivity/dbmetadata.hxx new file mode 100644 index 000000000..17a392dfe --- /dev/null +++ b/include/connectivity/dbmetadata.hxx @@ -0,0 +1,194 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_DBMETADATA_HXX +#define INCLUDED_CONNECTIVITY_DBMETADATA_HXX + +#include + +#include +#include + +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::uno { class XComponentContext; } + +namespace dbtools +{ + + + //= DatabaseMetaData + + struct DatabaseMetaData_Impl; + /** encapsulates meta data about a database/connection which cannot be obtained + from the usual XDatabaseMetaData result set. + + Meta data perhaps isn't really the right term ... Some of the methods + in this class involved heuristics, some are just a convenient wrapper + around more complex ways to obtain the same information. + + @todo + Once CWS dba30 is integrated, we could easily add all the meta data + which is part of the "Info" property of a data source. + */ + class OOO_DLLPUBLIC_DBTOOLS DatabaseMetaData + { + private: + ::std::unique_ptr< DatabaseMetaData_Impl > m_pImpl; + + public: + DatabaseMetaData(); + /** constructs a DatabaseMetaData instance + @param _rxConnection + is the connection whose meta data you're interested in. + Note that some of the information provided by this class can only be obtained + if this connection denotes an application-level connection, i.e. supports + the com.sun.star.sdb.Connection service. + + @throws css::lang::IllegalArgumentException + if the given connection is not , but the XDatabaseMetaData provided by it + are + @throws css::sdbc::SQLException + if obtaining the meta data from the connection throws an SQLException + @throws css::uno::RuntimeException + if obtaining the meta data from the connection throws a RuntimeException + */ + DatabaseMetaData( + const css::uno::Reference< css::sdbc::XConnection >& _connection ); + DatabaseMetaData( const DatabaseMetaData& _copyFrom ); + DatabaseMetaData& operator=( const DatabaseMetaData& _copyFrom ); + DatabaseMetaData(DatabaseMetaData&& _copyFrom) noexcept; + DatabaseMetaData& operator=(DatabaseMetaData&& _copyFrom) noexcept; + + ~DatabaseMetaData(); + + public: + /** determines whether or not the instances is based on a valid connection + + As long as this method returns true, you should expect all other + methods throwing an SQLException when called. + */ + bool isConnected() const; + + /** resets the instance so that it's based on a new connection + */ + void reset( const css::uno::Reference< css::sdbc::XConnection >& _connection ) + { + *this = DatabaseMetaData( _connection ); + } + + /// wraps XDatabaseMetaData::getIdentifierQuoteString + const OUString& getIdentifierQuoteString() const; + + /// wraps XDatabaseMetaData::getCatalogSeparator + const OUString& getCatalogSeparator() const; + + /** determines whether the database supports sub queries in the FROM part + of a SELECT clause are supported. + @throws css::sdbc::SQLException + with SQLState 08003 (connection does not exist) if the instances was + default-constructed and does not have a connection, yet. + */ + bool supportsSubqueriesInFrom() const; + + /** checks whether the database supports primary keys + + Since there's no dedicated API to ask a database for this, a heuristics needs to be applied. + First, the PrimaryKeySupport settings of the data source is examined. If it is + or , then value is returned. If it is , then the database meta data are examined + for support of core SQL grammar, and the result is returned. The assumption is that a database/driver + which supports core SQL grammar usually also supports primary keys, and vice versa. At least, experience + shows this is true most of the time. + */ + bool supportsPrimaryKeys() const; + + /** determines whether names in the database should be restricted to SQL-92 identifiers + + Effectively, this method checks the EnableSQL92Check property of the data source settings, + if present. + */ + bool restrictIdentifiersToSQL92() const; + + /** determines whether when generating SQL statements, an AS keyword should be generated + before a correlation name. + + E.g., it determines whether SELECT * FROM table AS correlation_name or + SELECT * FROM table correlation_name is generated. + */ + bool generateASBeforeCorrelationName() const; + + /** should date time be escaped like '2001-01-01' => {D '2001-01-01' } + */ + bool shouldEscapeDateTime() const; + + /** should named parameters (:foo, [foo]) be replaced by unnamed parameters (?) + */ + bool shouldSubstituteParameterNames() const; + + /** auto increment columns should be automatically used as primary key. + */ + bool isAutoIncrementPrimaryKey() const; + + /** determines the syntax to use for boolean comparison predicates + + @see css::sdb::BooleanComparisonMode + */ + sal_Int32 + getBooleanComparisonMode() const; + + /** determines in relations are supported. + * + * \return when relations are supported, otherwise + */ + bool supportsRelations() const; + + /** determines if column alias names can be used in the order by clause. + * + * \return when relations are supported, otherwise + */ + bool supportsColumnAliasInOrderBy() const; + + /** determines whether user administration is supported for the database + + User administration support is controlled by the availability of the XUsersSupplier + interface, and it returning a non-NULL users container. + + @param _rContext + the component context we operate in. Might be needed to create the + css.sdbc.DriverManager instance. + */ + bool supportsUserAdministration( const css::uno::Reference& _rContext ) const; + + /** determines whether in the application UI, empty table folders (aka catalogs/schemas) should be displayed + */ + bool displayEmptyTableFolders() const; + + /** determines that threads are supported. + * + * \return when threads are supported, otherwise + */ + bool supportsThreads() const; + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_DBMETADATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/dbtools.hxx b/include/connectivity/dbtools.hxx new file mode 100644 index 000000000..58f34f170 --- /dev/null +++ b/include/connectivity/dbtools.hxx @@ -0,0 +1,867 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_DBTOOLS_HXX +#define INCLUDED_CONNECTIVITY_DBTOOLS_HXX + +#include + +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + +namespace sdb { + class XSingleSelectQueryComposer; +} +namespace sdbcx { + class XTablesSupplier; +} +namespace sdbc { + class XConnection; + class XDatabaseMetaData; + class XRowSet; + class XDataSource; + class SQLException; + class XParameters; + class XRowUpdate; +} +namespace beans { + class XPropertySet; +} +namespace awt { + class XWindow; +} +namespace lang { + struct Locale; +} +namespace container { + class XNameAccess; +} +namespace uno { + class XComponentContext; +} +namespace util { + class XNumberFormatTypes; + class XNumberFormatsSupplier; +} +namespace task { + class XInteractionHandler; +} + +} + +class SvStream; + +namespace dbtools +{ + class ISQLStatementHelper; + typedef ::utl::SharedUNOComponent< css::sdbc::XConnection > SharedConnection; + + enum class EComposeRule + { + InTableDefinitions, + InIndexDefinitions, + InDataManipulation, + InProcedureCalls, + InPrivilegeDefinitions, + Complete + }; + + // date conversion + + // calculates the default numberformat for a given datatype and a give language + OOO_DLLPUBLIC_DBTOOLS + sal_Int32 getDefaultNumberFormat(const css::uno::Reference< css::beans::XPropertySet >& _xColumn, + const css::uno::Reference< css::util::XNumberFormatTypes >& _xTypes, + const css::lang::Locale& _rLocale); + + // calculates the default numberformat for a given datatype and a give language + // @param _nDataType @see com.sun.star.sdbc.DataType + // @param _nScale can be zero + OOO_DLLPUBLIC_DBTOOLS + sal_Int32 getDefaultNumberFormat(sal_Int32 _nDataType, + sal_Int32 _nScale, + bool _bIsCurrency, + const css::uno::Reference< css::util::XNumberFormatTypes >& _xTypes, + const css::lang::Locale& _rLocale); + + + /** creates a connection which can be used for the rowset given + + The function tries to obtain a connection for the row set with the following + steps (in this order): + +
  • If the rowset already has an ActiveConnection (means a non- value for this property), + this one is used.
  • +
  • If row set is part of a database form document (see ->isEmbeddedInDatabase), + a connection for the respective database is used.
  • +
  • If in the parent hierarchy of the row set, there is an object supporting + the XConnection interface, this one is returned.
  • +
  • If the DataSourceName property of the row set is not empty, a connection for this + data source is retrieved.
  • +
  • If the URL property of the row set is not empty, a connection for this URL is + retrieved from the driver manager. + + + The calculated connection is set as ActiveConnection property on the rowset. + + If the connection was newly created by the method, then + the ownership of the connection is delivered to a temporary object, which observes the + row set: As soon as a connection-relevant property of the row set changes, or as soon + as somebody else sets another ActiveConnection at the row set, the original + connection (the one which this function calculated) is disposed and discarded. At this + very moment, also the temporary observer object dies. This way, it is ensured that + there's no resource leak from an un-owned connection object. + + @param _rxRowSet + the row set + + @param _rxFactory + a service factory, which can be used to create data sources, interaction handler etc (the usual stuff) + + */ + OOO_DLLPUBLIC_DBTOOLS + css::uno::Reference< css::sdbc::XConnection> connectRowset( + const css::uno::Reference< css::sdbc::XRowSet>& _rxRowSet, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext, + const css::uno::Reference< css::awt::XWindow>& _rxParent + ); + + /** ensures that a row set has a valid ActiveConnection, if possible + + This function does nearly the same as ->connectRowset. In fact, it is to be preferred over + ->connectRowset, if possible. + + There are a few differences: +
    • If a connection could be determined for the given RowSet, it is always + set as ActiveConnection.
    • +
    • Definition of the ownership of the created connection allows for more scenarios: +
      • If the connection was not newly created, the returned ->SharedConnection + instance will not have the ownership, since in this case it's assumed + that there already is an instance which has the ownership.
      • +
      • If the connection was newly created, then the returned SharedConnection + instance will have the ownership of the XConnection.
      • +
      +
    • +
    + */ + OOO_DLLPUBLIC_DBTOOLS SharedConnection ensureRowSetConnection( + const css::uno::Reference< css::sdbc::XRowSet>& _rxRowSet, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext, + const css::uno::Reference< css::awt::XWindow>& _rxParent + ); + + /** returns the connection the RowSet is currently working with (which is the ActiveConnection property) + + @throws css::uno::RuntimeException + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::sdbc::XConnection> getConnection(const css::uno::Reference< css::sdbc::XRowSet>& _rxRowSet); + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::sdbc::XConnection> getConnection_withFeedback( + const OUString& _rDataSourceName, + const OUString& _rUser, + const OUString& _rPwd, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext, + const css::uno::Reference< css::awt::XWindow>& _rxParent); + + + /** determines whether the given component is part of a document which is an embedded database + document (such as a form) + */ + OOO_DLLPUBLIC_DBTOOLS bool isEmbeddedInDatabase( + const css::uno::Reference< css::uno::XInterface >& _rxComponent, + css::uno::Reference< css::sdbc::XConnection >& _rxActualConnection + ); + + /** returns the columns of the named table of the given connection + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::container::XNameAccess> getTableFields( + const css::uno::Reference< css::sdbc::XConnection>& _rxConn, + const OUString& _rName + ); + + /** returns the primary key columns of the table + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::container::XNameAccess> getPrimaryKeyColumns_throw( + const css::uno::Any& i_aTable + ); + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::container::XNameAccess> getPrimaryKeyColumns_throw( + const css::uno::Reference< css::beans::XPropertySet >& i_xTable + ); + + /** get fields for a result set given by a "command descriptor" + +

    A command descriptor here means: +

    • a SDB-level connection (com.sun.star.sdb::Connection
    • +
    • a string specifying the name of an object relative to the connection
    • +
    • a com.sun.star.sdb::CommandType value specifying the type + of the object
    • +
    +

    + + @param _rxConnection + the connection relative to which the to-be-examined object exists + + @param _nCommandType + the type of the object + + @param _rCommand + the object. This may be a table name, a query name, or an SQL statement, depending on the value + of _nCommandType + + @param _rxCollectionOner + If (and only if) CommandType is CommandType.COMMAND, the fields collection which is returned + by this function here is a temporary object. It is kept alive by another object, which is to be + created temporarily, too. To ensure that the fields you get are valid as long as you need them, + the owner which controls their life time is transferred to this parameter upon return.
    + + Your fields live as long as this component lives.
    + + Additionally, you are encouraged to dispose this component as soon as you don't need the fields anymore. + It depends on the connection's implementation if this is necessary, but the is no guarantee, so to + be on the safe side with respect to resource leaks, you should dispose the component. + + @param _pErrorInfo + If not , then upon return from the function the instance pointed to by this argument will + contain any available error information in case something went wrong. + + @return + the container of the columns (aka fields) of the object + */ + OOO_DLLPUBLIC_DBTOOLS + css::uno::Reference< css::container::XNameAccess > + getFieldsByCommandDescriptor( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const sal_Int32 _nCommandType, + const OUString& _rCommand, + css::uno::Reference< css::lang::XComponent >& _rxKeepFieldsAlive, + SQLExceptionInfo* _pErrorInfo = nullptr + ); + + + /** get fields for a result set given by a "command descriptor" + +

    A command descriptor here means: +

    • a SDB-level connection (com.sun.star.sdb::Connection
    • +
    • a string specifying the name of an object relative to the connection
    • +
    • a com.sun.star.sdb::CommandType value specifying the type + of the object
    • +
    +

    + + @param _rxConnection + the connection relative to which the to-be-examined object exists + + @param _nCommandType + the type of the object + + @param _rCommand + the object. This may be a table name, a query name, or an SQL statement, depending on the value + of _nCommandType + + @param _pErrorInfo + If not , then upon return from the function the instance pointed to by this argument will + contain any available error information in case something went wrong. + + @return + an array of strings containing the names of the columns (aka fields) of the object + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Sequence< OUString > + getFieldNamesByCommandDescriptor( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const sal_Int32 _nCommandType, + const OUString& _rCommand, + SQLExceptionInfo* _pErrorInfo = nullptr + ); + + + /** create a new css::sdbc::SQLContext, fill it with the given descriptions and the given source, + and append _rException (i.e. put it into the NextException member of the SQLContext). + */ + OOO_DLLPUBLIC_DBTOOLS + css::sdbc::SQLException prependErrorInfo( + const css::sdbc::SQLException& _rChainedException, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const OUString& _rAdditionalError, + const StandardSQLState _eSQLState = StandardSQLState::ERROR_UNSPECIFIED); + + /** search the parent hierarchy for a data source. + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::sdbc::XDataSource> findDataSource(const css::uno::Reference< css::uno::XInterface >& _xParent); + + /** determines the value of a boolean data source setting, given by ASCII name + + @param _rxConnection + the connection belonging to the data source whose setting is to be retrieved + @param _pAsciiSettingName + the ASCII name of the setting + */ + OOO_DLLPUBLIC_DBTOOLS bool getBooleanDataSourceSetting( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const char* _pAsciiSettingName + ); + OOO_DLLPUBLIC_DBTOOLS bool getBooleanDataSourceSetting( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const OUString& rSettingName + ); + + /** check if a specific property is enabled in the info sequence + @deprecated + Use getBooleanDataSourceSetting instead, which cares for the default of the property itself, + instead of spreading this knowledge through all callers. + */ + OOO_DLLPUBLIC_DBTOOLS + bool isDataSourcePropertyEnabled(const css::uno::Reference< css::uno::XInterface>& _xProp, + const OUString& _sProperty, + bool _bDefault); + + /** retrieves a particular indirect data source setting + + @param _rxDataSource + a data source component + @param _pAsciiSettingsName + the ASCII name of the setting to obtain + @param _rSettingsValue + the value of the setting, upon successful return + + @return + if the setting is not present in the DataSource::Info + member of the data source + otherwise + */ + OOO_DLLPUBLIC_DBTOOLS + bool getDataSourceSetting( + const css::uno::Reference< css::uno::XInterface >& _rxDataSource, + const char* _pAsciiSettingsName, + css::uno::Any& /* [out] */ _rSettingsValue + ); + OOO_DLLPUBLIC_DBTOOLS + bool getDataSourceSetting( + const css::uno::Reference< css::uno::XInterface >& _rxDataSource, + const OUString& _sSettingsName, + css::uno::Any& /* [out] */ _rSettingsValue + ); + + OOO_DLLPUBLIC_DBTOOLS OUString getDefaultReportEngineServiceName(const css::uno::Reference< css::uno::XComponentContext>& _rxFactory); + + /** quote the given name with the given quote string. + */ + OOO_DLLPUBLIC_DBTOOLS OUString quoteName(const OUString& _rQuote, const OUString& _rName); + + /** quote the given table name (which may contain a catalog and a schema) according to the rules provided by the meta data + */ + OOO_DLLPUBLIC_DBTOOLS + OUString quoteTableName(const css::uno::Reference< css::sdbc::XDatabaseMetaData>& _rxMeta + , const OUString& _rName + ,EComposeRule _eComposeRule); + + /** split a fully qualified table name (including catalog and schema, if applicable) into its component parts. + @param _rxConnMetaData meta data describing the connection where you got the table name from + @param _rQualifiedName fully qualified table name + @param _rCatalog (out parameter) upon return, contains the catalog name + @param _rSchema (out parameter) upon return, contains the schema name + @param _rName (out parameter) upon return, contains the table name + @param _eComposeRule where do you need the name for + */ + OOO_DLLPUBLIC_DBTOOLS void qualifiedNameComponents(const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _rxConnMetaData, + const OUString& _rQualifiedName, OUString& _rCatalog, OUString& _rSchema, OUString& _rName,EComposeRule _eComposeRule); + + /** calculate a NumberFormatsSupplier for use with a given connection + @param _rxConn the connection for which the formatter is requested + @param _bAllowDefault if the connection (and related components, such as its parent) cannot supply + a formatter, we can ask the DatabaseEnvironment for a default one. This parameter + states if this is allowed. + @param _rxFactory required (only of _bAllowDefault is sal_True) for creating the DatabaseEnvironment. + @return the formatter all object related to the given connection should work with. + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::util::XNumberFormatsSupplier> getNumberFormats( + const css::uno::Reference< css::sdbc::XConnection>& _rxConn, + bool _bAllowDefault = false, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext = css::uno::Reference< css::uno::XComponentContext>() + ); + + /** create a css::sdb::XSingleSelectQueryComposer which represents + the current settings (Command/CommandType/Filter/Order) of the given rowset. + + As such an instance can be obtained from a css::sdb::Connection + only the function searches for the connection the RowSet is using via connectRowset. + This implies that a connection will be set on the RowSet if needed. + (need to changes this sometimes ...) + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::sdb::XSingleSelectQueryComposer > getCurrentSettingsComposer( + const css::uno::Reference< css::beans::XPropertySet>& _rxRowSetProps, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext, + const css::uno::Reference< css::awt::XWindow>& _rxParent + ); + + /** transfer and translate properties between two FormComponents + @param _rxOld the source property set + @param _rxNew the destination property set + @param _rLocale the locale for converting number related properties + */ + OOO_DLLPUBLIC_DBTOOLS void TransferFormComponentProperties( + const css::uno::Reference< css::beans::XPropertySet>& _rxOld, + const css::uno::Reference< css::beans::XPropertySet>& _rxNew, + const css::lang::Locale& _rLocale + ); + + /** check if the property "Privileges" supports css::sdbcx::Privilege::INSERT + @param _rxCursorSet the property set + */ + OOO_DLLPUBLIC_DBTOOLS bool canInsert(const css::uno::Reference< css::beans::XPropertySet>& _rxCursorSet); + /** check if the property "Privileges" supports css::sdbcx::Privilege::UPDATE + @param _rxCursorSet the property set + */ + OOO_DLLPUBLIC_DBTOOLS bool canUpdate(const css::uno::Reference< css::beans::XPropertySet>& _rxCursorSet); + /** check if the property "Privileges" supports css::sdbcx::Privilege::DELETE + @param _rxCursorSet the property set + */ + OOO_DLLPUBLIC_DBTOOLS bool canDelete(const css::uno::Reference< css::beans::XPropertySet>& _rxCursorSet); + + + /** compose a complete table name from its up to three parts, regarding to the database meta data composing rules + */ + OOO_DLLPUBLIC_DBTOOLS OUString composeTableName( const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _rxMetaData, + const OUString& _rCatalog, + const OUString& _rSchema, + const OUString& _rName, + bool _bQuote, + EComposeRule _eComposeRule); + + /** composes a table name for usage in a SELECT statement + + This includes quoting of the table as indicated by the connection's meta data, plus respecting + the settings "UseCatalogInSelect" and "UseSchemaInSelect", which might be present + in the data source which the connection belongs to. + */ + OOO_DLLPUBLIC_DBTOOLS OUString composeTableNameForSelect( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const OUString& _rCatalog, + const OUString& _rSchema, + const OUString& _rName ); + + /** composes a table name for usage in a SELECT statement + + This includes quoting of the table as indicated by the connection's meta data, plus respecting + the settings "UseCatalogInSelect" and "UseSchemaInSelect", which might be present + in the data source which the connection belongs to. + */ + OOO_DLLPUBLIC_DBTOOLS OUString composeTableNameForSelect( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const css::uno::Reference< css::beans::XPropertySet>& _xTable ); + + /** compose the table name out of the property set which must support the properties from the service table + @param _xMetaData + The metadata from the connection. + @param _xTable + The table. + */ + OOO_DLLPUBLIC_DBTOOLS OUString composeTableName( + const css::uno::Reference< css::sdbc::XDatabaseMetaData>& _xMetaData, + const css::uno::Reference< css::beans::XPropertySet>& _xTable, + EComposeRule _eComposeRule, + bool _bQuote); + + + OOO_DLLPUBLIC_DBTOOLS sal_Int32 getSearchColumnFlag( const css::uno::Reference< css::sdbc::XConnection>& _rxConn, + sal_Int32 _nDataType); + // return the datasource for the given datasource name + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::sdbc::XDataSource> getDataSource(const OUString& _rsDataSourceName, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext); + + /** search for a name that is NOT in the NameAcces + @param _rxContainer + the NameAccess container to search in + @param _rBaseName + the base name that should be used to create the new name + @param _bStartWithNumber + When the name ends with number even when the name itself doesn't occur in the collection. + @return + A name which doesn't exist in the collection. + */ + OOO_DLLPUBLIC_DBTOOLS + OUString createUniqueName(const css::uno::Reference< css::container::XNameAccess>& _rxContainer, + const OUString& _rBaseName, + bool _bStartWithNumber = true); + + /** creates a unique name which is not already used in the given name array + */ + OOO_DLLPUBLIC_DBTOOLS OUString createUniqueName( + const css::uno::Sequence< OUString >& _rNames, + const OUString& _rBaseName, + bool _bStartWithNumber + ); + + /** create a name which is a valid SQL 92 identifier name + @param _rName the string which should be converted + @param _rSpecials @see com.sun.star.sdbc.XDatabaseMetaData.getExtraNameCharacters + + @see isValidSQLName + */ + OOO_DLLPUBLIC_DBTOOLS OUString convertName2SQLName(const OUString& _rName, std::u16string_view _rSpecials); + + /** checks whether the given name is a valid SQL name + + @param _rName the string which should be converted + @param _rSpecials @see com.sun.star.sdbc.XDatabaseMetaData.getExtraNameCharacters + + @see convertName2SQLName + */ + OOO_DLLPUBLIC_DBTOOLS bool isValidSQLName( const OUString& _rName, std::u16string_view _rSpecials ); + + OOO_DLLPUBLIC_DBTOOLS + void showError( const SQLExceptionInfo& _rInfo, + const css::uno::Reference< css::awt::XWindow>& _pParent, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext); + + /** implements XRowUpdate::updateObject +

    The object which is to be set is analyzed, and in case it is a simlpe scalar type for which there + is another updateXXX method, this other method is used.

    + @param _rxUpdatedObject + the interface to forward all updateXXX calls to (except updateObject) + @param _nColumnIndex + the column index to update + @param _rValue + the value to update + @return + if the update request was successfully re-routed to one of the other updateXXX methods + */ + OOO_DLLPUBLIC_DBTOOLS + bool implUpdateObject( const css::uno::Reference< css::sdbc::XRowUpdate >& _rxUpdatedObject, + const sal_Int32 _nColumnIndex, + const css::uno::Any& _rValue); + + + /** ask the user for parameters if the prepared statement needs some and sets them in the prepared statement + @param _xConnection the connection must be able to create css::sdb::SingleSelectQueryComposers + @param _xPreparedStmt the prepared statement where the parameters could be set when needed + @param _aParametersSet contains which parameters have to asked for and which already have set. + */ + OOO_DLLPUBLIC_DBTOOLS + void askForParameters( const css::uno::Reference< css::sdb::XSingleSelectQueryComposer >& _xComposer, + const css::uno::Reference< css::sdbc::XParameters>& _xParameters, + const css::uno::Reference< css::sdbc::XConnection>& _xConnection, + const css::uno::Reference< css::task::XInteractionHandler >& _rxHandler, + const ::std::vector >& _aParametersSet = ::std::vector >()); + + /** call the appropriate set method for the specific sql type @see css::sdbc::DataType + @param _xParams the parameters where to set the value + @param parameterIndex the index of the parameter, 1 based + @param x the value to set + @param sqlType the corresponding sql type @see css::sdbc::DataType + @param scale the scale of the sql type can be 0 + @throws css::sdbc::SQLException + @throws css::uno::RuntimeException + */ + OOO_DLLPUBLIC_DBTOOLS + void setObjectWithInfo( const css::uno::Reference< css::sdbc::XParameters>& _xParameters, + sal_Int32 parameterIndex, + const css::uno::Any& x, + sal_Int32 sqlType, + sal_Int32 scale=0); + + /** call the appropriate set method for the specific sql type @see css::sdbc::DataType + @param _xParams the parameters where to set the value + @param parameterIndex the index of the parameter, 1 based + @param x the value to set + @param sqlType the corresponding sql type @see css::sdbc::DataType + @param scale the scale of the sql type can be 0 + @throws css::sdbc::SQLException + @throws css::uno::RuntimeException + */ + OOO_DLLPUBLIC_DBTOOLS + void setObjectWithInfo( const css::uno::Reference< css::sdbc::XParameters>& _xParameters, + sal_Int32 parameterIndex, + const ::connectivity::ORowSetValue& x, + sal_Int32 sqlType, + sal_Int32 scale); + + + /** implements XParameters::setObject +

    The object which is to be set is analyzed, and in case it is a simlpe scalar type for which there + is another setXXX method, this other method is used.

    + @param _rxParameters + the interface to forward all setXXX calls to (except setObject) + @param _nColumnIndex + the column index to update + @param _rValue + the value to update + @return + if the update request was successfully re-routed to one of the other updateXXX methods + */ + OOO_DLLPUBLIC_DBTOOLS + bool implSetObject( const css::uno::Reference< css::sdbc::XParameters>& _rxParameters, + const sal_Int32 _nColumnIndex, + const css::uno::Any& _rValue); + + /** creates the standard sql create table statement without the key part. + @param descriptor + The descriptor of the new table. + @param _xConnection + The connection. + @param _bAddScale + The scale will also be added when the value is 0. + */ + OOO_DLLPUBLIC_DBTOOLS + OUString createStandardCreateStatement( const css::uno::Reference< css::beans::XPropertySet >& descriptor, + const css::uno::Reference< css::sdbc::XConnection>& _xConnection, + ISQLStatementHelper* _pHelper, + std::u16string_view _sCreatePattern); + + /** creates the standard sql statement for the key part of a create table statement. + @param descriptor + The descriptor of the new table. + @param _xConnection + The connection. + */ + OOO_DLLPUBLIC_DBTOOLS + OUString createStandardKeyStatement( const css::uno::Reference< css::beans::XPropertySet >& descriptor, + const css::uno::Reference< css::sdbc::XConnection>& _xConnection); + + /** creates the standard sql statement for the type part of a create or alter table statement. + @param _pHelper + Allow to add special SQL constructs. + @param descriptor + The descriptor of the column. + @param _xConnection + The connection. + */ + OOO_DLLPUBLIC_DBTOOLS + OUString createStandardTypePart( const css::uno::Reference< css::beans::XPropertySet >& descriptor + ,const css::uno::Reference< css::sdbc::XConnection>& _xConnection + ,std::u16string_view _sCreatePattern = {}); + + /** creates the standard sql statement for the column part of a create table statement. + @param _pHelper + Allow to add special SQL constructs. + @param descriptor + The descriptor of the column. + @param _xConnection + The connection. + @param _pHelper + Allow to add special SQL constructs. + */ + OOO_DLLPUBLIC_DBTOOLS + OUString createStandardColumnPart( const css::uno::Reference< css::beans::XPropertySet >& descriptor + ,const css::uno::Reference< css::sdbc::XConnection>& _xConnection + ,ISQLStatementHelper* _pHelper = nullptr + ,std::u16string_view _sCreatePattern = {}); + + /** creates a SQL CREATE TABLE statement + + @param descriptor + The descriptor of the new table. + @param _xConnection + The connection. + + @return + The CREATE TABLE statement. + */ + OOO_DLLPUBLIC_DBTOOLS + OUString createSqlCreateTableStatement( const css::uno::Reference< css::beans::XPropertySet >& descriptor + ,const css::uno::Reference< css::sdbc::XConnection>& _xConnection); + + /** creates a SDBC column with the help of getColumns. + @param _xTable + The table. + @param _rName + The name of the column. + @param _bCase + Is the column case sensitive. + @param _bQueryForInfo + If the autoincrement and currency field will be read from the meta data, otherwise the following parameters will be used instead + @param _bIsAutoIncrement + if the column is an autoincrement. + @param _bIsCurrency + if the column is a currency field. + @param _nDataType + The data type of the column. + */ + OOO_DLLPUBLIC_DBTOOLS + css::uno::Reference< css::beans::XPropertySet> + createSDBCXColumn( const css::uno::Reference< css::beans::XPropertySet>& _xTable, + const css::uno::Reference< css::sdbc::XConnection>& _xConnection, + const OUString& _rName, + bool _bCase, + bool _bQueryForInfo, + bool _bIsAutoIncrement, + bool _bIsCurrency, + sal_Int32 _nDataType); + + /** tries to locate the corresponding DataDefinitionSupplier for the given url and connection + @param _rsUrl + The URL used to connect to the database. + @param _xConnection + The connection used to find the correct driver. + @param _rxContext + Used to create the drivermanager. + @return + The datadefinition object. + */ + OOO_DLLPUBLIC_DBTOOLS css::uno::Reference< css::sdbcx::XTablesSupplier> getDataDefinitionByURLAndConnection( + const OUString& _rsUrl, + const css::uno::Reference< css::sdbc::XConnection>& _xConnection, + const css::uno::Reference< css::uno::XComponentContext>& _rxContext); + + /** returns the table privileges to the given parameters + @param _xMetaData + The meta data. + @param _sCatalog + contains the catalog name + @param _sSchema + contains the schema name + @param _sTable + contains the table name + */ + OOO_DLLPUBLIC_DBTOOLS + sal_Int32 getTablePrivileges(const css::uno::Reference< css::sdbc::XDatabaseMetaData>& _xMetaData, + const OUString& _sCatalog, + const OUString& _sSchema, + const OUString& _sTable); + + typedef ::std::pair TBoolPair; + typedef ::std::pair< TBoolPair,sal_Int32 > ColumnInformation; + typedef ::std::multimap< OUString, ColumnInformation, ::comphelper::UStringMixLess> ColumnInformationMap; + /** collects the information about auto increment, currency and data type for the given column name. + The column must be quoted, * is also valid. + @param _xConnection + The connection. + @param _sComposedTableName + The quoted table name. ccc.sss.ttt + @param _sName + The name of the column, or * + @param _rInfo + The information about the column(s). + */ + OOO_DLLPUBLIC_DBTOOLS + void collectColumnInformation( const css::uno::Reference< css::sdbc::XConnection>& _xConnection, + std::u16string_view _sComposedTableName, + std::u16string_view _rName, + ColumnInformationMap& _rInfo); + + + /** adds a boolean comparison clause to the given SQL predicate + + @param _rExpression + the expression which is to be compared with a boolean value + @param _bValue + the boolean value which the expression is to be compared with + @param _nBooleanComparisonMode + the boolean comparison mode to be used. Usually obtained from + a css.sdb.DataSource's Settings member. + @param _out_rSQLPredicate + the buffer to which the comparison predicate will be appended + */ + OOO_DLLPUBLIC_DBTOOLS void getBooleanComparisonPredicate( + std::u16string_view _rExpression, + const bool _bValue, + const sal_Int32 _nBooleanComparisonMode, + OUStringBuffer& _out_rSQLPredicate + ); + + /** is this field an aggregate? + + @param _xComposer + a query composer that knows the field by name + @param _xField + the field + */ + OOO_DLLPUBLIC_DBTOOLS bool isAggregateColumn( + const css::uno::Reference< css::sdb::XSingleSelectQueryComposer > &_xComposer, + const css::uno::Reference< css::beans::XPropertySet > &_xField + ); + + /** is this column an aggregate? + + @param _xColumns collection of columns + look for column sName in there + @param _sName + name of the column + */ + OOO_DLLPUBLIC_DBTOOLS bool isAggregateColumn( + const css::uno::Reference< css::container::XNameAccess > &_xColumns, + const OUString &_sName + ); + + /** is this column an aggregate? + + @param _xColumn + */ + OOO_DLLPUBLIC_DBTOOLS bool isAggregateColumn( + const css::uno::Reference< css::beans::XPropertySet > &_xColumn + ); + +} // namespace dbtools + +namespace connectivity +{ +namespace dbase +{ + enum DBFType { dBaseIII = 0x03, + dBaseIV = 0x04, + dBaseV = 0x05, + VisualFoxPro = 0x30, + VisualFoxProAuto = 0x31, // Visual FoxPro with AutoIncrement field + dBaseFS = 0x43, + dBaseFSMemo = 0xB3, + dBaseIIIMemo = 0x83, + dBaseIVMemo = 0x8B, + dBaseIVMemoSQL = 0x8E, + FoxProMemo = 0xF5 + }; + + /** decode a DBase file's codepage byte to a RTL charset + @param _out_nCharset + in case of success, the decoded RTL charset is written there. + else, this is not written to. + @param nType + the file's type byte + @param nCodepage + the file's codepage byte + @return + true if a RTL charset was successfully decoded and written to _out_nCharset + false if nothing was written to _out_nCharset + */ + OOO_DLLPUBLIC_DBTOOLS bool dbfDecodeCharset(rtl_TextEncoding &_out_nCharset, sal_uInt8 nType, sal_uInt8 nCodepage); + + /** decode a DBase file's codepage byte to a RTL charset + @param _out_nCharset + in case of success, the decoded RTL charset is written there. + else, this is not written to. + @param dbf_Stream + pointer to a SvStream encapsulating the DBase file. + The stream will be rewinded and read from. + No guarantee is made on its position afterwards. Caller must reposition it itself. + @return + true if a RTL charset was successfully decoded and written to _out_nCharset + false if nothing was written to _out_nCharset + */ + OOO_DLLPUBLIC_DBTOOLS bool dbfReadCharset(rtl_TextEncoding &nCharSet, SvStream* dbf_Stream); + +} // namespace connectivity::dbase +} // namespace connectivity + +#endif // INCLUDED_CONNECTIVITY_DBTOOLS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/dbtoolsdllapi.hxx b/include/connectivity/dbtoolsdllapi.hxx new file mode 100644 index 000000000..466d5ab23 --- /dev/null +++ b/include/connectivity/dbtoolsdllapi.hxx @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_DBTOOLSDLLAPI_HXX +#define INCLUDED_CONNECTIVITY_DBTOOLSDLLAPI_HXX + +#include + +#include + +#if defined OOO_DLLIMPLEMENTATION_DBTOOLS +#define OOO_DLLPUBLIC_DBTOOLS SAL_DLLPUBLIC_EXPORT +#else +#define OOO_DLLPUBLIC_DBTOOLS SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/filtermanager.hxx b/include/connectivity/filtermanager.hxx new file mode 100644 index 000000000..b6f104aa4 --- /dev/null +++ b/include/connectivity/filtermanager.hxx @@ -0,0 +1,114 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_FILTERMANAGER_HXX +#define INCLUDED_CONNECTIVITY_FILTERMANAGER_HXX + +#include + +#include + +#include + +namespace com::sun::star::beans { class XPropertySet; } + + +namespace dbtools +{ + + + //= FilterManager + + /** manages the filter of a database component with filter properties + + The idea is that the filter which a database component actually really uses is composed of several single + filter components (which all are conjunctive). + + First, there is a component which is visible to the clients of the database component itself - if they ask + the database component for the Filter property, they will get this public filter. + + Second, there is an implicit filter, which is (to be) created from the MasterFields and DetailFields + property of the database component, if the latter denote columns.
    + For instance, if there is a link-pair CustomerID->cid, where |CustomerID| is a column of the master + database component, and |cid| is a column of the detail database component (the database component we're responsible for), then there will + be an implicit filter "cid = :param_cid_link" (or something like this), which is never visible + to the clients of the database component, but nevertheless needs to be propagated to the aggregated RowSet.
    + Actually, this implicit filter is maintained by the FormParameterManager. + + Potentially, there could be more filter components (for instance, you could imagine database component + controls which act as live filter, which could be implemented with a third component), but + at the moment there are only these two. + */ + class OOO_DLLPUBLIC_DBTOOLS FilterManager + { + public: + enum class FilterComponent + { + PublicFilter, // The filter which is to be published as "Filter" property of the database component. + LinkFilter, // The filter part which is implicitly created for a database component when connecting + // master and detail database components via column names. + PublicHaving, // the same, but should go in HAVING clause instead of WHERE clause + LinkHaving + }; + + private: + css::uno::Reference< css::beans::XPropertySet > m_xComponentAggregate; + OUString m_aPublicFilterComponent; + OUString m_aPublicHavingComponent; + OUString m_aLinkFilterComponent; + OUString m_aLinkHavingComponent; + bool m_bApplyPublicFilter; + + public: + /// ctor + explicit FilterManager(); + + /// late ctor + void initialize(const css::uno::Reference< css::beans::XPropertySet >& _rxComponentAggregate ); + + /// makes the object forgetting the references to the database component + void dispose( ); + + const OUString& getFilterComponent( FilterComponent _eWhich ) const; + void setFilterComponent( FilterComponent _eWhich, const OUString& _rComponent ); + + bool isApplyPublicFilter( ) const { return m_bApplyPublicFilter; } + void setApplyPublicFilter( bool _bApply ); + + private: + /** retrieves a filter which is a conjunction of all single filter components + */ + OUString getComposedFilter( ) const; + OUString getComposedHaving( ) const; + + /** appends one filter component to the statement in our composer + */ + static void appendFilterComponent( OUStringBuffer& io_appendTo, std::u16string_view i_component ); + + /// checks whether there is only one (or even no) non-empty filter component + bool isThereAtMostOneFilterComponent( OUString& o_singleComponent ) const; + bool isThereAtMostOneHavingComponent( OUString& o_singleComponent ) const; + }; + + +} // namespacefrm + + +#endif // CONNECTIVITY_FORMFILTERMANAGER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/formattedcolumnvalue.hxx b/include/connectivity/formattedcolumnvalue.hxx new file mode 100644 index 000000000..9fdf227ed --- /dev/null +++ b/include/connectivity/formattedcolumnvalue.hxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_FORMATTEDCOLUMNVALUE_HXX +#define INCLUDED_CONNECTIVITY_FORMATTEDCOLUMNVALUE_HXX + +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::sdbc { class XRowSet; } +namespace com::sun::star::sdb { class XColumn; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { template class Reference; } +namespace com::sun::star::util { class XNumberFormatter; } + +namespace dbtools +{ + struct FormattedColumnValue_Data; + + //= FormattedColumnValue + + /** a class which helps retrieving and setting the value of a database column + as formatted string. + */ + class OOO_DLLPUBLIC_DBTOOLS FormattedColumnValue final + { + public: + /** constructs an instance + + The format key for the string value exchange is taken from the given column object. + If it has a non- property value FormatKey, this key is taken. + Otherwise, a default format matching the column type is determined. + + The locale of this fallback format is the current system locale. + + The number formats supplier is determined from the given RowSet, by + examining its ActiveConnection. + */ + FormattedColumnValue( + const css::uno::Reference< css::uno::XComponentContext >& _rxContext, + const css::uno::Reference< css::sdbc::XRowSet >& _rxRowSet, + const css::uno::Reference< css::beans::XPropertySet >& _rxColumn + ); + + /** constructs an instance + + The format key for the string value exchange is taken from the given column object. + If it has a non- property value FormatKey, this key is taken. + Otherwise, a default format matching the column type is determined. + + The locale of this fallback format is the current system locale. + */ + FormattedColumnValue( + const css::uno::Reference< css::util::XNumberFormatter >& i_rNumberFormatter, + const css::uno::Reference< css::beans::XPropertySet >& i_rColumn + ); + + ~FormattedColumnValue(); + + // access to the details of the formatting we determined + sal_Int16 getKeyType() const; + const css::uno::Reference< css::sdb::XColumn >& + getColumn() const; + + bool setFormattedValue( const OUString& _rFormattedStringValue ) const; + OUString getFormattedValue() const; + + private: + FormattedColumnValue(const FormattedColumnValue&) = delete; + FormattedColumnValue& operator=(const FormattedColumnValue&) = delete; + std::unique_ptr< FormattedColumnValue_Data > m_pData; + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_FORMATTEDCOLUMNVALUE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/internalnode.hxx b/include/connectivity/internalnode.hxx new file mode 100644 index 000000000..3402f8e3a --- /dev/null +++ b/include/connectivity/internalnode.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +#include + +namespace connectivity +{ + + //= OSQLInternalNode + + /** special node for avoiding memory leaks + */ + class OSQLInternalNode final : public OSQLParseNode + { + public: + OSQLInternalNode(const char* pNewValue, + SQLNodeType eNodeType, + sal_uInt32 nNodeID = 0); + OSQLInternalNode(std::string_view _rNewValue, + SQLNodeType eNodeType, + sal_uInt32 nNodeID = 0); + OSQLInternalNode(const OUString& _rNewValue, + SQLNodeType eNodeType, + sal_uInt32 nNodeID = 0); + + virtual ~OSQLInternalNode() override; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/odbc.hxx b/include/connectivity/odbc.hxx new file mode 100644 index 000000000..9f1e487eb --- /dev/null +++ b/include/connectivity/odbc.hxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#if defined(_WIN32) + +#include + +// just to go with calling convention of windows +#if SYSTEM_ODBC_HEADERS +#if !defined WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif +#include +#define SQL_API __stdcall +#include +#else +#define SQL_API __stdcall +#include +#endif +#undef SQL_API +#define SQL_API __stdcall + +#ifndef SQL_C_BOOKMARK +#define SQL_C_BOOKMARK SQL_C_ULONG /* BOOKMARK */ +#endif + +#ifndef SQL_OPT_TRACE_OFF +#define SQL_OPT_TRACE_OFF 0UL +#endif + +#define SDB_ODBC_CHAR UCHAR + +#include + +#endif + + +#ifdef UNX + +#ifndef ODBC_UNX +#define ODBC_UNX +#endif +#define CALLBACK +#define EXPORT +#ifdef SYSTEM_ODBC_HEADERS +#include +#else +#include +#endif + +#define SDB_ODBC_CHAR UCHAR + +#endif // UNX + + +#ifndef SQL_WCHAR +#define SQL_WCHAR (-8) +#endif +#ifndef SQL_WVARCHAR +#define SQL_WVARCHAR (-9) +#endif +#ifndef SQL_WLONGVARCHAR +#define SQL_WLONGVARCHAR (-10) +#endif +#ifndef SQL_C_WCHAR +#define SQL_C_WCHAR SQL_WCHAR +#endif + +#ifndef SQL_C_TCHAR +#ifdef UNICODE +#define SQL_C_TCHAR SQL_C_WCHAR +#else +#define SQL_C_TCHAR SQL_C_CHAR +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/parameters.hxx b/include/connectivity/parameters.hxx new file mode 100644 index 000000000..f2196af12 --- /dev/null +++ b/include/connectivity/parameters.hxx @@ -0,0 +1,415 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_PARAMETERS_HXX +#define INCLUDED_CONNECTIVITY_PARAMETERS_HXX + +#include +#include + +#include + +#include +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::container { class XIndexAccess; } +namespace com::sun::star::form { class XDatabaseParameterListener; } +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::sdbc { class XArray; } +namespace com::sun::star::sdbc { class XBlob; } +namespace com::sun::star::sdbc { class XClob; } +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::sdbc { class XDatabaseMetaData; } +namespace com::sun::star::sdbc { class XParameters; } +namespace com::sun::star::sdbc { class XRef; } +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::uno { class XAggregation; } +namespace com::sun::star::uno { class XComponentContext; } + +namespace dbtools +{ + + + typedef ::utl::SharedUNOComponent< css::sdb::XSingleSelectQueryComposer, ::utl::DisposableComponent > + SharedQueryComposer; + + + //= ParameterManager + + class FilterManager; + class OOO_DLLPUBLIC_DBTOOLS ParameterManager + { + public: + /// classifies the origin of the data to fill a parameter + enum class ParameterClassification + { + /** parameters which are filled from the master-detail relationship, where the detail + name is an explicit parameter name + */ + LinkedByParamName, + /** parameters which are filled from the master-detail relationship, where the detail + name is a column name, so an implicit parameter had to be generated for it + */ + LinkedByColumnName, + /** parameters which are filled externally (i.e. by XParameters::setXXX, or by the parameter listeners) + */ + FilledExternally + }; + /** meta data about an inner parameter + */ + private: + struct ParameterMetaData + { + /// the type of the parameter + ParameterClassification eType; + /// the column object for this parameter, as returned by the query composer + css::uno::Reference< css::beans::XPropertySet > + xComposerColumn; + /// the indices of inner parameters which need to be filled when this concrete parameter is set + ::std::vector< sal_Int32 > aInnerIndexes; + + /// ctor with composer column + ParameterMetaData( const css::uno::Reference< css::beans::XPropertySet >& _rxColumn ) + :eType ( ParameterClassification::FilledExternally ) + ,xComposerColumn ( _rxColumn ) + { + } + }; + + typedef ::std::map< OUString, ParameterMetaData > ParameterInformation; + + private: + ::osl::Mutex& m_rMutex; + ::comphelper::OInterfaceContainerHelper3 m_aParameterListeners; + + css::uno::Reference< css::uno::XComponentContext > + m_xContext; + + css::uno::WeakReference< css::beans::XPropertySet > + m_xComponent; // the database component whose parameters we're handling + css::uno::Reference< css::uno::XAggregation > + m_xAggregatedRowSet; // the aggregated row set - necessary for unwrapped access to some interfaces + css::uno::Reference< css::sdbc::XParameters > + m_xInnerParamUpdate; // write access to the inner parameters + SharedQueryComposer m_xComposer; // query composer wrapping the statement which the *aggregate* is based on + SharedQueryComposer m_xParentComposer; // query composer wrapping the statement of our parent database component + css::uno::Reference< css::container::XIndexAccess > + m_xInnerParamColumns; // index access to the parameter columns, as got from the query composer + + ::dbtools::param::ParametersContainerRef + m_pOuterParameters; // the container of parameters which still need to be filled in by + // external instances + sal_Int32 m_nInnerCount; // overall number of parameters as required by the database component's aggregate + + ParameterInformation m_aParameterInformation; + + std::vector< OUString > m_aMasterFields; + std::vector< OUString > m_aDetailFields; + + OUString m_sIdentifierQuoteString; + OUString m_sSpecialCharacters; + css::uno::Reference< css::sdbc::XDatabaseMetaData > m_xConnectionMetadata; + + ::std::vector< bool > m_aParametersVisited; + + bool m_bUpToDate; + + public: + /** ctor + */ + explicit ParameterManager( + ::osl::Mutex& _rMutex, + const css::uno::Reference< css::uno::XComponentContext >& _rxContext + ); + + /// late ctor + void initialize( + const css::uno::Reference< css::beans::XPropertySet >& _rxComponent, + const css::uno::Reference< css::uno::XAggregation >& _rxComponentAggregate + ); + + /// makes the object forgetting the references to the database component + void dispose( ); + + /// clears the instance data + void clearAllParameterInformation(); + + /// checks whether the parameter information is up-to-date + bool isUpToDate() const { return m_bUpToDate; } + + /** updates all parameter information represented by the instance + */ + void updateParameterInfo( FilterManager& _rFilterManager ); + + /** fills parameter values, as extensive as possible + +

    In particular, all values which can be filled from the master-detail relationship of + between our database component and its parent are filled in.

    + + @param _rxCompletionHandler + an interaction handler which should be used to fill all parameters which + cannot be filled by other means. May be + @param _rClearForNotifies + the mutex guard to be (temporarily) cleared for notifications + + @precond + the instance is alive, i.e. isAlive returns + + @return + if and only if the parameter filling has not been cancelled by the user + */ + bool fillParameterValues( + const css::uno::Reference< css::task::XInteractionHandler >& _rxCompletionHandler, + ::osl::ResettableMutexGuard& _rClearForNotifies + ); + + /** sets all parameter values to null (via XParameters::setNull) + + @precond + the instance is alive, i.e. isAlive returns + */ + void setAllParametersNull(); + + /** resets all detail columns which are, via a parameter, linked to a master column, to + the value of this master column. + + For instance, if the database component is bound to a statement SELECT * from invoice where inv_id = :cid, + and there is one master-detail link from + + @precond + the instance is alive, i.e. isAlive returns + */ + void resetParameterValues(); + + /** adds the given listener to the list of parameter listeners + */ + void addParameterListener( + const css::uno::Reference< css::form::XDatabaseParameterListener >& _rxListener + ); + + /** removes the given listener from the list of parameter listeners + */ + void removeParameterListener( + const css::uno::Reference< css::form::XDatabaseParameterListener >& _rxListener + ); + + // XParameters equivalents + void setNull ( sal_Int32 _nIndex, sal_Int32 sqlType); + void setObjectNull ( sal_Int32 _nIndex, sal_Int32 sqlType, const OUString& typeName); + void setBoolean ( sal_Int32 _nIndex, bool x); + void setByte ( sal_Int32 _nIndex, sal_Int8 x); + void setShort ( sal_Int32 _nIndex, sal_Int16 x); + void setInt ( sal_Int32 _nIndex, sal_Int32 x); + void setLong ( sal_Int32 _nIndex, sal_Int64 x); + void setFloat ( sal_Int32 _nIndex, float x); + void setDouble ( sal_Int32 _nIndex, double x); + void setString ( sal_Int32 _nIndex, const OUString& x); + void setBytes ( sal_Int32 _nIndex, const css::uno::Sequence< sal_Int8 >& x); + void setDate ( sal_Int32 _nIndex, const css::util::Date& x); + void setTime ( sal_Int32 _nIndex, const css::util::Time& x); + void setTimestamp ( sal_Int32 _nIndex, const css::util::DateTime& x); + void setBinaryStream ( sal_Int32 _nIndex, const css::uno::Reference< css::io::XInputStream>& x, sal_Int32 length); + void setCharacterStream ( sal_Int32 _nIndex, const css::uno::Reference< css::io::XInputStream>& x, sal_Int32 length); + void setObject ( sal_Int32 _nIndex, const css::uno::Any& x); + void setObjectWithInfo ( sal_Int32 _nIndex, const css::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale); + void setRef ( sal_Int32 _nIndex, const css::uno::Reference< css::sdbc::XRef>& x); + void setBlob ( sal_Int32 _nIndex, const css::uno::Reference< css::sdbc::XBlob>& x); + void setClob ( sal_Int32 _nIndex, const css::uno::Reference< css::sdbc::XClob>& x); + void setArray ( sal_Int32 _nIndex, const css::uno::Reference< css::sdbc::XArray>& x); + void clearParameters(); + + private: + /// checks whether the object is already initialized, and not yet disposed + bool isAlive() const { return m_xComponent.get().is() && m_xInnerParamUpdate.is(); } + + /** creates a filter expression from a master-detail link where the detail denotes a column name + */ + OUString + createFilterConditionFromColumnLink( + const OUString& /* [in] */ _rMasterColumn, + const css::uno::Reference< css::beans::XPropertySet >& /* [in] */ xDetailColumn, + OUString& /* [out] */ _rNewParamName + ); + + /** initializes our query composer, and the collection of inner parameter columns + + @param _rxComponent + the database component to initialize from. Must not be + @return + if and only if the initialization was successful + + @postcond + if and only if is returned, then m_xInnerParamColumns contains the collection of + inner parameters + */ + bool initializeComposerByComponent( + const css::uno::Reference< css::beans::XPropertySet >& _rxComponent + ); + + /** collects initial meta information about inner parameters (i.e. it initially fills + m_aParameterInformation). + + @param _bSecondRun + if , this is the second run, because we ourself previously extended the filter of + the RowSet + + @precond + m_xInnerParamColumns is not + */ + void collectInnerParameters( bool _bSecondRun ); + + /** analyzes the master-detail links for our database component, and initializes m_aMasterFields and m_aDetailFields + + @param _rFilterManager + the filter manager of the database component + @param _rColumnsInLinkDetails + will be set to if and only if there were link pairs where the detail field denoted + a column name of our database component + + @precond + the instance is alive, i.e. isAlive returns + */ + void analyzeFieldLinks( FilterManager& _rFilterManager, bool& /* [out] */ _rColumnsInLinkDetails ); + + /** classifies the link pairs + + @param _rxParentColumns + the columns of the parent database component + + @param _rxColumns + the columns of our own database component + + @param _out_rAdditionalFilterComponents + the additional filter components which are required for master-detail relationships where + the detail part denotes a column name. In such a case, an additional filter needs to be created, + containing a new parameter. + + @param _out_rAdditionalHavingComponents + the additional having clause components which are required for master-detail relationships where + the detail part denotes a column name. In such a case, an additional filter needs to be created, + containing a new parameter. + + @precond + m_aMasterFields and m_aDetailFields have the same length + */ + void classifyLinks( + const css::uno::Reference< css::container::XNameAccess >& _rxParentColumns, + const css::uno::Reference< css::container::XNameAccess >& _rxColumns, + ::std::vector< OUString >& _out_rAdditionalFilterComponents, + ::std::vector< OUString >& _out_rAdditionalHavingComponents + ); + + /** finalizes our m_pOuterParameters so that it can be used for + external parameter listeners + + @precond + m_pOuterParameters is + @precond + m_xInnerParamUpdate is not + */ + void createOuterParameters(); + + /** fills in the parameters values which result from the master-detail relationship + between the database component and its parent + + @param _rxParentColumns + the columns of the parameter database component. Must not be + @precond + the instance is alive, i.e. isAlive returns + */ + void fillLinkedParameters( + const css::uno::Reference< css::container::XNameAccess >& _rxParentColumns + ); + + /** completes all missing parameters via an interaction handler + + @precond + the instance is alive, i.e. isAlive returns + + @return + if and only if the parameter filling has not been cancelled by the user + */ + bool completeParameters( + const css::uno::Reference< css::task::XInteractionHandler >& _rxCompletionHandler, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection + ); + + /** asks the parameter listeners to fill in final values + + @precond + the instance is alive, i.e. isAlive returns + + @return + if and only if the parameter filling has not been cancelled by the user + */ + bool consultParameterListeners( ::osl::ResettableMutexGuard& _rClearForNotifies ); + + /** mark an externally filled parameter as visited + */ + void externalParameterVisited( sal_Int32 _nIndex ); + + private: + /** retrieves the columns of the parent database component + + @precond + the instance is alive, i.e. isAlive returns + @return + if and only if the columns could be successfully retrieved + */ + bool getParentColumns( + css::uno::Reference< css::container::XNameAccess >& /* [out] */ _out_rxParentColumns, + bool _bFromComposer + ); + + /** retrieves the columns of our database component + + @param _bFromComposer + if , the columns are obtained from the composer, else from the living database component itself + @return + if and only if the columns could be successfully retrieved + */ + bool getColumns( + css::uno::Reference< css::container::XNameAccess >& /* [out] */ _rxColumns, + bool _bFromComposer + ); + + /** retrieves the active connection of the database component + */ + void getConnection( + css::uno::Reference< css::sdbc::XConnection >& /* [out] */ _rxConnection + ); + + /** caches some info about the connection of our database component + */ + void cacheConnectionInfo(); + + private: + ParameterManager( const ParameterManager& ) = delete; + ParameterManager& operator=( const ParameterManager& ) = delete; + }; + + +} // namespacefrm + + +#endif // INCLUDED_CONNECTIVITY_PARAMETERS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/paramwrapper.hxx b/include/connectivity/paramwrapper.hxx new file mode 100644 index 000000000..bf16e0851 --- /dev/null +++ b/include/connectivity/paramwrapper.hxx @@ -0,0 +1,196 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_PARAMWRAPPER_HXX +#define INCLUDED_CONNECTIVITY_PARAMWRAPPER_HXX + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::sdbc { class XParameters; } +namespace com::sun::star::sdb { class XSingleSelectQueryAnalyzer; } + + +namespace dbtools::param +{ + + + //= ParameterWrapper + + /** wraps a parameter column as got from an SQLQueryComposer, so that it has an additional + property "Value", which is forwarded to an XParameters interface + */ + class UNLESS_MERGELIBS(OOO_DLLPUBLIC_DBTOOLS) ParameterWrapper final : public ::cppu::OWeakObject + ,public css::lang::XTypeProvider + ,public ::comphelper::OMutexAndBroadcastHelper + ,public ::cppu::OPropertySetHelper + { + private: + typedef ::cppu::OWeakObject UnoBase; + typedef ::cppu::OPropertySetHelper PropertyBase; + + private: + /// the most recently set value of the parameter + ::connectivity::ORowSetValue m_aValue; + /// the positions (in our m_xValueDestination) at which the value should be set (0-based!) + ::std::vector< sal_Int32 > m_aIndexes; + + /// the "delegator" column to which standard property requests are forwarded + css::uno::Reference< css::beans::XPropertySet > m_xDelegator; + /// the property set info for our delegator + css::uno::Reference< css::beans::XPropertySetInfo > m_xDelegatorPSI; + /// the component taking the value + css::uno::Reference< css::sdbc::XParameters > m_xValueDestination; + /// helper for implementing XPropertySetInfo + ::std::unique_ptr< ::cppu::OPropertyArrayHelper > m_pInfoHelper; + + + public: + const ::connectivity::ORowSetValue& Value() const { return m_aValue; } + ::connectivity::ORowSetValue& Value() { return m_aValue; } + + public: + ParameterWrapper( + const css::uno::Reference< css::beans::XPropertySet >& _rxColumn + ); + + ParameterWrapper( + const css::uno::Reference< css::beans::XPropertySet >& _rxColumn, + const css::uno::Reference< css::sdbc::XParameters >& _rxAllParameters, + std::vector< sal_Int32 >&& _rIndexes + ); + + DECLARE_XINTERFACE() + + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; + + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override; + virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() override; + + // OPropertySetHelper + virtual sal_Bool SAL_CALL convertFastPropertyValue( css::uno::Any& rConvertedValue, css::uno::Any& rOldValue, sal_Int32 nHandle, const css::uno::Any& rValue) override; + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const css::uno::Any& rValue ) override; + virtual void SAL_CALL getFastPropertyValue( css::uno::Any& rValue, sal_Int32 nHandle ) const override; + + // pseudo-XComponent + void dispose(); + + private: + virtual ~ParameterWrapper() override; + + // disambiguations + using ::cppu::OPropertySetHelper::getFastPropertyValue; + + OUString impl_getPseudoAggregatePropertyName( sal_Int32 _nHandle ) const; + }; + + + //= ParameterWrapper + + typedef ::std::vector< ::rtl::Reference< ParameterWrapper > > Parameters; + + + //= ParameterWrapperContainer + + typedef ::cppu::WeakComponentImplHelper < css::container::XIndexAccess + , css::container::XEnumerationAccess + > ParameterWrapperContainer_Base; + + /// class for the parameter event @see approveParameter + class OOO_DLLPUBLIC_DBTOOLS ParameterWrapperContainer final : + public ParameterWrapperContainer_Base + { + private: + ::osl::Mutex m_aMutex; + Parameters m_aParameters; + + virtual ~ParameterWrapperContainer() override; + + public: + /** creates an empty container + */ + ParameterWrapperContainer(); + + /** creates a container from a SingleSelectQuerAnalyzer's parameter columns + + Note that here, the simple constructor of the ParameterWrapper will be used, which does not + use a XParameters instance to forward values to, but only remembers the values itself. + */ + ParameterWrapperContainer( const css::uno::Reference< css::sdb::XSingleSelectQueryAnalyzer >& _rxComposer ); + + // css::container::XElementAccess + virtual css::uno::Type SAL_CALL getElementType() override; + virtual sal_Bool SAL_CALL hasElements() override; + + // css::container::XEnumerationAccess + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration() override; + + // css::container::XIndexAccess + virtual sal_Int32 SAL_CALL getCount() override; + virtual css::uno::Any SAL_CALL getByIndex(sal_Int32 _rIndex) override; + + public: + const Parameters& getParameters() const { return m_aParameters; } + + const ::connectivity::ORowSetValue& operator[]( size_t _index ) const { return m_aParameters[ _index ]->Value(); } + ::connectivity::ORowSetValue& operator[]( size_t _index ) { return m_aParameters[ _index ]->Value(); } + + /** adds a ParameterWrapper to the end of the array + */ + void push_back( ParameterWrapper* _pParameter ) + { + m_aParameters.push_back( _pParameter ); + } + + size_t size() const { return m_aParameters.size(); } + + private: + // XComponent + virtual void SAL_CALL disposing() override; + + void impl_checkDisposed_throw(); + }; + + + //= ParametersContainer + + typedef ::rtl::Reference< ParameterWrapperContainer > ParametersContainerRef; + + +} // namespace dbtools::param + + +#endif // INCLUDED_CONNECTIVITY_PARAMWRAPPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/predicateinput.hxx b/include/connectivity/predicateinput.hxx new file mode 100644 index 000000000..3d9fb0a71 --- /dev/null +++ b/include/connectivity/predicateinput.hxx @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_PREDICATEINPUT_HXX +#define INCLUDED_CONNECTIVITY_PREDICATEINPUT_HXX + +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::i18n { class XLocaleData4; } +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::util { class XNumberFormatter; } + + + +namespace dbtools +{ + + + //= OPredicateInputController + + /** A class which allows input of an SQL predicate for a row set column + into an edit field. + */ + class OOO_DLLPUBLIC_DBTOOLS OPredicateInputController + { + private: + css::uno::Reference< css::sdbc::XConnection > + m_xConnection; + css::uno::Reference< css::util::XNumberFormatter > + m_xFormatter; + css::uno::Reference< css::i18n::XLocaleData4 > + m_xLocaleData; + + ::connectivity::OSQLParser + m_aParser; + + public: + OPredicateInputController( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const ::connectivity::IParseContext* _pParseContext = nullptr + ); + + /** transforms a "raw" predicate value (usually obtained from a user input) into a valid predicate for the given column + @param _rPredicateValue + The text to normalize. + @param _rxField + The field for which the text should be a predicate value. + @param _pErrorMessage + If not , and a parsing error occurs, the error message will be copied to the string the argument + points to. + */ + bool normalizePredicateString( + OUString& _rPredicateValue, + const css::uno::Reference< css::beans::XPropertySet >& _rxField, + OUString* _pErrorMessage = nullptr + ) const; + + /** get the value of the predicate, as a string to be used in a WHERE clause + @param _rPredicateValue + the value which has been normalized using normalizePredicateString + @param _rxField + is the field for which a predicate is to be entered + @see normalizePredicateString + */ + OUString getPredicateValueStr( + const OUString& _rPredicateValue, + const css::uno::Reference< css::beans::XPropertySet > & _rxField + ) const; + + OUString getPredicateValueStr( + const OUString& _sField + , const OUString& _rPredicateValue) const; + + /** get the value of the predicate, either as an empty or as a string + @param _rPredicateValue + the value which has been normalized using normalizePredicateString + @param _rxField + is the field for which a predicate is to be entered + @see normalizePredicateString + */ + css::uno::Any getPredicateValue( + const OUString& _rPredicateValue, + const css::uno::Reference< css::beans::XPropertySet > & _rxField + ) const; + + private: + std::unique_ptr<::connectivity::OSQLParseNode> implPredicateTree( + OUString& _rErrorMessage, + const OUString& _rStatement, + const css::uno::Reference< css::beans::XPropertySet > & _rxField + ) const; + + bool getSeparatorChars( + const css::lang::Locale& _rLocale, + sal_Unicode& _rDecSep, + sal_Unicode& _rThdSep + ) const; + + css::uno::Any implParseNode(std::unique_ptr<::connectivity::OSQLParseNode> pParseNode, bool _bForStatementUse) const; + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_PREDICATEINPUT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sdbcx/IRefreshable.hxx b/include/connectivity/sdbcx/IRefreshable.hxx new file mode 100644 index 000000000..412ef8079 --- /dev/null +++ b/include/connectivity/sdbcx/IRefreshable.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_SDBCX_IREFRESHABLE_HXX +#define INCLUDED_CONNECTIVITY_SDBCX_IREFRESHABLE_HXX + +#include + +namespace connectivity::sdbcx + { + class OOO_DLLPUBLIC_DBTOOLS SAL_NO_VTABLE IRefreshableGroups + { + public: + virtual void refreshGroups() = 0; + + protected: + ~IRefreshableGroups() {} + }; + + class OOO_DLLPUBLIC_DBTOOLS SAL_NO_VTABLE IRefreshableUsers + { + public: + virtual void refreshUsers() = 0; + + protected: + ~IRefreshableUsers() {} + }; + + class OOO_DLLPUBLIC_DBTOOLS SAL_NO_VTABLE IRefreshableColumns + { + public: + virtual void refreshColumns() = 0; + + protected: + ~IRefreshableColumns() {} + }; + +} +#endif // INCLUDED_CONNECTIVITY_SDBCX_IREFRESHABLE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sdbcx/VCollection.hxx b/include/connectivity/sdbcx/VCollection.hxx new file mode 100644 index 000000000..0f5a0b3fb --- /dev/null +++ b/include/connectivity/sdbcx/VCollection.hxx @@ -0,0 +1,225 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_SDBCX_VCOLLECTION_HXX +#define INCLUDED_CONNECTIVITY_SDBCX_VCOLLECTION_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::container { class XEnumeration; } + + +namespace connectivity::sdbcx + { + + // the class OCollection is base class for collections :-) + typedef ::cppu::ImplHelper10< css::container::XNameAccess, + css::container::XIndexAccess, + css::container::XEnumerationAccess, + css::container::XContainer, + css::sdbc::XColumnLocate, + css::util::XRefreshable, + css::sdbcx::XDataDescriptorFactory, + css::sdbcx::XAppend, + css::sdbcx::XDrop, + css::lang::XServiceInfo> OCollectionBase; + + typedef css::uno::Reference< css::beans::XPropertySet > ObjectType; + + class UNLESS_MERGELIBS(OOO_DLLPUBLIC_DBTOOLS) SAL_NO_VTABLE IObjectCollection + { + public: + virtual ~IObjectCollection(); + virtual bool exists(const OUString& _sName ) = 0; + virtual bool empty() = 0; + virtual void swapAll() = 0; + virtual void swap() = 0; + virtual void clear() = 0; + virtual void reFill(const ::std::vector< OUString> &_rVector) = 0; + virtual void insert(const OUString& _sName, const ObjectType& _xObject) = 0; + virtual bool rename(const OUString& _sOldName, const OUString& _sNewName) = 0; + virtual sal_Int32 size() = 0; + virtual css::uno::Sequence< OUString > getElementNames() = 0; + virtual OUString getName(sal_Int32 _nIndex) = 0; + virtual void disposeAndErase(sal_Int32 _nIndex) = 0; + virtual void disposeElements() = 0; + virtual sal_Int32 findColumn( const OUString& columnName ) = 0; + virtual ObjectType getObject(sal_Int32 _nIndex) = 0; + virtual ObjectType getObject(const OUString& columnName) = 0; + virtual void setObject(sal_Int32 _nIndex,const ObjectType& _xObject) = 0; + virtual bool isCaseSensitive() const = 0; + }; + + // OCollection + + class OOO_DLLPUBLIC_DBTOOLS SAL_NO_VTABLE OCollection : + public OCollectionBase + { + protected: + ::std::unique_ptr m_pElements; + + ::comphelper::OInterfaceContainerHelper3 m_aContainerListeners; + ::comphelper::OInterfaceContainerHelper3 m_aRefreshListeners; + + protected: + ::cppu::OWeakObject& m_rParent; // parent of the collection + ::osl::Mutex& m_rMutex; // mutex of the parent + bool m_bUseIndexOnly; // is only TRUE when only an indexaccess is needed + + // the implementing class should refresh their elements + /// @throws css::uno::RuntimeException + virtual void impl_refresh() = 0; + + // will be called when an object was requested by one of the accessing methods like getByIndex + virtual ObjectType createObject(const OUString& _rName) = 0; + + // will be called when a new object should be generated by a call of createDataDescriptor + // the returned object is empty will be filled outside and added to the collection + virtual css::uno::Reference< css::beans::XPropertySet > createDescriptor(); + + /** appends an object described by a descriptor, under a given name + @param _rForName + is the name under which the object should be appended. Guaranteed to not be empty. + This is passed for convenience only, since it's the result of a call of + getNameForObject for the given descriptor + @param descriptor + describes the object to append + @return + the new object which is to be inserted into the collection. This might be the result + of a call of createObject( _rForName ), or a clone of the descriptor. + */ + virtual ObjectType appendObject( const OUString& _rForName, const css::uno::Reference< css::beans::XPropertySet >& descriptor ); + + // called when XDrop was called + virtual void dropObject(sal_Int32 _nPos, const OUString& _sElementName); + + /** returns the name for the object. The default implementation ask for the property NAME. If this doesn't satisfy, it has to be overridden. + @param _xObject The object where the name should be extracted. + @return The name of the object. + */ + virtual OUString getNameForObject(const ObjectType& _xObject); + + /** clones the given descriptor + + The method calls createDescriptor to create a new, empty descriptor, and then copies all properties from + _descriptor to the new object, which is returned. + + This method might come handy in derived classes for implementing appendObject, when the object + is not actually appended to any backend (e.g. for the columns collection of a descriptor object itself, + where there is not yet a database backend to append the column to). + */ + ObjectType cloneDescriptor( const ObjectType& _descriptor ); + + OCollection(::cppu::OWeakObject& _rParent, + bool _bCase, + ::osl::Mutex& _rMutex, + const ::std::vector< OUString> &_rVector, + bool _bUseIndexOnly = false, + bool _bUseHardRef = true); + + /** clear the name map +

    Does not dispose the objects hold by the collection.

    + */ + void clear_NoDispose(); + + /** insert a new element into the collection + */ + void insertElement(const OUString& _sElementName,const ObjectType& _xElement); + + /** return the object, if not existent it creates it. + @param _nIndex + The index of the object to create. + @return ObjectType + */ + ObjectType getObject(sal_Int32 _nIndex); + + public: + virtual ~OCollection(); + DECLARE_SERVICE_INFO(); + + void reFill(const ::std::vector< OUString> &_rVector); + bool isCaseSensitive() const { return m_pElements->isCaseSensitive(); } + void renameObject(const OUString& _sOldName, const OUString& _sNewName); + + // only the name is identical to ::cppu::OComponentHelper + virtual void disposing(); + // dispatch the refcounting to the parent + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override; + + // css::container::XElementAccess + virtual css::uno::Type SAL_CALL getElementType( ) override; + virtual sal_Bool SAL_CALL hasElements( ) override; + // css::container::XIndexAccess + virtual sal_Int32 SAL_CALL getCount( ) override; + virtual css::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) override; + + // css::container::XNameAccess + virtual css::uno::Any SAL_CALL getByName( const OUString& aName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getElementNames( ) override; + virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) override; + // XEnumerationAccess + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration( ) override; + // css::util::XRefreshable + virtual void SAL_CALL refresh( ) override; + virtual void SAL_CALL addRefreshListener( const css::uno::Reference< css::util::XRefreshListener >& l ) override; + virtual void SAL_CALL removeRefreshListener( const css::uno::Reference< css::util::XRefreshListener >& l ) override; + // XDataDescriptorFactory + virtual css::uno::Reference< css::beans::XPropertySet > SAL_CALL createDataDescriptor( ) override; + // XAppend + virtual void SAL_CALL appendByDescriptor( const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + // XDrop + virtual void SAL_CALL dropByName( const OUString& elementName ) override; + virtual void SAL_CALL dropByIndex( sal_Int32 index ) override; + // XColumnLocate + virtual sal_Int32 SAL_CALL findColumn( const OUString& columnName ) override; + // css::container::XContainer + virtual void SAL_CALL addContainerListener( const css::uno::Reference< css::container::XContainerListener >& xListener ) override; + virtual void SAL_CALL removeContainerListener( const css::uno::Reference< css::container::XContainerListener >& xListener ) override; + private: + void notifyElementRemoved(const OUString& _sName); + void disposeElements(); + void dropImpl(sal_Int32 _nIndex, bool _bReallyDrop = true); + }; + +} +#endif // INCLUDED_CONNECTIVITY_SDBCX_VCOLLECTION_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sdbcx/VColumn.hxx b/include/connectivity/sdbcx/VColumn.hxx new file mode 100644 index 000000000..579611cdf --- /dev/null +++ b/include/connectivity/sdbcx/VColumn.hxx @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_SDBCX_VCOLUMN_HXX +#define INCLUDED_CONNECTIVITY_SDBCX_VCOLUMN_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace connectivity::sdbcx + { + class OColumn; + typedef ::comphelper::OIdPropertyArrayUsageHelper OColumn_PROP; + + typedef ::cppu::WeakComponentImplHelper< css::container::XNamed, + css::lang::XServiceInfo> OColumnDescriptor_BASE; + typedef ::cppu::ImplHelper1< css::sdbcx::XDataDescriptorFactory > OColumn_BASE; + + + class OOO_DLLPUBLIC_DBTOOLS OColumn : + public cppu::BaseMutex, + public OColumn_BASE, + public OColumnDescriptor_BASE, + public OColumn_PROP, + public ODescriptor + { + protected: + OUString m_TypeName; + OUString m_Description; + OUString m_DefaultValue; + + sal_Int32 m_IsNullable; + sal_Int32 m_Precision; + sal_Int32 m_Scale; + sal_Int32 m_Type; + + bool m_IsAutoIncrement; + bool m_IsRowVersion; + bool m_IsCurrency; + + OUString m_CatalogName; + OUString m_SchemaName; + OUString m_TableName; + + using OColumnDescriptor_BASE::rBHelper; + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const override; + virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() override; + + virtual ~OColumn() override; + public: + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + OColumn( bool _bCase); + OColumn( const OUString& Name, + const OUString& TypeName, + const OUString& DefaultValue, + const OUString& Description, + sal_Int32 IsNullable, + sal_Int32 Precision, + sal_Int32 Scale, + sal_Int32 Type, + bool IsAutoIncrement, + bool IsRowVersion, + bool IsCurrency, + bool _bCase, + const OUString& CatalogName, + const OUString& SchemaName, + const OUString& TableName); + + DECLARE_SERVICE_INFO(); + //XInterface + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + //XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + // ODescriptor + virtual void construct() override; + // ::cppu::OComponentHelper + virtual void SAL_CALL disposing() override; + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + // XNamed + virtual OUString SAL_CALL getName( ) override; + virtual void SAL_CALL setName( const OUString& aName ) override; + // XDataDescriptorFactory + virtual css::uno::Reference< css::beans::XPropertySet > SAL_CALL createDataDescriptor( ) override; + }; + +} + +#endif // INCLUDED_CONNECTIVITY_SDBCX_VCOLUMN_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sdbcx/VDescriptor.hxx b/include/connectivity/sdbcx/VDescriptor.hxx new file mode 100644 index 000000000..3147a5187 --- /dev/null +++ b/include/connectivity/sdbcx/VDescriptor.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_SDBCX_VDESCRIPTOR_HXX +#define INCLUDED_CONNECTIVITY_SDBCX_VDESCRIPTOR_HXX + +#include +#include +#include +#include + +namespace connectivity::sdbcx + { + + // = ODescriptor + + typedef ::comphelper::OPropertyContainer ODescriptor_PBASE; + class OOO_DLLPUBLIC_DBTOOLS ODescriptor + :public ODescriptor_PBASE + ,public css::lang::XUnoTunnel + { + protected: + OUString m_Name; + + /** helper for derived classes to implement OPropertyArrayUsageHelper::createArrayHelper + + This method just calls describeProperties, and flags all properties as READONLY if and + only if we do *not* act as descriptor, but as final object. + + @seealso isNew + */ + ::cppu::IPropertyArrayHelper* doCreateArrayHelper() const; + + private: + comphelper::UStringMixEqual m_aCase; + bool m_bNew; + + public: + ODescriptor(::cppu::OBroadcastHelper& _rBHelper, bool _bCase, bool _bNew = false); + + virtual ~ODescriptor() override; + + bool isNew() const { return m_bNew; } + void setNew(bool _bNew); + + bool isCaseSensitive() const { return m_aCase.isCaseSensitive(); } + + virtual void construct(); + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + /// @throws css::uno::RuntimeException + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ); + + // css::lang::XUnoTunnel + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId(); + + // retrieves the ODescriptor implementation of a given UNO component, and returns its ->isNew flag + static bool isNew( const css::uno::Reference< css::uno::XInterface >& _rxDescriptor ); + }; + +} + +#endif // INCLUDED_CONNECTIVITY_SDBCX_VDESCRIPTOR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sdbcx/VTable.hxx b/include/connectivity/sdbcx/VTable.hxx new file mode 100644 index 000000000..6d575615f --- /dev/null +++ b/include/connectivity/sdbcx/VTable.hxx @@ -0,0 +1,142 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_SDBCX_VTABLE_HXX +#define INCLUDED_CONNECTIVITY_SDBCX_VTABLE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::sdbc { class XDatabaseMetaData; } + +namespace connectivity::sdbcx + { + + class OTable; + class OCollection; + + typedef ::cppu::WeakComponentImplHelper< css::sdbcx::XColumnsSupplier, + css::sdbcx::XKeysSupplier, + css::container::XNamed, + css::lang::XServiceInfo> OTableDescriptor_BASE; + + typedef ::cppu::ImplHelper4< css::sdbcx::XDataDescriptorFactory, + css::sdbcx::XIndexesSupplier, + css::sdbcx::XRename, + css::sdbcx::XAlterTable > OTable_BASE; + + typedef ::comphelper::OIdPropertyArrayUsageHelper OTable_PROP; + + + class OOO_DLLPUBLIC_DBTOOLS OTable : + public cppu::BaseMutex, + public OTable_BASE, + public OTableDescriptor_BASE, + public IRefreshableColumns, + public OTable_PROP, + public ODescriptor + { + protected: + OUString m_CatalogName; + OUString m_SchemaName; + OUString m_Description; + OUString m_Type; + + // no Reference! see OCollection::acquire + std::unique_ptr m_xKeys; + std::unique_ptr m_xColumns; + std::unique_ptr m_xIndexes; + OCollection* m_pTables; // must hold his own container to notify him when renaming + + using OTableDescriptor_BASE::rBHelper; + + // OPropertyArrayUsageHelper + virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 _nId ) const override; + // OPropertySetHelper + virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper() override; + public: + OTable( OCollection* _pTables, + bool _bCase); + OTable( OCollection* _pTables, + bool _bCase, + const OUString& Name, + const OUString& Type, + const OUString& Description = OUString(), + const OUString& SchemaName = OUString(), + const OUString& CatalogName = OUString()); + + virtual ~OTable() override; + + DECLARE_SERVICE_INFO(); + //XInterface + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + //XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + + // ODescriptor + virtual void construct() override; + virtual void refreshColumns() override; + virtual void refreshKeys(); + virtual void refreshIndexes(); + // ::cppu::OComponentHelper + virtual void SAL_CALL disposing() override; + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + // XColumnsSupplier + virtual css::uno::Reference< css::container::XNameAccess > SAL_CALL getColumns( ) override; + // XKeysSupplier + virtual css::uno::Reference< css::container::XIndexAccess > SAL_CALL getKeys( ) override; + // XNamed + virtual OUString SAL_CALL getName() override; + virtual void SAL_CALL setName( const OUString& aName ) override; + // XDataDescriptorFactory + virtual css::uno::Reference< css::beans::XPropertySet > SAL_CALL createDataDescriptor() override; + // XIndexesSupplier + virtual css::uno::Reference< css::container::XNameAccess > SAL_CALL getIndexes( ) override; + // XRename + virtual void SAL_CALL rename( const OUString& newName ) override; + // XAlterTable + virtual void SAL_CALL alterColumnByName( const OUString& colName, const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + virtual void SAL_CALL alterColumnByIndex( sal_Int32 index, const css::uno::Reference< css::beans::XPropertySet >& descriptor ) override; + + // helper method + virtual css::uno::Reference< css::sdbc::XDatabaseMetaData> getMetaData() const; + }; + +} + +#endif // INCLUDED_CONNECTIVITY_SDBCX_VTABLE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sdbcx/VView.hxx b/include/connectivity/sdbcx/VView.hxx new file mode 100644 index 000000000..3a7714f95 --- /dev/null +++ b/include/connectivity/sdbcx/VView.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_SDBCX_VVIEW_HXX +#define INCLUDED_CONNECTIVITY_SDBCX_VVIEW_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::sdbc { class XDatabaseMetaData; } + +namespace connectivity::sdbcx + { + + typedef ::cppu::WeakImplHelper< css::lang::XServiceInfo, + css::container::XNamed> OView_BASE; + + + class OOO_DLLPUBLIC_DBTOOLS OView : + public ::comphelper::OMutexAndBroadcastHelper, + public OView_BASE, + public ::comphelper::OIdPropertyArrayUsageHelper, + public ODescriptor + { + protected: + OUString m_CatalogName; + OUString m_SchemaName; + OUString m_Command; + sal_Int32 m_CheckOption; + // need for the getName method + css::uno::Reference< css::sdbc::XDatabaseMetaData > m_xMetaData; + + // OPropertyArrayUsageHelper + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const override; + // OPropertySetHelper + virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper() override; + + public: + DECLARE_SERVICE_INFO(); + + OView(bool _bCase,const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _xMetaData); + OView( bool _bCase, + const OUString& _rName, + const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _xMetaData, + const OUString& _rCommand = OUString(), + const OUString& _rSchemaName = OUString(), + const OUString& _rCatalogName = OUString()); + virtual ~OView() override; + + // ODescriptor + virtual void construct() override; + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + //XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + // XNamed + virtual OUString SAL_CALL getName( ) override; + virtual void SAL_CALL setName( const OUString& ) override; + }; + +} + +#endif // INCLUDED_CONNECTIVITY_SDBCX_VVIEW_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sqlbison_exports.hxx b/include/connectivity/sqlbison_exports.hxx new file mode 100644 index 000000000..ba0dbd9c5 --- /dev/null +++ b/include/connectivity/sqlbison_exports.hxx @@ -0,0 +1,21 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +namespace connectivity { class OSQLParseNode; } +namespace connectivity { class OSQLParser; } + +OUString ConvertLikeToken(const ::connectivity::OSQLParseNode* pTokenNode, const ::connectivity::OSQLParseNode* pEscapeNode, bool bInternational); +int SQLyyparse(); +void setParser( ::connectivity::OSQLParser* ); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sqlerror.hxx b/include/connectivity/sqlerror.hxx new file mode 100644 index 000000000..252fe479e --- /dev/null +++ b/include/connectivity/sqlerror.hxx @@ -0,0 +1,239 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_SQLERROR_HXX +#define INCLUDED_CONNECTIVITY_SQLERROR_HXX + +#include +#include +#include +#include + +namespace connectivity +{ + + + //= ErrorCondition + + /** the type of error codes to be used in SQLExceptions + + @see css::sdbc::SQLException::ErrorCode + */ + typedef ::sal_Int32 ErrorCode; + + /** error condition values as defined in css::sdb::ErrorCondition + */ + typedef ::sal_Int32 ErrorCondition; + + + //= SQLError + + class SQLError_Impl; + + /** a class which provides helpers for working with SQLErrors + + In particular, this class provides vendor-specific error codes (where + the vendor is OpenOffice.org Base), which can be used in OOo's various + database drivers, and checked in application-level code, to properly + recognize highly specific error conditions. + + @see css::sdb::ErrorCondition + */ + class OOO_DLLPUBLIC_DBTOOLS SQLError + { + public: + SQLError(); + ~SQLError(); + + /** returns the message associated with a given error condition, after (optionally) replacing + a placeholder with a given string + + Some error messages need to contain references to runtime-dependent data (say, the + name of a concrete table in the database), which in the resource file's strings are + represented by a placeholder, namely $1$, $2, and so on. This method allows to + retrieve such an error message, and replace up to 3 placeholders with their concrete + values. + + In a non-product build, assertions will fire if the number of placeholders in the + message's resource string does not match the number of passed parameter values. + + As specified in the css::sdb::ErrorCondition type, + error messages thrown by core components of OpenOffice.org Base will contain + a standardized prefix "[OOoBase]" in every message. + + @see css::sdb::ErrorCondition + */ + OUString getErrorMessage( + const ErrorCondition _eCondition + ) const; + + /** returns the error code associated with a given error condition + + @see getErrorMessage + @see css::sdb::ErrorCondition + @see css::sdbc::SQLException::ErrorCode + */ + static ErrorCode + getErrorCode( const ErrorCondition _eCondition ); + + /** returns the prefix which is used for OpenOffice.org Base's error messages + + As specified in the css::sdb::ErrorCondition type, + error messages thrown by core components of OpenOffice.org Base will + contain a standardized prefix in every message. getBaseErrorMessagePrefix + returns this prefix, so clients of such error messages might decide to strip this + prefix before presenting the message to the user, or use it to determine + whether a concrete error has been raised by a OpenOffice.org core component. + */ + static const OUString& + getMessagePrefix(); + + + /** throws an SQLException describing the given error condition + + The thrown SQLException will contain the OOo-specific error code which derives + from the given error condition, and the error message associated with that condition. + + @param _eCondition + the ErrorCondition which hit you + + @param _rxContext + the context in which the error occurred. This will be filled in as + Exception::Context member. + + @param _rParamValue1 + a runtime-dependent value which should be filled into the error message + which is associated with _eCondition, replacing the first placeholder + in this message. + + @param _rParamValue2 + a runtime-dependent value which should be filled into the error message + which is associated with _eCondition, replacing the second placeholder + in this message. + + @param _rParamValue3 + a runtime-dependent value which should be filled into the error message + which is associated with _eCondition, replacing the third placeholder + in this message. + + @see getErrorMessage + @see getErrorCode + */ + void raiseException( + const ErrorCondition _eCondition, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const std::optional& _rParamValue1 = std::nullopt, + const std::optional& _rParamValue2 = std::nullopt, + const std::optional& _rParamValue3 = std::nullopt + ) const; + + /** throws an SQLException describing the given error condition + + The thrown SQLException will contain the OOo-specific error code which derives + from the given error condition, and the error message associated with that condition. + + Note: You should prefer the version of raiseException which takes + an additional Context parameter, since this allows clients of your + exception to examine where the error occurred. + + @param _eCondition + the ErrorCondition which hit you + + @see getErrorMessage + @see getErrorCode + */ + void raiseException( + const ErrorCondition _eCondition + ) const; + + /** raises a typed exception, that is, a UNO exception which is derived from + css::sdbc::SQLException + + @param _eCondition + the ErrorCondition which hit you + + @param _rxContext + the context in which the error occurred. This will be filled in as + Exception::Context member. + + @param _rExceptionType + the type of the exception to throw. This type must specify + an exception class derived from css::sdbc::SQLException. + + @throws ::std::bad_cast + if _rExceptionType does not specify an exception class derived from + css::sdbc::SQLException. + + @see getErrorMessage + @see getErrorCode + */ + void raiseTypedException( + const ErrorCondition _eCondition, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const css::uno::Type& _rExceptionType + ) const; + + /** retrieves an SQLException object which contains information about + the given error condition + + @param _eCondition + the ErrorCondition which hit you + + @param _rxContext + the context in which the error occurred. This will be filled in as + Exception::Context member. + + @param _rParamValue1 + a runtime-dependent value which should be filled into the error message + which is associated with _eCondition, replacing the first placeholder + in this message. + + @param _rParamValue2 + a runtime-dependent value which should be filled into the error message + which is associated with _eCondition, replacing the second placeholder + in this message. + + @param _rParamValue3 + a runtime-dependent value which should be filled into the error message + which is associated with _eCondition, replacing the third placeholder + in this message. + + @see getErrorMessage + @see getErrorCode + */ + css::sdbc::SQLException + getSQLException( + const ErrorCondition _eCondition, + const css::uno::Reference< css::uno::XInterface >& _rxContext, + const std::optional& _rParamValue1 = std::nullopt, + const std::optional& _rParamValue2 = std::nullopt, + const std::optional& _rParamValue3 = std::nullopt + ) const; + + private: + std::shared_ptr< SQLError_Impl > m_pImpl; + }; + + +} // namespace connectivity + + +#endif // INCLUDED_CONNECTIVITY_SQLERROR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sqliterator.hxx b/include/connectivity/sqliterator.hxx new file mode 100644 index 000000000..201b31294 --- /dev/null +++ b/include/connectivity/sqliterator.hxx @@ -0,0 +1,341 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_SQLITERATOR_HXX +#define INCLUDED_CONNECTIVITY_SQLITERATOR_HXX + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::beans { class XPropertySet; } + +namespace connectivity +{ + enum class TraversalParts + { + Parameters = 0x0001, + TableNames = 0x0002, + SelectColumns = 0x0006, // note that this includes TableNames. No SelectColumns without TableNames + + // Those are not implemented currently + // GroupColumns = 0x0008, + // OrderColumns = 0x0010, + // SelectColumns = 0x0020, + // CreateColumns = 0x0040, + + All = 0xFFFF + }; +} +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace connectivity +{ + + class OSQLParseNode; + class OSQLParser; + + typedef ::std::pair TNodePair; + + enum class OSQLStatementType { + Unknown, + Select, + Insert, + Update, + Delete, + OdbcCall, + CreateTable + }; + + struct OSQLParseTreeIteratorImpl; + + class OOO_DLLPUBLIC_DBTOOLS OSQLParseTreeIterator final + { + private: + std::optional m_xErrors; // contains the error while iterating through the statement + const OSQLParseNode* m_pParseTree; // current ParseTree + const OSQLParser& m_rParser; // if set used for general error messages from the context + OSQLStatementType m_eStatementType; + ::rtl::Reference m_aSelectColumns; // all columns from the Select clause + ::rtl::Reference m_aParameters; // all parameters + ::rtl::Reference m_aGroupColumns; // the group by columns + ::rtl::Reference m_aOrderColumns; // the order by columns + ::rtl::Reference m_aCreateColumns; // the columns for Create table clause + + ::std::unique_ptr< OSQLParseTreeIteratorImpl > m_pImpl; + + void traverseParameter(const OSQLParseNode* _pParseNode,const OSQLParseNode* _pColumnRef,const OUString& _aColumnName, OUString& _aTableRange, const OUString& _rColumnAlias); + // inserts a table into the map + void traverseOneTableName( OSQLTables& _rTables,const OSQLParseNode * pTableName, const OUString & rTableRange ); + void traverseSearchCondition(OSQLParseNode const * pSearchCondition); + void traverseOnePredicate( + OSQLParseNode const * pColumnRef, + OUString& aValue, + OSQLParseNode const * pParameter); + void traverseByColumnNames(const OSQLParseNode* pSelectNode, bool _bOrder); + void traverseParameters(const OSQLParseNode* pSelectNode); + + const OSQLParseNode* getTableNode( OSQLTables& _rTables, const OSQLParseNode* pTableRef, OUString& aTableRange ); + void getQualified_join( OSQLTables& _rTables, const OSQLParseNode *pTableRef, OUString& aTableRange ); + void getSelect_statement(OSQLTables& _rTables,const OSQLParseNode* pSelect); + // get all the column names of m_aSelectColumns and return in a vector sorted by a UStringMixLess that's constructed from + // isCaseSensitive() + std::vector getSelectColumnNames() const; + // rColumnNames is expected to be sorted as returned by getSelectColumnNames + OUString getUniqueColumnName(const std::vector& rColumnNames, const OUString & rColumnName) const; + + /** finds the column with a given name, belonging to a given table, in a given tables collection + @param _rTables + the tables collection to look in + @param rColumnName + the column name to look for + @param rTableRange + the table alias name; if empty, look in all tables + @return + the desired column object, or if no such column could be found + */ + static css::uno::Reference< css::beans::XPropertySet > findColumn( + const OSQLTables& _rTables, const OUString & rColumnName, OUString & rTableRange ); + + /** finds a column with a given name, belonging to a given table + @param rColumnName + the column name to look for + @param rTableRange + the table alias name; if empty, look in all tables + @param _bLookInSubTables + if and only if not only our direct tables, but also our sub tables (from sub selects) + should be searched + @return + */ + css::uno::Reference< css::beans::XPropertySet > findColumn( + const OUString & rColumnName, OUString & rTableRange, bool _bLookInSubTables ); + + /** finds a column with a given name among the select columns + @param rColumnName + the column name to look for + @return + */ + css::uno::Reference< css::beans::XPropertySet > findSelectColumn( + std::u16string_view rColumnName ); + + void setSelectColumnName(const OUString& rColumnName, const OUString& rColumnAlias, const OUString& rTableRange, bool bFkt = false, sal_Int32 _nType = css::sdbc::DataType::VARCHAR, bool bAggFkt = false); + void appendColumns(const OUString& _rTableAlias, const OSQLTable& _rTable); + // Other member variables that should be available in the "set" functions + // can be defined in the derived class. They can be initialized + // in its constructor and, after the "traverse" routines have been used, + // they can be queried using other functions. + + OSQLParseTreeIterator(const OSQLParseTreeIterator & rIter) = delete; + + public: + OSQLParseTreeIterator( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const css::uno::Reference< css::container::XNameAccess >& _rxTables, + const OSQLParser& _rParser ); + ~OSQLParseTreeIterator(); + + void dispose(); + bool isCaseSensitive() const; + // The parse tree to be analysed/traversed: + // If NULL is passed, the current parse tree will be deleted and the error status cleared. + void setParseTree(const OSQLParseNode * pNewParseTree); + const OSQLParseNode * getParseTree() const { return m_pParseTree; }; + + // subtrees in case of a select statement + const OSQLParseNode* getWhereTree() const; + const OSQLParseNode* getOrderTree() const; + const OSQLParseNode* getGroupByTree() const; + const OSQLParseNode* getHavingTree() const; + + const OSQLParseNode* getSimpleWhereTree() const; + const OSQLParseNode* getSimpleOrderTree() const; + const OSQLParseNode* getSimpleGroupByTree() const; + const OSQLParseNode* getSimpleHavingTree() const; + + /** returns the errors which occurred during parsing. + + The returned object contains a chain (via SQLException::NextException) of SQLExceptions. + */ + const css::sdbc::SQLException& getErrors() const { return *m_xErrors; } + bool hasErrors() const { return bool(m_xErrors); } + + // statement type (already set in setParseTree): + OSQLStatementType getStatementType() const { return m_eStatementType; } + + /** traverses the complete statement tree, and fills all our data with + the information obatined during traversal. + + Implemented by calling the single traverse* methods in the proper + order (depending on the statement type). + */ + void traverseAll(); + + // The TableRangeMap contains all tables associated with the range name found first. + const OSQLTables& getTables() const; + + const ::rtl::Reference& getSelectColumns() const { return m_aSelectColumns;} + const ::rtl::Reference& getGroupColumns() const { return m_aGroupColumns;} + const ::rtl::Reference& getOrderColumns() const { return m_aOrderColumns;} + const ::rtl::Reference& getParameters() const { return m_aParameters; } + + /** return the columname and the table range + @param _pColumnRef + The column ref parse node. + @param _rColumnName + The column name to be set. + @param _rTableRange + The table range to be set. + */ + void getColumnRange( const OSQLParseNode* _pColumnRef, + OUString &_rColumnName, + OUString& _rTableRange) const; + + /** retrieves a column's name, table range, and alias + + @param _pColumnRef + The column_ref parse node. + @param _out_rColumnName + The column name to be set. + @param _out_rTableRange + The table range to be set. + @param _out_rColumnAliasIfPresent + If the column specified by _pColumnRef is part of the select columns, and contains a column alias there, + this alias is returned here. + */ + void getColumnRange( const OSQLParseNode* _pColumnRef, + OUString& _out_rColumnName, + OUString& _out_rTableRange, + OUString& _out_rColumnAliasIfPresent + ) const; + + /** return the alias name of a column + @param _pDerivedColumn + The parse node where SQL_ISRULE(_pDerivedColumn,derived_column) must be true + @return + The alias name of the column or an empty string. + */ + static OUString getColumnAlias(const OSQLParseNode* _pDerivedColumn); + + /** return the columname and the table range + @param _pColumnRef + The column ref parse node. + @param _xMetaData + The database meta data. + @param _rColumnName + The column name to be set. + @param _rTableRange + The table range to be set. + */ + static void getColumnRange( const OSQLParseNode* _pColumnRef, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + OUString &_rColumnName, + OUString& _rTableRange); + + // return true when the tableNode is a rule like catalog_name, schema_name or table_name + static bool isTableNode(const OSQLParseNode* _pTableNode); + + // tries to find the correct type of the function + sal_Int32 getFunctionReturnType(const OSQLParseNode* _pNode ); + + // returns a lis of all joined columns + ::std::vector< TNodePair >& getJoinConditions() const; + + private: + + /** traverses the list of table names, and fills _rTables + */ + bool traverseTableNames( OSQLTables& _rTables ); + + /// traverses columns in a SELECT statement + bool traverseSelectColumnNames(const OSQLParseNode* pSelectNode); + /// traverses columns in a CREATE TABLE statement + void traverseCreateColumns(const OSQLParseNode* pSelectNode); + + bool traverseOrderByColumnNames(const OSQLParseNode* pSelectNode); + bool traverseGroupByColumnNames(const OSQLParseNode* pSelectNode); + + bool traverseSelectionCriteria(const OSQLParseNode* pSelectNode); + + /** constructs a new iterator, which inherits some of the settings from a parent iterator + */ + OSQLParseTreeIterator( + const OSQLParseTreeIterator& _rParentIterator, + const OSQLParser& _rParser, + const OSQLParseNode* pRoot ); + + /** creates a table object and inserts it into our tables collection + + only used when we're iterating through a CREATE TABLE statement + */ + OSQLTable impl_createTableObject( + const OUString& rTableName, const OUString& rCatalogName, const OUString& rSchemaName ); + + /** locates a record source (a table or query) with the given name + */ + OSQLTable impl_locateRecordSource( + const OUString& _rComposedName + ); + + /** implementation for both traverseAll and traverseSome + */ + void impl_traverse( TraversalParts _nIncludeMask ); + + /** retrieves the parameter columns of the given query + */ + void impl_getQueryParameterColumns( const OSQLTable& _rQuery ); + + void setOrderByColumnName(const OUString & rColumnName, OUString & rTableRange, bool bAscending); + void setGroupByColumnName(const OUString & rColumnName, OUString & rTableRange); + + /** appends an SQLException corresponding to the given error code to our error collection + + @param _eError + the code of the error which occurred + @param _pReplaceToken1 + if not , the first occurrence of '#' in the error message will be replaced + with the given token + @param _pReplaceToken2 + if not , and if _rReplaceToken1 is not , the second occurrence of '#' + in the error message will be replaced with _rReplaceToken2 + */ + void impl_appendError( IParseContext::ErrorCode _eError, + const OUString* _pReplaceToken1 = nullptr, const OUString* _pReplaceToken2 = nullptr ); + + /** appends an SQLException corresponding to the given error code to our error collection + */ + void impl_appendError( const css::sdbc::SQLException& _rError ); + + void impl_fillJoinConditions(const OSQLParseNode* i_pJoinCondition); + }; +} + +#endif // INCLUDED_CONNECTIVITY_SQLITERATOR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sqlnode.hxx b/include/connectivity/sqlnode.hxx new file mode 100644 index 000000000..3bd9327e1 --- /dev/null +++ b/include/connectivity/sqlnode.hxx @@ -0,0 +1,455 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_SQLNODE_HXX +#define INCLUDED_CONNECTIVITY_SQLNODE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::lang { struct Locale; } +namespace com::sun::star::sdbc { class SQLException; } +namespace com::sun::star::sdbc { class XDatabaseMetaData; } + +namespace com::sun::star +{ + namespace beans + { + class XPropertySet; + } + namespace util + { + class XNumberFormatter; + } + namespace container + { + class XNameAccess; + } +} + +#define ORDER_BY_CHILD_POS 5 +#define TABLE_EXPRESSION_CHILD_COUNT 9 + +namespace connectivity +{ + class OSQLParser; + class IParseContext; + + enum class SQLNodeType { Rule, ListRule, CommaListRule, + Keyword, Name, + String, IntNum, ApproxNum, + Equal, Less, Great, LessEq, GreatEq, NotEqual, + Punctuation, AccessDate, Concat}; + + typedef ::std::set< OUString > QueryNameSet; + + //= SQLParseNodeParameter + + struct SQLParseNodeParameter + { + const css::lang::Locale& rLocale; + ::dbtools::DatabaseMetaData aMetaData; + OSQLParser* pParser; + std::shared_ptr< QueryNameSet > pSubQueryHistory; + css::uno::Reference< css::util::XNumberFormatter > xFormatter; + css::uno::Reference< css::beans::XPropertySet > xField; + OUString sPredicateTableAlias; + css::uno::Reference< css::container::XNameAccess > xQueries; // see bParseToSDBCLevel + const IParseContext& m_rContext; + OUString sDecSep; + bool bQuote : 1; /// should we quote identifiers? + bool bInternational : 1; /// should we internationalize keywords and placeholders? + bool bPredicate : 1; /// are we going to parse a mere predicate? + bool bParseToSDBCLevel : 1; /// should we create an SDBC-level statement (e.g. with substituted sub queries)? + + SQLParseNodeParameter( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const css::uno::Reference< css::util::XNumberFormatter >& _xFormatter, + const css::uno::Reference< css::beans::XPropertySet >& _xField, + const OUString &_sPredicateTableAlias, + const css::lang::Locale& _rLocale, + const IParseContext* _pContext, + bool _bIntl, + bool _bQuote, + OUString _sDecSep, + bool _bPredicate, + bool _bParseToSDBC + ); + }; + + //= OSQLParseNode + + class OOO_DLLPUBLIC_DBTOOLS OSQLParseNode + { + friend class OSQLParser; + + std::vector< std::unique_ptr > + m_aChildren; + OSQLParseNode* m_pParent; // pParent for reverse linkage in the tree + OUString m_aNodeValue; // token name, or empty in case of rules, + // or OUString in case of + // OUString, INT, etc. + SQLNodeType m_eNodeType; // see above + sal_uInt32 m_nNodeID; // Rule ID (if IsRule()) + // or Token ID (if !IsRule()) + // Rule IDs and Token IDs can't + // be distinguished by their values, + // IsRule has to be used for that! + public: + enum Rule + { + UNKNOWN_RULE = 0, // ID indicating that a node is no rule with a matching Rule-enum value (see getKnownRuleID) + // we make sure it is 0 so that it is the default-constructor value of this enum + // and std::map::operator[](bar) default-inserts UNKNOWN_RULE rather than select_statement (!) + select_statement, + table_exp, + table_ref_commalist, + table_ref, + catalog_name, + schema_name, + table_name, + opt_column_commalist, + column_commalist, + column_ref_commalist, + column_ref, + opt_order_by_clause, + ordering_spec_commalist, + ordering_spec, + opt_asc_desc, + where_clause, + opt_where_clause, + search_condition, + comparison, + comparison_predicate, + between_predicate, + like_predicate, + opt_escape, + test_for_null, + scalar_exp_commalist, + scalar_exp, + parameter_ref, + parameter, + general_set_fct, + range_variable, + column, + delete_statement_positioned, + delete_statement_searched, + update_statement_positioned, + update_statement_searched, + assignment_commalist, + assignment, + values_or_query_spec, + insert_statement, + insert_atom_commalist, + insert_atom, + from_clause, + qualified_join, + cross_union, + select_sublist, + derived_column, + column_val, + set_fct_spec, + boolean_term, + boolean_primary, + num_value_exp, + join_type, + position_exp, + extract_exp, + length_exp, + char_value_fct, + odbc_call_spec, + in_predicate, + existence_test, + unique_test, + all_or_any_predicate, + named_columns_join, + join_condition, + joined_table, + boolean_factor, + sql_not, + manipulative_statement, + subquery, + value_exp_commalist, + odbc_fct_spec, + union_statement, + outer_join_type, + char_value_exp, + term, + value_exp_primary, + value_exp, + selection, + fold, + char_substring_fct, + factor, + base_table_def, + base_table_element_commalist, + data_type, + column_def, + table_node, + as_clause, + opt_as, + op_column_commalist, + table_primary_as_range_column, + datetime_primary, + concatenation, + char_factor, + bit_value_fct, + comparison_predicate_part_2, + parenthesized_boolean_value_expression, + character_string_type, + other_like_predicate_part_2, + between_predicate_part_2, + null_predicate_part_2, + cast_spec, + window_function, + rule_count // last value + }; + + // must be ascii encoding for the value + OSQLParseNode(const char* _pValueStr, + SQLNodeType _eNodeType, + sal_uInt32 _nNodeID = 0); + + OSQLParseNode(std::string_view _rValue, + SQLNodeType eNewNodeType, + sal_uInt32 nNewNodeID=0); + + OSQLParseNode(const OUString& _rValue, + SQLNodeType _eNodeType, + sal_uInt32 _nNodeID = 0); + + // copies the respective ParseNode + OSQLParseNode(const OSQLParseNode& rParseNode); + OSQLParseNode& operator=(const OSQLParseNode& rParseNode); + + bool operator==(OSQLParseNode const & rParseNode) const; + + // destructor destructs the tree recursively + virtual ~OSQLParseNode(); + + OSQLParseNode* getParent() const {return m_pParent;}; + + void setParent(OSQLParseNode* pParseNode) {m_pParent = pParseNode;}; + + size_t count() const {return m_aChildren.size();}; + inline OSQLParseNode* getChild(sal_uInt32 nPos) const; + + void append(OSQLParseNode* pNewSubTree); + void insert(sal_uInt32 nPos, OSQLParseNode* pNewSubTree); + + OSQLParseNode* replace(OSQLParseNode* pOldSubTree, OSQLParseNode* pNewSubTree); + + OSQLParseNode* removeAt(sal_uInt32 nPos); + + void replaceNodeValue(const OUString& rTableAlias,const OUString& rColumnName); + + /** parses the node to a string which can be passed to a driver's connection for execution + + Any particles of the parse tree which represent application-level features - such + as queries appearing in the FROM part - are substituted, so that the resulting statement can + be executed at an SDBC-level connection. + + @param _out_rString + is an output parameter taking the resulting SQL statement + + @param _rxConnection + the connection relative to which to parse. This must be an SDB-level connection (e.g. + support the XQueriesSupplier interface) for the method to be able to do all necessary + substitutions. + + @param _rParser + the SQLParser used to create the node. This is needed in case we need to parse + sub queries which are present in the SQL statement - those sub queries need to be parsed, + too, to check whether they contain nested sub queries. + + @param _pErrorHolder + takes the error which occurred while generating the statement, if any. Might be , + in this case the error is not reported back, and can only be recognized by examining the + return value. + + @return + if and only if the parsing was successful.
    + + Currently, there's only one condition how this method can fail: If it contains a nested + query which causes a cycle. E.g., consider a statement SELECT * from "foo", + where foo is a query defined as SELECT * FROM "bar", where + bar is defined as SELECT * FROM "foo". This statement obviously + cannot be parsed to an executable statement. + + If this method returns , you're encouraged to check and handle the error in + _pErrorHolder. + */ + bool parseNodeToExecutableStatement( OUString& _out_rString, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + OSQLParser& _rParser, + css::sdbc::SQLException* _pErrorHolder ) const; + + void parseNodeToStr(OUString& rString, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const IParseContext* pContext = nullptr, + bool _bIntl = false, + bool _bQuote= true) const; + + // quoted and internationalised + void parseNodeToPredicateStr(OUString& rString, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const css::uno::Reference< css::util::XNumberFormatter > & xFormatter, + const css::lang::Locale& rIntl, + OUString _sDec, + const IParseContext* pContext = nullptr ) const; + + void parseNodeToPredicateStr(OUString& rString, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const css::uno::Reference< css::util::XNumberFormatter > & xFormatter, + const css::uno::Reference< css::beans::XPropertySet > & _xField, + const OUString &_sTableAlias, + const css::lang::Locale& rIntl, + OUString strDec, + const IParseContext* pContext = nullptr ) const; + + OSQLParseNode* getByRule(OSQLParseNode::Rule eRule) const; + +#if OSL_DEBUG_LEVEL > 1 + // shows the ParseTree with tabs and linefeeds + void showParseTree( OUString& rString ) const; + void showParseTree( OUStringBuffer& _inout_rBuf, sal_uInt32 nLevel ) const; +#endif + + SQLNodeType getNodeType() const {return m_eNodeType;}; + + // RuleId returns the RuleID of the node's rule (only if IsRule()) + sal_uInt32 getRuleID() const {return m_nNodeID;} + + /** returns the ID of the rule represented by the node + If the node does not represent a rule, UNKNOWN_RULE is returned + */ + Rule getKnownRuleID() const; + + // returns the TokenId of the node's token (only if !isRule()) + sal_uInt32 getTokenID() const {return m_nNodeID;} + + // IsRule tests whether a node is a rule (NonTerminal) + // ATTENTION: rules can be leaves, for example empty lists + bool isRule() const + { return (m_eNodeType == SQLNodeType::Rule) || (m_eNodeType == SQLNodeType::ListRule) + || (m_eNodeType == SQLNodeType::CommaListRule);} + + // IsToken tests whether a Node is a Token (Terminal but not a rule) + bool isToken() const {return !isRule();} + + const OUString& getTokenValue() const {return m_aNodeValue;} + + bool isLeaf() const {return m_aChildren.empty();} + + // negate only a searchcondition, any other rule could cause a gpf + static void negateSearchCondition(OSQLParseNode*& pSearchCondition, bool bNegate=false); + + // normalize a logic form + // e.q. (a or b) and (c or d) <=> a and c or a and d or b and c or b and d + static void disjunctiveNormalForm(OSQLParseNode*& pSearchCondition); + + // Simplifies logic expressions + // a and a = a + // a or a = a + // a and ( a + b) = a + // a or a and b = a + static void absorptions(OSQLParseNode*& pSearchCondition); + + // erase unnecessary braces + static void eraseBraces(OSQLParseNode*& pSearchCondition); + + // makes the logic formula a little smaller + static void compress(OSQLParseNode*& pSearchCondition); + // return the catalog, schema and tablename from this node + // _pTableNode must be a rule of that above or a SQL_TOKEN_NAME + static bool getTableComponents(const OSQLParseNode* _pTableNode, + css::uno::Any &_rCatalog, + OUString &_rSchema, + OUString &_rTable, + const css::uno::Reference< css::sdbc::XDatabaseMetaData >& _xMetaData); + + // substitute all occurrences of :var or [name] into the dynamic parameter ? + // _pNode will be modified if parameters exists + static void substituteParameterNames(OSQLParseNode const * _pNode); + + /** return a table range when it exists. + */ + static OUString getTableRange(const OSQLParseNode* _pTableRef); + + protected: + // ParseNodeToStr concatenates all Tokens (leaves) of the ParseNodes. + void parseNodeToStr(OUString& rString, + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const css::uno::Reference< css::util::XNumberFormatter > & xFormatter, + const css::uno::Reference< css::beans::XPropertySet > & _xField, + const OUString &_sPredicateTableAlias, + const css::lang::Locale& rIntl, + const IParseContext* pContext, + bool _bIntl, + bool _bQuote, + OUString _sDecSep, + bool _bPredicate) const; + + private: + void impl_parseNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple=true ) const; + void impl_parseLikeNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple=true ) const; + void impl_parseTableRangeNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const; + + /** parses a table_name node into a SQL statement particle. + @return + if and only if parsing was successful, if default handling should + be applied. + */ + bool impl_parseTableNameNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const; + + bool addDateValue(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const; + static OUString convertDateTimeString(const SQLParseNodeParameter& rParam, const OUString& rString); + static OUString convertDateString(const SQLParseNodeParameter& rParam, std::u16string_view rString); + static OUString convertTimeString(const SQLParseNodeParameter& rParam, std::u16string_view rString); + void parseLeaf(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const; + }; + + inline OSQLParseNode* OSQLParseNode::getChild(sal_uInt32 nPos) const + { + return m_aChildren[nPos].get(); + } + + // utilities to query for a specific rule, token or punctuation + #define SQL_ISRULE(pParseNode, eRule) ((pParseNode)->isRule() && (pParseNode)->getRuleID() == OSQLParser::RuleID(OSQLParseNode::eRule)) + #define SQL_ISRULEOR2(pParseNode, e1, e2) ((pParseNode)->isRule() && ( \ + (pParseNode)->getRuleID() == OSQLParser::RuleID(OSQLParseNode::e1) || \ + (pParseNode)->getRuleID() == OSQLParser::RuleID(OSQLParseNode::e2))) + #define SQL_ISRULEOR3(pParseNode, e1, e2, e3) ((pParseNode)->isRule() && ( \ + (pParseNode)->getRuleID() == OSQLParser::RuleID(OSQLParseNode::e1) || \ + (pParseNode)->getRuleID() == OSQLParser::RuleID(OSQLParseNode::e2) || \ + (pParseNode)->getRuleID() == OSQLParser::RuleID(OSQLParseNode::e3))) + #define SQL_ISTOKEN(pParseNode, token) ((pParseNode)->isToken() && (pParseNode)->getTokenID() == SQL_TOKEN_##token) + #define SQL_ISTOKENOR2(pParseNode, tok0, tok1) ((pParseNode)->isToken() && ( (pParseNode)->getTokenID() == SQL_TOKEN_##tok0 || (pParseNode)->getTokenID() == SQL_TOKEN_##tok1 )) + #define SQL_ISTOKENOR3(pParseNode, tok0, tok1, tok2) ((pParseNode)->isToken() && ( (pParseNode)->getTokenID() == SQL_TOKEN_##tok0 || (pParseNode)->getTokenID() == SQL_TOKEN_##tok1 || (pParseNode)->getTokenID() == SQL_TOKEN_##tok2 )) + #define SQL_ISPUNCTUATION(pParseNode, aString) ((pParseNode)->getNodeType() == SQLNodeType::Punctuation && (pParseNode)->getTokenValue() == (aString)) +} + +#endif // INCLUDED_CONNECTIVITY_SQLNODE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sqlparse.hxx b/include/connectivity/sqlparse.hxx new file mode 100644 index 000000000..b92ff3b1c --- /dev/null +++ b/include/connectivity/sqlparse.hxx @@ -0,0 +1,230 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CONNECTIVITY_SQLPARSE_HXX +#define INCLUDED_CONNECTIVITY_SQLPARSE_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::i18n { class XCharacterClassification; } +namespace com::sun::star::i18n { class XLocaleData4; } + +namespace com::sun::star +{ + namespace beans + { + class XPropertySet; + } + namespace util + { + class XNumberFormatter; + } +} + +namespace connectivity +{ + class OSQLScanner; + + //= OParseContext + + class OParseContext final : public IParseContext + { + public: + OParseContext(); + + virtual ~OParseContext(); + // retrieves language specific error messages + virtual OUString getErrorMessage(ErrorCode _eCodes) const override; + + // retrieves language specific keyword strings (only ASCII allowed) + virtual OString getIntlKeywordAscii(InternationalKeyCode _eKey) const override; + + // finds out, if we have an international keyword (only ASCII allowed) + virtual InternationalKeyCode getIntlKeyCode(const OString& rToken) const override; + + // determines the default international setting + static const css::lang::Locale& getDefaultLocale(); + + /** gets a locale instance which should be used when parsing in the context specified by this instance +

    if this is not overridden by derived classes, it returns the static default locale.

    + */ + virtual css::lang::Locale getPreferredLocale( ) const override; + }; + + // OSQLParseNodesContainer + // garbage collection of nodes + + class OSQLParseNodesContainer + { + ::osl::Mutex m_aMutex; + ::std::vector< OSQLParseNode* > m_aNodes; + public: + OSQLParseNodesContainer(); + ~OSQLParseNodesContainer(); + + void push_back(OSQLParseNode* _pNode); + void erase(OSQLParseNode* _pNode); + void clear(); + void clearAndDelete(); + }; + + typedef salhelper::SingletonRef OSQLParseNodesGarbageCollector; + + //= OSQLParser + + struct OSQLParser_Data + { + css::lang::Locale aLocale; + ::connectivity::SQLError aErrors; + }; + + /** Parser for SQL92 + */ + class OOO_DLLPUBLIC_DBTOOLS OSQLParser + { + friend class OSQLParseNode; + friend class OSQLInternalNode; + friend struct SQLParseNodeParameter; + + private: + typedef ::std::map< sal_uInt32, OSQLParseNode::Rule > RuleIDMap; + // static parts for parsers + static sal_uInt32 s_nRuleIDs[OSQLParseNode::rule_count + 1]; + static RuleIDMap s_aReverseRuleIDLookup; + static OParseContext s_aDefaultContext; + + static OSQLScanner* s_pScanner; + static OSQLParseNodesGarbageCollector* s_pGarbageCollector; + static sal_Int32 s_nRefCount; + + // information on the current parse action + const IParseContext* m_pContext; + std::unique_ptr m_pParseTree; // result from parsing + ::std::unique_ptr< OSQLParser_Data > + m_pData; + OUString m_sFieldName; // current field name for a predicate + OUString m_sErrorMessage;// current error msg + + css::uno::Reference< css::beans::XPropertySet > + m_xField; // current field + css::uno::Reference< css::util::XNumberFormatter > + m_xFormatter; // current number formatter + sal_Int32 m_nFormatKey; // numberformat, which should be used + sal_Int32 m_nDateFormatKey; + css::uno::Reference< css::uno::XComponentContext > m_xContext; + css::uno::Reference< css::i18n::XCharacterClassification> m_xCharClass; + static css::uno::Reference< css::i18n::XLocaleData4> s_xLocaleData; + + // convert a string into double trim it to scale of _nscale and then transform it back to string + OUString stringToDouble(const OUString& _rValue,sal_Int16 _nScale); + OSQLParseNode* buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral); + bool extractDate(OSQLParseNode const * pLiteral,double& _rfValue); + void killThousandSeparator(OSQLParseNode* pLiteral); + OSQLParseNode* convertNode(sal_Int32 nType, OSQLParseNode* pLiteral); + // makes a string out of a number, pLiteral will be deleted + OSQLParseNode* buildNode_STR_NUM(OSQLParseNode*& pLiteral); + OSQLParseNode* buildNode_Date(const double& fValue, sal_Int32 nType); + + static ::osl::Mutex& getMutex(); + + public: + // if NULL, a default context will be used + // the context must live as long as the parser + OSQLParser(const css::uno::Reference< css::uno::XComponentContext >& rxContext, const IParseContext* _pContext = nullptr); + ~OSQLParser(); + + // Parsing an SQLStatement + std::unique_ptr parseTree(OUString& rErrorMessage, + const OUString& rStatement, + bool bInternational = false); + + // Check a Predicate + // set bUseRealName to false if you pass a xField that comes from where you got that field, + // as opposed from to from yourself. + std::unique_ptr predicateTree(OUString& rErrorMessage, const OUString& rStatement, + const css::uno::Reference< css::util::XNumberFormatter > & xFormatter, + const css::uno::Reference< css::beans::XPropertySet > & xField, + bool bUseRealName = true); + + // Access to the context + const IParseContext& getContext() const {return *m_pContext;} + + /// access to the SQLError instance owned by this parser + const SQLError& getErrorHelper() const; + + // TokenIDToStr: token name belonging to a token number. + static OString TokenIDToStr(sal_uInt32 nTokenID, const IParseContext* pContext = nullptr); + +#if OSL_DEBUG_LEVEL > 0 + // (empty string if not found) + static OUString RuleIDToStr(sal_uInt32 nRuleID); +#endif + + // StrToRuleID calculates the RuleID for an OUString (that is, css::sdbcx::Index in yytname) + // (0 if not found). The search for an ID based on a String is + // extremely inefficient (sequential search for OUString)! + static sal_uInt32 StrToRuleID(const OString & rValue); + + static OSQLParseNode::Rule RuleIDToRule( sal_uInt32 _nRule ); + + // RuleId with enum, far more efficient + static sal_uInt32 RuleID(OSQLParseNode::Rule eRule); + // compares the _sFunctionName with all known function names and return the DataType of the return value + static sal_Int32 getFunctionReturnType(std::u16string_view _sFunctionName, const IParseContext* pContext); + + // returns the type for a parameter in a given function name + static sal_Int32 getFunctionParameterType(sal_uInt32 _nTokenId,sal_uInt32 _nPos); + + void error(const char *fmt); + static int SQLlex(); +#ifdef YYBISON + void setParseTree(OSQLParseNode * pNewParseTree); + + // Is the parse in a special mode? + // Predicate check is used to check a condition for a field + bool inPredicateCheck() const {return m_xField.is();} + const OUString& getFieldName() const {return m_sFieldName;} + + static void reduceLiteral(OSQLParseNode*& pLiteral, bool bAppendBlank); + // does not change the pLiteral argument + sal_Int16 buildNode(OSQLParseNode*& pAppend,OSQLParseNode* pCompare,OSQLParseNode* pLiteral,OSQLParseNode* pLiteral2); + + sal_Int16 buildComparisonRule(OSQLParseNode*& pAppend,OSQLParseNode* pLiteral); + // pCompre will be deleted if it is not used + sal_Int16 buildPredicateRule(OSQLParseNode*& pAppend,OSQLParseNode* const pLiteral,OSQLParseNode* pCompare,OSQLParseNode* pLiteral2 = nullptr); + + sal_Int16 buildLikeRule(OSQLParseNode* pAppend, OSQLParseNode*& pLiteral, const OSQLParseNode* pEscape); + sal_Int16 buildStringNodes(OSQLParseNode*& pLiteral); +#endif + }; +} + +#endif // INCLUDED_CONNECTIVITY_SQLPARSE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/sqlscan.hxx b/include/connectivity/sqlscan.hxx new file mode 100644 index 000000000..fe463f506 --- /dev/null +++ b/include/connectivity/sqlscan.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +namespace connectivity +{ + + //= OSQLScanner + + /** Scanner for SQL92 + */ + class OSQLScanner + { + const IParseContext* m_pContext; // context for parse, knows all international stuff + OString m_sStatement; // statement to parse + OUString m_sErrorMessage; + + sal_Int32 m_nCurrentPos; // next position to read from the statement + bool m_bInternational; // do we have a statement which may uses + sal_Int32 m_nRule; // rule to be set + + public: + OSQLScanner(); + ~OSQLScanner(); + + sal_Int32 SQLyygetc(); + void SQLyyerror(char const *fmt); + IParseContext::InternationalKeyCode getInternationalTokenID(const char* sToken) const; + + // setting the new information before scanning + void prepareScan(const OUString & rNewStatement, const IParseContext* pContext, bool bInternational); + const OUString& getErrorMessage() const {return m_sErrorMessage;} + const OString& getStatement() const { return m_sStatement; } + + static sal_Int32 SQLlex(); + // set this as scanner for flex + void setScanner(bool _bNull=false); + // rules settings + void SetRule(sal_Int32 nRule) {m_nRule = nRule;} + static sal_Int32 GetGERRule(); + static sal_Int32 GetENGRule(); + static sal_Int32 GetSQLRule(); + static sal_Int32 GetDATERule(); + static sal_Int32 GetSTRINGRule(); + sal_Int32 GetCurrentPos() const { return m_nCurrentPos; } + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/standardsqlstate.hxx b/include/connectivity/standardsqlstate.hxx new file mode 100644 index 000000000..2569d3a02 --- /dev/null +++ b/include/connectivity/standardsqlstate.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_STANDARDSQLSTATE_HXX +#define INCLUDED_CONNECTIVITY_STANDARDSQLSTATE_HXX + +#include + +namespace dbtools +{ + + + /** standard SQLStates to be used with an SQLException + + Extend this list whenever you need a new state ... + + @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcodbc_error_codes.asp + */ + enum class StandardSQLState + { + INVALID_DESCRIPTOR_INDEX, // 07009 + INVALID_CURSOR_STATE, // 24000 + COLUMN_NOT_FOUND, // 42S22 + GENERAL_ERROR, // HY000 + INVALID_SQL_DATA_TYPE, // HY004 + FUNCTION_SEQUENCE_ERROR, // HY010 + INVALID_CURSOR_POSITION, // HY109 + FEATURE_NOT_IMPLEMENTED, // HYC00 + FUNCTION_NOT_SUPPORTED, // IM001 + CONNECTION_DOES_NOT_EXIST, // 08003 + + ERROR_UNSPECIFIED = SAL_MAX_ENUM // special value indicating that an SQLState is not to be specified + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_STANDARDSQLSTATE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/statementcomposer.hxx b/include/connectivity/statementcomposer.hxx new file mode 100644 index 000000000..88fa61f55 --- /dev/null +++ b/include/connectivity/statementcomposer.hxx @@ -0,0 +1,105 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_STATEMENTCOMPOSER_HXX +#define INCLUDED_CONNECTIVITY_STATEMENTCOMPOSER_HXX + +#include + +#include +#include + +namespace com::sun::star::sdbc { class XConnection; } +namespace com::sun::star::sdb { class XSingleSelectQueryComposer; } +namespace com::sun::star::uno { template class Reference; } + + +namespace dbtools +{ + + + //= StatementComposer + + struct StatementComposer_Data; + /** a class which is able to compose queries (SELECT statements) from a command and a command type + */ + class OOO_DLLPUBLIC_DBTOOLS StatementComposer + { + ::std::unique_ptr< StatementComposer_Data > m_pData; + + public: + /** constructs an instance + + @param _rxConnection + the connection to work with. Must not be . + */ + StatementComposer( + const css::uno::Reference< css::sdbc::XConnection >& _rxConnection, + const OUString& _rCommand, + const sal_Int32 _nCommandType, + const bool _bEscapeProcessing + ); + + ~StatementComposer(); + + /** controls whether or not the instance disposes its XSingleSelectQueryComposer upon + destruction + + Unless you explicitly call this method with the parameter being , + the XSingleSelectQueryComposer will be disposed when the StatementComposer + instance is destroyed. + */ + void setDisposeComposer( bool _bDoDispose ); + + void setFilter( const OUString& _rFilter ); + void setHavingClause( const OUString& _rHavingClause ); + void setOrder( const OUString& _rOrder ); + + /** returns the composer which has been fed with the current settings + + @throws css::sdbc::SQLException + if such an exception occurs while creating the composer + */ + css::uno::Reference< css::sdb::XSingleSelectQueryComposer > const & + getComposer(); + + /** returns the composer statement + + Effectively, this is equivalent to calling getComposer, and asking the composer + for its Query attribute. + + @throws css::sdbc::SQLException + if such an exception occurs while creating the composer + */ + OUString + getQuery(); + + private: + StatementComposer(const StatementComposer&) = delete; + StatementComposer& operator=(const StatementComposer&) = delete; + StatementComposer() = delete; + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_STATEMENTCOMPOSER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/connectivity/warningscontainer.hxx b/include/connectivity/warningscontainer.hxx new file mode 100644 index 000000000..7d017057b --- /dev/null +++ b/include/connectivity/warningscontainer.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CONNECTIVITY_WARNINGSCONTAINER_HXX +#define INCLUDED_CONNECTIVITY_WARNINGSCONTAINER_HXX + +#include + +#include + +namespace com::sun::star::sdbc { class SQLException; } +namespace com::sun::star::sdbc { class SQLWarning; } +namespace com::sun::star::sdbc { class XWarningsSupplier; } +namespace com::sun::star::sdb { class SQLContext; } +namespace com::sun::star::uno { class XInterface; } + +namespace dbtools +{ + + /** helper class for implementing XWarningsSupplier, which mixes own warnings with + warnings obtained from an external instance + */ + class OOO_DLLPUBLIC_DBTOOLS WarningsContainer + { + private: + css::uno::Reference< css::sdbc::XWarningsSupplier > m_xExternalWarnings; + css::uno::Any m_aOwnWarnings; + + public: + WarningsContainer() {} + WarningsContainer( const css::uno::Reference< css::sdbc::XWarningsSupplier >& _rxExternalWarnings ) + :m_xExternalWarnings( _rxExternalWarnings ) {} + + void setExternalWarnings( const css::uno::Reference< css::sdbc::XWarningsSupplier >& _rxExternalWarnings ) + { + m_xExternalWarnings = _rxExternalWarnings; + } + + // convenience + /** appends an SQLWarning instance to the chain + @param _rWarning + the warning message + @param _pAsciiSQLState + the SQLState of the warning + @param _rxContext + the context of the warning + */ + void appendWarning( + const OUString& _rWarning, + const char* _pAsciiSQLState, + const css::uno::Reference< css::uno::XInterface >& _rxContext ); + + void appendWarning(const css::sdbc::SQLException& _rWarning); + void appendWarning(const css::sdbc::SQLWarning& _rWarning); + void appendWarning(const css::sdb::SQLContext& _rContext); + + // XWarningsSupplier equivalents + css::uno::Any getWarnings( ) const; + void clearWarnings( ); + }; + + +} // namespace dbtools + + +#endif // INCLUDED_CONNECTIVITY_WARNINGSCONTAINER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/basegfxfactory.hxx b/include/cppcanvas/basegfxfactory.hxx new file mode 100644 index 000000000..611523066 --- /dev/null +++ b/include/cppcanvas/basegfxfactory.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_BASEGFXFACTORY_HXX +#define INCLUDED_CPPCANVAS_BASEGFXFACTORY_HXX + +#include +#include +#include +#include + +#include + +namespace basegfx +{ + class B2DPolygon; +} + + +/* Definition of BaseGfxFactory class */ + +namespace cppcanvas +{ + /** The BaseGfxFactory creates Canvas objects for various basegfx + primitives, such as polygons and bitmaps (not yet + implemented). + + Please note that the objects created for a specific Canvas can + only be drawn on exactly that canvas. You have to regenerate + them for different canvases. + */ + class CPPCANVAS_DLLPUBLIC BaseGfxFactory + { + public: + /** Create a polygon from a ::basegfx::B2DPolygon + + The created polygon initially has the same size in user + coordinate space as the source polygon + */ + static PolyPolygonSharedPtr createPolyPolygon( const CanvasSharedPtr&, const ::basegfx::B2DPolygon& rPoly ); + + /** Create an uninitialized bitmap with the given size + */ + static BitmapSharedPtr createBitmap( const CanvasSharedPtr&, const ::basegfx::B2ISize& rSize ); + + /** Create an uninitialized alpha bitmap with the given size + */ + static BitmapSharedPtr createAlphaBitmap( const CanvasSharedPtr&, const ::basegfx::B2ISize& rSize ); + + private: + BaseGfxFactory() = delete; + BaseGfxFactory(const BaseGfxFactory&) = delete; + BaseGfxFactory& operator=( const BaseGfxFactory& ) = delete; + }; + +} + +#endif // INCLUDED_CPPCANVAS_BASEGFXFACTORY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/bitmap.hxx b/include/cppcanvas/bitmap.hxx new file mode 100644 index 000000000..1b163b82d --- /dev/null +++ b/include/cppcanvas/bitmap.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_BITMAP_HXX +#define INCLUDED_CPPCANVAS_BITMAP_HXX + +#include +#include +#include +#include + +namespace com::sun::star::rendering +{ + class XBitmap; +} + + +/* Definition of Bitmap interface */ + +namespace cppcanvas +{ + + /** This interface defines a Bitmap canvas object + + Consider this object part of the view, and not of the model + data, as this bitmap can only be painted on its parent canvas + */ + class Bitmap : public virtual CanvasGraphic + { + public: + /** Render to parent canvas, with global alpha. + + This method renders the content to the parent canvas, + i.e. the canvas this object was constructed for. + + @param nAlphaModulation + Global alpha value, with which each pixel alpha value gets + multiplied. For a normal, opaque bitmap, this will make + the bitmap appear transparent with the given alpha value + (value must be in the range [0,1]). + */ + virtual void drawAlphaModulated( double nAlphaModulation ) const = 0; + + virtual BitmapCanvasSharedPtr getBitmapCanvas() const = 0; + + virtual css::uno::Reference< css::rendering::XBitmap > getUNOBitmap() const = 0; + }; + + typedef std::shared_ptr< ::cppcanvas::Bitmap > BitmapSharedPtr; +} + +#endif // INCLUDED_CPPCANVAS_BITMAP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/bitmapcanvas.hxx b/include/cppcanvas/bitmapcanvas.hxx new file mode 100644 index 000000000..9c3e7f843 --- /dev/null +++ b/include/cppcanvas/bitmapcanvas.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_BITMAPCANVAS_HXX +#define INCLUDED_CPPCANVAS_BITMAPCANVAS_HXX + +#include +#include +#include + + +/* Definition of BitmapCanvas */ + +namespace cppcanvas +{ + class BitmapCanvas; + + // forward declaration, since cloneBitmapCanvas() also references BitmapCanvas + typedef std::shared_ptr< BitmapCanvas > BitmapCanvasSharedPtr; + + /** BitmapCanvas interface + */ + class BitmapCanvas : public virtual Canvas + { + public: + virtual ::basegfx::B2ISize getSize() const = 0; + }; + +} + +#endif // INCLUDED_CPPCANVAS_BITMAPCANVAS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/canvas.hxx b/include/cppcanvas/canvas.hxx new file mode 100644 index 000000000..97562ede2 --- /dev/null +++ b/include/cppcanvas/canvas.hxx @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_CANVAS_HXX +#define INCLUDED_CPPCANVAS_CANVAS_HXX + +#include +#include + +namespace basegfx +{ + class B2DHomMatrix; + class B2DPolyPolygon; +} + +namespace com::sun::star::rendering +{ + class XCanvas; + struct ViewState; +} + + +/* Definition of BitmapCanvas */ + +namespace cppcanvas +{ + class PolyPolygon; + class Canvas; + + // forward declaration, since tools::PolyPolygon also references Canvas + typedef std::shared_ptr< PolyPolygon > PolyPolygonSharedPtr; + + // forward declaration, since cloneCanvas() also references Canvas + typedef std::shared_ptr< Canvas > CanvasSharedPtr; + + /** Canvas interface + */ + class Canvas + { + public: + /** Extra pixel used when canvas anti-aliases. + + Enlarge the bounding box of drawing primitives by this + amount in both dimensions, and on both sides of the + bounds, to account for extra pixel touched outside the + actual primitive bounding box, when the canvas + performs anti-aliasing. + */ + static constexpr auto ANTIALIASING_EXTRA_SIZE=2; + + Canvas() = default; + Canvas(Canvas const &) = default; + Canvas(Canvas &&) = default; + Canvas & operator =(Canvas const &) = default; +#if !(defined __GNUC__ && !defined __clang__ && __GNUC__ == 8) // bogus -Werror=virtual-move-assign + Canvas & operator =(Canvas &&) = default; +#endif + + virtual ~Canvas() {} + + virtual void setTransformation( const ::basegfx::B2DHomMatrix& rMatrix ) = 0; + virtual ::basegfx::B2DHomMatrix getTransformation() const = 0; + + virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0; + virtual void setClip() = 0; + + /** Get current clip + + @return NULL, if no clip is set, otherwise the current clip poly-polygon + */ + virtual ::basegfx::B2DPolyPolygon const* getClip() const = 0; + + virtual CanvasSharedPtr clone() const = 0; + virtual void clear() const = 0; + + // this should be considered private. if RTTI gets enabled + // someday, remove that to a separate interface + virtual css::uno::Reference< + css::rendering::XCanvas > getUNOCanvas() const = 0; + virtual css::rendering::ViewState getViewState() const = 0; + }; + +} + +#endif // INCLUDED_CPPCANVAS_CANVAS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/canvasgraphic.hxx b/include/cppcanvas/canvasgraphic.hxx new file mode 100644 index 000000000..ebee831f0 --- /dev/null +++ b/include/cppcanvas/canvasgraphic.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_CANVASGRAPHIC_HXX +#define INCLUDED_CPPCANVAS_CANVASGRAPHIC_HXX + +#include +#include + +namespace basegfx +{ + class B2DHomMatrix; + class B2DPolyPolygon; +} + + +/* Definition of CanvasGraphic interface */ + +namespace cppcanvas +{ + // forward declaration, since tools::PolyPolygon also derives from CanvasGraphic + typedef std::shared_ptr< class PolyPolygon > PolyPolygonSharedPtr; + + + /** This interface defines basic properties of + objects that can be painted on a Canvas + */ + class CanvasGraphic + { + public: + + virtual ~CanvasGraphic() {} + + /** Set object transformation matrix + */ + virtual void setTransformation( const ::basegfx::B2DHomMatrix& rMatrix ) = 0; + + /** Set object clipping polygon + */ + virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0; + /** Clear object clipping polygon + */ + virtual void setClip() = 0; + + /** Set object composite mode + * @see css::rendering::CompositeOperation + */ + virtual void setCompositeOp( sal_Int8 aOp ) = 0; + + /** Render to parent canvas + + This method renders the content to the parent canvas, + i.e. the canvas this object was constructed for. + + @return whether the rendering finished successfully. + */ + virtual bool draw() const = 0; + + }; +} + +#endif // INCLUDED_CPPCANVAS_CANVASGRAPHIC_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/color.hxx b/include/cppcanvas/color.hxx new file mode 100644 index 000000000..500e5953e --- /dev/null +++ b/include/cppcanvas/color.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_COLOR_HXX +#define INCLUDED_CPPCANVAS_COLOR_HXX + +#include + +/* Definition of Color class */ + +namespace cppcanvas +{ + /** Color in the sRGB color space, plus alpha channel + + The four bytes of the sal_uInt32 are allocated as follows + to the color channels and alpha: 0xRRGGBBAA. + */ + typedef sal_uInt32 IntSRGBA; + + inline sal_uInt8 getRed( IntSRGBA nCol ) + { + return static_cast( (nCol&0xFF000000U) >> 24U ); + } + + inline sal_uInt8 getGreen( IntSRGBA nCol ) + { + return static_cast( (nCol&0x00FF0000U) >> 16U ); + } + + inline sal_uInt8 getBlue( IntSRGBA nCol ) + { + return static_cast( (nCol&0x0000FF00U) >> 8U ); + } + + inline sal_uInt8 getAlpha( IntSRGBA nCol ) + { + return static_cast( nCol&0x000000FFU ); + } + + inline IntSRGBA makeColor( sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue, sal_uInt8 nAlpha ) + { + 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 // INCLUDED_CPPCANVAS_COLOR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/cppcanvasdllapi.h b/include/cppcanvas/cppcanvasdllapi.h new file mode 100644 index 000000000..90b0ba893 --- /dev/null +++ b/include/cppcanvas/cppcanvasdllapi.h @@ -0,0 +1,31 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_CPPCANVASDLLAPI_H +#define INCLUDED_CPPCANVAS_CPPCANVASDLLAPI_H + +#if defined CPPCANVAS_DLLIMPLEMENTATION + +#define CPPCANVAS_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define CPPCANVAS_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define CPPCANVAS_DLLPRIVATE SAL_DLLPRIVATE + +#endif diff --git a/include/cppcanvas/customsprite.hxx b/include/cppcanvas/customsprite.hxx new file mode 100644 index 000000000..abbd0c00b --- /dev/null +++ b/include/cppcanvas/customsprite.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_CUSTOMSPRITE_HXX +#define INCLUDED_CPPCANVAS_CUSTOMSPRITE_HXX + +#include +#include +#include + +/* Definition of CustomSprite class */ + +namespace cppcanvas +{ + + class CustomSprite : public virtual Sprite + { + public: + + virtual CanvasSharedPtr getContentCanvas() const = 0; + }; + + typedef std::shared_ptr< ::cppcanvas::CustomSprite > CustomSpriteSharedPtr; +} + +#endif // INCLUDED_CPPCANVAS_CUSTOMSPRITE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/polypolygon.hxx b/include/cppcanvas/polypolygon.hxx new file mode 100644 index 000000000..917ef4daf --- /dev/null +++ b/include/cppcanvas/polypolygon.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_POLYPOLYGON_HXX +#define INCLUDED_CPPCANVAS_POLYPOLYGON_HXX + +#include +#include +#include +#include + +namespace com::sun::star::rendering +{ + class XPolyPolygon2D; +} + + +/* Definition of tools::PolyPolygon interface */ + +namespace cppcanvas +{ + + /** This interface defines a tools::PolyPolygon canvas object + + Consider this object part of the view, and not of the model + data. Although the given polygon is typically copied and held + internally (to facilitate migration to incompatible canvases), + ::basegfx::B2DPolygon et al. are ref-counted copy-on-write + classes, i.e. memory shouldn't be wasted. On the other hand, + the API polygon created internally _does_ necessarily + duplicate the data held, but can be easily flushed away via + flush(). + */ + class PolyPolygon : public virtual CanvasGraphic + { + public: + + /** Set polygon fill color + */ + virtual void setRGBAFillColor( IntSRGBA ) = 0; + /** Set polygon line color + */ + virtual void setRGBALineColor( IntSRGBA ) = 0; + /** Get polygon line color + */ + virtual IntSRGBA getRGBALineColor() const = 0; + + virtual void setStrokeWidth( const double& rStrokeWidth ) = 0; + virtual double getStrokeWidth() const = 0; + + virtual css::uno::Reference< + css::rendering::XPolyPolygon2D > getUNOPolyPolygon() const = 0; + }; + + typedef std::shared_ptr< ::cppcanvas::PolyPolygon > PolyPolygonSharedPtr; +} + +#endif // INCLUDED_CPPCANVAS_POLYPOLYGON_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/renderer.hxx b/include/cppcanvas/renderer.hxx new file mode 100644 index 000000000..d71be2f09 --- /dev/null +++ b/include/cppcanvas/renderer.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_RENDERER_HXX +#define INCLUDED_CPPCANVAS_RENDERER_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace basegfx +{ + class B2DRange; +} + +/* Definition of Renderer interface */ + +namespace cppcanvas +{ + + class Renderer : public virtual CanvasGraphic + { + public: + /** Render subset of metafile to given canvas + + This method renders the given subset of the content to the + associated canvas. + + @param nStartIndex + The index of the first action to be rendered (the indices + correspond roughly to the action indices of the + originating GDIMetaFile. Note, although, that certain + actions, e.g. text, accounts for more than one index: a + text produces as many addressable indices as it has + characters). + + @param nEndIndex + The index of the first action _not_ painted anymore, + i.e. the action after the last action rendered (the + indices correspond roughly to the action indices of the + originating GDIMetaFile. Note, although, that certain + actions, e.g. text, accounts for more than one index: a + text produces as many addressable indices as it has + characters). + + @return whether the rendering finished successfully. + */ + virtual bool drawSubset( sal_Int32 nStartIndex, + sal_Int32 nEndIndex ) const = 0; + + /** Query bounding box of metafile subset + + This method queries the actual bounding box of the given + subset, when rendered on the associated canvas. + + @param nStartIndex + The index of the first action to be rendered (the indices + correspond roughly to the action indices of the + originating GDIMetaFile. Note, although, that certain + actions, e.g. text, accounts for more than one index: a + text produces as many addressable indices as it has + characters). + + @param nEndIndex + The index of the first action _not_ painted anymore, + i.e. the action after the last action rendered (the + indices correspond roughly to the action indices of the + originating GDIMetaFile. Note, although, that certain + actions, e.g. text, accounts for more than one index: a + text produces as many addressable indices as it has + characters). + + @return the bounding box of the specified subset + */ + virtual ::basegfx::B2DRange getSubsetArea( sal_Int32 nStartIndex, + sal_Int32 nEndIndex ) const = 0; + + /** Parameters for the Renderer + */ + struct Parameters + { + /// Optionally forces the fill color attribute for all actions + ::std::optional< IntSRGBA > maFillColor; + + /// Optionally forces the line color attribute for all actions + ::std::optional< IntSRGBA > maLineColor; + + /// Optionally forces the text color attribute for all actions + ::std::optional< IntSRGBA > maTextColor; + + /// Optionally forces the given fontname for all text actions + ::std::optional< OUString > maFontName; + + /** Optionally transforms all text output actions with the + given matrix (in addition to the overall canvas + transformation). + + Note that the matrix given here is applied to the unit + rect coordinate system, i.e. the metafile is assumed + to be contained in the unit rect. + */ + ::std::optional< ::basegfx::B2DHomMatrix > maTextTransformation; + + /// Optionally forces the given font weight for all text actions + ::std::optional< sal_Int8 > maFontWeight; + + /// Optionally forces the given font letter form (italics etc.) for all text actions + ::std::optional< sal_Int8 > maFontLetterForm; + + /// Optionally forces underlining for all text actions + ::std::optional< bool > maFontUnderline; + }; + }; + + typedef std::shared_ptr< ::cppcanvas::Renderer > RendererSharedPtr; +} + +#endif // INCLUDED_CPPCANVAS_RENDERER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/sprite.hxx b/include/cppcanvas/sprite.hxx new file mode 100644 index 000000000..3321eb6a0 --- /dev/null +++ b/include/cppcanvas/sprite.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_SPRITE_HXX +#define INCLUDED_CPPCANVAS_SPRITE_HXX + +namespace basegfx +{ + class B2DHomMatrix; + class B2DPolyPolygon; + class B2DPoint; +} + + +/* Definition of Sprite class */ + +namespace cppcanvas +{ + + class Sprite + { + public: + virtual ~Sprite() {} + + virtual void setAlpha( const double& rAlpha ) = 0; + + /** Set the sprite position on screen + + This method differs from the XSprite::move() insofar, as + no viewstate/renderstate transformations are applied to + the specified position. The given position is interpreted + in device coordinates (i.e. screen pixel) + */ + virtual void movePixel( const ::basegfx::B2DPoint& rNewPos ) = 0; + + /** Set the sprite position on screen + + This method sets the sprite position in the view + coordinate system of the parent canvas + */ + virtual void move( const ::basegfx::B2DPoint& rNewPos ) = 0; + + virtual void transform( const ::basegfx::B2DHomMatrix& rMatrix ) = 0; + + /** Set output clipping + + This method differs from the XSprite::clip() insofar, as + no viewstate/renderstate transformations are applied to + the specified clip polygon. The given polygon is + interpreted in device coordinates (i.e. screen pixel) + */ + virtual void setClipPixel( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0; + + /** Set output clipping + + This method applies the clip poly-polygon interpreted in + the view coordinate system of the parent canvas. + */ + virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0; + + virtual void setClip() = 0; + + virtual void show() = 0; + virtual void hide() = 0; + + /** Change the sprite priority + + @param fPriority + New sprite priority. The higher the priority, the further + towards the viewer the sprite appears. That is, sprites + with higher priority appear before ones with lower + priority. + */ + virtual void setPriority( double fPriority ) = 0; + }; +} + +#endif // INCLUDED_CPPCANVAS_SPRITE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/spritecanvas.hxx b/include/cppcanvas/spritecanvas.hxx new file mode 100644 index 000000000..c4d100dbe --- /dev/null +++ b/include/cppcanvas/spritecanvas.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_SPRITECANVAS_HXX +#define INCLUDED_CPPCANVAS_SPRITECANVAS_HXX + +#include +#include +#include +#include + +namespace com::sun::star::rendering +{ + class XSpriteCanvas; +} + + +/* Definition of SpriteCanvas */ + +namespace cppcanvas +{ + class SpriteCanvas; + + // forward declaration, since cloneSpriteCanvas() also references SpriteCanvas + typedef std::shared_ptr< ::cppcanvas::SpriteCanvas > SpriteCanvasSharedPtr; + + /** SpriteCanvas interface + */ + class SpriteCanvas : public virtual Canvas + { + SpriteCanvas(const SpriteCanvas&) = delete; + SpriteCanvas& operator=( const SpriteCanvas& ) = delete; + public: + SpriteCanvas() {} + virtual bool updateScreen( bool bUpdateAll ) const = 0; + + virtual CustomSpriteSharedPtr createCustomSprite( const ::basegfx::B2DSize& ) const = 0; + + virtual css::uno::Reference< + css::rendering::XSpriteCanvas > getUNOSpriteCanvas() const = 0; + }; + +} + +#endif // INCLUDED_CPPCANVAS_SPRITECANVAS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppcanvas/vclfactory.hxx b/include/cppcanvas/vclfactory.hxx new file mode 100644 index 000000000..73867626d --- /dev/null +++ b/include/cppcanvas/vclfactory.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPCANVAS_VCLFACTORY_HXX +#define INCLUDED_CPPCANVAS_VCLFACTORY_HXX + +#include +#include +#include +#include +#include + +#include + +namespace vcl { class Window; } +class BitmapEx; + +class GDIMetaFile; + +namespace com::sun::star::rendering +{ + class XCanvas; + class XBitmapCanvas; + class XSpriteCanvas; +} + +/* Definition of VCLFactory class */ + +namespace cppcanvas +{ + /** The VCLFactory creates Canvas objects for various VCL + OutputDevice primitives, such as windows, polygons, bitmaps + and metafiles. + + Please note that the objects created for a specific Canvas can + only be drawn on exactly that canvas. You have to regenerate + them for different canvases. + */ + class CPPCANVAS_DLLPUBLIC VCLFactory + { + public: + static CanvasSharedPtr createCanvas( const css::uno::Reference< css::rendering::XCanvas >& xCanvas ); + static BitmapCanvasSharedPtr createBitmapCanvas( const css::uno::Reference< css::rendering::XBitmapCanvas >& xCanvas ); + + static SpriteCanvasSharedPtr createSpriteCanvas( const vcl::Window& rVCLWindow ); + static SpriteCanvasSharedPtr createSpriteCanvas( const css::uno::Reference< css::rendering::XSpriteCanvas >& xCanvas ); + + /** Create a bitmap from a VCL Bitmap + */ + static BitmapSharedPtr createBitmap( const CanvasSharedPtr&, const ::BitmapEx& rBmpEx ); + + /** Create a renderer object from a Metafile + + The created renderer initially draws the metafile + one-by-one units large, in user coordinate space + */ + static RendererSharedPtr createRenderer( const CanvasSharedPtr& rCanvas, + const ::GDIMetaFile& rMtf, + const Renderer::Parameters& rParms ); + + private: + VCLFactory() = delete; + VCLFactory(const VCLFactory&) = delete; + VCLFactory& operator=( const VCLFactory& ) = delete; + }; + +} + +#endif // INCLUDED_CPPCANVAS_VCLFACTORY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/Enterable.hxx b/include/cppu/Enterable.hxx new file mode 100644 index 000000000..b5cc789e4 --- /dev/null +++ b/include/cppu/Enterable.hxx @@ -0,0 +1,112 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_ENTERABLE_HXX +#define INCLUDED_CPPU_ENTERABLE_HXX + +#include "uno/Enterable.h" +#include "rtl/ustring.hxx" + +namespace cppu +{ +/** C++ wrapper for binary C Enterable + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Environment_Stack) + + @see uno_Enterable + @since UDK 3.2.7 +*/ +class Enterable : public uno_Enterable +{ +public: + /* These methods need to be implemented in a derived class. + */ + virtual void v_enter() = 0; + virtual void v_leave() = 0; + virtual void v_callInto_v(uno_EnvCallee * pCallee, va_list * pParam) = 0; + virtual void v_callOut_v (uno_EnvCallee * pCallee, va_list * pParam) = 0; + virtual bool v_isValid (rtl::OUString * pReason) = 0; + + virtual ~Enterable() {} + +public: + inline explicit Enterable(); + + void enter() {m_enter(this);} + void leave() {m_leave(this);} + + void callInto_v(uno_EnvCallee * pCallee, va_list * pParam) {m_callInto_v(this, pCallee, pParam);} + void callOut_v (uno_EnvCallee * pCallee, va_list * pParam) {m_callOut_v (this, pCallee, pParam);} + + inline void callInto(uno_EnvCallee * pCallee, ...); + inline void callOut (uno_EnvCallee * pCallee, ...); + + int isValid (rtl::OUString * pReason) {return m_isValid(this, &pReason->pData);} + +private: + Enterable(Enterable const &) SAL_DELETED_FUNCTION; + Enterable & operator = (Enterable const &) SAL_DELETED_FUNCTION; +}; + +extern "C" inline void Enterable_call_enter (void * context) { static_cast(context)->v_enter(); } +extern "C" inline void Enterable_call_leave (void * context) { static_cast(context)->v_leave(); } +extern "C" inline void Enterable_call_callInto_v(void * context, uno_EnvCallee * pCallee, va_list * pParam) + { static_cast(context)->v_callInto_v(pCallee, pParam); } +extern "C" inline void Enterable_call_callOut_v (void * context, uno_EnvCallee * pCallee, va_list * pParam) + { static_cast(context)->v_callOut_v(pCallee, pParam); } +extern "C" inline int Enterable_call_isValid (void * context, rtl_uString ** pReason) + {return static_cast(context)->v_isValid(reinterpret_cast(pReason));} + + +Enterable::Enterable() +{ + m_enter = Enterable_call_enter; + m_leave = Enterable_call_leave; + m_callInto_v = Enterable_call_callInto_v; + m_callOut_v = Enterable_call_callOut_v; + m_isValid = Enterable_call_isValid; +} + +void Enterable::callInto(uno_EnvCallee * pCallee, ...) +{ + va_list param; + + va_start(param, pCallee); + callInto_v(pCallee, ¶m); + va_end(param); +} + +void Enterable::callOut(uno_EnvCallee * pCallee, ...) +{ + va_list param; + + va_start(param, pCallee); + callOut_v(pCallee, ¶m); + va_end(param); +} + +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/EnvDcp.hxx b/include/cppu/EnvDcp.hxx new file mode 100644 index 000000000..02eb0301d --- /dev/null +++ b/include/cppu/EnvDcp.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_ENVDCP_HXX +#define INCLUDED_CPPU_ENVDCP_HXX + +#include "rtl/ustring.hxx" +#include "uno/EnvDcp.h" + +namespace cppu +{ +namespace EnvDcp +{ +/** Get the OBI type part of an environment descriptor. + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Environment_Descriptor) + + @param rEnvDcp the Environment Descriptor + @return the OBI type + @since UDK 3.2.7 +*/ +inline rtl::OUString getTypeName(rtl::OUString const& rEnvDcp) +{ + rtl::OUString typeName; + + uno_EnvDcp_getTypeName(rEnvDcp.pData, &typeName.pData); + + return typeName; +} + +/** Get the purpose part of an environment descriptor. + (http://wiki.openoffice.org/wiki/Uno/Binary/Spec/Environment_Descriptor) + + @param rEnvDcp the Environment Descriptor + @return the purpose + @since UDK 3.2.7 +*/ +inline rtl::OUString getPurpose(rtl::OUString const& rEnvDcp) +{ + rtl::OUString purpose; + + uno_EnvDcp_getPurpose(rEnvDcp.pData, &purpose.pData); + + return purpose; +} +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/EnvGuards.hxx b/include/cppu/EnvGuards.hxx new file mode 100644 index 000000000..b8a2d30a8 --- /dev/null +++ b/include/cppu/EnvGuards.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_ENVGUARDS_HXX +#define INCLUDED_CPPU_ENVGUARDS_HXX + +#include "uno/environment.hxx" + + +namespace cppu +{ + /** Environment Guard + The provided Environment becomes entered in the constructor and left + in the destructor. + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Environment_Guard) + + @since UDK 3.2.7 + */ + class EnvGuard + { + css::uno::Environment m_env; + + public: + explicit EnvGuard(css::uno::Environment const & env) + { + if (env.is()) + { + m_env = css::uno::Environment::getCurrent(); + env.enter(); + } + } + + ~EnvGuard() + { + m_env.enter(); + } + + /** Checks if the associated environment is non empty. + + @return 0 == empty, 1 == non empty + */ + bool SAL_CALL is() const + { + return m_env.is(); + } + + /** Leaves the associated environment and clears + the reference. + */ + void clear() + { + if (m_env.is()) + { + m_env.enter(); + m_env.clear(); + } + } + }; + + /** Environment Anti-Guard + Any entered Environment becomes left in the constructor and re-entered + in the destructor. + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Environment_AntiGuard) + + @since UDK 3.2.7 + */ + class AntiEnvGuard + { + css::uno::Environment m_env; + + public: + explicit AntiEnvGuard() + : m_env(css::uno::Environment::getCurrent()) + { + uno_Environment_enter(NULL); + } + + ~AntiEnvGuard() + { + m_env.enter(); + } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/Map.hxx b/include/cppu/Map.hxx new file mode 100644 index 000000000..da3af7ec1 --- /dev/null +++ b/include/cppu/Map.hxx @@ -0,0 +1,109 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_MAP_HXX +#define INCLUDED_CPPU_MAP_HXX + +#include "uno/mapping.hxx" + + +namespace cppu +{ + /** Helpers for mapping objects relative to the current environment. + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Map_Helpers) + */ + + /** Maps an object from the current to an outer Environment, returns mapped object. + + @param pT the object to be mapped + @param outerEnv the target environment + @return the mapped object + @since UDK 3.2.7 + */ + template inline T * mapOut(T * pT, css::uno::Environment const & outerEnv) + { + css::uno::Mapping curr2outer(css::uno::Environment::getCurrent(), outerEnv); + + return reinterpret_cast(curr2outer.mapInterface(pT, cppu::UnoType::get())); + } + + + /** Maps an object from an outer Environment to the current, returns mapped object. + + @param pT the object to be mapped + @param outerEnv the source environment + @return the mapped object + @since UDK 3.2.7 + */ + template inline T * mapIn(T * pT, css::uno::Environment const & outerEnv) + { + css::uno::Mapping outer2curr(outerEnv, css::uno::Environment::getCurrent()); + + return reinterpret_cast(outer2curr.mapInterface(pT, cppu::UnoType::get())); + } + + + /** Maps an any from the current to an outer Environment, fills passed any. + + @param any the any to be mapped + @param res the target any + @param outerEnv the target environment + @since UDK 3.2.7 + */ + // Problem: any gets assigned to something, acquire/releases may be called in wrong env. + inline void mapOutAny(css::uno::Any const & any, css::uno::Any * res, css::uno::Environment const & outerEnv) + { + css::uno::Mapping curr2outer(css::uno::Environment::getCurrent(), outerEnv); + + uno_any_destruct(res, css::uno::cpp_release); + uno_type_any_constructAndConvert( + res, + const_cast(any.getValue()), + any.getValueTypeRef(), + curr2outer.get()); + } + + + /** Maps an any from an outer Environment to the current, fills passed any. + + @param any the any to be mapped + @param res the target any + @param outerEnv the source environment + @since UDK 3.2.7 + */ + inline void mapInAny(css::uno::Any const & any, css::uno::Any * res, css::uno::Environment const & outerEnv) + { + css::uno::Mapping outer2curr(outerEnv, css::uno::Environment::getCurrent()); + + uno_any_destruct(res, css::uno::cpp_release); + uno_type_any_constructAndConvert( + res, + const_cast(any.getValue()), + any.getValueTypeRef(), + outer2curr.get()); + } +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/cppudllapi.h b/include/cppu/cppudllapi.h new file mode 100644 index 000000000..121b6defc --- /dev/null +++ b/include/cppu/cppudllapi.h @@ -0,0 +1,24 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPU_CPPUDLLAPI_H +#define INCLUDED_CPPU_CPPUDLLAPI_H + +#include "sal/types.h" + +#if defined(CPPU_DLLIMPLEMENTATION) +#define CPPU_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define CPPU_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#if defined(PURPENV_DLLIMPLEMENTATION) +#define PURPENV_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define PURPENV_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif // INCLUDED_CPPU_CPPUDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/helper/purpenv/Environment.hxx b/include/cppu/helper/purpenv/Environment.hxx new file mode 100644 index 000000000..0024d34dd --- /dev/null +++ b/include/cppu/helper/purpenv/Environment.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_HELPER_PURPENV_ENVIRONMENT_HXX +#define INCLUDED_CPPU_HELPER_PURPENV_ENVIRONMENT_HXX + +#include "cppu/cppudllapi.h" +#include "uno/environment.h" + +namespace cppu { class Enterable; } + +namespace cppu { namespace helper { namespace purpenv { + +/** C++ helper for implementing Purpose Environments. + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Purpose_Bridge_Implementation_Helper) + + @since UDK 3.2.7 +*/ +PURPENV_DLLPUBLIC void Environment_initWithEnterable( + uno_Environment * pEnvironment, cppu::Enterable * pEnterable); + +}}} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/helper/purpenv/Mapping.hxx b/include/cppu/helper/purpenv/Mapping.hxx new file mode 100644 index 000000000..18acf35f4 --- /dev/null +++ b/include/cppu/helper/purpenv/Mapping.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_HELPER_PURPENV_MAPPING_HXX +#define INCLUDED_CPPU_HELPER_PURPENV_MAPPING_HXX + +#include "cppu/cppudllapi.h" +#include "typelib/typedescription.h" +#include "uno/any2.h" +#include "uno/environment.h" +#include "uno/mapping.h" + + +namespace cppu { namespace helper { namespace purpenv { + +/** C++ helper for implementing Purpose Environments. + (http://wiki.openoffice.org/wiki/Uno/Cpp/Spec/Purpose_Bridge_Implementation_Helper) + + @since UDK 3.2.7 +*/ + +typedef void ProbeFun( + bool pre, + void * pThis, + void * pContext, + typelib_TypeDescriptionReference * pReturnTypeRef, + typelib_MethodParameter * pParams, + sal_Int32 nParams, + typelib_TypeDescription const * pMemberType, + void * pReturn, + void * pArgs[], + uno_Any ** ppException ); + + +PURPENV_DLLPUBLIC void createMapping(uno_Mapping ** ppMapping, + uno_Environment * pFrom, + uno_Environment * pTo, + ProbeFun * probeFun = NULL, + void * pContext = NULL + ); + +}}} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/macros.hxx b/include/cppu/macros.hxx new file mode 100644 index 000000000..e891e7238 --- /dev/null +++ b/include/cppu/macros.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPU_MACROS_HXX +#define INCLUDED_CPPU_MACROS_HXX + +#include "sal/types.h" + +/** Namespace name for compiler/ platform, e.g. gcc3, msci + + @deprecated implementation detail, not to be used by client code +*/ +#define CPPU_CURRENT_NAMESPACE CPPU_ENV + +/// @cond INTERNAL + +/** Patching the GCC 3 incompatible alignment change for Linux. + + This macro is appended by cppumaker to every first member of a struct, if + the struct inherits from a base struct and the first member is neither + double nor sal_[u]Int64. (The double/sal_[u]Int64 restriction is due to a + bug in GCC prior to version 3.3, which would cause __alignof__ of such a + struct to become 8 instead of 4 if CPPU_GCC3_ALIGN were added to its first + member.) +*/ +#if defined(__GNUC__) +#define CPPU_GCC3_ALIGN( base_struct ) __attribute__ ((aligned (__alignof__ (base_struct)))) +#else +#define CPPU_GCC3_ALIGN( base_struct ) +#endif + +/** + Exporting the symbols necessary for exception handling on GCC. + + These macros are used in the headers generated by cppumaker for UNO exception + types, to ensure that exception handling does not fail on GCC. +*/ +#define CPPU_GCC_DLLPUBLIC_EXPORT SAL_EXCEPTION_DLLPUBLIC_EXPORT +#define CPPU_GCC_DLLPRIVATE SAL_EXCEPTION_DLLPRIVATE + +/// @endcond + +#endif // INCLUDED_CPPU_MACROS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppu/unotype.hxx b/include/cppu/unotype.hxx new file mode 100644 index 000000000..e794747ba --- /dev/null +++ b/include/cppu/unotype.hxx @@ -0,0 +1,412 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPU_UNOTYPE_HXX +#define INCLUDED_CPPU_UNOTYPE_HXX + +#include "sal/config.h" + +#include + +#if defined LIBO_INTERNAL_ONLY +#include +#endif + +#include "sal/types.h" +#include "typelib/typeclass.h" +#include "typelib/typedescription.h" + +namespace com { namespace sun { namespace star { namespace uno { + class Type; + class Any; + class Exception; + template< typename > class Reference; + template< typename > class Sequence; + class XInterface; +} } } } +namespace rtl { class OUString; } + +namespace cppu { + +template< typename > class UnoType; + +/** + A unique C++ type representing the UNO type VOID in cppu::UnoType. + + This type is declared but not defined. Its only use is as a template + argument to cppu::UnoType. + + @since UDK 3.2.2 +*/ +struct UnoVoidType; + +/** + A unique C++ type representing the UNO type UNSIGNED SHORT in cppu::UnoType. + + The UNO types UNSIGNED SHORT and CHAR map to the same C++ type, so this C++ + type is needed to unambiguously specify UNO types in cppu::UnoType. + + This type is declared but not defined. Its only use is as a template + argument to cppu::UnoType. + + @since UDK 3.2.2 +*/ +struct UnoUnsignedShortType; + +/** + A unique C++ type representing the UNO type CHAR in cppu::UnoType. + + The UNO types UNSIGNED SHORT and CHAR map to the same C++ type, so this C++ + type is needed to unambiguously specify UNO types in cppu::UnoType. + + This type is declared but not defined. Its only use is as a template + argument to cppu::UnoType. + + @since UDK 3.2.2 +*/ +struct UnoCharType; + +/** + A unique C++ type template representing the UNO sequence types in + cppu::UnoType. + + The UNO types UNSIGNED SHORT and CHAR map to the same C++ type, so this C++ + type is needed to unambiguously specify UNO types in cppu::UnoType. + + This type is declared but not defined. Its only use is as a template + argument to cppu::UnoType. + + @since UDK 3.2.2 +*/ +template< typename > struct UnoSequenceType; + +namespace detail { + +inline css::uno::Type const & getTypeFromTypeDescriptionReference( + ::typelib_TypeDescriptionReference * const * tdr) +{ + return *reinterpret_cast< css::uno::Type const * >(tdr); +} + +inline css::uno::Type const & +getTypeFromTypeClass(::typelib_TypeClass tc) { + return getTypeFromTypeDescriptionReference( + ::typelib_static_type_getByTypeClass(tc)); +} + +} + +} + +namespace cppu { namespace detail { + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::cppu::UnoVoidType const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_VOID); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER bool const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_BOOLEAN); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER sal_Bool const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_BOOLEAN); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::sal_Int8 const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_BYTE); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::sal_Int16 const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_SHORT); +} + +inline css::uno::Type const & +cppu_detail_getUnoType( + SAL_UNUSED_PARAMETER ::cppu::UnoUnsignedShortType const *) +{ + return ::cppu::detail::getTypeFromTypeClass( + ::typelib_TypeClass_UNSIGNED_SHORT); +} + +#if defined LIBO_INTERNAL_ONLY + // cf. sal/types.h sal_Unicode +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER sal_uInt16 const *) { + return cppu::detail::getTypeFromTypeClass(typelib_TypeClass_UNSIGNED_SHORT); +} +#endif + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::sal_Int32 const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_LONG); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::sal_uInt32 const *) { + return ::cppu::detail::getTypeFromTypeClass( + ::typelib_TypeClass_UNSIGNED_LONG); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::sal_Int64 const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_HYPER); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::sal_uInt64 const *) { + return ::cppu::detail::getTypeFromTypeClass( + ::typelib_TypeClass_UNSIGNED_HYPER); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER float const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_FLOAT); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER double const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_DOUBLE); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::cppu::UnoCharType const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_CHAR); +} + +#if defined LIBO_INTERNAL_ONLY + // cf. sal/types.h sal_Unicode +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER sal_Unicode const *) { + return cppu::detail::getTypeFromTypeClass(typelib_TypeClass_CHAR); +} +#endif + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::rtl::OUString const *) { + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_STRING); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER css::uno::Type const *) +{ + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_TYPE); +} + +inline css::uno::Type const & +cppu_detail_getUnoType(SAL_UNUSED_PARAMETER css::uno::Any const *) +{ + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_ANY); +} + +template< typename T > inline css::uno::Type const & +cppu_detail_getUnoType( + SAL_UNUSED_PARAMETER ::cppu::UnoSequenceType< T > const *) +{ + //TODO: depending on memory model, the following might not work reliably + static typelib_TypeDescriptionReference * p = NULL; + if (p == NULL) { + ::typelib_static_sequence_type_init( + &p, ::cppu::UnoType< T >::get().getTypeLibType()); + } + return ::cppu::detail::getTypeFromTypeDescriptionReference(&p); +} + +template< typename T > inline css::uno::Type const & +cppu_detail_getUnoType( + SAL_UNUSED_PARAMETER css::uno::Sequence< T > const *) +{ + return cppu_detail_getUnoType( + static_cast< ::cppu::UnoSequenceType< T > * >(NULL)); +} + +inline css::uno::Type const & cppu_detail_getUnoType( + SAL_UNUSED_PARAMETER css::uno::Exception const *) +{ + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_EXCEPTION); +} + +inline css::uno::Type const & cppu_detail_getUnoType( + SAL_UNUSED_PARAMETER css::uno::XInterface const *) +{ + return ::cppu::detail::getTypeFromTypeClass(::typelib_TypeClass_INTERFACE); +} + +template< typename T > inline css::uno::Type const & +cppu_detail_getUnoType( + SAL_UNUSED_PARAMETER css::uno::Reference< T > const *) +{ + return ::cppu::UnoType< T >::get(); +} + +} } + +namespace cppu { + +/** + Get the css::uno::Type instance representing a certain UNO type. + + For each C++ type representing a UNO type, the corresponding instantiation of + this template has a public static member function get(). (The template is + specialized for C++ templates representing polymorphic struct type templates + of UNO. In those cases, it does not work to instantiate UnoType with a C++ + type that is derived from a C++ type that represents a UNO type, but does not + itself represent a UNO type. In all other cases, UnoType even works for such + C++ types that are unambiguously derived from one C++ type that represents a + UNO type.) In addition to those C++ types that are mappings of UNO types + (except for sal_uInt16 and sal_Unicode, see below), the following C++ types + are appropriate as template arguments: void, cppu::UnoVoidType, bool, + cppu::UnoUnsignedShortType, cppu::UnoCharType, cppu::UnoSequenceType with any + appropriate template argument (the latter three to unambiguously specify UNO + types, as the UNO types UNSIGNED SHORT and CHAR map to the same C++ type), + and css::uno::Reference with any appropriate template argument. + + @since UDK 3.2.2 +*/ +template< typename T > class UnoType { +public: + static css::uno::Type const & get() { + using namespace ::cppu::detail; +#if defined LIBO_INTERNAL_ONLY + typedef typename std::remove_reference::type T1; + // for certain uses of UnoType +#else + typedef T T1; +#endif + return cppu_detail_getUnoType(static_cast< T1 * >(NULL)); + } + +private: + UnoType(UnoType &) SAL_DELETED_FUNCTION; + ~UnoType() SAL_DELETED_FUNCTION; + void operator =(UnoType &) SAL_DELETED_FUNCTION; +}; + +template<> css::uno::Type inline const & UnoType::get() { + return cppu::UnoType::get(); +} + +/** + A working replacement for getCppuType (see there). + + There are three overloads of this function that together form the replacement + of getCppuType. The replacement has exactly the same semantics as + getCppuType, in that it returns correct results for the UNO type UNSIGNED + SHORT but not for the UNO type CHAR. + + @since UDK 3.2.2 +*/ +template< typename T > inline css::uno::Type const & +getTypeFavourUnsigned(SAL_UNUSED_PARAMETER T const *) { + return ::cppu::UnoType< T >::get(); +} + +/** + A working replacement for getCppuType (see there). + + There are three overloads of this function that together form the replacement + of getCppuType. The replacement has exactly the same semantics as + getCppuType, in that it returns correct results for the UNO type UNSIGNED + SHORT but not for the UNO type CHAR. + + @since UDK 3.2.2 +*/ +inline css::uno::Type const & +getTypeFavourUnsigned(SAL_UNUSED_PARAMETER ::sal_uInt16 const *) { + return ::cppu::UnoType< ::cppu::UnoUnsignedShortType >::get(); +} + +/** + A working replacement for getCppuType (see there). + + There are three overloads of this function that together form the replacement + of getCppuType. The replacement has exactly the same semantics as + getCppuType, in that it returns correct results for the UNO type UNSIGNED + SHORT but not for the UNO type CHAR. + + @since UDK 3.2.2 +*/ +template< typename T > inline css::uno::Type const & +getTypeFavourUnsigned(css::uno::Sequence< T > const *); + // defined in com/sun/star/uno/Sequence.hxx + +/// @cond INTERNAL + +/** + A working replacement for getCppuType (see there). + + There are three overloads of this function that together form the replacement + of the getCppuType template. The replacement has exactly the same semantics + as the getCppuType template, in that it returns correct results for the UNO + type CHAR but not for the UNO type UNSIGNED SHORT. Additionally, it also + returns the intended results for sequence types. + + @since UDK 3.2.3 +*/ +template< typename T > inline css::uno::Type const & +getTypeFavourChar(SAL_UNUSED_PARAMETER T const *) { + return ::cppu::UnoType< T >::get(); +} + +/** + A working replacement for getCppuType (see there). + + There are three overloads of this function that together form the replacement + of the getCppuType template. The replacement has exactly the same semantics + as the getCppuType template, in that it returns correct results for the UNO + type CHAR but not for the UNO type UNSIGNED SHORT. Additionally, it also + returns the intended results for sequence types. + + @since UDK 3.2.3 +*/ +inline css::uno::Type const & +getTypeFavourChar(SAL_UNUSED_PARAMETER ::sal_Unicode const *) { + return ::cppu::UnoType< ::cppu::UnoCharType >::get(); +} + +/** + A working replacement for getCppuType (see there). + + There are three overloads of this function that together form the replacement + of the getCppuType template. The replacement has exactly the same semantics + as the getCppuType template, in that it returns correct results for the UNO + type CHAR but not for the UNO type UNSIGNED SHORT. Additionally, it also + returns the intended results for sequence types. + + @since UDK 3.2.3 +*/ +template< typename T > inline css::uno::Type const & +getTypeFavourChar(css::uno::Sequence< T > const *); + // defined in com/sun/star/uno/Sequence.hxx + +/// @endcond + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/TODO b/include/cppuhelper/TODO new file mode 100644 index 000000000..e00fd0df5 --- /dev/null +++ b/include/cppuhelper/TODO @@ -0,0 +1,3 @@ +compbase1.hxx, compbase2.hxx, ... are just there because they are part of the published API. +In LO internals, we could just use compbase.hxx so it would allow us to make the compbase.hxx deprecated +See https://lists.freedesktop.org/archives/libreoffice/2022-January/088279.html diff --git a/include/cppuhelper/access_control.hxx b/include/cppuhelper/access_control.hxx new file mode 100644 index 000000000..d0c382cdf --- /dev/null +++ b/include/cppuhelper/access_control.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_ACCESS_CONTROL_HXX +#define INCLUDED_CPPUHELPER_ACCESS_CONTROL_HXX + +#include "cppuhelper/cppuhelperdllapi.h" +#include "com/sun/star/uno/Reference.hxx" + +namespace com { namespace sun { namespace star { namespace security { class XAccessController; } } } } +namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; } } } } + +namespace cppu +{ + +/** Helper class for retrieving access controller singleton from component context. +*/ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC AccessControl +{ + css::uno::Reference< css::security::XAccessController > m_xController; + +public: + /** Ctor. + + @param xContext component context to retrieve access controller singleton + */ + AccessControl( + css::uno::Reference< css::uno::XComponentContext > const & xContext ); + /** Ctor. + + @param xController access controller + */ + AccessControl( + css::uno::Reference< css::security::XAccessController > const & xController ); + /** Copy ctor. + + @param ac another object + */ + AccessControl( ::cppu::AccessControl const & ac ); + + /** Clears the access controller reference being used. + */ + void SAL_CALL clear() + { m_xController.clear(); } + + /** Returns access to the access controller reference being used. + + @return access controller + */ + css::uno::Reference< css::security::XAccessController > const & SAL_CALL get() const + { return m_xController; } + + /** Returns access to the access controller reference being used. + + @return access controller + */ + css::security::XAccessController * SAL_CALL operator -> () const + { return m_xController.get(); } + + + /** A com.sun.star.security.RuntimePermission is for runtime permissions. + A RuntimePermission contains a name (also referred to as a "target name") but no + actions list; you either have the named permission or you don't. + + @param name name of permission + */ + void SAL_CALL checkRuntimePermission( + ::rtl::OUString const & name ); + + /** A com.sun.star.io.FilePermission represents access to a file or directory. + A FilePermission consists of a file url and a set of actions valid for that pathname. + + @param url file url + @param actions actions list + */ + void SAL_CALL checkFilePermission( + ::rtl::OUString const & url, + ::rtl::OUString const & actions ); + + /** A com.sun.star.connection.SocketPermission represents access to a network via sockets. + A SocketPermission consists of a host specification and a set of "actions" + specifying ways to connect to that host. + + @param host host and optional portrange + @param actions actions list + */ + void SAL_CALL checkSocketPermission( + ::rtl::OUString const & host, + ::rtl::OUString const & actions ); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/basemutex.hxx b/include/cppuhelper/basemutex.hxx new file mode 100644 index 000000000..5bed36a6e --- /dev/null +++ b/include/cppuhelper/basemutex.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_BASEMUTEX_HXX +#define INCLUDED_CPPUHELPER_BASEMUTEX_HXX + +#include "osl/mutex.hxx" + +namespace cppu +{ + /** base class for all classes who want derive from + cppu::WeakComponentImplHelperXX. + + Implementation classes have first to derive from BaseMutex and then from + cppu::WeakComponentImplHelperXX to ensure that the BaseMutex is completely + initialized when the mutex is used to initialize the + cppu::WeakComponentImplHelperXX + */ + class SAL_WARN_UNUSED BaseMutex + { + protected: + mutable ::osl::Mutex m_aMutex; + }; +} +#endif // INCLUDED_CPPUHELPER_BASEMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/bootstrap.hxx b/include/cppuhelper/bootstrap.hxx new file mode 100644 index 000000000..b8cc113f5 --- /dev/null +++ b/include/cppuhelper/bootstrap.hxx @@ -0,0 +1,169 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_BOOTSTRAP_HXX +#define INCLUDED_CPPUHELPER_BOOTSTRAP_HXX + +#include "sal/config.h" +#include "com/sun/star/uno/Reference.h" +#include "rtl/ustring.hxx" +#include "sal/types.h" +#include "cppuhelper/cppuhelperdllapi.h" + +namespace com { namespace sun { namespace star { + namespace container { class XHierarchicalNameAccess; } + namespace uno { class XComponentContext; } +} } } + +namespace cppu +{ + +/** Installs type description manager instance, i.e. registers a callback at cppu core. + + @param xTDMgr manager instance + @return true, if successfully registered +*/ +CPPUHELPER_DLLPUBLIC sal_Bool SAL_CALL installTypeDescriptionManager( + css::uno::Reference< css::container::XHierarchicalNameAccess > const & xTDMgr ); + +/** Bootstraps an initial component context with service manager upon + information from bootstrap variables. + + This function tries to find its parameters via these bootstrap variables: + + - UNO_TYPES -- a space separated list of file urls of type rdbs + - UNO_SERVICES -- a space separated list of file urls of service rdbs + + Please look at http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html + for further info. + + @return component context +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::uno::XComponentContext > SAL_CALL +defaultBootstrap_InitialComponentContext(); + + +/** Bootstraps an initial component context with service manager upon + information from an ini file. + + This function tries to find its parameters via these bootstrap variables: + + - UNO_TYPES -- a space separated list of file urls of type rdbs + - UNO_SERVICES -- a space separated list of file urls of service rdbs + + Please look at http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html + for further info. + + @param iniFile ini filename to get bootstrap variables + @return component context +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::uno::XComponentContext > SAL_CALL +defaultBootstrap_InitialComponentContext(const ::rtl::OUString & iniFile); + +/** + * An exception indicating a bootstrap error. + * + * @since UDK 3.2.0 + */ +class CPPUHELPER_DLLPUBLIC BootstrapException +{ +public: + /** + * Constructs a BootstrapException. + */ + BootstrapException(); + + /** + * Constructs a BootstrapException with the specified detail message. + * + * @param rMessage + * A message containing any details about the exception. + */ + BootstrapException( const ::rtl::OUString & rMessage ); + + /** + * Copy constructs a BootstrapException. + */ + BootstrapException( const BootstrapException & e ); + + /** + * Destructs a BootstrapException. + */ + virtual ~BootstrapException(); + + /** + * Assigns a BootstrapException. + */ + BootstrapException & operator=( const BootstrapException & e ); + + /** Gets the message. + + @return + A reference to the message. The reference is valid for the lifetime of + this BootstrapException. + */ + const ::rtl::OUString & getMessage() const; + +private: + ::rtl::OUString m_aMessage; +}; + +/** + * Bootstraps the component context from a UNO installation. + * + * @return a bootstrapped component context + * @exception BootstrapException + * Thrown in case bootstrap() signals an exception due to a + * bootstrap error. + * + * @since UDK 3.2.0 + */ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::uno::XComponentContext > +SAL_CALL bootstrap(); + +/// @cond INTERNAL +/** + * Helper function to expand vnd.sun.star.expand URLs in contexts where no + * properly bootstrapped UNO is (yet) available. + * + * @param uri + * Some URI (but not a URI reference). + * + * @return + * If uri is a vnd.sun.star.expand URL, then the expansion of that URL is + * returned; expansion may lead to a string that is not a legal URI. Otherwise, + * the uri is returned unchanged. + * + * @exception css::lang::IllegalArgumentException + * If uri is a vnd.sun.star.expand URL that contains unknown macros. + * + * @since UDK 3.2.8 + */ +CPPUHELPER_DLLPUBLIC ::rtl::OUString +SAL_CALL bootstrap_expandUri(::rtl::OUString const & uri); +/// @endcond + +} // end namespace cppu + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase.hxx b/include/cppuhelper/compbase.hxx new file mode 100644 index 000000000..d647efc60 --- /dev/null +++ b/include/cppuhelper/compbase.hxx @@ -0,0 +1,133 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPUHELPER_COMPBASE_HXX +#define INCLUDED_CPPUHELPER_COMPBASE_HXX + +#include "sal/config.h" + +#include "com/sun/star/lang/XTypeProvider.hpp" +#include "com/sun/star/uno/Any.h" +#include "com/sun/star/uno/Reference.h" +#include "com/sun/star/uno/Sequence.h" +#include "com/sun/star/uno/Type.h" +#include "cppuhelper/compbase_ex.hxx" +#include "cppuhelper/implbase.hxx" +#include "rtl/instance.hxx" +#include "sal/types.h" + +namespace com { namespace sun { namespace star { namespace lang { + class XEventListener; +} } } } +namespace osl { class Mutex; } + +#if defined LIBO_INTERNAL_ONLY + +// A replacement for WeakAggComponentImplHelper1 has deliberately been left out, +// as the underlying aggregation mechanism is known broken in general and should +// not be used. + +namespace cppu { + +/** Implementation helper implementing interfaces + css::uno::XInterface, css::lang::XTypeProvider, and + css::lang::XComponent. + + Like WeakComponentImplHelper, but does not define + XComponent::add/removeEventListener. Use for classes deriving from multiple + UNO interfaces with competing add/removeEventListener methods, to avoid + warnings about hiding of overloaded virtual functions. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. + + @attention + The mutex reference passed to the constructor has to outlive the constructed + instance. +*/ +template +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper: + public WeakComponentImplHelperBase, public css::lang::XTypeProvider, + public Ifc... +{ + struct cd: + rtl::StaticAggregate< + class_data, + detail::ImplClassData> + {}; + +public: + PartialWeakComponentImplHelper(osl::Mutex & mutex) SAL_NOEXCEPT: + WeakComponentImplHelperBase(mutex) {} + + css::uno::Any SAL_CALL queryInterface(css::uno::Type const & aType) SAL_OVERRIDE + { return WeakComponentImplHelper_query(aType, cd::get(), this, this); } + + void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + + void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + + void SAL_CALL dispose() + SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + + css::uno::Sequence SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes(cd::get()); } + + css::uno::Sequence SAL_CALL getImplementationId() SAL_OVERRIDE + { return css::uno::Sequence(); } +}; + +/** Implementation helper implementing interfaces + css::uno::XInterface, css::lang::XTypeProvider, and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. + + @attention + The mutex reference passed to the constructor has to outlive the constructed + instance. +*/ +template +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper: + public PartialWeakComponentImplHelper +{ +public: + WeakComponentImplHelper(osl::Mutex & mutex) SAL_NOEXCEPT: + PartialWeakComponentImplHelper(mutex) {} + + void SAL_CALL addEventListener( + css::uno::Reference const & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + + void SAL_CALL removeEventListener( + css::uno::Reference const & aListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(aListener); } +}; + +} + +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase1.hxx b/include/cppuhelper/compbase1.hxx new file mode 100644 index 000000000..02c812920 --- /dev/null +++ b/include/cppuhelper/compbase1.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE1_HXX +#define INCLUDED_CPPUHELPER_COMPBASE1_HXX + +#include "cppuhelper/implbase1.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper1 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, WeakComponentImplHelper1< Ifc1 > > > {}; + public: + WeakComponentImplHelper1( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper1, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper1 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, PartialWeakComponentImplHelper1< Ifc1 > > > {}; + public: + PartialWeakComponentImplHelper1( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper1 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, WeakAggComponentImplHelper1< Ifc1 > > > {}; + public: + WeakAggComponentImplHelper1( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase10.hxx b/include/cppuhelper/compbase10.hxx new file mode 100644 index 000000000..27682f83c --- /dev/null +++ b/include/cppuhelper/compbase10.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE10_HXX +#define INCLUDED_CPPUHELPER_COMPBASE10_HXX + +#include "cppuhelper/implbase10.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper10 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, WeakComponentImplHelper10 > > {}; + public: + WeakComponentImplHelper10( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper10, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper10 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, PartialWeakComponentImplHelper10 > > {}; + public: + PartialWeakComponentImplHelper10( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper10 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, WeakAggComponentImplHelper10 > > {}; + public: + WeakAggComponentImplHelper10( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase11.hxx b/include/cppuhelper/compbase11.hxx new file mode 100644 index 000000000..9edfb3f46 --- /dev/null +++ b/include/cppuhelper/compbase11.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE11_HXX +#define INCLUDED_CPPUHELPER_COMPBASE11_HXX + +#include "cppuhelper/implbase11.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper11 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, WeakComponentImplHelper11 > > {}; + public: + WeakComponentImplHelper11( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper11, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper11 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, PartialWeakComponentImplHelper11 > > {}; + public: + PartialWeakComponentImplHelper11( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper11 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, WeakAggComponentImplHelper11 > > {}; + public: + WeakAggComponentImplHelper11( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase12.hxx b/include/cppuhelper/compbase12.hxx new file mode 100644 index 000000000..c5dd62158 --- /dev/null +++ b/include/cppuhelper/compbase12.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE12_HXX +#define INCLUDED_CPPUHELPER_COMPBASE12_HXX + +#include "cppuhelper/implbase12.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper12 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, WeakComponentImplHelper12 > > {}; + public: + WeakComponentImplHelper12( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper12, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper12 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, PartialWeakComponentImplHelper12 > > {}; + public: + PartialWeakComponentImplHelper12( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper12 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, WeakAggComponentImplHelper12 > > {}; + public: + WeakAggComponentImplHelper12( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase2.hxx b/include/cppuhelper/compbase2.hxx new file mode 100644 index 000000000..ed74588f6 --- /dev/null +++ b/include/cppuhelper/compbase2.hxx @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE2_HXX +#define INCLUDED_CPPUHELPER_COMPBASE2_HXX + +#include "cppuhelper/implbase2.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper2 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, WeakComponentImplHelper2 > > {}; + public: + WeakComponentImplHelper2( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper2, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper2 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, PartialWeakComponentImplHelper2 > > {}; + public: + PartialWeakComponentImplHelper2( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper2 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, WeakAggComponentImplHelper2 > > {}; + public: + WeakAggComponentImplHelper2( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase3.hxx b/include/cppuhelper/compbase3.hxx new file mode 100644 index 000000000..10681422b --- /dev/null +++ b/include/cppuhelper/compbase3.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE3_HXX +#define INCLUDED_CPPUHELPER_COMPBASE3_HXX + +#include "cppuhelper/implbase3.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper3 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, WeakComponentImplHelper3 > > {}; + public: + WeakComponentImplHelper3( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper3, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper3 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, PartialWeakComponentImplHelper3 > > {}; + public: + PartialWeakComponentImplHelper3( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper3 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, WeakAggComponentImplHelper3 > > {}; + public: + WeakAggComponentImplHelper3( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase4.hxx b/include/cppuhelper/compbase4.hxx new file mode 100644 index 000000000..04a8cdd88 --- /dev/null +++ b/include/cppuhelper/compbase4.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE4_HXX +#define INCLUDED_CPPUHELPER_COMPBASE4_HXX + +#include "cppuhelper/implbase4.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper4 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, WeakComponentImplHelper4 > > {}; + public: + WeakComponentImplHelper4( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper4, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper4 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, PartialWeakComponentImplHelper4 > > {}; + public: + PartialWeakComponentImplHelper4( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper4 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, WeakAggComponentImplHelper4 > > {}; + public: + WeakAggComponentImplHelper4( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase5.hxx b/include/cppuhelper/compbase5.hxx new file mode 100644 index 000000000..f48a2f21e --- /dev/null +++ b/include/cppuhelper/compbase5.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE5_HXX +#define INCLUDED_CPPUHELPER_COMPBASE5_HXX + +#include "cppuhelper/implbase5.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper5 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakComponentImplHelper5 > > {}; + public: + WeakComponentImplHelper5( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper5, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper5 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, PartialWeakComponentImplHelper5 > > {}; + public: + PartialWeakComponentImplHelper5( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper5 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakAggComponentImplHelper5 > > {}; + public: + WeakAggComponentImplHelper5( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase6.hxx b/include/cppuhelper/compbase6.hxx new file mode 100644 index 000000000..971a1e4c5 --- /dev/null +++ b/include/cppuhelper/compbase6.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE6_HXX +#define INCLUDED_CPPUHELPER_COMPBASE6_HXX + +#include "cppuhelper/implbase6.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper6 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, WeakComponentImplHelper6 > > {}; + public: + WeakComponentImplHelper6( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper6, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper6 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, PartialWeakComponentImplHelper6 > > {}; + public: + PartialWeakComponentImplHelper6( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper6 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, WeakAggComponentImplHelper6 > > {}; + public: + WeakAggComponentImplHelper6( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase7.hxx b/include/cppuhelper/compbase7.hxx new file mode 100644 index 000000000..c6176e185 --- /dev/null +++ b/include/cppuhelper/compbase7.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE7_HXX +#define INCLUDED_CPPUHELPER_COMPBASE7_HXX + +#include "cppuhelper/implbase7.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper7 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, WeakComponentImplHelper7 > > {}; + public: + WeakComponentImplHelper7( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper7, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper7 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, PartialWeakComponentImplHelper7 > > {}; + public: + PartialWeakComponentImplHelper7( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper7 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, WeakAggComponentImplHelper7 > > {}; + public: + WeakAggComponentImplHelper7( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase8.hxx b/include/cppuhelper/compbase8.hxx new file mode 100644 index 000000000..c70e26f7f --- /dev/null +++ b/include/cppuhelper/compbase8.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE8_HXX +#define INCLUDED_CPPUHELPER_COMPBASE8_HXX + +#include "cppuhelper/implbase8.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper8 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, WeakComponentImplHelper8 > > {}; + public: + WeakComponentImplHelper8( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper8, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper8 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, PartialWeakComponentImplHelper8 > > {}; + public: + PartialWeakComponentImplHelper8( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper8 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, WeakAggComponentImplHelper8 > > {}; + public: + WeakAggComponentImplHelper8( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase9.hxx b/include/cppuhelper/compbase9.hxx new file mode 100644 index 000000000..e1f28d536 --- /dev/null +++ b/include/cppuhelper/compbase9.hxx @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE9_HXX +#define INCLUDED_CPPUHELPER_COMPBASE9_HXX + +#include "cppuhelper/implbase9.hxx" +#include "cppuhelper/compbase_ex.hxx" + +namespace cppu +{ + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakComponentImplHelper9 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, WeakComponentImplHelper9 > > {}; + public: + WeakComponentImplHelper9( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual void SAL_CALL dispose() SAL_OVERRIDE + { WeakComponentImplHelperBase::dispose(); } + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::addEventListener(xListener); } + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & xListener) SAL_OVERRIDE + { WeakComponentImplHelperBase::removeEventListener(xListener); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Same as WeakComponentImplHelper9, except doesn't implement + addEventListener, removeEventListener and dispose. + + This requires derived classes to implement those three methods. + This makes it possible to implement classes which are required to + implement methods from multiple bases which have different + addEventListener/removeEventListener signatures without triggering + the g++ overloaded-virtual warning + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE PartialWeakComponentImplHelper9 + : public WeakComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, PartialWeakComponentImplHelper9 > > {}; + public: + PartialWeakComponentImplHelper9( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakComponentImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + + /** Implementation helper supporting css::lang::XTypeProvider and + css::lang::XComponent. + Upon disposing objects of this class, sub-classes receive a disposing() + call. Objects of this class can be held weakly, i.e. by a + css::uno::WeakReference. Object of this class can be + aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + @deprecated + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggComponentImplHelper9 + : public WeakAggComponentImplHelperBase + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, WeakAggComponentImplHelper9 > > {}; + public: + WeakAggComponentImplHelper9( ::osl::Mutex & rMutex ) SAL_NOEXCEPT + : WeakAggComponentImplHelperBase( rMutex ) + {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelperBase::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggComponentImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { WeakAggComponentImplHelperBase::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggComponentImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/compbase_ex.hxx b/include/cppuhelper/compbase_ex.hxx new file mode 100644 index 000000000..3976c3afb --- /dev/null +++ b/include/cppuhelper/compbase_ex.hxx @@ -0,0 +1,162 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPBASE_EX_HXX +#define INCLUDED_CPPUHELPER_COMPBASE_EX_HXX + +#include "cppuhelper/interfacecontainer.h" +#include "com/sun/star/lang/XComponent.hpp" +#include "cppuhelper/cppuhelperdllapi.h" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" + +/// @cond INTERNAL + +namespace osl { class Mutex; } +namespace cppu { struct class_data; } + +namespace cppu +{ + +/** Implementation helper base class for components. Inherits from ::cppu::OWeakObject and + css::lang::XComponent. +*/ +class CPPUHELPER_DLLPUBLIC SAL_NO_VTABLE WeakComponentImplHelperBase + : public ::cppu::OWeakObject + , public css::lang::XComponent +{ +protected: + /** broadcast helper for disposing events + */ + ::cppu::OBroadcastHelper rBHelper; + + /** this function is called upon disposing the component + */ + virtual void SAL_CALL disposing(); + + /** This is the one and only constructor that is called from derived implementations. + + @param rMutex mutex to sync upon disposing + */ + WeakComponentImplHelperBase( ::osl::Mutex & rMutex ); +public: + /** Destructor + */ + virtual ~WeakComponentImplHelperBase() SAL_OVERRIDE; + + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + virtual css::uno::Any SAL_CALL queryInterface( + css::uno::Type const & rType ) SAL_OVERRIDE; + virtual void SAL_CALL acquire() + SAL_NOEXCEPT SAL_OVERRIDE; + virtual void SAL_CALL release() + SAL_NOEXCEPT SAL_OVERRIDE; + virtual void SAL_CALL dispose() SAL_OVERRIDE; + virtual void SAL_CALL addEventListener( + css::uno::Reference< css::lang::XEventListener > const & xListener ) SAL_OVERRIDE; + virtual void SAL_CALL removeEventListener( + css::uno::Reference< css::lang::XEventListener > const & xListener ) SAL_OVERRIDE; +}; + +/** Implementation helper base class for components. Inherits from ::cppu::OWeakAggObject and + css::lang::XComponent. +*/ +class CPPUHELPER_DLLPUBLIC SAL_NO_VTABLE WeakAggComponentImplHelperBase + : public ::cppu::OWeakAggObject + , public css::lang::XComponent +{ +protected: + ::cppu::OBroadcastHelper rBHelper; + + /** Is called upon disposing the component. + */ + virtual void SAL_CALL disposing(); + + WeakAggComponentImplHelperBase( ::osl::Mutex & rMutex ); +public: + virtual ~WeakAggComponentImplHelperBase() SAL_OVERRIDE; + + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + virtual css::uno::Any SAL_CALL queryInterface( + css::uno::Type const & rType ) SAL_OVERRIDE; + virtual css::uno::Any SAL_CALL queryAggregation( + css::uno::Type const & rType ) SAL_OVERRIDE; + virtual void SAL_CALL acquire() + SAL_NOEXCEPT SAL_OVERRIDE; + virtual void SAL_CALL release() + SAL_NOEXCEPT SAL_OVERRIDE; + virtual void SAL_CALL dispose() SAL_OVERRIDE; + virtual void SAL_CALL addEventListener( + css::uno::Reference< css::lang::XEventListener > const & xListener ) SAL_OVERRIDE; + virtual void SAL_CALL removeEventListener( + css::uno::Reference< css::lang::XEventListener > const & xListener ) SAL_OVERRIDE; +}; + +/** WeakComponentImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any SAL_CALL WeakComponentImplHelper_query( + css::uno::Type const & rType, + class_data * cd, + void * that, + ::cppu::WeakComponentImplHelperBase * pBase ); +/** WeakComponentImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< css::uno::Type > SAL_CALL WeakComponentImplHelper_getTypes( + class_data * cd ); + +/** WeakAggComponentImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any SAL_CALL WeakAggComponentImplHelper_queryAgg( + css::uno::Type const & rType, + class_data * cd, + void * that, + ::cppu::WeakAggComponentImplHelperBase * pBase ); +/** WeakAggComponentImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< css::uno::Type > SAL_CALL WeakAggComponentImplHelper_getTypes( + class_data * cd ); + +} + +/// @endcond + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/component.hxx b/include/cppuhelper/component.hxx new file mode 100644 index 000000000..e59e1b9d4 --- /dev/null +++ b/include/cppuhelper/component.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPONENT_HXX +#define INCLUDED_CPPUHELPER_COMPONENT_HXX + +#include "cppuhelper/weakagg.hxx" +#include "cppuhelper/interfacecontainer.h" + +#include "com/sun/star/lang/XComponent.hpp" +#include "com/sun/star/lang/XTypeProvider.hpp" + +#include "cppuhelper/cppuhelperdllapi.h" + +namespace osl { class Mutex; } + +namespace cppu +{ + +/** Deprecated. Helper for implementing css::lang::XComponent. + Upon disposing objects of this class, sub-classes receive a disposing() call. Objects of + this class can be held weakly, i.e. by a css::uno::WeakReference. Object of + this class can be aggregated, i.e. incoming queryInterface() calls are delegated. + + @attention + The life-cycle of the passed mutex reference has to be longer than objects of this class. + @deprecated +*/ +class CPPUHELPER_DLLPUBLIC OComponentHelper + : public ::cppu::OWeakAggObject + , public css::lang::XTypeProvider + , public css::lang::XComponent +{ +public: + /** Constructor. + + @param rMutex + the mutex used to protect multi-threaded access; + lifetime must be longer than the lifetime of this object. + */ + OComponentHelper( ::osl::Mutex & rMutex ); + /** Destructor. If this object was not disposed previously, object will be disposed manually. + */ + virtual ~OComponentHelper() SAL_OVERRIDE; + + // XAggregation + virtual css::uno::Any SAL_CALL queryInterface( + css::uno::Type const & rType ) SAL_OVERRIDE; + virtual css::uno::Any SAL_CALL queryAggregation( + css::uno::Type const & rType ) SAL_OVERRIDE; + virtual void SAL_CALL acquire() + SAL_NOEXCEPT SAL_OVERRIDE; + virtual void SAL_CALL release() + SAL_NOEXCEPT SAL_OVERRIDE; + + /** @attention + XTypeProvider::getImplementationId() has to be implemented separately! + */ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE = 0; + /** @attention + XTypeProvider::getTypes() has to be re-implemented! + */ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE; + + // XComponent + virtual void SAL_CALL dispose() SAL_OVERRIDE; + virtual void SAL_CALL addEventListener( + const css::uno::Reference< css::lang::XEventListener >& aListener ) SAL_OVERRIDE; + virtual void SAL_CALL removeEventListener( + const css::uno::Reference< css::lang::XEventListener >& aListener ) SAL_OVERRIDE; + +protected: + /** Called in dispose method after the listeners were notified. + */ + virtual void SAL_CALL disposing(); + + /// @cond INTERNAL + OBroadcastHelper rBHelper; + /// @endcond + +private: + OComponentHelper( const OComponentHelper & ) SAL_DELETED_FUNCTION; + OComponentHelper & operator = ( const OComponentHelper & ) + SAL_DELETED_FUNCTION; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/component_context.hxx b/include/cppuhelper/component_context.hxx new file mode 100644 index 000000000..787264ab5 --- /dev/null +++ b/include/cppuhelper/component_context.hxx @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_COMPONENT_CONTEXT_HXX +#define INCLUDED_CPPUHELPER_COMPONENT_CONTEXT_HXX + +#include "com/sun/star/uno/Any.hxx" +#include "com/sun/star/uno/Reference.hxx" +#include "cppuhelper/cppuhelperdllapi.h" +#include "rtl/ustring.hxx" +#include "sal/types.h" + +namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; } } } } + +namespace cppu +{ + +/** Context entries init struct calling createComponentContext(). +*/ +struct SAL_WARN_UNUSED ContextEntry_Init +{ + /** late init denotes an object that will be raised when first get() is calling for it + + The context implementation expects either a css::lang::XSingleComponentFactory + object as value (to instantiate the object) or a string as value for raising + a service via the used service manager. + */ + bool bLateInitService; + /** name of context value + */ + ::rtl::OUString name; + /** context value + */ + css::uno::Any value; + + /** Default ctor. + */ + ContextEntry_Init() + : bLateInitService( false ) + {} + /** Ctor. + + @param name_ + name of entry + @param value_ + value of entry + @param bLateInitService_ + whether this entry is a late-init named object entry + (value is object factory or service string) + */ + ContextEntry_Init( + ::rtl::OUString const & name_, + css::uno::Any const & value_, + bool bLateInitService_ = false ) + : bLateInitService( bLateInitService_ ), + name( name_ ), + value( value_ ) + {} +}; + +/** Creates a component context with the given entries. + + @param pEntries array of entries + @param nEntries number of entries + @param xDelegate delegation to further context, if value was not found + @return new context object +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::uno::XComponentContext > +SAL_CALL createComponentContext( + ContextEntry_Init const * pEntries, sal_Int32 nEntries, + css::uno::Reference< css::uno::XComponentContext > const & xDelegate = + css::uno::Reference< css::uno::XComponentContext >() ); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/cppuhelperdllapi.h b/include/cppuhelper/cppuhelperdllapi.h new file mode 100644 index 000000000..1fa74845a --- /dev/null +++ b/include/cppuhelper/cppuhelperdllapi.h @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_CPPUHELPERDLLAPI_H +#define INCLUDED_CPPUHELPER_CPPUHELPERDLLAPI_H + +#include "sal/types.h" + +#if defined(CPPUHELPER_DLLIMPLEMENTATION) +#define CPPUHELPER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define CPPUHELPER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define CPPUHELPER_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_CPPUHELPER_CPPUHELPERDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/exc_hlp.hxx b/include/cppuhelper/exc_hlp.hxx new file mode 100644 index 000000000..fa3c3d05b --- /dev/null +++ b/include/cppuhelper/exc_hlp.hxx @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_EXC_HLP_HXX +#define INCLUDED_CPPUHELPER_EXC_HLP_HXX + +#include "com/sun/star/uno/Any.hxx" +#include "cppuhelper/cppuhelperdllapi.h" + +namespace cppu +{ +/** This function throws the exception given by rExc. The given value has to + be of typeclass EXCEPTION and must be derived from or of + type com.sun.star.uno.Exception. + + @param rExc + exception to be thrown. +*/ +CPPUHELPER_DLLPUBLIC void SAL_CALL throwException(const css::uno::Any& rExc); + +/** Use this function to get the dynamic type of a caught C++-UNO exception; + completes the above function throwing exceptions generically. + + @code + try + { + ... + } + catch (css::uno::RuntimeException &) + { + // you ought not handle RuntimeExceptions: + throw; + } + catch (css::uno::Exception &) + { + css::uno::Any caught( ::cppu::getCaughtException() ); + ... + } + @endcode + + Restrictions: + - use only for caught C++-UNO exceptions (UNOIDL defined) + - only as first statement in a catch block! + - don't do a C++ rethrow (throw;) after you have called this function + - call getCaughtException() just once in your catch block! + (function internally uses a C++ rethrow) + + @return + caught UNO exception + + @attention Caution! + This function is limited to the same C++ compiler runtime library. + E.g. for MSVC, this means that the catch handler code (the one + that calls getCaughtException()) needs to use the very same + C++ runtime library, e.g. msvcrt.dll as cppuhelper, e.g. + cppuhelper3MSC.dll and the bridge library, e.g. msci_uno.dll. + This is the case if all of them are compiled with the same + compiler version. + Background: The msci_uno.dll gets a rethrown exception out + of the internal msvcrt.dll thread local storage (tls). + Thus you _must_ not use this function if your code needs to run + in newer UDK versions without being recompiled, because those + newer UDK (-> OOo versions) potentially use newer C++ runtime + libraries which most often become incompatible! + + But this function ought to be usable for most OOo internal C++-UNO + development, because the whole OOo code base is compiled using the + same C++ compiler (and linking against one runtime library). +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any SAL_CALL getCaughtException(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/factory.hxx b/include/cppuhelper/factory.hxx new file mode 100644 index 000000000..e6a9ee2f1 --- /dev/null +++ b/include/cppuhelper/factory.hxx @@ -0,0 +1,278 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_FACTORY_HXX +#define INCLUDED_CPPUHELPER_FACTORY_HXX + +#include "sal/config.h" + +#include + +#include "rtl/ustring.hxx" +#include "rtl/unload.h" + +#include "com/sun/star/uno/Reference.h" +#include "cppuhelper/cppuhelperdllapi.h" + +namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } } +namespace com { namespace sun { namespace star { namespace lang { class XSingleComponentFactory; } } } } +namespace com { namespace sun { namespace star { namespace lang { class XSingleServiceFactory; } } } } +namespace com { namespace sun { namespace star { namespace registry { class XRegistryKey; } } } } +namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; } } } } +namespace com { namespace sun { namespace star { namespace uno { class XInterface; } } } } +namespace com { namespace sun { namespace star { namespace uno { template class Sequence; } } } } + +#define COMPONENT_GETENV "component_getImplementationEnvironment" +#define COMPONENT_GETENVEXT "component_getImplementationEnvironmentExt" +#define COMPONENT_WRITEINFO "component_writeInfo" +#define COMPONENT_GETFACTORY "component_getFactory" + +typedef struct _uno_Environment uno_Environment; + +/** Function pointer declaration. + Function determines the environment of the component implementation, i.e. which compiler + compiled it. If the environment is NOT session specific (needs no additional context), + then this function should return the environment type name and leave ppEnv (to 0). + + @param ppEnvTypeName environment type name; string must be constant + @param ppEnv function returns its environment if the environment is session specific, + i.e. has special context +*/ +typedef void (SAL_CALL * component_getImplementationEnvironmentFunc)( + const char ** ppEnvTypeName, uno_Environment ** ppEnv ); + +/** Function pointer declaration. + Function determines the environment of the component implementation, i.e. the compiler. + If the environment is NOT session specific (needs no additional context), + then this function should return the environment type name and leave ppEnv (to 0). + + @param ppEnvTypeName environment type name; string must be a constant + @param ppEnv function returns an environment if the environment is session specific, + i.e. has special context + @param pImplName +*/ +typedef void (SAL_CALL * component_getImplementationEnvironmentExtFunc)( + char const ** ppEnvTypeName, + uno_Environment ** ppEnv, + char const * pImplName, + uno_Environment * pTargetEnv +); + +/** Function pointer declaration. + Function retrieves a component description. + + @return an XML formatted string containing a short component description + @deprecated +*/ +typedef const char * (SAL_CALL * component_getDescriptionFunc)(void); + +/** Function pointer declaration. + + @deprecated component_writeInfo should no longer be used in new components + + Function writes component registry info, at least writing the supported service names. + + @param pServiceManager + a service manager (the type is an XMultiServiceFactory that can be used + by the environment returned by component_getImplementationEnvironment) + @param pRegistryKey a registry key + (the type is XRegistryKey that can be used by the environment + returned by component_getImplementationEnvironment) + @return true if everything went fine +*/ +typedef sal_Bool (SAL_CALL * component_writeInfoFunc)( + void * pServiceManager, void * pRegistryKey ); + +/** Function pointer declaration. + Retrieves a factory to create component instances. + + @param pImplName + desired implementation name + @param pServiceManager + a service manager (the type is XMultiServiceFactory that can be used by the environment + returned by component_getImplementationEnvironment) + @param pRegistryKey + a registry key (the type is XRegistryKey that can be used by the environment + returned by component_getImplementationEnvironment) + @return acquired component factory + (the type is lang::XSingleComponentFactory or lang::XSingleServiceFactory to be used by the + environment returned by component_getImplementationEnvironment) +*/ +typedef void * (SAL_CALL * component_getFactoryFunc)( + const char * pImplName, void * pServiceManager, void * pRegistryKey ); + + +namespace cppu +{ + +/** Function pointer declaration. + Function creates component instance passing the component context to be used. + + @param xContext component context to be used + @return component instance +*/ +typedef css::uno::Reference< css::uno::XInterface >( + SAL_CALL * ComponentFactoryFunc)( + css::uno::Reference< css::uno::XComponentContext > const & xContext ); + +/** Creates a single component factory supporting the XSingleComponentFactory interface. + + @param fptr function pointer for instantiating the object + @param rImplementationName implementation name of service + @param rServiceNames supported services + @param pModCount a backwards-compatibility remainder of a removed library + unloading feature; always set to null +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleComponentFactory > +SAL_CALL createSingleComponentFactory( + ComponentFactoryFunc fptr, + ::rtl::OUString const & rImplementationName, + css::uno::Sequence< ::rtl::OUString > const & rServiceNames, + rtl_ModuleCount * pModCount = NULL ); + +/** Creates a single service factory which holds the instance created only once. + + @param fptr function pointer for instantiating the object + @param rImplementationName implementation name of service + @param rServiceNames supported services + @param pModCount a backwards-compatibility remainder of a removed library + unloading feature; always set to null + + @see createSingleComponentFactory +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleComponentFactory > SAL_CALL +createOneInstanceComponentFactory( + ComponentFactoryFunc fptr, + ::rtl::OUString const & rImplementationName, + css::uno::Sequence< ::rtl::OUString > const & rServiceNames, + rtl_ModuleCount * pModCount = NULL ); + +/** Deprecated. The type of the instantiate function used as argument of the create*Factory functions. + + @see createSingleFactory + @see createOneInstanceFactory + @deprecated +*/ +typedef css::uno::Reference< css::uno::XInterface >(SAL_CALL * ComponentInstantiation)( + const css::uno::Reference< css::lang::XMultiServiceFactory > & rServiceManager ); + +/** Deprecated. Creates a single service factory. + + @param rServiceManager the service manager used by the implementation. + @param rImplementationName the implementation name. An empty string is possible. + @param pCreateFunction the function pointer to create an object. + @param rServiceNames the service supported by the implementation. + @param pModCount a backwards-compatibility remainder of a removed library + unloading feature; always set to null. + @return a factory that support the interfaces XServiceProvider, XServiceInfo + XSingleServiceFactory and XComponent. + + @see createOneInstanceFactory + @deprecated +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL +createSingleFactory( + const css::uno::Reference< css::lang::XMultiServiceFactory > & rServiceManager, + const ::rtl::OUString & rImplementationName, + ComponentInstantiation pCreateFunction, + const css::uno::Sequence< ::rtl::OUString > & rServiceNames, + rtl_ModuleCount * pModCount = NULL ); + +/** Deprecated. Creates a factory wrapping another one. + This means the methods of the interfaces XServiceProvider, XServiceInfo and + XSingleServiceFactory are forwarded. + @attention + The XComponent interface is not supported! + + @param rServiceManager the service manager used by the implementation. + @param rFactory the wrapped service factory. + @return a factory that support the interfaces XServiceProvider, XServiceInfo + XSingleServiceFactory. + + @see createSingleFactory + @deprecated +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL +createFactoryProxy( + const css::uno::Reference< css::lang::XMultiServiceFactory > & rServiceManager, + const css::uno::Reference< css::lang::XSingleServiceFactory > & rFactory ); + +/** Deprecated. Creates a single service factory which holds the instance created only once. + + @param rServiceManager the service manager used by the implementation. + @param rComponentName the implementation name. An empty string is possible. + @param pCreateFunction the function pointer to create an object. + @param rServiceNames the service supported by the implementation. + @param pModCount a backwards-compatibility remainder of a removed library + unloading feature; always set to null. + @return a factory that support the interfaces XServiceProvider, XServiceInfo + XSingleServiceFactory and XComponent. + + @see createSingleFactory + @deprecated +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL +createOneInstanceFactory( + const css::uno::Reference< css::lang::XMultiServiceFactory > & rServiceManager, + const ::rtl::OUString & rComponentName, + ComponentInstantiation pCreateFunction, + const css::uno::Sequence< ::rtl::OUString > & rServiceNames, + rtl_ModuleCount * pModCount = NULL ); + +/** Deprecated. Creates a single service factory based on a registry. + + @param rServiceManager the service manager used by the implementation. + @param rImplementationName the implementation name. An empty string is possible. + @param rImplementationKey the registry key of the implementation section. + @return a factory that support the interfaces XServiceProvider, XServiceInfo + XSingleServiceFactory and XComponent. + @deprecated +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL +createSingleRegistryFactory( + const css::uno::Reference< css::lang::XMultiServiceFactory > & rServiceManager, + const ::rtl::OUString & rImplementationName, + const css::uno::Reference< css::registry::XRegistryKey > & rImplementationKey ); + +/** Deprecated. Creates a single service factory which holds the instance created only once + based on a registry. + + @param rServiceManager the service manager used by the implementation. + @param rComponentName the implementation name. An empty string is possible. + @param rImplementationKey the registry key of the implementation section. + @return a factory that support the interfaces XServiceProvider, XServiceInfo + XSingleServiceFactory and XComponent. + + @see createSingleRegistryFactory + @deprecated +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL +createOneInstanceRegistryFactory( + const css::uno::Reference< css::lang::XMultiServiceFactory > & rServiceManager, + const ::rtl::OUString & rComponentName, + const css::uno::Reference< css::registry::XRegistryKey > & rImplementationKey ); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/findsofficepath.h b/include/cppuhelper/findsofficepath.h new file mode 100644 index 000000000..19d031f5b --- /dev/null +++ b/include/cppuhelper/findsofficepath.h @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_FINDSOFFICEPATH_H +#define INCLUDED_CPPUHELPER_FINDSOFFICEPATH_H + +#include "sal/config.h" + +#if defined __cplusplus +extern "C" { +#endif + +/* Internal function to find an soffice installation. + Not to be called by client code. + Returned pointer must be released with free() */ +#if defined(_WIN32) +wchar_t* +#else +char* +#endif +cppuhelper_detail_findSofficePath(void); + +#if defined __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase.hxx b/include/cppuhelper/implbase.hxx new file mode 100644 index 000000000..f2f08650e --- /dev/null +++ b/include/cppuhelper/implbase.hxx @@ -0,0 +1,186 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPUHELPER_IMPLBASE_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE_HXX + +#include "sal/config.h" + +#include +#include + +#include "com/sun/star/lang/XTypeProvider.hpp" +#include "com/sun/star/uno/Any.h" +#include "com/sun/star/uno/Sequence.hxx" +#include "com/sun/star/uno/Type.h" +#include "cppuhelper/implbase_ex.hxx" +#include "cppuhelper/weak.hxx" +#include "rtl/instance.hxx" +#include "sal/types.h" + +#if defined LIBO_INTERNAL_ONLY + +// A replacement for ImplHelperN has deliberately been left out, as ImplHelperN +// is unlikely ever be a better choice than WeakImplHelper, so all their +// existing uses are probably confused and should use WeakImplHelper instead. +// +// Replacements for WeakAggImplHelperN and AggImplInheritanceHelperN have +// deliberately been left out, as the underlying aggregation mechanism is known +// broken in general and should not be used. + +namespace cppu { + +/// @cond INTERNAL + +namespace detail { + +template struct class_dataN { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[16]; + type_entry m_typeEntries[N + 1]; +}; + +template struct ImplClassData { + class_data * operator ()() { + static class_dataN s_cd = { + sizeof... (Ifc) + 1, false, false, {}, + { + { { Ifc::static_type }, + (reinterpret_cast( + static_cast(reinterpret_cast(16))) + - 16) + }..., + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast(&s_cd); + } +}; + +} + +/// @endcond + +/** Implementation helper implementing interfaces + css::uno::XInterface, css::lang::XTypeProvider, and + css::uno::XWeak (through cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as + template argument(s). +*/ +template +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper: + public OWeakObject, public css::lang::XTypeProvider, public Ifc... +{ + struct cd: + rtl::StaticAggregate< + class_data, detail::ImplClassData> + {}; + +protected: + WeakImplHelper() {} + + virtual ~WeakImplHelper() override {} + +public: + WeakImplHelper(WeakImplHelper const &) = default; + WeakImplHelper(WeakImplHelper &&) = default; + WeakImplHelper & operator =(WeakImplHelper const &) = default; + WeakImplHelper & operator =(WeakImplHelper &&) = default; + + css::uno::Any SAL_CALL queryInterface(css::uno::Type const & aType) override + { return WeakImplHelper_query(aType, cd::get(), this, this); } + + void SAL_CALL acquire() SAL_NOEXCEPT override { OWeakObject::acquire(); } + + void SAL_CALL release() SAL_NOEXCEPT override { OWeakObject::release(); } + + css::uno::Sequence SAL_CALL getTypes() override + { return WeakImplHelper_getTypes(cd::get()); } + + css::uno::Sequence SAL_CALL getImplementationId() override + { return css::uno::Sequence(); } +}; + +/** Implementation helper implementing interfaces + css::uno::XInterface and css::lang::XTypeProvider + inheriting from a BaseClass. + + All acquire() and release() calls are delegated to the BaseClass. Upon + queryInterface(), if a demanded interface is not supported by this class + directly, the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in the sense that + css::uno::XInterface and css::lang::XTypeProvider are + implemented properly. + + @derive + Inherit from this class giving your additional interface(s) to be + implemented as template argument(s). +*/ +template +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper: + public BaseClass, public Ifc... +{ + struct cd: + rtl::StaticAggregate< + class_data, detail::ImplClassData> + {}; + +protected: + template ImplInheritanceHelper(Arg &&... arg): + BaseClass(std::forward(arg)...) + {} + + virtual ~ImplInheritanceHelper() {} + +public: + ImplInheritanceHelper(ImplInheritanceHelper const &) = default; + ImplInheritanceHelper(ImplInheritanceHelper &&) = default; + ImplInheritanceHelper & operator =(ImplInheritanceHelper const &) = default; + ImplInheritanceHelper & operator =(ImplInheritanceHelper &&) = default; + + css::uno::Any SAL_CALL queryInterface(css::uno::Type const & aType) override + { + css::uno::Any ret(ImplHelper_queryNoXInterface(aType, cd::get(), this)); + return ret.hasValue() ? ret : BaseClass::queryInterface(aType); + } + + void SAL_CALL acquire() SAL_NOEXCEPT override { BaseClass::acquire(); } + + void SAL_CALL release() SAL_NOEXCEPT override { BaseClass::release(); } + + css::uno::Sequence SAL_CALL getTypes() override + { return ImplInhHelper_getTypes(cd::get(), BaseClass::getTypes()); } + + css::uno::Sequence SAL_CALL getImplementationId() override + { return css::uno::Sequence(); } +}; + +} + +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase1.hxx b/include/cppuhelper/implbase1.hxx new file mode 100644 index 000000000..dc82a7308 --- /dev/null +++ b/include/cppuhelper/implbase1.hxx @@ -0,0 +1,311 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE1_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE1_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data1 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 1 + 1 ]; + }; + + template< typename Ifc1, typename Impl > struct SAL_WARN_UNUSED ImplClassData1 + { + class_data* operator ()() + { + static class_data1 s_cd = + { + 1 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper1 + : public css::lang::XTypeProvider + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1 < Ifc1, ImplHelper1 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper1() = default; + ImplHelper1(ImplHelper1 const &) = default; + ImplHelper1(ImplHelper1 &&) = default; + ImplHelper1 & operator =(ImplHelper1 const &) = default; + ImplHelper1 & operator =(ImplHelper1 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper1() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + + These classes are used when you implement your UNO component. + WeakImplHelper1 till WeakImplHelper12 can be used when you want + to implement 1 till 12 interfaces in your component. + */ + template< class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE SAL_DLLPUBLIC_EXPORT WeakImplHelper1 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, WeakImplHelper1< Ifc1 > > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper1 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, WeakAggImplHelper1< Ifc1 > > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper1 + : public BaseClass + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, ImplInheritanceHelper1< BaseClass, Ifc1 > > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper1(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper1(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper1() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper1 + : public BaseClass + , public Ifc1 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData1< Ifc1, AggImplInheritanceHelper1< BaseClass, Ifc1 > > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper1(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper1(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper1( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper1() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase10.hxx b/include/cppuhelper/implbase10.hxx new file mode 100644 index 000000000..e3938563d --- /dev/null +++ b/include/cppuhelper/implbase10.hxx @@ -0,0 +1,317 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE10_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE10_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data10 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 10 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Ifc8, typename Ifc9, typename Ifc10, typename Impl > + struct SAL_WARN_UNUSED ImplClassData10 + { + class_data* operator ()() + { + static class_data10 s_cd = + { + 10 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc8), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc9), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc10), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper10 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, ImplHelper10 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper10() = default; + ImplHelper10(ImplHelper10 const &) = default; + ImplHelper10(ImplHelper10 &&) = default; + ImplHelper10 & operator =(ImplHelper10 const &) = default; + ImplHelper10 & operator =(ImplHelper10 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper10() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper10 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, WeakImplHelper10 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper10 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, WeakAggImplHelper10 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper10 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, ImplInheritanceHelper10 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper10(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper10(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper10() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper10 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData10< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, AggImplInheritanceHelper10 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper10(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper10(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper10( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper10() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase11.hxx b/include/cppuhelper/implbase11.hxx new file mode 100644 index 000000000..02fad9040 --- /dev/null +++ b/include/cppuhelper/implbase11.hxx @@ -0,0 +1,318 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE11_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE11_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data11 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 11 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Ifc8, typename Ifc9, typename Ifc10, typename Ifc11, typename Impl > + struct SAL_WARN_UNUSED ImplClassData11 + { + class_data* operator ()() + { + static class_data11 s_cd = + { + 11 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc8), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc9), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc10), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc11), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper11 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, ImplHelper11 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper11() = default; + ImplHelper11(ImplHelper11 const &) = default; + ImplHelper11(ImplHelper11 &&) = default; + ImplHelper11 & operator =(ImplHelper11 const &) = default; + ImplHelper11 & operator =(ImplHelper11 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper11() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper11 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, WeakImplHelper11 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper11 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, WeakAggImplHelper11 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper11 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, ImplInheritanceHelper11 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper11(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper11(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper11() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper11 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData11< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, AggImplInheritanceHelper11 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper11(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper11(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper11( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper11() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase12.hxx b/include/cppuhelper/implbase12.hxx new file mode 100644 index 000000000..df90f2b64 --- /dev/null +++ b/include/cppuhelper/implbase12.hxx @@ -0,0 +1,319 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE12_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE12_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data12 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 12 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Ifc8, typename Ifc9, typename Ifc10, typename Ifc11, typename Ifc12, typename Impl > + struct SAL_WARN_UNUSED ImplClassData12 + { + class_data* operator ()() + { + static class_data12 s_cd = + { + 12 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc8), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc9), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc10), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc11), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc12), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper12 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, ImplHelper12 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper12() = default; + ImplHelper12(ImplHelper12 const &) = default; + ImplHelper12(ImplHelper12 &&) = default; + ImplHelper12 & operator =(ImplHelper12 const &) = default; + ImplHelper12 & operator =(ImplHelper12 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper12() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper12 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, WeakImplHelper12 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper12 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, WeakAggImplHelper12 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper12 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, ImplInheritanceHelper12 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper12(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper12(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper12() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper12 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData12< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, AggImplInheritanceHelper12 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper12(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper12(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper12( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper12() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase13.hxx b/include/cppuhelper/implbase13.hxx new file mode 100644 index 000000000..5ed124597 --- /dev/null +++ b/include/cppuhelper/implbase13.hxx @@ -0,0 +1,320 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE13_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE13_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data13 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 13 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Ifc8, typename Ifc9, typename Ifc10, typename Ifc11, typename Ifc12, typename Ifc13, typename Impl > + struct SAL_WARN_UNUSED ImplClassData13 + { + class_data* operator ()() + { + static class_data13 s_cd = + { + 13 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc8), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc9), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc10), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc11), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc12), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc13), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12, class Ifc13 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper13 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12, public Ifc13 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData13< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, Ifc13, ImplHelper13 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper13() = default; + ImplHelper13(ImplHelper13 const &) = default; + ImplHelper13(ImplHelper13 &&) = default; + ImplHelper13 & operator =(ImplHelper13 const &) = default; + ImplHelper13 & operator =(ImplHelper13 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper13() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12, class Ifc13 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper13 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12, public Ifc13 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData13< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, Ifc13, WeakImplHelper13 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12, class Ifc13 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper13 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12, public Ifc13 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData13< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, Ifc13, WeakAggImplHelper13 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12, class Ifc13 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper13 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12, public Ifc13 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData13< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, Ifc13, ImplInheritanceHelper13 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper13(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper13(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper13() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9, class Ifc10, class Ifc11, class Ifc12, class Ifc13 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper13 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9, public Ifc10, public Ifc11, public Ifc12, public Ifc13 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData13< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, Ifc10, Ifc11, Ifc12, Ifc13, AggImplInheritanceHelper13 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper13(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper13(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper13( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper13() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase2.hxx b/include/cppuhelper/implbase2.hxx new file mode 100644 index 000000000..d6b326122 --- /dev/null +++ b/include/cppuhelper/implbase2.hxx @@ -0,0 +1,308 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE2_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE2_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data2 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 2 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Impl > struct SAL_WARN_UNUSED ImplClassData2 + { + class_data* operator ()() + { + static class_data2 s_cd = + { + 2 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your base class defines method implementations, acquire(), release() and delegates incoming + queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper2 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, ImplHelper2 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper2() = default; + ImplHelper2(ImplHelper2 const &) = default; + ImplHelper2(ImplHelper2 &&) = default; + ImplHelper2 & operator =(ImplHelper2 const &) = default; + ImplHelper2 & operator =(ImplHelper2 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper2() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE SAL_DLLPUBLIC_EXPORT WeakImplHelper2 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, WeakImplHelper2 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper2 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, WeakAggImplHelper2 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper2 + : public BaseClass + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, ImplInheritanceHelper2 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper2(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper2(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper2() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper2 + : public BaseClass + , public Ifc1, public Ifc2 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData2 < Ifc1, Ifc2, AggImplInheritanceHelper2 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper2(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper2(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper2( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper2() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase3.hxx b/include/cppuhelper/implbase3.hxx new file mode 100644 index 000000000..7c95ef596 --- /dev/null +++ b/include/cppuhelper/implbase3.hxx @@ -0,0 +1,310 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE3_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE3_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data3 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 3 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Impl > struct SAL_WARN_UNUSED ImplClassData3 + { + class_data* operator ()() + { + static class_data3 s_cd = + { + 3 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper3 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, ImplHelper3 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper3() = default; + ImplHelper3(ImplHelper3 const &) = default; + ImplHelper3(ImplHelper3 &&) = default; + ImplHelper3 & operator =(ImplHelper3 const &) = default; + ImplHelper3 & operator =(ImplHelper3 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper3() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper3 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, WeakImplHelper3 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper3 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, WeakAggImplHelper3 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + also has to have a default ctor. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper3 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, ImplInheritanceHelper3 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper3(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper3(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper3() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper3 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData3 < Ifc1, Ifc2, Ifc3, AggImplInheritanceHelper3 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper3(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper3(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper3( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper3() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase4.hxx b/include/cppuhelper/implbase4.hxx new file mode 100644 index 000000000..61bce6722 --- /dev/null +++ b/include/cppuhelper/implbase4.hxx @@ -0,0 +1,311 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE4_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE4_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data4 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 4 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Impl > + struct SAL_WARN_UNUSED ImplClassData4 + { + class_data* operator ()() + { + static class_data4 s_cd = + { + 4 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper4 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, ImplHelper4 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper4() = default; + ImplHelper4(ImplHelper4 const &) = default; + ImplHelper4(ImplHelper4 &&) = default; + ImplHelper4 & operator =(ImplHelper4 const &) = default; + ImplHelper4 & operator =(ImplHelper4 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper4() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper4 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, WeakImplHelper4 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper4 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, WeakAggImplHelper4 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper4 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, ImplInheritanceHelper4 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper4(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper4(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper4() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper4 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData4 < Ifc1, Ifc2, Ifc3, Ifc4, AggImplInheritanceHelper4 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper4(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper4(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper4( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper4() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase5.hxx b/include/cppuhelper/implbase5.hxx new file mode 100644 index 000000000..993c71a17 --- /dev/null +++ b/include/cppuhelper/implbase5.hxx @@ -0,0 +1,312 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE5_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE5_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data5 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 5 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Impl > + struct SAL_WARN_UNUSED ImplClassData5 + { + class_data* operator ()() + { + static class_data5 s_cd = + { + 5 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper5 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, ImplHelper5 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper5() = default; + ImplHelper5(ImplHelper5 const &) = default; + ImplHelper5(ImplHelper5 &&) = default; + ImplHelper5 & operator =(ImplHelper5 const &) = default; + ImplHelper5 & operator =(ImplHelper5 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper5() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak thru ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper5 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakImplHelper5 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak thru ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation thru ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper5 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, WeakAggImplHelper5 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper5 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, ImplInheritanceHelper5 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper5(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper5(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper5() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper5 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData5 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, AggImplInheritanceHelper5 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper5(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper5(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper5( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper5() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase6.hxx b/include/cppuhelper/implbase6.hxx new file mode 100644 index 000000000..8adb7549d --- /dev/null +++ b/include/cppuhelper/implbase6.hxx @@ -0,0 +1,313 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE6_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE6_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data6 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 6 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Impl > + struct SAL_WARN_UNUSED ImplClassData6 + { + class_data* operator ()() + { + static class_data6 s_cd = + { + 6 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper6 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, ImplHelper6 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper6() = default; + ImplHelper6(ImplHelper6 const &) = default; + ImplHelper6(ImplHelper6 &&) = default; + ImplHelper6 & operator =(ImplHelper6 const &) = default; + ImplHelper6 & operator =(ImplHelper6 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper6() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper6 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, WeakImplHelper6 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper6 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, WeakAggImplHelper6 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper6 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, ImplInheritanceHelper6 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper6(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper6(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper6() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper6 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData6 < Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, AggImplInheritanceHelper6 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper6(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper6(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper6( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper6() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase7.hxx b/include/cppuhelper/implbase7.hxx new file mode 100644 index 000000000..305c94d4b --- /dev/null +++ b/include/cppuhelper/implbase7.hxx @@ -0,0 +1,314 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE7_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE7_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data7 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 7 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Impl > + struct SAL_WARN_UNUSED ImplClassData7 + { + class_data* operator ()() + { + static class_data7 s_cd = + { + 7 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper7 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, ImplHelper7 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper7() = default; + ImplHelper7(ImplHelper7 const &) = default; + ImplHelper7(ImplHelper7 &&) = default; + ImplHelper7 & operator =(ImplHelper7 const &) = default; + ImplHelper7 & operator =(ImplHelper7 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper7() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper7 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, WeakImplHelper7 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper7 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, WeakAggImplHelper7 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper7 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, ImplInheritanceHelper7 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper7(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper7(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper7() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper7 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData7< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, AggImplInheritanceHelper7 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper7(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper7(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper7( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper7() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase8.hxx b/include/cppuhelper/implbase8.hxx new file mode 100644 index 000000000..a0903f1b5 --- /dev/null +++ b/include/cppuhelper/implbase8.hxx @@ -0,0 +1,315 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE8_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE8_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data8 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 8 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Ifc8, typename Impl > + struct SAL_WARN_UNUSED ImplClassData8 + { + class_data* operator ()() + { + static class_data8 s_cd = + { + 8 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc8), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper8 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, ImplHelper8 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper8() = default; + ImplHelper8(ImplHelper8 const &) = default; + ImplHelper8(ImplHelper8 &&) = default; + ImplHelper8 & operator =(ImplHelper8 const &) = default; + ImplHelper8 & operator =(ImplHelper8 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper8() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper8 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, WeakImplHelper8 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper8 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, WeakAggImplHelper8 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper8 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, ImplInheritanceHelper8 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper8(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper8(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper8() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper8 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData8< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, AggImplInheritanceHelper8 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper8(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper8(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper8( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper8() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase9.hxx b/include/cppuhelper/implbase9.hxx new file mode 100644 index 000000000..75840ec80 --- /dev/null +++ b/include/cppuhelper/implbase9.hxx @@ -0,0 +1,316 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE9_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE9_HXX + +#include "cppuhelper/implbase_ex.hxx" +#include "rtl/instance.hxx" +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakagg.hxx" +#include "com/sun/star/lang/XTypeProvider.hpp" + +namespace cppu +{ + /// @cond INTERNAL + + struct class_data9 + { + sal_Int16 m_nTypes; + sal_Bool m_storedTypeRefs; + sal_Bool m_storedId; + sal_Int8 m_id[ 16 ]; + type_entry m_typeEntries[ 9 + 1 ]; + }; + + template< typename Ifc1, typename Ifc2, typename Ifc3, typename Ifc4, typename Ifc5, typename Ifc6, typename Ifc7, typename Ifc8, typename Ifc9, typename Impl > + struct SAL_WARN_UNUSED ImplClassData9 + { + class_data* operator ()() + { + static class_data9 s_cd = + { + 9 +1, false, false, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { + CPPUHELPER_DETAIL_TYPEENTRY(Ifc1), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc2), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc3), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc4), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc5), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc6), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc7), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc8), + CPPUHELPER_DETAIL_TYPEENTRY(Ifc9), + CPPUHELPER_DETAIL_TYPEENTRY(css::lang::XTypeProvider) + } + }; + return reinterpret_cast< class_data * >(&s_cd); + } + }; + + /// @endcond + + /** Implementation helper implementing interface css::lang::XTypeProvider + and method XInterface::queryInterface(), but no reference counting. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s) including acquire()/ + release() and delegates incoming queryInterface() calls to this base class. + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper9 + : public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, ImplHelper9 > > {}; + public: +#if defined LIBO_INTERNAL_ONLY + ImplHelper9() = default; + ImplHelper9(ImplHelper9 const &) = default; + ImplHelper9(ImplHelper9 &&) = default; + ImplHelper9 & operator =(ImplHelper9 const &) = default; + ImplHelper9 & operator =(ImplHelper9 &&) = default; +#endif + + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return ImplHelper_query( rType, cd::get(), this ); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + +#if !defined _MSC_VER // public -> protected changes mangled names there + protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~ImplHelper9() SAL_NOEXCEPT {} +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakObject). + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper9 + : public OWeakObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, WeakImplHelper9 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakImplHelper_query( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface which supports weak mechanism to be held weakly + (supporting css::uno::XWeak through ::cppu::OWeakAggObject). + In addition, it supports also aggregation meaning object of this class can be aggregated + (css::uno::XAggregation through ::cppu::OWeakAggObject). + If a delegator is set (this object is aggregated), then incoming queryInterface() + calls are delegated to the delegator object. If the delegator does not support the + demanded interface, it calls queryAggregation() on its aggregated objects. + + @derive + Inherit from this class giving your interface(s) to be implemented as template argument(s). + Your sub class defines method implementations for these interface(s). + */ + template< class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper9 + : public OWeakAggObject + , public css::lang::XTypeProvider + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, WeakAggImplHelper9 > > {}; + public: + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return OWeakAggObject::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { return WeakAggImplHelper_queryAgg( rType, cd::get(), this, static_cast(this) ); } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { OWeakAggObject::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return WeakAggImplHelper_getTypes( cd::get() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire() and release() calls are delegated to the BaseClass. Upon queryInterface(), + if a demanded interface is not supported by this class directly, the request is + delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface + and css::lang::XTypeProvider are implemented properly. The + BaseClass must have at least one ctor that can be called with six or + fewer arguments, of which none is of non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper9 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, ImplInheritanceHelper9 > > {}; + protected: + template< typename T1 > + explicit ImplInheritanceHelper9(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + ImplInheritanceHelper9(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + ImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + ImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + ImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + ImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + ImplInheritanceHelper9() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryInterface( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; + /** Implementation helper implementing interfaces css::lang::XTypeProvider and + css::uno::XInterface inheriting from a BaseClass. + All acquire(), release() and queryInterface() calls are delegated to the BaseClass. + Upon queryAggregation(), if a demanded interface is not supported by this class directly, + the request is delegated to the BaseClass. + + @attention + The BaseClass has to be complete in a sense, that css::uno::XInterface, + css::uno::XAggregation and css::lang::XTypeProvider + are implemented properly. The BaseClass must have at least one ctor + that can be called with six or fewer arguments, of which none is of + non-const reference type. + + @derive + Inherit from this class giving your additional interface(s) to be implemented as + template argument(s). Your sub class defines method implementations for these interface(s). + */ + template< class BaseClass, class Ifc1, class Ifc2, class Ifc3, class Ifc4, class Ifc5, class Ifc6, class Ifc7, class Ifc8, class Ifc9 > + class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper9 + : public BaseClass + , public Ifc1, public Ifc2, public Ifc3, public Ifc4, public Ifc5, public Ifc6, public Ifc7, public Ifc8, public Ifc9 + { + struct cd : public rtl::StaticAggregate< class_data, ImplClassData9< Ifc1, Ifc2, Ifc3, Ifc4, Ifc5, Ifc6, Ifc7, Ifc8, Ifc9, AggImplInheritanceHelper9 > > {}; + protected: + template< typename T1 > + explicit AggImplInheritanceHelper9(T1 const & arg1): BaseClass(arg1) {} + template< typename T1, typename T2 > + AggImplInheritanceHelper9(T1 const & arg1, T2 const & arg2): + BaseClass(arg1, arg2) {} + template< typename T1, typename T2, typename T3 > + AggImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3): + BaseClass(arg1, arg2, arg3) {} + template< typename T1, typename T2, typename T3, typename T4 > + AggImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4): + BaseClass(arg1, arg2, arg3, arg4) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5 > + AggImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5): + BaseClass(arg1, arg2, arg3, arg4, arg5) {} + template< + typename T1, typename T2, typename T3, typename T4, typename T5, + typename T6 > + AggImplInheritanceHelper9( + T1 const & arg1, T2 const & arg2, T3 const & arg3, T4 const & arg4, + T5 const & arg5, T6 const & arg6): + BaseClass(arg1, arg2, arg3, arg4, arg5, arg6) {} + public: + AggImplInheritanceHelper9() {} + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE + { return BaseClass::queryInterface( rType ); } + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE + { + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, cd::get(), this ) ); + if (aRet.hasValue()) + return aRet; + return BaseClass::queryAggregation( rType ); + } + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::acquire(); } + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE + { BaseClass::release(); } + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE + { return ImplInhHelper_getTypes( cd::get(), BaseClass::getTypes() ); } + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE + { return ImplHelper_getImplementationId( cd::get() ); } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase_ex.hxx b/include/cppuhelper/implbase_ex.hxx new file mode 100644 index 000000000..e9e31bbdb --- /dev/null +++ b/include/cppuhelper/implbase_ex.hxx @@ -0,0 +1,167 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE_EX_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE_EX_HXX + +#include "com/sun/star/uno/Any.h" +#include "com/sun/star/uno/Sequence.h" +#include "com/sun/star/uno/Type.h" +#include "com/sun/star/uno/genfunc.h" +#include "cppuhelper/cppuhelperdllapi.h" +#include "sal/types.h" + +namespace cppu { class OWeakAggObject; } +namespace cppu { class OWeakObject; } + + +/* If you need to define implementation helper classes that deal with more than + 12 interfaces, then use macros as follows, e.g. for 3 interfaces: + +#include +#define __IFC_EX_TYPE_INIT3( class_cast ) \ + __IFC_EX_TYPE_INIT( class_cast, 1 ), __IFC_EX_TYPE_INIT( class_cast, 2 ), \ + __IFC_EX_TYPE_INIT( class_cast, 3 ) +#include +__DEF_IMPLHELPER_EX( 3 ) +*/ + +/// @cond INTERNAL + +namespace cppu +{ + +/** function pointer signature for getCppuType +*/ +typedef css::uno::Type const & (SAL_CALL * fptr_getCppuType)( void * ); + +/** single type + object offset +*/ +struct SAL_WARN_UNUSED type_entry +{ + /** the type_entry is initialized with function pointer to ::getCppuType() function first, + but holds an unacquired typelib_TypeDescriptionReference * after initialization, + thus reusing the memory. Flag class_data::m_storedTypeRefs + */ + union + { + fptr_getCppuType getCppuType; + typelib_TypeDescriptionReference * typeRef; + } m_type; + /** offset for interface pointer + */ + sal_IntPtr m_offset; +}; + +/** in the future, this can be a constexpr template method */ +#define CPPUHELPER_DETAIL_TYPEENTRY(Ifc) \ + { { Ifc::static_type }, \ + reinterpret_cast( static_cast( reinterpret_cast(16) )) - 16 } + +/** identical dummy struct for casting class_dataN to class_data +*/ +struct SAL_WARN_UNUSED class_data +{ + /** number of supported types in m_typeEntries + */ + sal_Int16 m_nTypes; + + /** determines whether m_typeEntries is initialized and carries unacquired type refs + */ + sal_Bool m_storedTypeRefs; + + /** determines whether an implementation id was created in m_id + */ + sal_Bool m_createdId; + + /** implementation id + */ + sal_Int8 m_id[ 16 ]; + + /** type, object offset + */ + type_entry m_typeEntries[ 1 ]; +}; + +/** ImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any SAL_CALL ImplHelper_query( + css::uno::Type const & rType, + class_data * cd, + void * that ); +/** ImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any SAL_CALL ImplHelper_queryNoXInterface( + css::uno::Type const & rType, + class_data * cd, + void * that ); +/** ImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< css::uno::Type > +SAL_CALL ImplHelper_getTypes( + class_data * cd ); +/** ImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< css::uno::Type > +SAL_CALL ImplInhHelper_getTypes( + class_data * cd, + css::uno::Sequence< css::uno::Type > const & rAddTypes ); +/** ImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< sal_Int8 > +SAL_CALL ImplHelper_getImplementationId( + class_data * cd ); + +/** WeakImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any SAL_CALL WeakImplHelper_query( + css::uno::Type const & rType, + class_data * cd, + void * that, + ::cppu::OWeakObject * pBase ); +/** WeakImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< css::uno::Type > +SAL_CALL WeakImplHelper_getTypes( + class_data * cd ); + +/** WeakAggImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Any +SAL_CALL WeakAggImplHelper_queryAgg( + css::uno::Type const & rType, + class_data * cd, + void * that, + ::cppu::OWeakAggObject * pBase ); +/** WeakAggImplHelper +*/ +CPPUHELPER_DLLPUBLIC css::uno::Sequence< css::uno::Type > +SAL_CALL WeakAggImplHelper_getTypes( + class_data * cd ); + +} + +/// @endcond + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase_ex_post.hxx b/include/cppuhelper/implbase_ex_post.hxx new file mode 100644 index 000000000..d1a51c9eb --- /dev/null +++ b/include/cppuhelper/implbase_ex_post.hxx @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE_EX_POST_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE_EX_POST_HXX + +/// @cond INTERNAL + +#define __DEF_CLASS_DATA_INIT_EX( N, class_cast ) \ +{ \ +N +1, sal_False, sal_False, \ +{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, \ +{ \ +__IFC_EX_TYPE_INIT##N( class_cast ), \ +__IFC_EX_TYPE_INIT_NAME( class_cast, css::lang::XTypeProvider ) \ +} \ +} + +#define __DEF_IMPLHELPER_EX( N ) \ +namespace cppu \ +{ \ +struct class_data##N \ +{ \ + sal_Int16 m_nTypes; \ + sal_Bool m_storedTypeRefs; \ + sal_Bool m_storedId; \ + sal_Int8 m_id[ 16 ]; \ + type_entry m_typeEntries[ N + 1 ]; \ +}; \ +template< __CLASS_IFC##N > \ +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplHelper##N \ + : public css::lang::XTypeProvider \ + , __PUBLIC_IFC##N \ +{ \ + static class_data##N s_cd; \ +public: \ + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE \ + { return ImplHelper_query( rType, (class_data *)&s_cd, this ); } \ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE \ + { return ImplHelper_getTypes( (class_data *)&s_cd ); } \ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE \ + { return ImplHelper_getImplementationId( (class_data *)&s_cd ); } \ +}; \ +template< __CLASS_IFC##N > \ +class_data##N ImplHelper##N< __IFC##N >::s_cd = \ +__DEF_CLASS_DATA_INIT_EX( N, (ImplHelper##N< __IFC##N > *) ); \ +template< __CLASS_IFC##N > \ +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakImplHelper##N \ + : public OWeakObject \ + , public css::lang::XTypeProvider \ + , __PUBLIC_IFC##N \ +{ \ + static class_data##N s_cd; \ +public: \ + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE \ + { return WeakImplHelper_query( rType, (class_data *)&s_cd, this, static_cast(this) ); } \ + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE \ + { OWeakObject::acquire(); } \ + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE \ + { OWeakObject::release(); } \ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE \ + { return WeakImplHelper_getTypes( (class_data *)&s_cd ); } \ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE \ + { return ImplHelper_getImplementationId( (class_data *)&s_cd ); } \ +}; \ +template< __CLASS_IFC##N > \ +class_data##N WeakImplHelper##N< __IFC##N >::s_cd = \ +__DEF_CLASS_DATA_INIT_EX( N, (WeakImplHelper##N< __IFC##N > *) ); \ +template< __CLASS_IFC##N > \ +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE WeakAggImplHelper##N \ + : public OWeakAggObject \ + , public css::lang::XTypeProvider \ + , __PUBLIC_IFC##N \ +{ \ + static class_data##N s_cd; \ +public: \ + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) SAL_OVERRIDE \ + { return OWeakAggObject::queryInterface( rType ); } \ + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) SAL_OVERRIDE \ + { return WeakAggImplHelper_queryAgg( rType, (class_data *)&s_cd, this, static_cast(this) ); } \ + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE \ + { OWeakAggObject::acquire(); } \ + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE \ + { OWeakAggObject::release(); } \ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() SAL_OVERRIDE \ + { return WeakAggImplHelper_getTypes( (class_data *)&s_cd ); } \ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() SAL_OVERRIDE \ + { return ImplHelper_getImplementationId( (class_data *)&s_cd ); } \ +}; \ +template< __CLASS_IFC##N > \ +class_data##N WeakAggImplHelper##N< __IFC##N >::s_cd = \ +__DEF_CLASS_DATA_INIT_EX( N, (WeakAggImplHelper##N< __IFC##N > *) ); \ +template< class BaseClass, __CLASS_IFC##N > \ +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE ImplInheritanceHelper##N \ + : public BaseClass \ + , __PUBLIC_IFC##N \ +{ \ + static class_data##N s_cd; \ +public: \ + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) \ + { \ + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, (class_data *)&s_cd, this ) ); \ + if (aRet.hasValue()) \ + return aRet; \ + return BaseClass::queryInterface( rType ); \ + } \ + virtual void SAL_CALL acquire() SAL_NOEXCEPT \ + { BaseClass::acquire(); } \ + virtual void SAL_CALL release() SAL_NOEXCEPT \ + { BaseClass::release(); } \ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() \ + { return ImplInhHelper_getTypes( (class_data *)&s_cd, BaseClass::getTypes() ); } \ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() \ + { return ImplHelper_getImplementationId( (class_data *)&s_cd ); } \ +}; \ +template< class BaseClass, __CLASS_IFC##N > \ +class_data##N ImplInheritanceHelper##N< BaseClass, __IFC##N >::s_cd = \ +__DEF_CLASS_DATA_INIT_EX( N, (ImplInheritanceHelper##N< BaseClass, __IFC##N > *) ); \ +template< class BaseClass, __CLASS_IFC##N > \ +class SAL_NO_VTABLE SAL_DLLPUBLIC_TEMPLATE AggImplInheritanceHelper##N \ + : public BaseClass \ + , __PUBLIC_IFC##N \ +{ \ + static class_data##N s_cd; \ +public: \ + virtual css::uno::Any SAL_CALL queryInterface( css::uno::Type const & rType ) \ + { return BaseClass::queryInterface( rType ); } \ + virtual css::uno::Any SAL_CALL queryAggregation( css::uno::Type const & rType ) \ + { \ + css::uno::Any aRet( ImplHelper_queryNoXInterface( rType, (class_data *)&s_cd, this ) ); \ + if (aRet.hasValue()) \ + return aRet; \ + return BaseClass::queryAggregation( rType ); \ + } \ + virtual void SAL_CALL acquire() SAL_NOEXCEPT \ + { BaseClass::acquire(); } \ + virtual void SAL_CALL release() SAL_NOEXCEPT \ + { BaseClass::release(); } \ + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() \ + { return ImplInhHelper_getTypes( (class_data *)&s_cd, BaseClass::getTypes() ); } \ + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() \ + { return ImplHelper_getImplementationId( (class_data *)&s_cd ); } \ +}; \ +template< class BaseClass, __CLASS_IFC##N > \ +class_data##N AggImplInheritanceHelper##N< BaseClass, __IFC##N >::s_cd = \ +__DEF_CLASS_DATA_INIT_EX( N, (AggImplInheritanceHelper##N< BaseClass, __IFC##N > *) ); \ +} + +/// @endcond + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implbase_ex_pre.hxx b/include/cppuhelper/implbase_ex_pre.hxx new file mode 100644 index 000000000..f64e7f056 --- /dev/null +++ b/include/cppuhelper/implbase_ex_pre.hxx @@ -0,0 +1,37 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLBASE_EX_PRE_HXX +#define INCLUDED_CPPUHELPER_IMPLBASE_EX_PRE_HXX + +/// @cond INTERNAL + +#define __IFC_EX_TYPE_INIT_NAME( class_cast, ifc_name ) \ +{ { ifc_name::static_type }, ((sal_IntPtr)(ifc_name *) class_cast 16) - 16 } + +#define __IFC_EX_TYPE_INIT( class_cast, N ) __IFC_EX_TYPE_INIT_NAME( class_cast, Ifc##N ) + +/// @endcond + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/implementationentry.hxx b/include/cppuhelper/implementationentry.hxx new file mode 100644 index 000000000..b99460014 --- /dev/null +++ b/include/cppuhelper/implementationentry.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_IMPLEMENTATIONENTRY_HXX +#define INCLUDED_CPPUHELPER_IMPLEMENTATIONENTRY_HXX + +#include "cppuhelper/factory.hxx" +#include "cppuhelper/cppuhelperdllapi.h" + +namespace cppu +{ +/** One struct instance represents all data necessary for registering one service implementation. + + */ +struct SAL_WARN_UNUSED ImplementationEntry +{ + /** Function that creates an instance of the implementation + */ + ComponentFactoryFunc create; + + /** Function that returns the implementation-name of the implementation + (same as XServiceInfo.getImplementationName() ). + */ + rtl::OUString (SAL_CALL * getImplementationName)(); + + /** Function that returns all supported servicenames of the implementation + ( same as XServiceInfo.getSupportedServiceNames() ). + */ + css::uno::Sequence< rtl::OUString > (SAL_CALL * getSupportedServiceNames) (); + + /** Function that creates a SingleComponentFactory. + + The pModCount parameter is a backwards-compatibility remainder of a + removed library unloading feature; always set to null. + */ + css::uno::Reference< css::lang::XSingleComponentFactory > + (SAL_CALL * createFactory)( + ComponentFactoryFunc fptr, + ::rtl::OUString const & rImplementationName, + css::uno::Sequence< ::rtl::OUString > const & rServiceNames, + rtl_ModuleCount * pModCount ); + + /** Backwards-compatibility remainder of a removed library unloading + feature; always set to null. + */ + rtl_ModuleCount * moduleCounter; + + /** Must be set to 0 ! + For future extensions. + */ + sal_Int32 nFlags; +}; + +/** Helper function for implementation of the component_writeInfo()-function. + + @deprecated component_writeInfo should no longer be used in new components + + @param pServiceManager The first parameter passed to component_writeInfo()-function + (This is an instance of the service manager, that creates the factory). + @param pRegistryKey The second parameter passed to the component_writeInfo()-function. + This is a reference to the registry key, into which the implementation + data shall be written to. + @param entries Each element of the entries-array must contains a function pointer + table for registering an implementation. The end of the array + must be marked with a 0 entry in the create-function. + @return sal_True, if all implementations could be registered, otherwise sal_False. + */ +CPPUHELPER_DLLPUBLIC sal_Bool component_writeInfoHelper( + void *pServiceManager, void *pRegistryKey , const struct ImplementationEntry entries[] ); + +/** Helper function for implementation of the component_getFactory()-function, + that must be implemented by every shared library component. + + @param pImplName The implementation-name to be instantiated ( This is the + first parameter passed to the component_getFactory + @param pServiceManager The second parameter passed to component_getFactory()-function + (This is a of the service manager, that creates the factory). + @param pRegistryKey The third parameter passed to the component_getFactory()-function. + This is a reference to the registry key, where the implementation + data has been written to. + @param entries Each element of the entries-array must contains a function pointer + table for creating a factor of the implementation. The end of the array + must be marked with a 0 entry in the create-function. + @return 0 if the helper failed to instantiate a factory, otherwise an acquired pointer + to a factory. + */ +CPPUHELPER_DLLPUBLIC void *component_getFactoryHelper( + const char * pImplName, + void * pServiceManager, + void * pRegistryKey, + const struct ImplementationEntry entries[] ); + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/interfacecontainer.h b/include/cppuhelper/interfacecontainer.h new file mode 100644 index 000000000..d901b2db3 --- /dev/null +++ b/include/cppuhelper/interfacecontainer.h @@ -0,0 +1,614 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_INTERFACECONTAINER_H +#define INCLUDED_CPPUHELPER_INTERFACECONTAINER_H + +#include "sal/config.h" + +#include +#include +#include +#include + +#include "osl/diagnose.h" +#include "osl/mutex.hxx" +#include "rtl/alloc.h" +#include "com/sun/star/uno/Sequence.hxx" +#include "com/sun/star/lang/EventObject.hpp" + +#include "com/sun/star/lang/DisposedException.hpp" +#include "cppuhelper/cppuhelperdllapi.h" + +namespace com { namespace sun { namespace star { namespace uno { class XInterface; } } } } + +namespace cppu +{ + +namespace detail { + + /** + This is here to optimise space in the common case that there are zero or one + listeners. + */ + union element_alias + { + std::vector< css::uno::Reference< css::uno::XInterface > > *pAsVector; + css::uno::XInterface * pAsInterface; + element_alias() : pAsInterface(NULL) {} + }; + +} + + +class OInterfaceContainerHelper; +/** + This is the iterator of an InterfaceContainerHelper. Typically + one constructs an instance on the stack for one firing session. + It is not allowed to assign or copy an instance of this class. + + @see OInterfaceContainerHelper + */ +class CPPUHELPER_DLLPUBLIC OInterfaceIteratorHelper +{ +public: + /** + Create an iterator over the elements of the container. The iterator + copies the elements of the container. A change to the container + during the lifetime of an iterator is allowed and does not + affect the iterator-instance. The iterator and the container take cares + themself for concurrent access, no additional guarding is necessary. + + Remark: The copy is on demand. The iterator copy the elements only if the container + change the contents. It is not allowed to destroy the container as long + as an iterator exist. + + @param rCont the container of the elements. + */ + OInterfaceIteratorHelper( OInterfaceContainerHelper & rCont ); + + /** + Releases the connection to the container. + */ + ~OInterfaceIteratorHelper(); + + /** Return true, if there are more elements in the iterator. */ + bool SAL_CALL hasMoreElements() const + { return nRemain != 0; } + /** Return the next element of the iterator. Calling this method if + hasMoreElements() has returned false, is an error. Cast the + returned pointer to the + */ + css::uno::XInterface * SAL_CALL next(); + + /** Removes the current element (the last one returned by next()) + from the underlying container. Calling this method before + next() has been called or calling it twice with no next() + inbetween is an error. + */ + void SAL_CALL remove(); + +private: + OInterfaceContainerHelper & rCont; + sal_Bool bIsList; + + detail::element_alias aData; + + sal_Int32 nRemain; + + OInterfaceIteratorHelper( const OInterfaceIteratorHelper & ) + SAL_DELETED_FUNCTION; + OInterfaceIteratorHelper & operator = ( const OInterfaceIteratorHelper & ) + SAL_DELETED_FUNCTION; +}; + + +/** + A container of interfaces. To access the elements use an iterator. + This implementation is thread save. + + @see OInterfaceIteratorHelper + */ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC OInterfaceContainerHelper +{ +public: + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + /** + Create an interface container. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + OInterfaceContainerHelper( ::osl::Mutex & rMutex ); + /** + Release all interfaces. All iterators must be destroyed before + the container is destructed. + */ + ~OInterfaceContainerHelper(); + /** + Return the number of Elements in the container. Only useful if you have acquired + the mutex. + */ + sal_Int32 SAL_CALL getLength() const; + + /** + Return all interfaces added to this container. + **/ + css::uno::Sequence< css::uno::Reference< css::uno::XInterface > > SAL_CALL getElements() const; + + /** Inserts an element into the container. The position is not specified, thus it is not + specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rxIFace + interface to be added; it is allowed to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + sal_Int32 SAL_CALL addInterface( const css::uno::Reference< css::uno::XInterface > & rxIFace ); + /** Removes an element from the container. It uses interface equality to remove the interface. + + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + sal_Int32 SAL_CALL removeInterface( const css::uno::Reference< css::uno::XInterface > & rxIFace ); + /** + Call disposing on all object in the container that + support XEventListener. Then clear the container. + */ + void SAL_CALL disposeAndClear( const css::lang::EventObject & rEvt ); + /** + Clears the container without calling disposing(). + */ + void SAL_CALL clear(); + + /** Executes a functor for each contained listener of specified type, e.g. + forEach(.... + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam ListenerT listener type + @tparam FuncT unary functor type, let your compiler deduce this for you + @param func unary functor object expecting an argument of type + css::uno::Reference + */ + template + inline void forEach( FuncT const& func ); + + /** Calls a UNO listener method for each contained listener. + + The listener method must take a single argument of type EventT, + and return void. + + If a css::lang::DisposedException occurs which relates to + the called listener, then that listener is removed from the container. + + @tparam ListenerT UNO event listener type, let your compiler deduce this for you + @tparam EventT event type, let your compiler deduce this for you + @param NotificationMethod + Pointer to a method of a ListenerT interface. + @param Event + Event to notify to all contained listeners + + Example: +@code + awt::PaintEvent aEvent( static_cast< cppu::OWeakObject* >( this ), ... ); + listeners.notifyEach( &XPaintListener::windowPaint, aEvent ); +@endcode + */ + template< typename ListenerT, typename EventT > + inline void notifyEach( void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& ), const EventT& Event ); + +private: +friend class OInterfaceIteratorHelper; + /** + bIsList == TRUE -> aData.pAsSequence of type Sequence< XInterfaceSequence >, + otherwise aData.pAsInterface == of type (XEventListener *) + */ + detail::element_alias aData; + ::osl::Mutex & rMutex; + /** TRUE -> used by an iterator. */ + sal_Bool bInUse; + /** TRUE -> aData.pAsSequence is of type Sequence< XInterfaceSequence >. */ + sal_Bool bIsList; + + OInterfaceContainerHelper( const OInterfaceContainerHelper & ) + SAL_DELETED_FUNCTION; + OInterfaceContainerHelper & operator = ( const OInterfaceContainerHelper & ) + SAL_DELETED_FUNCTION; + + /* + Duplicate content of the container and release the old one without destroying. + The mutex must be locked and the memberbInUse must be true. + */ + void copyAndResetInUse(); + +private: + template< typename ListenerT, typename EventT > + class NotifySingleListener + { + private: + typedef void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& ); + NotificationMethod m_pMethod; + const EventT& m_rEvent; + public: + NotifySingleListener( NotificationMethod method, const EventT& event ) : m_pMethod( method ), m_rEvent( event ) { } + + void operator()( const css::uno::Reference& listener ) const + { + (listener.get()->*m_pMethod)( m_rEvent ); + } + }; +}; + +template +inline void OInterfaceContainerHelper::forEach( FuncT const& func ) +{ + OInterfaceIteratorHelper iter( *this ); + while (iter.hasMoreElements()) { + css::uno::Reference const xListener( iter.next(), css::uno::UNO_QUERY ); + if (xListener.is()) { + try { + func( xListener ); + } + catch (css::lang::DisposedException const& exc) { + if (exc.Context == xListener) + iter.remove(); + } + } + } +} + +template< typename ListenerT, typename EventT > +inline void OInterfaceContainerHelper::notifyEach( void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& ), const EventT& Event ) +{ + forEach< ListenerT, NotifySingleListener< ListenerT, EventT > >( NotifySingleListener< ListenerT, EventT >( NotificationMethod, Event ) ); +} + + +/** + A helper class to store interface references of different types. + + @see OInterfaceIteratorHelper + @see OInterfaceContainerHelper + */ +template< class key, class hashImpl = void, class equalImpl = std::equal_to > +class OMultiTypeInterfaceContainerHelperVar +{ +public: + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + /** + Create a container of interface containers. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + inline OMultiTypeInterfaceContainerHelperVar( ::osl::Mutex & rMutex ); + /** + Deletes all containers. + */ + inline ~OMultiTypeInterfaceContainerHelperVar(); + + /** + Return all id's under which at least one interface is added. + */ + inline css::uno::Sequence< key > SAL_CALL getContainedTypes() const; + + /** + Return the container created under this key. + The InterfaceContainerHelper exists until the whole MultiTypeContainer is destroyed. + @return the container created under this key. If the container + was not created, null was returned. + */ + inline OInterfaceContainerHelper * SAL_CALL getContainer( const key & ) const; + + /** Inserts an element into the container with the specified key. + The position is not specified, thus it is not specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rKey + the id of the container + @param r + interface to be added; it is allowed, to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + inline sal_Int32 SAL_CALL addInterface( + const key & rKey, + const css::uno::Reference< css::uno::XInterface > & r ); + + /** Removes an element from the container with the specified key. + It uses interface equality to remove the interface. + + @param rKey + the id of the container + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + inline sal_Int32 SAL_CALL removeInterface( + const key & rKey, + const css::uno::Reference< css::uno::XInterface > & rxIFace ); + + /** + Call disposing on all references in the container, that + support XEventListener. Then clears the container. + @param rEvt the event object which is passed during disposing() call + */ + inline void SAL_CALL disposeAndClear( const css::lang::EventObject & rEvt ); + /** + Remove all elements of all containers. Does not delete the container. + */ + inline void SAL_CALL clear(); + + typedef key keyType; +private: + typedef ::std::vector< std::pair < key , void* > > InterfaceMap; + InterfaceMap *m_pMap; + ::osl::Mutex & rMutex; + + typename InterfaceMap::iterator find(const key &rKey) const + { + typename InterfaceMap::iterator iter = m_pMap->begin(); + typename InterfaceMap::iterator end = m_pMap->end(); + + while( iter != end ) + { + equalImpl equal; + if( equal( iter->first, rKey ) ) + break; + ++iter; + } + return iter; + } + + OMultiTypeInterfaceContainerHelperVar( const OMultiTypeInterfaceContainerHelperVar & ) SAL_DELETED_FUNCTION; + OMultiTypeInterfaceContainerHelperVar & operator = ( const OMultiTypeInterfaceContainerHelperVar & ) SAL_DELETED_FUNCTION; +}; + + + + +/** + This struct contains the standard variables of a broadcaster. Helper + classes only know a reference to this struct instead of references + to the four members. The access to the members must be guarded with + rMutex. + + The additional template parameter keyType has been added, because gcc + can't compile addListener( const container::keyType &key ). + */ +template < class container , class keyType > +struct SAL_WARN_UNUSED OBroadcastHelperVar +{ + /** The shared mutex. */ + ::osl::Mutex & rMutex; + /** ListenerContainer class is thread safe. */ + container aLC; + /** Dispose call ready. */ + sal_Bool bDisposed; + /** In dispose call. */ + sal_Bool bInDispose; + + /** + Initialize the structure. bDispose and bInDispose are set to false. + @param rMutex_ the mutex reference. + */ + OBroadcastHelperVar( ::osl::Mutex & rMutex_ ) + : rMutex( rMutex_ ) + , aLC( rMutex_ ) + , bDisposed( false ) + , bInDispose( false ) + {} + + /** + adds a listener threadsafe. + **/ + void addListener( + const keyType &key, + const css::uno::Reference < css::uno::XInterface > &r ) + { + ::osl::MutexGuard guard( rMutex ); + OSL_ENSURE( !bInDispose, "do not add listeners in the dispose call" ); + OSL_ENSURE( !bDisposed, "object is disposed" ); + if( ! bInDispose && ! bDisposed ) + aLC.addInterface( key , r ); + } + + /** + removes a listener threadsafe + **/ + void removeListener( + const keyType &key, + const css::uno::Reference < css::uno::XInterface > & r ) + { + ::osl::MutexGuard guard( rMutex ); + if( ! bInDispose && ! bDisposed ) + aLC.removeInterface( key , r ); + } + + /** + Return the container created under this key. + @return the container created under this key. If the container + was not created, null was returned. This can be used to optimize + performance ( construction of an event object can be avoided ). + ***/ + OInterfaceContainerHelper * SAL_CALL getContainer( const keyType &key ) const + { return aLC.getContainer( key ); } +}; + +/*------------------------------------------ +* +* In general, the above templates are used with a Type as key. +* Therefore a default declaration is given ( OMultiTypeInterfaceContainerHelper and OBroadcastHelper ) +* +*------------------------------------------*/ + +// helper function call class +struct hashType_Impl +{ + size_t operator()(const css::uno::Type & s) const + { return static_cast(s.getTypeName().hashCode()); } +}; + + +/** Specialized class for key type css::uno::Type, + without explicit usage of STL symbols. +*/ +class CPPUHELPER_DLLPUBLIC OMultiTypeInterfaceContainerHelper +{ +public: + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + /** + Create a container of interface containers. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + OMultiTypeInterfaceContainerHelper( ::osl::Mutex & rMutex ); + /** + Delete all containers. + */ + ~OMultiTypeInterfaceContainerHelper(); + + /** + Return all id's under which at least one interface is added. + */ + css::uno::Sequence< css::uno::Type > SAL_CALL getContainedTypes() const; + + /** + Return the container created under this key. + @return the container created under this key. If the container + was not created, null was returned. + */ + OInterfaceContainerHelper * SAL_CALL getContainer( const css::uno::Type & rKey ) const; + + /** Inserts an element into the container with the specified key. + The position is not specified, thus it is not specified in which order events are fired. + + @attention + If you add the same interface more than once, then it will be added to the elements list + more than once and thus if you want to remove that interface from the list, you have to call + removeInterface() the same number of times. + In the latter case, you will also get events fired more than once (if the interface is a + listener interface). + + @param rKey + the id of the container + @param r + interface to be added; it is allowed, to insert null or + the same interface more than once + @return + the new count of elements in the container + */ + sal_Int32 SAL_CALL addInterface( + const css::uno::Type & rKey, + const css::uno::Reference< css::uno::XInterface > & r ); + + /** Removes an element from the container with the specified key. + It uses interface equality to remove the interface. + + @param rKey + the id of the container + @param rxIFace + interface to be removed + @return + the new count of elements in the container + */ + sal_Int32 SAL_CALL removeInterface( + const css::uno::Type & rKey, + const css::uno::Reference< css::uno::XInterface > & rxIFace ); + + /** + Call disposing on all object in the container that + support XEventListener. Then clear the container. + */ + void SAL_CALL disposeAndClear( const css::lang::EventObject & rEvt ); + /** + Remove all elements of all containers. Does not delete the container. + */ + void SAL_CALL clear(); + + typedef css::uno::Type keyType; +private: + void * m_pMap; + ::osl::Mutex & rMutex; + + OMultiTypeInterfaceContainerHelper( const OMultiTypeInterfaceContainerHelper & ) SAL_DELETED_FUNCTION; + OMultiTypeInterfaceContainerHelper & operator = ( const OMultiTypeInterfaceContainerHelper & ) SAL_DELETED_FUNCTION; +}; + +typedef OBroadcastHelperVar< OMultiTypeInterfaceContainerHelper , OMultiTypeInterfaceContainerHelper::keyType > OBroadcastHelper; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/interfacecontainer.hxx b/include/cppuhelper/interfacecontainer.hxx new file mode 100644 index 000000000..a3bb65e4d --- /dev/null +++ b/include/cppuhelper/interfacecontainer.hxx @@ -0,0 +1,197 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_INTERFACECONTAINER_HXX +#define INCLUDED_CPPUHELPER_INTERFACECONTAINER_HXX + +#include "sal/config.h" + +#include + +#include "cppuhelper/interfacecontainer.h" + + +namespace cppu +{ + +template< class key , class hashImpl , class equalImpl > +inline OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::OMultiTypeInterfaceContainerHelperVar( ::osl::Mutex & rMutex_ ) + : rMutex( rMutex_ ) +{ + m_pMap = new InterfaceMap; +} + + +template< class key , class hashImpl , class equalImpl > +inline OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::~OMultiTypeInterfaceContainerHelperVar() +{ + typename InterfaceMap::iterator iter = m_pMap->begin(); + typename InterfaceMap::iterator end = m_pMap->end(); + + while( iter != end ) + { + delete static_cast((*iter).second); + (*iter).second = NULL; + ++iter; + } + delete m_pMap; +} + + +template< class key , class hashImpl , class equalImpl > +inline css::uno::Sequence< key > OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::getContainedTypes() const +{ + ::osl::MutexGuard aGuard( rMutex ); + typename InterfaceMap::size_type nSize = m_pMap->size(); + if( nSize != 0 ) + { + css::uno::Sequence< key > aInterfaceTypes( nSize ); + key * pArray = aInterfaceTypes.getArray(); + + typename InterfaceMap::iterator iter = m_pMap->begin(); + typename InterfaceMap::iterator end = m_pMap->end(); + + sal_uInt32 i = 0; + while( iter != end ) + { + // are interfaces added to this container? + if( static_cast((*iter).second)->getLength() ) + // yes, put the type in the array + pArray[i++] = (*iter).first; + ++iter; + } + if( i != nSize ) { + // may be empty container, reduce the sequence to the right size + aInterfaceTypes = css::uno::Sequence( pArray, i ); + } + return aInterfaceTypes; + } + return css::uno::Sequence(); +} + + +template< class key , class hashImpl , class equalImpl > +OInterfaceContainerHelper * OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::getContainer( + const key & rKey ) const +{ + ::osl::MutexGuard aGuard( rMutex ); + + typename InterfaceMap::iterator iter = find( rKey ); + if( iter != m_pMap->end() ) + return static_cast( (*iter).second ); + return NULL; +} + + +template< class key , class hashImpl , class equalImpl > +sal_Int32 OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::addInterface( + const key & rKey, + const css::uno::Reference< css::uno::XInterface > & rListener ) +{ + ::osl::MutexGuard aGuard( rMutex ); + typename InterfaceMap::iterator iter = find( rKey ); + if( iter == m_pMap->end() ) + { + OInterfaceContainerHelper * pLC = new OInterfaceContainerHelper( rMutex ); + m_pMap->push_back(std::pair(rKey, pLC)); + return pLC->addInterface( rListener ); + } + else + return static_cast((*iter).second)->addInterface( rListener ); +} + + +template< class key , class hashImpl , class equalImpl > +inline sal_Int32 OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::removeInterface( + const key & rKey, + const css::uno::Reference< css::uno::XInterface > & rListener ) +{ + ::osl::MutexGuard aGuard( rMutex ); + + // search container with id nUik + typename InterfaceMap::iterator iter = find( rKey ); + // container found? + if( iter != m_pMap->end() ) + return static_cast((*iter).second)->removeInterface( rListener ); + + // no container with this id. Always return 0 + return 0; +} + + +template< class key , class hashImpl , class equalImpl > +void OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::disposeAndClear( + const css::lang::EventObject & rEvt ) +{ + typename InterfaceMap::size_type nSize = 0; + OInterfaceContainerHelper ** ppListenerContainers = NULL; + { + ::osl::MutexGuard aGuard( rMutex ); + nSize = m_pMap->size(); + if( nSize ) + { + typedef OInterfaceContainerHelper* ppp; + ppListenerContainers = new ppp[nSize]; + + typename InterfaceMap::iterator iter = m_pMap->begin(); + typename InterfaceMap::iterator end = m_pMap->end(); + + typename InterfaceMap::size_type i = 0; + while( iter != end ) + { + ppListenerContainers[i++] = static_cast((*iter).second); + ++iter; + } + } + } + + // create a copy, because do not fire event in a guarded section + for( typename InterfaceMap::size_type i = 0; i < nSize; i++ ) + { + if( ppListenerContainers[i] ) + ppListenerContainers[i]->disposeAndClear( rEvt ); + } + + delete [] ppListenerContainers; +} + + +template< class key , class hashImpl , class equalImpl > +void OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::clear() +{ + ::osl::MutexGuard aGuard( rMutex ); + typename InterfaceMap::iterator iter = m_pMap->begin(); + typename InterfaceMap::iterator end = m_pMap->end(); + + while( iter != end ) + { + static_cast((*iter).second)->clear(); + ++iter; + } +} + + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/propertysetmixin.hxx b/include/cppuhelper/propertysetmixin.hxx new file mode 100644 index 000000000..e25f3f738 --- /dev/null +++ b/include/cppuhelper/propertysetmixin.hxx @@ -0,0 +1,423 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_PROPERTYSETMIXIN_HXX +#define INCLUDED_CPPUHELPER_PROPERTYSETMIXIN_HXX + +#include "sal/config.h" + +#include "com/sun/star/beans/XFastPropertySet.hpp" +#include "com/sun/star/beans/XPropertyAccess.hpp" +#include "com/sun/star/beans/XPropertySet.hpp" +#include "com/sun/star/uno/Reference.h" +#include "com/sun/star/uno/Sequence.hxx" +#include "sal/types.h" +#include "cppuhelper/cppuhelperdllapi.h" + +namespace com { namespace sun { namespace star { + namespace beans { + class XPropertyChangeListener; + class XPropertySetInfo; + class XVetoableChangeListener; + struct PropertyValue; + } + namespace uno { + class Type; + class XComponentContext; + } +} } } + +namespace cppu { + +/** + @short A helper base class for cppu::PropertySetMixin. + + See the documentation of cppu::PropertySetMixin for + further details. + + That cppu::PropertySetMixin is derived from this + base class should be considered an implementation detail. The functionality + of cppu::PropertySetMixin that is inherited from this base + class and is visible to subclasses of + cppu::PropertySetMixin should be treated by such + subclasses as being provided by cppu::PropertySetMixin + directly (e.g., in such subclasses, use + “PropertySetMixin::Implements” instead of + “PropertySetMixinImpl::Implements”). + + @since UDK 3.2.1 +*/ +#if defined __GNUC__ && !defined __clang__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" +#endif +class CPPUHELPER_DLLPUBLIC PropertySetMixinImpl: + public css::beans::XPropertySet, + public css::beans::XFastPropertySet, + public css::beans::XPropertyAccess +{ +protected: + /** + @short Flags used by subclasses of + cppu::PropertySetMixin to specify what UNO interface + types shall be supported. + */ + enum Implements { + /** + @short Flag specifying that the UNO interface type + css::beans::XPropertySet shall be supported. + */ + IMPLEMENTS_PROPERTY_SET = 1, + + /** + @short Flag specifying that the UNO interface type + css::beans::XFastPropertySet shall be + supported. + */ + IMPLEMENTS_FAST_PROPERTY_SET = 2, + + /** + @short Flag specifying that the UNO interface type + css::beans::XPropertyAccess shall be + supported. + */ + IMPLEMENTS_PROPERTY_ACCESS = 4 + }; + + /** + @short A class used by subclasses of + cppu::PropertySetMixin when implementing UNO interface + type attribute setter functions. + + This class is not thread safe; that is, the constructor, + notify, and the destructor must be called from the same + thread. + + See cppu::PropertySetMixinImpl::prepareSet for + further details. + */ + class CPPUHELPER_DLLPUBLIC BoundListeners { + public: + /** + @short The constructor. + + May throw std::bad_alloc. + */ + BoundListeners(); + + /** + @short The destructor. + + Does not throw. + */ + ~BoundListeners(); + + /** + @short Notifies any + css::beans::XPropertyChangeListeners. + + May throw css::uno::RuntimeException + and std::bad_alloc. + + See cppu::PropertySetMixinImpl::prepareSet + for further details. + */ + void notify() const; + + private: + BoundListeners( const BoundListeners&) SAL_DELETED_FUNCTION; + void operator=( const BoundListeners&) SAL_DELETED_FUNCTION; + + class Impl; + Impl * m_impl; + + friend class PropertySetMixinImpl; + }; + + /** + @short A function used by subclasses of + cppu::PropertySetMixin when implementing UNO interface + type attribute setter functions. + + First, this function checks whether this instance has already been + disposed (see cppu::PropertySetMixinImpl::dispose), + and throws a css::lang::DisposedException if + applicable. For a constrained attribute (whose setter can explicitly + raise css::beans::PropertyVetoException), this + function notifies any + css::beans::XVetoableChangeListeners. For a + bound attribute, this function modifies the passed-in + boundListeners so that it can afterwards be used to notify + any css::beans::XPropertyChangeListeners. This + function should be called before storing the new attribute value, and + boundListeners->notify() should be called exactly once after + storing the new attribute value (in case the attribute is bound; + otherwise, calling boundListeners->notify() is ignored). + Furthermore, boundListeners->notify() and this function have + to be called from the same thread. + + May throw + css::beans::PropertyVetoException, + css::uno::RuntimeException (and + css::lang::DisposedException in particular), and + std::bad_alloc. + + @param propertyName the name of the property (which is the same as the + name of the attribute that is going to be set) + + @param oldValue the property value corresponding to the old attribute + value. This is only used as + css::beans::PropertyChangeEvent::OldValue, which + is rather useless, anyway (see “Using the Observer Pattern” + in + OpenOffice.org Coding Guidelines). If the attribute + that is going to be set is neither bound nor constrained, or if + css::beans::PropertyChangeEvent::OldValue should + not be set, a VOID Any can be used instead. + + @param newValue the property value corresponding to the new + attribute value. This is only used as + css::beans::PropertyChangeEvent::NewValue, which + is rather useless, anyway (see “Using the Observer Pattern” + in + OpenOffice.org Coding Guidelines), unless the + attribute that is going to be set is constrained. If the attribute + that is going to be set is neither bound nor constrained, or if it is + only bound but + css::beans::PropertyChangeEvent::NewValue should + not be set, a VOID Any can be used instead. + + @param boundListeners a pointer to a fresh + cppu::PropertySetMixinImpl::BoundListeners instance + (which has not been passed to this function before, and on which + notify has not yet been called); may only be null if the + attribute that is going to be set is not bound + */ + void prepareSet( + rtl::OUString const & propertyName, + css::uno::Any const & oldValue, + css::uno::Any const & newValue, + BoundListeners * boundListeners); + + /** + @short Mark this instance as being disposed. + + See css::lang::XComponent for the general + concept of disposing UNO objects. On the first call to this function, + all registered listeners + (css::beans::XPropertyChangeListeners and + css::beans::XVetoableChangeListeners) are + notified of the disposing source. Any subsequent calls to this function + are ignored. + + May throw css::uno::RuntimeException and + std::bad_alloc. + */ + void dispose(); + + /** + @short A function used by subclasses of + cppu::PropertySetMixin when implementing + css::uno::XInterface::queryInterface. + + This function checks for support of any of the UNO interface types + specified in the call of the cppu::PropertySetMixin + constructor. It does not check for any other UNO interface types (not + even for css::uno::XInterface), and should not + be used directly as the implementation of + css::uno::XInterface::queryInterface of this UNO + object. + */ + virtual css::uno::Any SAL_CALL queryInterface( + css::uno::Type const & type) SAL_OVERRIDE; + + // @see css::beans::XPropertySet::getPropertySetInfo + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() SAL_OVERRIDE; + + // @see css::beans::XPropertySet::setPropertyValue + virtual void SAL_CALL setPropertyValue( + rtl::OUString const & propertyName, + css::uno::Any const & value) SAL_OVERRIDE; + + // @see css::beans::XPropertySet::getPropertyValue + virtual css::uno::Any SAL_CALL getPropertyValue( + rtl::OUString const & propertyName) SAL_OVERRIDE; + + /** + @short Adds a + css::beans::XPropertyChangeListener. + + If a listener is added more than once, it will receive all + relevant notifications multiple times. + + @see css::beans::XPropertySet::addPropertyChangeListener + */ + virtual void SAL_CALL addPropertyChangeListener( + rtl::OUString const & propertyName, + css::uno::Reference< + css::beans::XPropertyChangeListener > const & listener) SAL_OVERRIDE; + + // @see css::beans::XPropertySet::removePropertyChangeListener + virtual void SAL_CALL removePropertyChangeListener( + rtl::OUString const & propertyName, + css::uno::Reference< + css::beans::XPropertyChangeListener > const & listener) SAL_OVERRIDE; + + /** + @short Adds a + css::beans::XVetoableChangeListener. + + If a listener is added more than once, it will receive all + relevant notifications multiple times. + + @see css::beans::XPropertySet::addVetoableChangeListener + */ + virtual void SAL_CALL addVetoableChangeListener( + rtl::OUString const & propertyName, + css::uno::Reference< + css::beans::XVetoableChangeListener > const & listener) SAL_OVERRIDE; + + // @see css::beans::XPropertySet::removeVetoableChangeListener + virtual void SAL_CALL removeVetoableChangeListener( + rtl::OUString const & propertyName, + css::uno::Reference< + css::beans::XVetoableChangeListener > const & listener) SAL_OVERRIDE; + + // @see css::beans::XFastPropertySet::setFastPropertyValue + virtual void SAL_CALL setFastPropertyValue( + sal_Int32 handle, css::uno::Any const & value) SAL_OVERRIDE; + + // @see css::beans::XFastPropertySet::getFastPropertyValue + virtual css::uno::Any SAL_CALL getFastPropertyValue( + sal_Int32 handle) SAL_OVERRIDE; + + // @see css::beans::XPropertyAccess::getPropertyValues + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getPropertyValues() SAL_OVERRIDE; + + // @see css::beans::XPropertyAccess::setPropertyValues + virtual void SAL_CALL setPropertyValues( + css::uno::Sequence< css::beans::PropertyValue > const & props) SAL_OVERRIDE; + +private: + PropertySetMixinImpl( const PropertySetMixinImpl&) SAL_DELETED_FUNCTION; + void operator=( const PropertySetMixinImpl&) SAL_DELETED_FUNCTION; + + PropertySetMixinImpl( + css::uno::Reference< css::uno::XComponentContext > const & context, + Implements implements, + css::uno::Sequence< rtl::OUString > const & absentOptional, + css::uno::Type const & type); + + class Impl; + Impl * m_impl; + + friend class Impl; + template< typename T > friend class PropertySetMixin; + + ~PropertySetMixinImpl(); + + void checkUnknown(rtl::OUString const & propertyName); +}; + +/** + @short A helper mixin to implement certain UNO interfaces related to property + set handling on top of the attributes of a given UNO interface type. + + The UNO interface type is specified by the type parameter + T (which must correspond to a UNO interface type). + + No specializations of this class template should be added by client + code. + + @since UDK 3.2.1 +*/ +template< typename T > class PropertySetMixin: public PropertySetMixinImpl { +protected: + /** + @short The constructor. + + May throw css::uno::RuntimeException and + std::bad_alloc. + + @param context the component context used by this class template; must + not be null, and must supply the + com.sun.star.reflection.theCoreReflection and + com.sun.star.reflection.theTypeDescriptionManager singletons + + @param implements a combination of zero or more flags specifying what + UNO interface types shall be supported + + @param absentOptional a list of optional properties that are not + present, and should thus not be visible via + css::beans::XPropertySet::getPropertySetInfo, + css::beans::XPropertySet::addPropertyChangeListener, css::beans::XPropertySet::removePropertyChangeListener, + css::beans::XPropertySet::addVetoableChangeListener, and css::beans::XPropertySet::removeVetoableChangeListener. For consistency reasons, the + given absentOptional should only contain the names of + attributes that represent optional properties that are not present (that + is, the attribute getters and setters always throw a + css::beans::UnknownPropertyException), and should + contain each such name only once. If an optional property is not present + (that is, the corresponding attribute getter and setter always throw a + css::beans::UnknownPropertyException) but is not + contained in the given absentOptional, then it will be + visible via + css::beans::XPropertySet::getPropertySetInfo as a + css::beans::Property with a set + css::beans::PropertyAttribute::OPTIONAL. If the + given implements specifies that + css::beans::XPropertySet is not supported, then + the given absentOptional is effectively ignored and can be + empty. + */ + PropertySetMixin( + css::uno::Reference< css::uno::XComponentContext > const & context, + Implements implements, + css::uno::Sequence< rtl::OUString > const & absentOptional): + PropertySetMixinImpl( + context, implements, absentOptional, T::static_type()) + {} + + /** + @short The destructor. + + Does not throw. + */ + ~PropertySetMixin() {} + +private: + PropertySetMixin( const PropertySetMixin&) SAL_DELETED_FUNCTION; + void operator=( const PropertySetMixin&) SAL_DELETED_FUNCTION; +}; +#if defined __GNUC__ && !defined __clang__ +#pragma GCC diagnostic pop +#endif + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/propshlp.hxx b/include/cppuhelper/propshlp.hxx new file mode 100644 index 000000000..d2e73d707 --- /dev/null +++ b/include/cppuhelper/propshlp.hxx @@ -0,0 +1,729 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_PROPSHLP_HXX +#define INCLUDED_CPPUHELPER_PROPSHLP_HXX + +#include "rtl/alloc.h" + +#include "cppuhelper/interfacecontainer.h" + +#include "com/sun/star/beans/XPropertySet.hpp" +#include "com/sun/star/beans/XPropertySetOption.hpp" +#include "com/sun/star/beans/XMultiPropertySet.hpp" +#include "com/sun/star/beans/XFastPropertySet.hpp" + +#include "cppuhelper/cppuhelperdllapi.h" + + +namespace cppu +{ + + +/************************************************************************* +*************************************************************************/ + + +/** + This interface is used by the OPropertyHelper, to access the property description. + */ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC IPropertyArrayHelper +{ +public: + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + /** + Following the rule, the first virtual method implies a virtual destructor. + */ + virtual ~IPropertyArrayHelper(); + + /** + Return the property members Name and Attribute from the handle nHandle. + @param nHandle the handle of a property. If the values of the handles + are sorted in the same way as the names and the highest handle value + is getCount() -1, then it must be an indexed access to the property array. + @param pPropName is an out parameter filled with property name of the property with the + handle nHandle. May be NULL. + @param pAttributes is an out parameter filled with attributes of the property with the + handle nHandle. May be NULL. + @return True, if the handle exist, otherwise false. + */ + virtual sal_Bool SAL_CALL fillPropertyMembersByHandle( + ::rtl::OUString * pPropName, sal_Int16 * pAttributes, sal_Int32 nHandle ) = 0; + /** + Return the sequence of properties. The sequence is sorted by name. + */ + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() = 0; + /** + Return the property with the name rPropertyName. + @param rPropertyName the name of the property. + @exception UnknownPropertyException thrown if the property name is unknown. + */ + virtual css::beans::Property SAL_CALL getPropertyByName( + const ::rtl::OUString& rPropertyName ) = 0; + /** + Return true if the property with the name rPropertyName exist, otherwise false. + @param rPropertyName the name of the property. + */ + virtual sal_Bool SAL_CALL hasPropertyByName(const ::rtl::OUString& rPropertyName) = 0; + /** + Return the handle of the property with the name rPropertyName. + If the property does not exist -1 is returned. + @param rPropertyName the name of the property. + */ + virtual sal_Int32 SAL_CALL getHandleByName( const ::rtl::OUString & rPropertyName ) = 0; + /** + Fill the array with the handles of the properties. + @return the handles of the names from the pHandles array. -1 + indicates an unknown property name. + */ + virtual sal_Int32 SAL_CALL fillHandles( + /*out*/ sal_Int32 * pHandles, const css::uno::Sequence< ::rtl::OUString > & rPropNames ) = 0; +}; + +/** + You can use this helper class to map a XPropertySet-Interface to a XFast- + or a XMultiPropertySet interface. + */ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC OPropertyArrayHelper : public IPropertyArrayHelper +{ +public: + /** + Create an object which supports the common property interfaces. + + @param pProps array of properties + The array pProps should be sorted. + @param nElements is the number of properties in the pProps structure. + @param bSorted indicates that the elements are sorted. + *********/ + OPropertyArrayHelper( + css::beans::Property *pProps, + sal_Int32 nElements , + sal_Bool bSorted = true ); + + /** + Create an object which supports the common property interfaces. + @param aProps sequence of properties which are supported by this helper. + The sequence aProps should be sorted. + @param bSorted indicates that the elements are sorted. + */ + OPropertyArrayHelper( + const css::uno::Sequence< css::beans::Property > & aProps, + sal_Bool bSorted = true ); + + /** + Return the number of properties. + */ + sal_Int32 SAL_CALL getCount() const; + /** + Return the property members Name and Attribute from the handle nHandle. + @param nHandle the handle of a property. If the values of the handles + are sorted in the same way as the names and the highest handle value + is getCount() -1, then it is only an indexed access to the property array. + Otherwise it is a linear search through the array. + @param pPropName is an out parameter filled with property name of the property with the + handle nHandle. May be NULL. + @param pAttributes is an out parameter filled with attributes of the property with the + handle nHandle. May be NULL. + @return True, if the handle exist, otherwise false. + */ + virtual sal_Bool SAL_CALL fillPropertyMembersByHandle( + ::rtl::OUString * pPropName, sal_Int16 * pAttributes, sal_Int32 nHandle ) SAL_OVERRIDE; + /** + Return the sequence of properties. The sequence is sorted by name. + */ + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() SAL_OVERRIDE; + /** + Return the property with the name rPropertyName. + @param rPropertyName the name of the property. + @exception UnknownPropertyException thrown if the property name is unknown. + */ + virtual css::beans::Property SAL_CALL getPropertyByName( + const ::rtl::OUString& rPropertyName ) SAL_OVERRIDE; + /** + Return true if the property with the name rPropertyName exist, otherwise false. + @param rPropertyName the name of the property. + */ + virtual sal_Bool SAL_CALL hasPropertyByName(const ::rtl::OUString& rPropertyName) SAL_OVERRIDE; + /** + Return the handle of the property with the name rPropertyName. + If the property does not exist -1 is returned. + @param rPropertyName the name of the property. + */ + virtual sal_Int32 SAL_CALL getHandleByName( const ::rtl::OUString & rPropertyName ) SAL_OVERRIDE; + /** + Fill the array with the handles of the properties. + @return the handles of the names from the pHandles array. -1 + indicates an unknown property name. + */ + virtual sal_Int32 SAL_CALL fillHandles( + /*out*/sal_Int32 * pHandles, const css::uno::Sequence< ::rtl::OUString > & rPropNames ) SAL_OVERRIDE; + +protected: + /** reserved for future use. do not use. + */ + void * m_pReserved; + +private: + void init( sal_Bool bSorted ); + + /** The sequence generated from the pProperties array. */ + css::uno::Sequence< css::beans::Property > aInfos; + + /** + True, If the values of the handles are sorted in the same way as the names + and the highest handle value is getCount() -1, otherwise false. + */ + sal_Bool bRightOrdered; +}; + + +// helper defines needed for an interface container with a 32 bit key values + +struct equalInt32_Impl +{ + bool operator()(const sal_Int32 & i1 , const sal_Int32 & i2) const + { return i1 == i2; } +}; + +struct hashInt32_Impl +{ + size_t operator()(const sal_Int32 & i) const + { return i; } +}; + +/** Specialized class for key type sal_Int32, + without explicit usage of STL symbols. +*/ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC OMultiTypeInterfaceContainerHelperInt32 +{ +public: + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + /** + Create a container of interface containers. + + @param rMutex the mutex to protect multi thread access. + The lifetime must be longer than the lifetime + of this object. + */ + OMultiTypeInterfaceContainerHelperInt32( ::osl::Mutex & rMutex ); + /** + Delete all containers. + */ + ~OMultiTypeInterfaceContainerHelperInt32(); + + /** + Return all id's under which at least one interface is added. + */ + css::uno::Sequence< sal_Int32 > SAL_CALL getContainedTypes() const; + + /** + Return the container created under this key. + @return the container created under this key. If the container + was not created, null was returned. + */ + OInterfaceContainerHelper * SAL_CALL getContainer( const sal_Int32 & rKey ) const; + + /** + Insert an element in the container specified with the key. The position is not specified. + @param rKey the id of the container. + @param r the added interface. It is allowed to insert null or + the same pointer more than once. + @return the new count of elements in the container. + */ + sal_Int32 SAL_CALL addInterface( + const sal_Int32 & rKey, + const css::uno::Reference< css::uno::XInterface > & r ); + + /** + Remove an element from the container specified with the key. + It uses the equal definition of uno objects to remove the interfaces. + @param rKey the id of the container. + @param rxIFace the removed interface. + @return the new count of elements in the container. + */ + sal_Int32 SAL_CALL removeInterface( + const sal_Int32 & rKey, + const css::uno::Reference< css::uno::XInterface > & rxIFace ); + + /** + Call disposing on all objects in the container that + support XEventListener. Then clear the container. + */ + void SAL_CALL disposeAndClear( const css::lang::EventObject & rEvt ); + /** + Remove all elements of all containers. Does not delete the container. + */ + void SAL_CALL clear(); + + typedef sal_Int32 keyType; +private: + void * m_pMap; + ::osl::Mutex & rMutex; + + OMultiTypeInterfaceContainerHelperInt32( const OMultiTypeInterfaceContainerHelperInt32 & ) SAL_DELETED_FUNCTION; + OMultiTypeInterfaceContainerHelperInt32 & operator = ( const OMultiTypeInterfaceContainerHelperInt32 & )SAL_DELETED_FUNCTION; +}; + + +/** An interface to extend event notification actions. + */ +class IEventNotificationHook +{ +public: + /** + Method to be called by OPropertySetHelper::fire. + + @param pnHandles the id's of the properties that changed. + @param nCount the number of elements in the arrays pnHandles, pNewValues and pOldValues. + @param bVetoable true means fire to VetoableChangeListener, false means fire to + XPropertyChangedListener and XMultiPropertyChangedListener. + @param bIgnoreRuntimeExceptionsWhileFiring + indicates whether occurring RuntimeExceptions will be + ignored when firing notifications + (vetoableChange(), propertyChange()) + to listeners. + PropertyVetoExceptions may still be thrown. + This flag is useful in an inter-process scenario when + remote bridges may break down + (firing DisposedExceptions). + + @see OPropertySetHelper::fire + */ + virtual void fireEvents( + sal_Int32 * pnHandles, + sal_Int32 nCount, + sal_Bool bVetoable, + bool bIgnoreRuntimeExceptionsWhileFiring) = 0; + +#if !defined _MSC_VER // public -> protected changes mangled names there +protected: +#elif defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + ~IEventNotificationHook() {} + // avoid warnings about virtual members and non-virtual dtor +#if defined _MSC_VER && defined __clang__ +#pragma clang diagnostic pop +#endif +}; + + +/** + This abstract class maps the methods of the interfaces XMultiPropertySet, XFastPropertySet + and XPropertySet to the methods getInfoHelper, convertFastPropertyValue, + setFastPropertyValue_NoBroadcast and getFastPropertyValue. You must derive from + this class and override the methods. + It provides a standard implementation of the XPropertySetInfo. + The XPropertiesChangeListener are inserted in the rBHelper.aLC structure. + The XPropertyChangeListener and XVetoableChangeListener with no names are inserted + in the rBHelper.aLC structure. So it is possible to advise property listeners with + the connection point interfaces. But only listeners that listen to all property changes. + + */ +class CPPUHELPER_DLLPUBLIC OPropertySetHelper : + public css::beans::XMultiPropertySet, + public css::beans::XFastPropertySet, + public css::beans::XPropertySet +{ +public: + /** + @param rBHelper this structure contains the basic members of + a broadcaster. + The lifetime must be longer than the lifetime + of this object. Stored in the variable rBHelper. + */ + OPropertySetHelper( OBroadcastHelper & rBHelper ); + + /** Constructor. + + @param rBHelper + this structure contains the basic members of + a broadcaster. + The lifetime must be longer than the lifetime + of this object. Stored in the variable rBHelper. + + @param bIgnoreRuntimeExceptionsWhileFiring + indicates whether occurring RuntimeExceptions will be + ignored when firing notifications + (vetoableChange(), propertyChange()) + to listeners. + PropertyVetoExceptions may still be thrown. + This flag is useful in an inter-process scenario when + remote bridges may break down + (firing DisposedExceptions). + */ + OPropertySetHelper( + OBroadcastHelper & rBHelper, bool bIgnoreRuntimeExceptionsWhileFiring ); + + /** Constructor. + + @param rBHelper + this structure contains the basic members of + a broadcaster. + The lifetime must be longer than the lifetime + of this object. Stored in the variable rBHelper. + + @param i_pFireEvents + additional event notifier + + @param bIgnoreRuntimeExceptionsWhileFiring + indicates whether occurring RuntimeExceptions will be + ignored when firing notifications + (vetoableChange(), propertyChange()) + to listeners. + PropertyVetoExceptions may still be thrown. + This flag is useful in an inter-process scenario when + remote bridges may break down + (firing DisposedExceptions). + */ + OPropertySetHelper( + OBroadcastHelper & rBHelper, + IEventNotificationHook *i_pFireEvents, + bool bIgnoreRuntimeExceptionsWhileFiring = false); + + /** + Only returns a reference to XMultiPropertySet, XFastPropertySet, XPropertySet and + XEventListener. + */ + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) SAL_OVERRIDE; + + /** eases implementing XTypeProvider::getTypes, returns the types of XMultiPropertySet, XFastPropertySet, XPropertySet + + @throws css::uno::RuntimeException + */ + css::uno::Sequence< css::uno::Type > getTypes(); + + /** + Send a disposing notification to the listeners in the containers aBoundLC + and aVetoableLC. + + @see OComponentHelper + */ + void SAL_CALL disposing(); + + /** + Throw UnknownPropertyException or PropertyVetoException if the property with the name + rPropertyName does not exist or is readonly. Otherwise rPropertyName is changed to its handle + value and setFastPropertyValue is called. + */ + virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& rPropertyName, const css::uno::Any& aValue ) SAL_OVERRIDE; + /** + Throw UnknownPropertyException if the property with the name + rPropertyName does not exist. + */ + virtual css::uno::Any SAL_CALL getPropertyValue(const ::rtl::OUString& aPropertyName) SAL_OVERRIDE; + /** Ignored if the property is not bound. */ + virtual void SAL_CALL addPropertyChangeListener( + const ::rtl::OUString& aPropertyName, + const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener) SAL_OVERRIDE; + + /** Ignored if the property is not bound. */ + virtual void SAL_CALL removePropertyChangeListener( + const ::rtl::OUString& aPropertyName, + const css::uno::Reference < css::beans::XPropertyChangeListener >& aListener) SAL_OVERRIDE; + + /** Ignored if the property is not constrained. */ + virtual void SAL_CALL addVetoableChangeListener( + const ::rtl::OUString& aPropertyName, + const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener) SAL_OVERRIDE; + + /** Ignored if the property is not constrained. */ + virtual void SAL_CALL removeVetoableChangeListener( + const ::rtl::OUString& aPropertyName, + const css::uno::Reference< css::beans::XVetoableChangeListener > & aListener ) SAL_OVERRIDE; + + /** + Throw UnknownPropertyException or PropertyVetoException if the property with the name + rPropertyName does not exist or is readonly. Otherwise the method convertFastPropertyValue + is called, then the vetoable listeners are notified. After this the value of the property + is changed with the setFastPropertyValue_NoBroadcast method and the bound listeners are + notified. + */ + virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const css::uno::Any& rValue ) SAL_OVERRIDE; + + /** + @exception css::beans::UnknownPropertyException + if the property with the handle nHandle does not exist. + */ + virtual css::uno::Any SAL_CALL getFastPropertyValue( sal_Int32 nHandle ) SAL_OVERRIDE; + + // XMultiPropertySet + virtual void SAL_CALL setPropertyValues( + const css::uno::Sequence< ::rtl::OUString >& PropertyNames, + const css::uno::Sequence< css::uno::Any >& Values ) SAL_OVERRIDE; + + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyValues( + const css::uno::Sequence< ::rtl::OUString >& PropertyNames ) SAL_OVERRIDE; + + virtual void SAL_CALL addPropertiesChangeListener( + const css::uno::Sequence< ::rtl::OUString >& PropertyNames, + const css::uno::Reference< css::beans::XPropertiesChangeListener >& Listener ) SAL_OVERRIDE; + + virtual void SAL_CALL removePropertiesChangeListener( + const css::uno::Reference< css::beans::XPropertiesChangeListener >& Listener ) SAL_OVERRIDE; + + virtual void SAL_CALL firePropertiesChangeEvent( + const css::uno::Sequence< ::rtl::OUString >& PropertyNames, + const css::uno::Reference< css::beans::XPropertiesChangeListener > & Listener ) SAL_OVERRIDE; + + /** + The property sequence is created in the call. The interface isn't used after the call. + */ + static css::uno::Reference < css::beans::XPropertySetInfo > SAL_CALL + createPropertySetInfo( IPropertyArrayHelper & rProperties ); +protected: + /** + This method fire events to all registered property listeners. + @param pnHandles the id's of the properties that changed. + @param pNewValues the new values of the properties. + @param pOldValues the old values of the properties. + @param nCount the number of elements in the arrays pnHandles, pNewValues and pOldValues. + @param bVetoable true means fire to VetoableChangeListener, false means fire to + XPropertyChangedListener and XMultiPropertyChangedListener. + */ + void SAL_CALL fire( + sal_Int32 * pnHandles, + const css::uno::Any * pNewValues, + const css::uno::Any * pOldValues, + sal_Int32 nCount, + sal_Bool bVetoable ); + + /** + Set multiple properties with the handles. + @param nSeqLen the length of the arrays pHandles and Values. + @param pHandles the handles of the properties. The number of elements + in the Values sequence is the length of the handle array. A value of -1 + of a handle means invalid property. These are ignored. + @param pValues the values of the properties. + @param nHitCount the number of valid entries in the handle array. + */ + void SAL_CALL setFastPropertyValues( + sal_Int32 nSeqLen, + sal_Int32 * pHandles, + const css::uno::Any * pValues, + sal_Int32 nHitCount ); + + /** + This abstract method must return the name to index table. This table contains all property + names and types of this object. The method is not implemented in this class. + */ + virtual IPropertyArrayHelper & SAL_CALL getInfoHelper() = 0; + + /** + Converted the value rValue and return the result in rConvertedValue and the + old value in rOldValue. An IllegalArgumentException is thrown. + The method is not implemented in this class. After this call the vetoable + listeners are notified. + + @param rConvertedValue the converted value. Only set if return is true. + @param rOldValue the old value. Only set if return is true. + @param nHandle the handle of the property. + @param rValue the value to be converted + @return true if the value converted. + @throws css::lang::IllegalArgumentException + @throws css::beans::UnknownPropertyException + @throws css::uno::RuntimeException + */ + virtual sal_Bool SAL_CALL convertFastPropertyValue( + css::uno::Any & rConvertedValue, + css::uno::Any & rOldValue, + sal_Int32 nHandle, + const css::uno::Any& rValue ) = 0; + + /** The same as setFastPropertyValue; nHandle is always valid. + The changes must not be broadcasted in this method. + The method is implemented in a derived class. + + @attention + Although you are permitted to throw any UNO exception, only the following + are valid for usage: + -- css::beans::UnknownPropertyException + -- css::beans::PropertyVetoException + -- css::lang::IllegalArgumentException + -- css::lang::WrappedTargetException + -- css::uno::RuntimeException + + @param nHandle + handle + @param rValue + value + @throws css::uno::Exception + */ + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const css::uno::Any& rValue ) = 0; + /** + The same as getFastPropertyValue, but return the value through rValue and nHandle + is always valid. + The method is not implemented in this class. + */ + virtual void SAL_CALL getFastPropertyValue( + css::uno::Any& rValue, + sal_Int32 nHandle ) const = 0; + + /** sets an dependent property's value + +

    Sometimes setting a given property needs to implicitly modify another property's value. Calling |setPropertyValue| + from within |setFastPropertyValue_NoBroadcast| is not an option here, as it would notify the property listeners + while our mutex is still locked. Setting the dependent property's value directly (e.g. by calling |setFastPropertyValue_NoBroadcast| + recursively) is not an option, too, since it would miss firing the property change event.

    + +

    So, in such cases, you use |setDependentFastPropertyValue| from within |setFastPropertyValue_NoBroadcast|. + It will convert and actually set the property value (invoking |convertFastPropertyValue| and |setFastPropertyValue_NoBroadcast| + for the given handle and value), and add the property change event to the list of events to be notified + when the bottom-most |setFastPropertyValue_NoBroadcast| on the stack returns.

    + +

    Note: The method will not invoke veto listeners for the property.

    + +

    Note: It's the caller's responsibility to ensure that our mutex is locked. This is + canonically given when the method is invoked from within |setFastPropertyValue_NoBroadcast|, in other + contexts, you might need to take own measures.

    + */ + void setDependentFastPropertyValue( + sal_Int32 i_handle, + const css::uno::Any& i_value + ); + + /** The common data of a broadcaster. Use the mutex, disposing state and the listener container. */ + OBroadcastHelper &rBHelper; + /** + Container for the XPropertyChangedListener. The listeners are inserted by handle. + */ + OMultiTypeInterfaceContainerHelperInt32 aBoundLC; + /** + Container for the XPropertyVetoableListener. The listeners are inserted by handle. + */ + OMultiTypeInterfaceContainerHelperInt32 aVetoableLC; + + class Impl; + + /** reserved for future use. finally, the future has arrived... + */ + Impl * const m_pReserved; + +private: + OPropertySetHelper( const OPropertySetHelper & ) SAL_DELETED_FUNCTION; + OPropertySetHelper & operator = ( const OPropertySetHelper & ) + SAL_DELETED_FUNCTION; + + /** notifies the given changes in property's values, plus all property changes collected during recent + |setDependentFastPropertyValue| calls. + */ + void impl_fireAll( + sal_Int32* i_handles, + const css::uno::Any * i_newValues, + const css::uno::Any * i_oldValues, + sal_Int32 i_count + ); + +#if defined _MSC_VER // public -> protected changes mangled names there +public: +#else +protected: +#endif +// Suppress warning about virtual functions but non-virtual destructor: +#if defined _MSC_VER +#if defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif +#endif + /** + You must call disposing before destruction. + */ + ~OPropertySetHelper(); +}; +#if defined _MSC_VER +#if defined __clang__ +#pragma clang diagnostic pop +#endif +#endif + +/** + OPropertySetHelper plus XPropertySetOption + + @attention + The getTypes() inherited from OPropertysetHelper does not cover + XPropertySetOption. +*/ +class CPPUHELPER_DLLPUBLIC OPropertySetHelper2 : public OPropertySetHelper, + public css::beans::XPropertySetOption +{ +public: + /** Constructor. + + See OPropertySetHelper constructors documentation + */ + explicit OPropertySetHelper2( + OBroadcastHelper & rBHelper, + IEventNotificationHook *i_pFireEvents = NULL, + bool bIgnoreRuntimeExceptionsWhileFiring = false); + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) SAL_OVERRIDE; + + // XPropertySetOption + virtual void SAL_CALL enableChangeListenerNotification( sal_Bool bEnable ) SAL_OVERRIDE; + + +private: + OPropertySetHelper2( const OPropertySetHelper2 & ) SAL_DELETED_FUNCTION; + OPropertySetHelper2 & operator = ( const OPropertySetHelper2 & ) + SAL_DELETED_FUNCTION; + +#if defined _MSC_VER // public -> protected changes mangled names there +public: +#else +protected: +#endif +// Suppress warning about virtual functions but non-virtual destructor: + /** + You must call disposing before destruction. + */ + virtual ~OPropertySetHelper2(); +}; + +} // end namespace cppuhelper +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/proptypehlp.h b/include/cppuhelper/proptypehlp.h new file mode 100644 index 000000000..348e45afb --- /dev/null +++ b/include/cppuhelper/proptypehlp.h @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_PROPTYPEHLP_H +#define INCLUDED_CPPUHELPER_PROPTYPEHLP_H + +#include "sal/types.h" + +namespace com { namespace sun { namespace star { namespace uno { class Any; } } } } + +namespace cppu { + +/** Converts the value stored in an any to a concrete C++ type. + The function does the same as the operator >>= () at the + Any class, except that it throws an IllegalArgumentException in case of + failures (the value cannot be extracted without data loss ) + + @exception css::lang::IllegalArgumentException when the type could not be converted. + */ +template < class target > +inline void SAL_CALL convertPropertyValue( target &value , const css::uno::Any & a); + +/** + conversion of basic types +*/ +inline void SAL_CALL convertPropertyValue( sal_Bool & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( bool & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_Int64 & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_uInt64 & target, const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_Int32 & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_uInt32 & target, const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_Int16 & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_uInt16 & target, const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( sal_Int8 & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( float & target , const css::uno::Any & source ); +inline void SAL_CALL convertPropertyValue( double &target , const css::uno::Any &source ); + +} // end namespace cppu + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/proptypehlp.hxx b/include/cppuhelper/proptypehlp.hxx new file mode 100644 index 000000000..339c3910e --- /dev/null +++ b/include/cppuhelper/proptypehlp.hxx @@ -0,0 +1,286 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_PROPTYPEHLP_HXX +#define INCLUDED_CPPUHELPER_PROPTYPEHLP_HXX + +#include "cppuhelper/proptypehlp.h" +#include "com/sun/star/lang/IllegalArgumentException.hpp" +#include "com/sun/star/uno/TypeClass.hpp" + +namespace cppu +{ + +template < class target > +inline void SAL_CALL convertPropertyValue( target &value , const css::uno::Any & a) +{ + + if( !( a >>= value ) ) { + throw css::lang::IllegalArgumentException(); + } +} + +void convertPropertyValue(bool & b, const css::uno::Any & a) +{ + if( a >>= b ) + return; + + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BYTE: + b = a.get() != 0; + break; + case css::uno::TypeClass_SHORT: + b = a.get() != 0; + break; + case css::uno::TypeClass_UNSIGNED_SHORT: + { + sal_uInt16 i16 = 0; + a >>= i16; + b = i16 != 0; + break; + } + case css::uno::TypeClass_LONG: + b = a.get() != 0; + break; + case css::uno::TypeClass_UNSIGNED_LONG: + b = a.get() != 0; + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c = *static_cast(a.getValue()); + b = c != 0; + break; + } + default: + throw css::lang::IllegalArgumentException(); + } +} + +void convertPropertyValue(sal_Bool & target, css::uno::Any const & source) { + bool b; + convertPropertyValue(b, source); + target = b; +} + +inline void SAL_CALL convertPropertyValue( sal_Int64 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + i = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } + } +} + + +inline void SAL_CALL convertPropertyValue( sal_uInt64 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + i = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } + } +} + +inline void SAL_CALL convertPropertyValue( sal_Int32 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + i = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } + } +} + +inline void SAL_CALL convertPropertyValue( sal_uInt32 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + i = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } + } +} + +inline void SAL_CALL convertPropertyValue( sal_Int16 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + i = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } + } +} + +inline void SAL_CALL convertPropertyValue( sal_uInt16 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + i = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } + } +} + +inline void SAL_CALL convertPropertyValue( sal_Int8 & i , const css::uno::Any & a ) +{ + if( !(a >>= i) ) { + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + i = static_cast(a.get()); + break; + default: + throw css::lang::IllegalArgumentException(); + } + } +} + +inline void SAL_CALL convertPropertyValue( float &f , const css::uno::Any &a ) +{ + if( a >>= f ) + return; + + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + f = static_cast(a.get()); + break; + case css::uno::TypeClass_LONG: + f = static_cast(a.get()); + break; + case css::uno::TypeClass_UNSIGNED_LONG: + f = static_cast(a.get()); + break; + case css::uno::TypeClass_HYPER: + f = static_cast(a.get()); + break; + case css::uno::TypeClass_UNSIGNED_HYPER: + f = static_cast(a.get()); + break; + case css::uno::TypeClass_DOUBLE: + f = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + f = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } +} + +inline void SAL_CALL convertPropertyValue( double &d , const css::uno::Any &a ) +{ + if( a >>= d ) + return; + + switch( a.getValueType().getTypeClass() ) { + case css::uno::TypeClass_BOOLEAN: + d = static_cast(a.get()); + break; + case css::uno::TypeClass_HYPER: + d = static_cast(a.get()); + break; + case css::uno::TypeClass_UNSIGNED_HYPER: + d = static_cast(a.get()); + break; + case css::uno::TypeClass_CHAR: + { + sal_Unicode c; + c = *static_cast(a.getValue()); + d = static_cast(c); + break; + } + default: + throw css::lang::IllegalArgumentException(); + } +} + +} // end namespace cppu + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/queryinterface.hxx b/include/cppuhelper/queryinterface.hxx new file mode 100644 index 000000000..df9c9916c --- /dev/null +++ b/include/cppuhelper/queryinterface.hxx @@ -0,0 +1,526 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_QUERYINTERFACE_HXX +#define INCLUDED_CPPUHELPER_QUERYINTERFACE_HXX + +#include "sal/config.h" +#include "com/sun/star/uno/Any.hxx" +#include "com/sun/star/uno/Type.h" +#include "sal/types.h" + +namespace cppu +{ + +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @param rType demanded type + @param p1 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @tparam Interface7 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @param p7 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6, class Interface7 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6, Interface7 * p7 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else if (rType == Interface7::static_type()) + return css::uno::Any( &p7, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @tparam Interface7 interface type + @tparam Interface8 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @param p7 interface pointer + @param p8 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6, class Interface7, class Interface8 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6, Interface7 * p7, Interface8 * p8 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else if (rType == Interface7::static_type()) + return css::uno::Any( &p7, rType ); + else if (rType == Interface8::static_type()) + return css::uno::Any( &p8, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @tparam Interface7 interface type + @tparam Interface8 interface type + @tparam Interface9 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @param p7 interface pointer + @param p8 interface pointer + @param p9 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6, class Interface7, class Interface8, class Interface9 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6, Interface7 * p7, Interface8 * p8, Interface9 * p9 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else if (rType == Interface7::static_type()) + return css::uno::Any( &p7, rType ); + else if (rType == Interface8::static_type()) + return css::uno::Any( &p8, rType ); + else if (rType == Interface9::static_type()) + return css::uno::Any( &p9, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @tparam Interface7 interface type + @tparam Interface8 interface type + @tparam Interface9 interface type + @tparam Interface10 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @param p7 interface pointer + @param p8 interface pointer + @param p9 interface pointer + @param p10 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6, class Interface7, class Interface8, class Interface9, class Interface10 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6, Interface7 * p7, Interface8 * p8, Interface9 * p9, Interface10 * p10 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else if (rType == Interface7::static_type()) + return css::uno::Any( &p7, rType ); + else if (rType == Interface8::static_type()) + return css::uno::Any( &p8, rType ); + else if (rType == Interface9::static_type()) + return css::uno::Any( &p9, rType ); + else if (rType == Interface10::static_type()) + return css::uno::Any( &p10, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @tparam Interface7 interface type + @tparam Interface8 interface type + @tparam Interface9 interface type + @tparam Interface10 interface type + @tparam Interface11 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @param p7 interface pointer + @param p8 interface pointer + @param p9 interface pointer + @param p10 interface pointer + @param p11 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6, class Interface7, class Interface8, class Interface9, class Interface10, + class Interface11 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6, Interface7 * p7, Interface8 * p8, Interface9 * p9, Interface10 * p10, + Interface11 * p11 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else if (rType == Interface7::static_type()) + return css::uno::Any( &p7, rType ); + else if (rType == Interface8::static_type()) + return css::uno::Any( &p8, rType ); + else if (rType == Interface9::static_type()) + return css::uno::Any( &p9, rType ); + else if (rType == Interface10::static_type()) + return css::uno::Any( &p10, rType ); + else if (rType == Interface11::static_type()) + return css::uno::Any( &p11, rType ); + else + return css::uno::Any(); +} +/** Compares demanded type to given template argument types. + + @tparam Interface1 interface type + @tparam Interface2 interface type + @tparam Interface3 interface type + @tparam Interface4 interface type + @tparam Interface5 interface type + @tparam Interface6 interface type + @tparam Interface7 interface type + @tparam Interface8 interface type + @tparam Interface9 interface type + @tparam Interface10 interface type + @tparam Interface11 interface type + @tparam Interface12 interface type + @param rType demanded type + @param p1 interface pointer + @param p2 interface pointer + @param p3 interface pointer + @param p4 interface pointer + @param p5 interface pointer + @param p6 interface pointer + @param p7 interface pointer + @param p8 interface pointer + @param p9 interface pointer + @param p10 interface pointer + @param p11 interface pointer + @param p12 interface pointer + @return acquired interface of demanded type or empty Any +*/ +template< class Interface1, class Interface2, class Interface3, class Interface4, class Interface5, + class Interface6, class Interface7, class Interface8, class Interface9, class Interface10, + class Interface11, class Interface12 > +inline css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType, + Interface1 * p1, Interface2 * p2, Interface3 * p3, Interface4 * p4, Interface5 * p5, + Interface6 * p6, Interface7 * p7, Interface8 * p8, Interface9 * p9, Interface10 * p10, + Interface11 * p11, Interface12 * p12 ) +{ + if (rType == Interface1::static_type()) + return css::uno::Any( &p1, rType ); + else if (rType == Interface2::static_type()) + return css::uno::Any( &p2, rType ); + else if (rType == Interface3::static_type()) + return css::uno::Any( &p3, rType ); + else if (rType == Interface4::static_type()) + return css::uno::Any( &p4, rType ); + else if (rType == Interface5::static_type()) + return css::uno::Any( &p5, rType ); + else if (rType == Interface6::static_type()) + return css::uno::Any( &p6, rType ); + else if (rType == Interface7::static_type()) + return css::uno::Any( &p7, rType ); + else if (rType == Interface8::static_type()) + return css::uno::Any( &p8, rType ); + else if (rType == Interface9::static_type()) + return css::uno::Any( &p9, rType ); + else if (rType == Interface10::static_type()) + return css::uno::Any( &p10, rType ); + else if (rType == Interface11::static_type()) + return css::uno::Any( &p11, rType ); + else if (rType == Interface12::static_type()) + return css::uno::Any( &p12, rType ); + else + return css::uno::Any(); +} + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/shlib.hxx b/include/cppuhelper/shlib.hxx new file mode 100644 index 000000000..07caef0ea --- /dev/null +++ b/include/cppuhelper/shlib.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_SHLIB_HXX +#define INCLUDED_CPPUHELPER_SHLIB_HXX + +#include "cppuhelper/cppuhelperdllapi.h" +#include "com/sun/star/uno/Reference.h" +#include "rtl/ustring.hxx" + +namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } } +namespace com { namespace sun { namespace star { namespace registry { class XRegistryKey; } } } } +namespace com { namespace sun { namespace star { namespace uno { class XInterface; } } } } + +namespace cppu +{ + +/** Loads a shared library component and gets the factory out of it. You can give either a + fully qualified libname or single lib name. The libname need not be pre/postfixed + (e.g. xxx.dll). + + @deprecated + This should never have been put into the URE interface. Do not call it from + client code. + + @param uri URI of the library + @param rPath deprecated, must be empty + @param rImplName implementation to be retrieved from the library + @param xMgr service manager to be provided to the component + @param xKey deprecated, must be null + @return + factory instance (css::lang::XSingleComponentFactory or legacy + css::lang::XSingleServiceFactory) +*/ +CPPUHELPER_DLLPUBLIC css::uno::Reference< css::uno::XInterface > +SAL_CALL loadSharedLibComponentFactory( + ::rtl::OUString const & uri, + ::rtl::OUString const & rPath, + ::rtl::OUString const & rImplName, + css::uno::Reference< css::lang::XMultiServiceFactory > const & xMgr, + css::uno::Reference< css::registry::XRegistryKey > const & xKey ); + +/** Invokes component_writeInfo() function of specified component library. You can give either + a fully qualified libname or single lib name. The libname need not be pre/postfixed + (e.g. xxx.dll). + + @deprecated + This should never have been put into the URE interface. Do not call it from + client code. Also, this functionality is not needed for passively + registered components, only for actively registered legacy ones. + + @param uri URI of the library + @param rPath deprecated, must be empty + @param xMgr service manager to be provided to the component + @param xKey registry key to be provided to the component +*/ +CPPUHELPER_DLLPUBLIC void +SAL_CALL writeSharedLibComponentInfo( + ::rtl::OUString const & uri, + ::rtl::OUString const & rPath, + css::uno::Reference< css::lang::XMultiServiceFactory > const & xMgr, + css::uno::Reference< css::registry::XRegistryKey > const & xKey ); + +} // end namespace cppu + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/supportsservice.hxx b/include/cppuhelper/supportsservice.hxx new file mode 100644 index 000000000..8834a3181 --- /dev/null +++ b/include/cppuhelper/supportsservice.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_SUPPORTSSERVICE_HXX +#define INCLUDED_CPPUHELPER_SUPPORTSSERVICE_HXX + +#include "sal/config.h" + +#include "cppuhelper/cppuhelperdllapi.h" + +namespace com { namespace sun { namespace star { namespace lang { + class XServiceInfo; +} } } } +namespace rtl { class OUString; } + +namespace cppu { + +/** A helper for implementations of com.sun.star.lang.XServiceInfo. + + This function is supposed to be called from implementations of + css::lang::XServiceInfo::supportsService (and therefore, for + easier coding takes the caller's this pointer by pointer rather than by + css::uno::Reference). + + @param implementation points to the service implementation whose + getSupportedServices method is consulted; must be non-null + + @param name the service name to test + + @return true iff the sequence returned by the given implementation's + getSupportedServices method contains the given name + + @since LibreOffice 4.0 +*/ +bool CPPUHELPER_DLLPUBLIC supportsService( + css::lang::XServiceInfo * implementation, + rtl::OUString const & name); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/typeprovider.hxx b/include/cppuhelper/typeprovider.hxx new file mode 100644 index 000000000..4c3bd99d1 --- /dev/null +++ b/include/cppuhelper/typeprovider.hxx @@ -0,0 +1,232 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_TYPEPROVIDER_HXX +#define INCLUDED_CPPUHELPER_TYPEPROVIDER_HXX + +#include "sal/config.h" + +#include + +#include "rtl/alloc.h" +#include "com/sun/star/uno/Sequence.hxx" +#include "cppuhelper/cppuhelperdllapi.h" + + +namespace cppu +{ + +/** Helper class to implement css::lang::XTypeProvider. Construct a static object + of this class with your UNO object's supported types. +*/ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC OTypeCollection +{ + css::uno::Sequence< css::uno::Type > _aTypes; + +public: + /// @cond INTERNAL + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + /// @endcond + + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Type & rType7, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Type & rType7, + const css::uno::Type & rType8, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Type & rType7, + const css::uno::Type & rType8, + const css::uno::Type & rType9, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Type & rType7, + const css::uno::Type & rType8, + const css::uno::Type & rType9, + const css::uno::Type & rType10, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Type & rType7, + const css::uno::Type & rType8, + const css::uno::Type & rType9, + const css::uno::Type & rType10, + const css::uno::Type & rType11, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + OTypeCollection( + const css::uno::Type & rType1, + const css::uno::Type & rType2, + const css::uno::Type & rType3, + const css::uno::Type & rType4, + const css::uno::Type & rType5, + const css::uno::Type & rType6, + const css::uno::Type & rType7, + const css::uno::Type & rType8, + const css::uno::Type & rType9, + const css::uno::Type & rType10, + const css::uno::Type & rType11, + const css::uno::Type & rType12, + const css::uno::Sequence< css::uno::Type > & rAddTypes = css::uno::Sequence< css::uno::Type >() ); + + /** Called upon XTypeProvider::getTypes(). + + @return type collection + */ + css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() + { return _aTypes; } +#if defined LIBO_INTERNAL_ONLY + css::uno::Sequence< css::uno::Type > const & getTypes() const + { return _aTypes; } +#endif +}; + +/** Helper class to implement IDs for XUnoTunnel. Construct a static object + of this class for your UNO object's implementation id. +*/ +class SAL_DEPRECATED("Uses broken double checked locking") SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC OImplementationId +{ + mutable css::uno::Sequence< sal_Int8 > * _pSeq; + sal_Bool _bUseEthernetAddress; + +public: + /// @cond INTERNAL + + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + ~OImplementationId(); + + /// @endcond + + /** Constructor. + + @param bUseEthernetAddress whether an ethernet mac address should be taken into account + */ + OImplementationId( bool bUseEthernetAddress = true ) + : _pSeq( NULL ) + , _bUseEthernetAddress( bUseEthernetAddress ) + {} + /** Constructor giving implementation id. + + @param rSeq implementation id + */ + OImplementationId( const css::uno::Sequence< sal_Int8 > & rSeq ) + : _pSeq( new css::uno::Sequence< sal_Int8 >( rSeq ) ) + , _bUseEthernetAddress( false ) + {} +SAL_WNODEPRECATED_DECLARATIONS_PUSH + OImplementationId( const OImplementationId & rId ) + : _pSeq( new css::uno::Sequence< sal_Int8 >( rId.getImplementationId() ) ) + , _bUseEthernetAddress( false ) + {} +SAL_WNODEPRECATED_DECLARATIONS_POP + + /** Get implementation id. + + @return implementation id + */ + css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() const; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/unourl.hxx b/include/cppuhelper/unourl.hxx new file mode 100644 index 000000000..45afaedad --- /dev/null +++ b/include/cppuhelper/unourl.hxx @@ -0,0 +1,188 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_CPPUHELPER_UNOURL_HXX +#define INCLUDED_CPPUHELPER_UNOURL_HXX + +#include "sal/config.h" + +#include "cppuhelper/cppuhelperdllapi.h" + +namespace rtl +{ +class OUString; +} + +namespace cppu +{ +/** A descriptor as part of a UNO URL (connection descriptor or protocol + descriptor). + + Such a descriptor can also be useful outside the context of a full UNO URL. + For example, some functions take a string representing a connection or + protocol descriptor as input, and can use this class to parse the string. + */ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC UnoUrlDescriptor +{ +public: + class Impl; + + /** Construct a descriptor from a string representation. + + @param rDescriptor + The string representation of a descriptor. + + @exception rtl::MalformedUriException + Thrown when the given string representation is invalid. + */ + explicit UnoUrlDescriptor(rtl::OUString const& rDescriptor); + + UnoUrlDescriptor(UnoUrlDescriptor const& rOther); + + ~UnoUrlDescriptor(); + + UnoUrlDescriptor& operator=(UnoUrlDescriptor const& rOther); + + /** Return the string representation of the descriptor. + + @return + A reference to the string representation used to construct this + descriptor, without any modifications. The reference is valid for the + lifetime of this URL object. + */ + rtl::OUString const& getDescriptor() const; + + /** Return the name component of the descriptor. + + @return + A reference to the (case insensitive) name, in lower case form. The + reference is valid for the lifetime of this URL object. + */ + rtl::OUString const& getName() const; + + /** Test whether the parameters contain a key. + + @param + rKey A (case insensitive) key. + + @return + True if the parameters contain a matching key/value pair. + */ + bool hasParameter(rtl::OUString const& rKey) const; + + /** Return the parameter value for a key. + + @param + rKey A (case insensitive) key. + + @return + The (case sensitive) value associated with the given key, or an empty + string if there is no matching key/value pair. + */ + rtl::OUString getParameter(rtl::OUString const& rKey) const; + +private: + Impl* m_pImpl; +}; + +/** Parse UNO URLs into their components. + + The ABNF for UNO URLs is as follows (see RFCs 2234, 2396, also see + ): + + uno-url = "UNO:" connection ";" protocol ";" object-name + connection = descriptor + protocol = descriptor + descriptor = name *("," parameter) + name = 1*alphanum + parameter = key "=" value + key = 1*alphanum + value = *vchar + valchar = unreserved / escaped / "$" / "&" / "+" / "/" / ":" / "?" / "@" + object-name = 1*ochar + ochar = unreserved / "$" / "&" / "+" / "," / "/" / ":" / "=" / "?" / "@" + + Within a descriptor, the name and the keys are case insensitive, and within + the parameter list all keys must be distinct. + + Parameter values are encoded using UTF-8. Note that parsing of parameter + values as done by UnoUrl and UnoUrlDescriptor is not strict: Invalid UTF-16 + entities in the input, as well as broken escape sequences ("%" not followed + by two hex digits) are copied verbatim to the output, invalid bytes in the + converted UTF-8 data are considered individual Unicode characters, and + invalid UTF-16 entities in the resulting output (e.g., a high surrogate not + followed by a low surrogate) are not detected. + */ +class SAL_WARN_UNUSED CPPUHELPER_DLLPUBLIC UnoUrl +{ +public: + /** Construct a UNO URL from a string representation. + + @param rUrl + The string representation of a UNO URL. + + @exception rtl::MalformedUriException + Thrown when the given string representation is invalid. + */ + explicit UnoUrl(rtl::OUString const& rUrl); + + UnoUrl(UnoUrl const& rOther); + + ~UnoUrl(); + + UnoUrl& operator=(UnoUrl const& rOther); + + /** Return the connection descriptor component of the URL. + + @return + A reference to the connection descriptor. The reference is valid for + the lifetime of this URL object. + */ + UnoUrlDescriptor const& getConnection() const; + + /** Return the protocol descriptor component of the URL. + + @return + A reference to the protocol descriptor. The reference is valid for the + lifetime of this URL object. + */ + UnoUrlDescriptor const& getProtocol() const; + + /** Return the object-name component of the URL. + + @return + A reference to the (case sensitive) object-name. The reference is valid + for the lifetime of this URL object. + */ + rtl::OUString const& getObjectName() const; + +private: + class Impl; + + Impl* m_pImpl; +}; +} + +#endif // INCLUDED_RTL_UNOURL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/weak.hxx b/include/cppuhelper/weak.hxx new file mode 100644 index 000000000..b8e4e9955 --- /dev/null +++ b/include/cppuhelper/weak.hxx @@ -0,0 +1,176 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_WEAK_HXX +#define INCLUDED_CPPUHELPER_WEAK_HXX + +#include +#include +#include "osl/interlck.h" +#include "rtl/alloc.h" +#include "com/sun/star/uno/XWeak.hpp" +#include "cppuhelper/cppuhelperdllapi.h" + + +namespace cppu +{ + +class OWeakConnectionPoint; + +/** Base class to implement a UNO object supporting weak references, i.e. the object can be held + weakly (by a css::uno::WeakReference). + This implementation copes with reference counting. Upon last release(), the virtual dtor + is called. + + @derive + Inherit from this class and delegate acquire()/ release() calls. +*/ +class CPPUHELPER_DLLPUBLIC OWeakObject : public css::uno::XWeak +{ + friend class OWeakConnectionPoint; + +protected: + /** Virtual dtor. + + @attention + Despite the fact that a RuntimeException is allowed to be thrown, you must not throw any + exception upon destruction! + */ + virtual ~OWeakObject() COVERITY_NOEXCEPT_FALSE; + + /** disposes and resets m_pWeakConnectionPoint + @pre + m_refCount equals 0 + */ + void disposeWeakConnectionPoint(); + + /** reference count. + + @attention + Don't modify manually! Use acquire() and release(). + */ + oslInterlockedCount m_refCount; + + /// @cond INTERNAL + + /** Container of all weak reference listeners and the connection point from the weak reference. + */ + OWeakConnectionPoint * m_pWeakConnectionPoint; + + /** reserved for future use. do not use. + */ + void * m_pReserved; + + /// @endcond + +public: + /// @cond INTERNAL + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + /// @endcond + + /** Default Constructor. Sets the reference count to zero. + */ + OWeakObject() + : m_refCount( 0 ) + , m_pWeakConnectionPoint( NULL ) + , m_pReserved(NULL) + {} + + /** Dummy copy constructor. Set the reference count to zero. + */ + OWeakObject( const OWeakObject & ) + : css::uno::XWeak() + , m_refCount( 0 ) + , m_pWeakConnectionPoint( NULL ) + , m_pReserved(NULL) + {} + /** Dummy assignment operator. Does not affect reference count. + + @return this OWeakObject + */ + OWeakObject & SAL_CALL operator = ( const OWeakObject &) + { return *this; } + + /** Basic queryInterface() implementation supporting com::sun::star::uno::XWeak and + com::sun::star::uno::XInterface. + + @param rType demanded type + @return demanded type or empty any + */ + virtual css::uno::Any SAL_CALL queryInterface( + const css::uno::Type & rType ) SAL_OVERRIDE; + /** increasing m_refCount + */ + virtual void SAL_CALL acquire() + SAL_NOEXCEPT SAL_OVERRIDE; + /** decreasing m_refCount + */ + virtual void SAL_CALL release() + SAL_NOEXCEPT SAL_OVERRIDE; + + /** XWeak::queryAdapter() implementation + + @return a com::sun::star::uno::XAdapter reference + */ + virtual css::uno::Reference< css::uno::XAdapter > SAL_CALL queryAdapter() SAL_OVERRIDE; + + /** Cast operator to XInterface reference. + + @return XInterface reference + */ + SAL_CALL operator css::uno::Reference< css::uno::XInterface > () + { return this; } +}; + +/// @cond INTERNAL +/** Convenience function for constructor-based service implementations. + + To be used like: + + css::uno::XInterface * FOO_constructor_function(...) { + return cppu::acquire(new FOO(...)); + } + + @param instance + Newly created instance that should be acquired. +*/ +static inline css::uno::XInterface * acquire(OWeakObject * instance) +{ + assert(instance != NULL); + instance->acquire(); + return instance; +} +/// @endcond + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/weakagg.hxx b/include/cppuhelper/weakagg.hxx new file mode 100644 index 000000000..0b770a428 --- /dev/null +++ b/include/cppuhelper/weakagg.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_WEAKAGG_HXX +#define INCLUDED_CPPUHELPER_WEAKAGG_HXX + +#include "cppuhelper/weak.hxx" +#include "cppuhelper/weakref.hxx" +#include "com/sun/star/uno/XAggregation.hpp" +#include "cppuhelper/cppuhelperdllapi.h" + + +namespace cppu +{ + +/** Base class to implement a UNO object supporting weak references, i.e. the object can be held + weakly (by a css::uno::WeakReference) and aggregation, i.e. the object can be + aggregated by another (delegator). + This implementation copes with reference counting. Upon last release(), the virtual dtor + is called. + + @derive + Inherit from this class and delegate acquire()/ release() calls. Re-implement + XAggregation::queryInterface(). +*/ +class CPPUHELPER_DLLPUBLIC OWeakAggObject + : public ::cppu::OWeakObject + , public css::uno::XAggregation +{ +public: + /** Constructor. No delegator set. + */ + OWeakAggObject() + {} + + /** If a delegator is set, then the delegators gets acquired. Otherwise call is delegated to + base class ::cppu::OWeakObject. + */ + virtual void SAL_CALL acquire() SAL_NOEXCEPT SAL_OVERRIDE; + /** If a delegator is set, then the delegators gets released. Otherwise call is delegated to + base class ::cppu::OWeakObject. + */ + virtual void SAL_CALL release() SAL_NOEXCEPT SAL_OVERRIDE; + /** If a delegator is set, then the delegator is queried for the demanded interface. If the + delegator cannot provide the demanded interface, it calls queryAggregation() on its + aggregated objects. + + @param rType demanded interface type + @return demanded type or empty any + @see queryAggregation. + */ + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) SAL_OVERRIDE; + + /** Set the delegator. The delegator member reference is a weak reference. + + @param Delegator the object that delegate its queryInterface to this aggregate. + */ + virtual void SAL_CALL setDelegator( const css::uno::Reference< css::uno::XInterface > & Delegator ) SAL_OVERRIDE; + /** Called by the delegator or queryInterface. Re-implement this method instead of + queryInterface. + + @see queryInterface + */ + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ) SAL_OVERRIDE; + +protected: + /** Virtual dtor. Called when reference count is 0. + + @attention + Despite the fact that a RuntimeException is allowed to be thrown, you must not throw any + exception upon destruction! + */ + virtual ~OWeakAggObject() SAL_OVERRIDE; + + /** weak reference to delegator. + */ + css::uno::WeakReferenceHelper xDelegator; +private: + OWeakAggObject( const OWeakAggObject & rObj ) SAL_DELETED_FUNCTION; + OWeakAggObject & operator = ( const OWeakAggObject & rObj ) + SAL_DELETED_FUNCTION; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppuhelper/weakref.hxx b/include/cppuhelper/weakref.hxx new file mode 100644 index 000000000..a5858b2e8 --- /dev/null +++ b/include/cppuhelper/weakref.hxx @@ -0,0 +1,228 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_CPPUHELPER_WEAKREF_HXX +#define INCLUDED_CPPUHELPER_WEAKREF_HXX + +#include "sal/config.h" + +#include + +#include "com/sun/star/uno/Reference.hxx" +#include "com/sun/star/uno/XInterface.hpp" +#include "cppuhelper/cppuhelperdllapi.h" + + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace uno +{ + +class OWeakRefListener; +class XWeak; + +/** The WeakReferenceHelper holds a weak reference to an object. + + That object must implement the css::uno::XWeak interface. + + The WeakReferenceHelper itself is *not* thread safe, just as + Reference itself isn't, but the implementation of the listeners etc. + behind it *is* thread-safe, so multiple threads can have their own + WeakReferences to the same XWeak object. +*/ +class CPPUHELPER_DLLPUBLIC WeakReferenceHelper +{ +public: + /** Default ctor. Creates an empty weak reference. + */ + WeakReferenceHelper() + : m_pImpl( NULL ) + {} + + /** Copy ctor. Initialize this reference with the same interface as in rWeakRef. + + @param rWeakRef another weak ref + */ + WeakReferenceHelper( const WeakReferenceHelper & rWeakRef ); + +#if defined LIBO_INTERNAL_ONLY + WeakReferenceHelper(WeakReferenceHelper && other) noexcept : m_pImpl(other.m_pImpl) + { other.m_pImpl = nullptr; } +#endif + + /** Initialize this reference with the hard interface reference xInt. If the implementation + behind xInt does not support XWeak or xInt is null then this reference will be null. + + @param xInt another hard interface reference + */ + WeakReferenceHelper( const css::uno::Reference< css::uno::XInterface > & xInt ); + +#if defined LIBO_INTERNAL_ONLY + /** Initialize this reference with the hard interface reference xWeak. This + is faster than the XInterface constructor because we can skip doing an + UNO_QUERY. + + @param xWeak another hard interface reference + */ + WeakReferenceHelper( const css::uno::Reference< css::uno::XWeak > & xWeak ); +#endif + + /** Releases this reference. + */ + ~WeakReferenceHelper(); + + /** Releases this reference and takes over rWeakRef. + + @param rWeakRef another weak ref + */ + WeakReferenceHelper & SAL_CALL operator = ( const WeakReferenceHelper & rWeakRef ); + +#if defined LIBO_INTERNAL_ONLY + WeakReferenceHelper & operator =(WeakReferenceHelper && other); +#endif + + /** Releases this reference and takes over hard reference xInt. + If the implementation behind xInt does not support XWeak + or XInt is null, then this reference is null. + + @param xInt another hard reference + */ + WeakReferenceHelper & SAL_CALL operator = ( + const css::uno::Reference< css::uno::XInterface > & xInt ); + +#if defined LIBO_INTERNAL_ONLY + /** Releases this reference and takes over hard reference xWeak. This + is faster than the XInterface constructor because we can skip doing an + UNO_QUERY. + + @param xWeak another hard reference + */ + WeakReferenceHelper & operator = ( + const css::uno::Reference< css::uno::XWeak > & xWeak ); +#endif + + /** Returns true if both weak refs reference to the same object. + + @param rObj another weak ref + @return true, if both weak refs reference to the same object. + */ + bool SAL_CALL operator == ( const WeakReferenceHelper & rObj ) const + { return (get() == rObj.get()); } + + /** Gets a hard reference to the object. + + @return hard reference or null, if the weakly referenced interface has gone + */ + css::uno::Reference< css::uno::XInterface > SAL_CALL get() const; + + /** Gets a hard reference to the object. + + @return hard reference or null, if the weakly referenced interface has gone + */ + SAL_CALL operator Reference< XInterface > () const + { return get(); } + + /** Releases this reference. + + @since UDK 3.2.12 + */ + void SAL_CALL clear(); + +protected: + /// @cond INTERNAL + OWeakRefListener * m_pImpl; + /// @endcond +}; + +/** The WeakReference<> holds a weak reference to an object. + + That object must implement the css::uno::XWeak interface. + + The WeakReference itself is *not* thread safe, just as + Reference itself isn't, but the implementation of the listeners etc. + behind it *is* thread-safe, so multiple threads can have their own + WeakReferences to the same XWeak object. + + @tparam interface_type type of interface +*/ +template< class interface_type > +class SAL_WARN_UNUSED WeakReference : public WeakReferenceHelper +{ +public: + /** Default ctor. Creates an empty weak reference. + */ + WeakReference() + : WeakReferenceHelper() + {} + + /** Copy ctor. Initialize this reference with a hard reference. + + @param rRef another hard ref + */ + WeakReference( const Reference< interface_type > & rRef ) + : WeakReferenceHelper( rRef ) + {} + + /** Releases this reference and takes over hard reference xInt. + If the implementation behind xInt does not support XWeak + or XInt is null, then this reference is null. + + @param xInt another hard reference + + @since UDK 3.2.12 + */ + WeakReference & SAL_CALL operator = ( + const css::uno::Reference< interface_type > & xInt ) + { WeakReferenceHelper::operator=(xInt); return *this; } + +#if defined LIBO_INTERNAL_ONLY + /** Releases this reference and takes over hard reference xWeak. This + is faster than the XInterface constructor because we can skip doing an + UNO_QUERY. + + @param xWeak another hard reference + */ + WeakReference & operator = ( + const css::uno::Reference< css::uno::XWeak > & xWeak ) + { WeakReferenceHelper::operator=(xWeak); return *this; } +#endif + + /** Gets a hard reference to the object. + + @return hard reference or null, if the weakly referenced interface has gone + */ + SAL_CALL operator Reference< interface_type > () const + { return Reference< interface_type >::query( get() ); } +}; + +} +} +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cppunittester/protectorfactory.hxx b/include/cppunittester/protectorfactory.hxx new file mode 100644 index 000000000..6617dbb47 --- /dev/null +++ b/include/cppunittester/protectorfactory.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_CPPUNITTESTER_PROTECTORFACTORY_HXX +#define INCLUDED_CPPUNITTESTER_PROTECTORFACTORY_HXX + +#include +#include + +namespace cppunittester +{ + // The type of CppUnit::Protector factory functions that can be plugged into + // cppunittester: + extern "C" typedef CppUnit::Protector * ProtectorFactory(); +} + +#ifdef DISABLE_DYNLOADING +extern "C" CppUnit::Protector *unoexceptionprotector(); +extern "C" CppUnit::Protector *unobootstrapprotector(); +extern "C" CppUnit::Protector *vclbootstrapprotector(); +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cui/cuicharmap.hxx b/include/cui/cuicharmap.hxx new file mode 100644 index 000000000..688fb570e --- /dev/null +++ b/include/cui/cuicharmap.hxx @@ -0,0 +1,194 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_CUI_CUICHARMAP_HXX +#define INCLUDED_CUI_CUICHARMAP_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace ::com::sun::star; +class SubsetMap; + +#define CHARMAP_MAXLEN 32 + +namespace svx +{ +struct SvxShowCharSetItem; +} + +/// Provides the show characters or texts in a drawing area with special sizes and fonts. +class CUI_DLLPUBLIC SvxShowText final : public weld::CustomWidgetController +{ +private: + ScopedVclPtr m_xVirDev; + OUString m_sText; + tools::Long mnY; + bool mbCenter; + vcl::Font m_aFont; + + virtual void Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle&) override; + virtual void Resize() override; + virtual void SetDrawingArea(weld::DrawingArea* pDrawingArea) override; + +public: + SvxShowText(const VclPtr& rVirDev); + + void SetFont(const vcl::Font& rFont); + vcl::Font const& GetFont() const { return m_aFont; } + void SetText(const OUString& rText); + OUString const& GetText() const { return m_sText; } + void SetCentered(bool bCenter) { mbCenter = bCenter; } + + Size get_preferred_size() const { return GetDrawingArea()->get_preferred_size(); } +}; + +/** The main purpose of this dialog is to enable the use of characters + that are not easily accessible from the keyboard. */ +class CUI_DLLPUBLIC SvxCharacterMap final : public SfxDialogController +{ +private: + void init(); + + ScopedVclPtr m_xVirDev; + vcl::Font aFont; + std::unique_ptr pSubsetMap; + bool isSearchMode; + css::uno::Reference m_xFrame; + std::deque maRecentCharList; + std::deque maRecentCharFontList; + std::deque maFavCharList; + std::deque maFavCharFontList; + + SvxCharView m_aRecentCharView[16]; + SvxCharView m_aFavCharView[16]; + SvxShowText m_aShowChar; + + std::unique_ptr m_xOKBtn; + std::unique_ptr m_xFontText; + std::unique_ptr m_xFontLB; + std::unique_ptr m_xSubsetText; + std::unique_ptr m_xSubsetLB; + std::unique_ptr m_xSearchText; + std::unique_ptr m_xHexCodeText; + std::unique_ptr m_xDecimalCodeText; + std::unique_ptr m_xFavouritesBtn; + std::unique_ptr m_xCharName; + std::unique_ptr m_xRecentGrid; + std::unique_ptr m_xFavGrid; + std::unique_ptr m_xShowChar; + std::unique_ptr m_xRecentCharView[16]; + std::unique_ptr m_xFavCharView[16]; + std::unique_ptr m_xShowSet; + std::unique_ptr m_xShowSetArea; + std::unique_ptr m_xSearchSet; + std::unique_ptr m_xSearchSetArea; + + std::unique_ptr m_xOutputSet; + + enum class Radix : sal_Int16 + { + decimal = 10, + hexadecimal = 16 + }; + + DECL_DLLPRIVATE_LINK(FontSelectHdl, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(SubsetSelectHdl, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(CharDoubleClickHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(CharSelectHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(CharHighlightHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(CharPreSelectHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(FavClickHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(SearchCharDoubleClickHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(SearchCharSelectHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(SearchCharHighlightHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(SearchCharPreSelectHdl, SvxShowCharSet*, void); + DECL_DLLPRIVATE_LINK(DecimalCodeChangeHdl, weld::Entry&, void); + DECL_DLLPRIVATE_LINK(HexCodeChangeHdl, weld::Entry&, void); + DECL_DLLPRIVATE_LINK(CharClickHdl, SvxCharView*, void); + DECL_DLLPRIVATE_LINK(RecentClearClickHdl, SvxCharView*, void); + DECL_DLLPRIVATE_LINK(FavClearClickHdl, SvxCharView*, void); + DECL_DLLPRIVATE_LINK(RecentClearAllClickHdl, SvxCharView*, void); + DECL_DLLPRIVATE_LINK(FavClearAllClickHdl, SvxCharView*, void); + DECL_DLLPRIVATE_LINK(InsertClickHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(FavSelectHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(SearchUpdateHdl, weld::Entry&, void); + DECL_DLLPRIVATE_LINK(SearchFieldGetFocusHdl, weld::Widget&, void); + + static void fillAllSubsets(weld::ComboBox& rListBox); + void selectCharByCode(Radix radix); + +public: + SvxCharacterMap(weld::Widget* pParent, const SfxItemSet* pSet, + css::uno::Reference xFrame); + virtual short run() override; + + void set_title(const OUString& rTitle) { m_xDialog->set_title(rTitle); } + + const SfxItemSet* GetOutputItemSet() const { return m_xOutputSet.get(); } + + void DisableFontSelection(); + + const vcl::Font& GetCharFont() const { return aFont; } + void SetCharFont(const vcl::Font& rFont); + + void SetChar(sal_UCS4); + sal_UCS4 GetChar() const; + + void getRecentCharacterList(); //gets both recent char and recent char font list + void updateRecentCharacterList(const OUString& rChar, const OUString& rFont); + + void getFavCharacterList(); //gets both Fav char and Fav char font list + void updateFavCharacterList(const OUString& rChar, const OUString& rFont); + void deleteFavCharacterFromList(std::u16string_view rChar, std::u16string_view rFont); + bool isFavChar(std::u16string_view sTitle, std::u16string_view rFont); + + void updateRecentCharControl(); + void insertCharToDoc(const OUString& sChar); + + void updateFavCharControl(); + void setFavButtonState(std::u16string_view sTitle, std::u16string_view rFont); + + void setCharName(sal_UCS4 nDecimalValue); + + void toggleSearchView(bool state); + +private: + std::pair::const_iterator, std::deque::const_iterator> + getRecentChar(std::u16string_view sTitle, std::u16string_view rFont) const; + + std::pair::const_iterator, std::deque::const_iterator> + getFavChar(std::u16string_view sTitle, std::u16string_view rFont) const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cui/cuidllapi.h b/include/cui/cuidllapi.h new file mode 100644 index 000000000..12277c602 --- /dev/null +++ b/include/cui/cuidllapi.h @@ -0,0 +1,23 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_CUI_CUIDLLAPI_H +#define INCLUDED_CUI_CUIDLLAPI_H + +#include + +#if defined(CUI_DLLIMPLEMENTATION) +#define CUI_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define CUI_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif // INCLUDED_CUI_CUIDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/cui/numberingpreview.hxx b/include/cui/numberingpreview.hxx new file mode 100644 index 000000000..8a7883522 --- /dev/null +++ b/include/cui/numberingpreview.hxx @@ -0,0 +1,31 @@ +#ifndef INCLUDED_CUI_NUMBERINGPREVIEW_HXX +#define INCLUDED_CUI_NUMBERINGPREVIEW_HXX + +#include +#include +#include + +/// Provides the preview to show how looks bullet or numbering format before the apply. +class CUI_DLLPUBLIC SvxNumberingPreview final : public weld::CustomWidgetController +{ + const SvxNumRule* pActNum; + vcl::Font aStdFont; + bool bPosition; + sal_uInt16 nActLevel; + + virtual void Paint(vcl::RenderContext& rRenderContext, + const ::tools::Rectangle& rRect) override; + +public: + SvxNumberingPreview(); + + void SetNumRule(const SvxNumRule* pNum) + { + pActNum = pNum; + Invalidate(); + }; + void SetPositionMode() { bPosition = true; } + void SetLevel(sal_uInt16 nSet) { nActLevel = nSet; } +}; + +#endif diff --git a/include/dbaccess/AsynchronousLink.hxx b/include/dbaccess/AsynchronousLink.hxx new file mode 100644 index 000000000..0b63cbed9 --- /dev/null +++ b/include/dbaccess/AsynchronousLink.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +struct ImplSVEvent; + +namespace dbaui +{ + + // a helper for multi-threaded handling of async events + + /** handles asynchronous links which may be called in multi-threaded environments + If you use an instance of this class as member of your own class, it will handle + several crucial points for you (for instance the case that somebody posts the + event while another thread tries to delete this event in the _destructor_ of the + class). + */ + class OAsynchronousLink final + { + Link m_aHandler; + ::osl::Mutex m_aEventSafety; + ::osl::Mutex m_aDestructionSafety; + ImplSVEvent * m_nEventId; + DECL_LINK(OnAsyncCall, void*, void); + + public: + /** constructs the object + @param _rHandler The link to be called asynchronously + */ + OAsynchronousLink( const Link& _rHandler ); + ~OAsynchronousLink(); + + bool IsRunning() const { return m_nEventId != nullptr; } + + void Call( void* _pArgument = nullptr ); + void CancelCall(); + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/IController.hxx b/include/dbaccess/IController.hxx new file mode 100644 index 000000000..c7374eb80 --- /dev/null +++ b/include/dbaccess/IController.hxx @@ -0,0 +1,120 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DBACCESS_ICONTROLLER_HXX +#define INCLUDED_DBACCESS_ICONTROLLER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { + struct PropertyValue; + } + namespace util { + struct URL; + } + namespace frame { + class XController; + } +} + +class NotifyEvent; + +namespace dbaui +{ + // interface for controller depended calls like commands + class DBACCESS_DLLPUBLIC IController + { + public: + /** executes the given command without checking if it is allowed + @param _rCommand the URL of the command + */ + virtual void executeUnChecked(const css::util::URL& _rCommand, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) = 0; + + /** executes the given command only when it is allowed + @param _rCommand + the URL of the command + */ + virtual void executeChecked(const css::util::URL& _rCommand, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) = 0; + + /** executes the given command without checking if it is allowed + @param _nCommandId + the id of the command URL + */ + virtual void executeUnChecked(sal_uInt16 _nCommandId, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) = 0; + + /** executes the given command only when it is allowed + @param _nCommandId + the id of the command URL + */ + virtual void executeChecked(sal_uInt16 _nCommandId, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) = 0; + + + /** checks if the given Command is enabled + @param _nCommandId + the id of the command URL + + @return + if the command is allowed, otherwise . + */ + virtual bool isCommandEnabled(sal_uInt16 _nCommandId) const = 0; + + /** checks if the given Command is enabled + @param _rCompleteCommandURL + the URL of the command + + @return + if the command is allowed, otherwise . + */ + virtual bool isCommandEnabled( const OUString& _rCompleteCommandURL ) const = 0; + + /** checks if the selected data source is read only + @return + if read only, otherwise + */ + virtual bool isDataSourceReadOnly() const = 0; + + /** provides access to the model of the controller + + This must be the same model as returned by XController::getModel, and might be when + the controller does not have an own model. + + @throws css::uno::RuntimeException + */ + virtual css::uno::Reference< css::frame::XController > + getXController() = 0; + + /** allows interception of user input, aka mouse clicks and key events + */ + virtual bool interceptUserInput( const NotifyEvent& _rEvent ) = 0; + + virtual void SAL_CALL acquire( ) noexcept = 0; + virtual void SAL_CALL release( ) noexcept = 0; + + protected: + ~IController() {} + }; +} +#endif // INCLUDED_DBACCESS_ICONTROLLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/controllerframe.hxx b/include/dbaccess/controllerframe.hxx new file mode 100644 index 000000000..97a9c249d --- /dev/null +++ b/include/dbaccess/controllerframe.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DBACCESS_CONTROLLERFRAME_HXX +#define INCLUDED_DBACCESS_CONTROLLERFRAME_HXX + +#include + +#include +#include + +namespace com::sun::star { + namespace frame { class XFrame; } +} + +namespace dbaui +{ + + + class IController; + + + //= ControllerFrame + + struct ControllerFrame_Data; + /** helper class to encapsulate the frame which a controller is plugged into, + doing some common actions on it. + */ + class ControllerFrame + { + public: + ControllerFrame( IController& _rController ); + ~ControllerFrame(); + + /// attaches a new frame + const css::uno::Reference< css::frame::XFrame >& + attachFrame( + const css::uno::Reference< css::frame::XFrame >& _rxFrame + ); + + // retrieves the current frame + const css::uno::Reference< css::frame::XFrame >& + getFrame() const; + + /** determines whether the frame is currently active + */ + bool isActive() const; + + /** notifies the instance that a certain frame action happened with our frame + */ + void frameAction( css::frame::FrameAction _eAction ); + + private: + ::std::unique_ptr< ControllerFrame_Data > m_pData; + }; + + +} // namespace dbaui + + +#endif // INCLUDED_DBACCESS_CONTROLLERFRAME_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/dataview.hxx b/include/dbaccess/dataview.hxx new file mode 100644 index 000000000..1c2cacdcf --- /dev/null +++ b/include/dbaccess/dataview.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_DBACCESS_DATAVIEW_HXX +#define INCLUDED_DBACCESS_DATAVIEW_HXX + +#include + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace frame { class XFrame; } + namespace uno { class XComponentContext; } +} + +namespace svt { + class AcceleratorExecute; +} + +class NotifyEvent; +namespace tools { class Rectangle; } + +namespace dbaui +{ + class IController; + class DBACCESS_DLLPUBLIC ODataView : public vcl::Window + { + css::uno::Reference< css::uno::XComponentContext > m_xContext; // the service factory to work with + + protected: + rtl::Reference m_xController; // the controller where we reside in + ::std::unique_ptr< ::svt::AcceleratorExecute> m_pAccel; + + public: + ODataView( vcl::Window* pParent, + IController& _rController, + const css::uno::Reference< css::uno::XComponentContext >& , + WinBits nStyle = 0 ); + virtual ~ODataView() override; + virtual void dispose() override; + + /// late construction + virtual void Construct(); + // initialize will be called when after the controller finished his initialize method + virtual void initialize(){} + // window overridables + virtual bool PreNotify( NotifyEvent& rNEvt ) override; + virtual void StateChanged( StateChangedType nStateChange ) override; + + IController& getCommandController() const { return *m_xController; } + + const css::uno::Reference< css::uno::XComponentContext >& getORB() const { return m_xContext;} + + // the default implementation simply calls resizeAll( GetSizePixel() ) + virtual void Resize() override; + + void attachFrame(const css::uno::Reference< css::frame::XFrame >& _xFrame); + protected: + // window overridables + virtual void Paint( vcl::RenderContext& rRenderContext, const tools::Rectangle& _rRect ) override; + + /// re-arrange all controls, including the toolbox, it's separator, and the "real view" + virtual void resizeAll( const tools::Rectangle& _rPlayground ); + + // re-arrange the controls belonging to the document itself + virtual void resizeDocumentView( tools::Rectangle& _rPlayground ); + }; +} +#endif // INCLUDED_DBACCESS_DATAVIEW_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/dbaccessdllapi.h b/include/dbaccess/dbaccessdllapi.h new file mode 100644 index 000000000..2f3771dce --- /dev/null +++ b/include/dbaccess/dbaccessdllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DBACCESS_DBACCESSDLLAPI_H +#define INCLUDED_DBACCESS_DBACCESSDLLAPI_H + +#include + +#if defined(DBACCESS_DLLIMPLEMENTATION) +#define DBACCESS_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define DBACCESS_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define DBACCESS_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_DBACCESS_DBACCESSDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/dbaundomanager.hxx b/include/dbaccess/dbaundomanager.hxx new file mode 100644 index 000000000..364b91d6c --- /dev/null +++ b/include/dbaccess/dbaundomanager.hxx @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DBACCESS_DBAUNDOMANAGER_HXX +#define INCLUDED_DBACCESS_DBAUNDOMANAGER_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace document { class XUndoAction; } + namespace document { class XUndoManagerListener; } + namespace uno { class XInterface; } +} + +namespace cppu { + class OWeakObject; +} + +namespace osl { + class Mutex; +} + +class SfxUndoManager; + + +namespace dbaui +{ + + + //= UndoManager + + struct UndoManager_Impl; + typedef ::cppu::ImplHelper1< css::document::XUndoManager > UndoManager_Base; + class DBACCESS_DLLPUBLIC UndoManager final : public UndoManager_Base + { + public: + UndoManager( ::cppu::OWeakObject& i_parent, ::osl::Mutex& i_mutex ); + virtual ~UndoManager(); + + SfxUndoManager& GetSfxUndoManager() const; + + // XInterface + virtual void SAL_CALL acquire( ) noexcept override; + virtual void SAL_CALL release( ) noexcept override; + + // XComponent equivalents + void disposing(); + + // XUndoManager + virtual void SAL_CALL enterUndoContext( const OUString& i_title ) override; + virtual void SAL_CALL enterHiddenUndoContext( ) override; + virtual void SAL_CALL leaveUndoContext( ) override; + virtual void SAL_CALL addUndoAction( const css::uno::Reference< css::document::XUndoAction >& i_action ) override; + virtual void SAL_CALL undo( ) override; + virtual void SAL_CALL redo( ) override; + virtual sal_Bool SAL_CALL isUndoPossible( ) override; + virtual sal_Bool SAL_CALL isRedoPossible( ) override; + virtual OUString SAL_CALL getCurrentUndoActionTitle( ) override; + virtual OUString SAL_CALL getCurrentRedoActionTitle( ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getAllUndoActionTitles( ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getAllRedoActionTitles( ) override; + virtual void SAL_CALL clear( ) override; + virtual void SAL_CALL clearRedo( ) override; + virtual void SAL_CALL reset( ) override; + virtual void SAL_CALL addUndoManagerListener( const css::uno::Reference< css::document::XUndoManagerListener >& i_listener ) override; + virtual void SAL_CALL removeUndoManagerListener( const css::uno::Reference< css::document::XUndoManagerListener >& i_listener ) override; + + // XLockable (base of XUndoManager) + virtual void SAL_CALL lock( ) override; + virtual void SAL_CALL unlock( ) override; + virtual sal_Bool SAL_CALL isLocked( ) override; + + // XChild (base of XUndoManager) + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL getParent( ) override; + virtual void SAL_CALL setParent( const css::uno::Reference< css::uno::XInterface >& Parent ) override; + + private: + std::unique_ptr< UndoManager_Impl > m_xImpl; + }; + + +} // namespace dbaui + + +#endif // INCLUDED_DBACCESS_DBAUNDOMANAGER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/dbsubcomponentcontroller.hxx b/include/dbaccess/dbsubcomponentcontroller.hxx new file mode 100644 index 000000000..a1bc687ce --- /dev/null +++ b/include/dbaccess/dbsubcomponentcontroller.hxx @@ -0,0 +1,208 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DBACCESS_DBSUBCOMPONENTCONTROLLER_HXX +#define INCLUDED_DBACCESS_DBSUBCOMPONENTCONTROLLER_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { class XPropertySet; } + namespace beans { struct PropertyValue; } + namespace document { class XEmbeddedScripts; } + namespace frame { class XModel; } + namespace sdbc { class XConnection; } + namespace sdbc { class XDatabaseMetaData; } + namespace uno { class XComponentContext; } + namespace util { class XModifyListener; } + namespace util { class XNumberFormatter; } +} + +namespace dbtools { + class DatabaseMetaData; + class SQLExceptionInfo; +} + +namespace dbaui +{ + //= DBSubComponentController + + typedef ::cppu::ImplInheritanceHelper< OGenericUnoController + , css::document::XScriptInvocationContext + , css::util::XModifiable + > DBSubComponentController_Base; + + struct DBSubComponentController_Impl; + class DBACCESS_DLLPUBLIC DBSubComponentController : public DBSubComponentController_Base + { + private: + ::std::unique_ptr m_pImpl; + + private: + /** forces usage of a connection which we do not own +

    To be used from within XInitialization::initialize, resp. impl_initialize, only.

    + */ + void initializeConnection( const css::uno::Reference< css::sdbc::XConnection >& _rxForeignConn ); + + protected: + // OGenericUnoController - initialization + virtual void impl_initialize() override; + + // OGenericUnoController + virtual void Execute(sal_uInt16 nId, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) override; + + virtual css::uno::Reference< css::frame::XModel > getPrivateModel() const override; + + bool impl_isModified() const; + virtual void impl_onModifyChanged(); + + public: + bool isReadOnly() const; + bool isEditable() const; + void setEditable(bool _bEditable); + + + // asking for connection-related stuff + + bool isConnected() const; + + css::uno::Reference< css::sdbc::XDatabaseMetaData > + getMetaData( ) const; + + + // access to the data source / document + OUString getDataSourceName() const; + const css::uno::Reference< css::beans::XPropertySet >& + getDataSource() const; + bool haveDataSource() const; + + css::uno::Reference< css::frame::XModel > + getDatabaseDocument() const; + + /** provides access to the SDB-level database meta data of the current connection + */ + const ::dbtools::DatabaseMetaData& getSdbMetaData() const; + + /** appends an error in the current environment. + */ + void appendError( const OUString& _rErrorMessage ); + + /** clears the error state. + */ + void clearError(); + + /** @return + when an error was set otherwise + */ + bool hasError() const; + + /** returns the current error + */ + const ::dbtools::SQLExceptionInfo& getError() const; + + /** displays the current error, or does nothing if there is no current error + */ + void displayError(); + + /** shows an info box with the string conntection lost. + */ + void connectionLostMessage() const; + + /** gives access to the currently used connection + @return + the currently used connection. + */ + const css::uno::Reference< css::sdbc::XConnection >& + getConnection() const; + + /** returns the number formatter + */ + css::uno::Reference< css::util::XNumberFormatter > const & getNumberFormatter() const; + + // css::frame::XController + virtual sal_Bool SAL_CALL suspend(sal_Bool bSuspend) override; + virtual sal_Bool SAL_CALL attachModel(const css::uno::Reference< css::frame::XModel > & xModel) override; + + // XScriptInvocationContext + virtual css::uno::Reference< css::document::XEmbeddedScripts > SAL_CALL getScriptContainer() override; + + // XModifiable + virtual sal_Bool SAL_CALL isModified( ) override; + virtual void SAL_CALL setModified( sal_Bool bModified ) override; + + // XModifyBroadcaster + virtual void SAL_CALL addModifyListener( const css::uno::Reference< css::util::XModifyListener >& aListener ) override; + virtual void SAL_CALL removeModifyListener( const css::uno::Reference< css::util::XModifyListener >& aListener ) override; + + // XTitle + virtual OUString SAL_CALL getTitle( ) override; + + protected: + DBSubComponentController(const css::uno::Reference< css::uno::XComponentContext>& _rxORB); + virtual ~DBSubComponentController() override; + + void disconnect(); + virtual void reconnect( bool _bUI ); + bool ensureConnected() { + if ( !isConnected() ) reconnect( false ); + return isConnected(); + } + + /** called when our connection is being disposed +

    The default implementation does a reconnect

    + */ + virtual void losingConnection( ); + + protected: + // XEventListener + virtual void SAL_CALL disposing(const css::lang::EventObject& Source) override; + + // OComponentHelper + virtual void SAL_CALL disposing() override; + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type& _rType) override; + + // XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + + protected: + sal_Int32 getCurrentStartNumber() const; + }; + + +} // namespace dbaui + + +#endif // INCLUDED_DBACCESS_DBSUBCOMPONENTCONTROLLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/dbaccess/genericcontroller.hxx b/include/dbaccess/genericcontroller.hxx new file mode 100644 index 000000000..50b939791 --- /dev/null +++ b/include/dbaccess/genericcontroller.hxx @@ -0,0 +1,506 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DBACCESS_GENERICCONTROLLER_HXX +#define INCLUDED_DBACCESS_GENERICCONTROLLER_HXX + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { class XKeyHandler; } + namespace awt { class XMouseClickHandler; } + namespace awt { class XWindow; } + namespace beans { struct PropertyValue; } + namespace frame { class XController; } + namespace frame { class XDispatchProvider; } + namespace frame { class XFrame; } + namespace frame { class XFrameActionListener; } + namespace frame { class XModel; } + namespace frame { class XStatusListener; } + namespace frame { class XTitleChangeListener; } + namespace frame { struct DispatchDescriptor; } + namespace frame { struct FrameActionEvent; } + namespace lang { class XEventListener; } + namespace sdb { class XDatabaseContext; } + namespace sdbc { class XConnection; } + namespace sdbc { class XDataSource; } + namespace ui { class XSidebarProvider; } + namespace uno { class XComponentContext; } + namespace util { class XURLTransformer; } +} + +namespace vcl { class Window; } +namespace weld { class Window; } +class NotifyEvent; + +namespace dbaui +{ + class ODataView; + + template< typename T > + inline bool SAL_CALL operator >>= (const css::uno::Any& _any, std::optional< T >& _value) + { + _value.reset(); // de-init the optional value + + T directValue = T(); + if ( _any >>= directValue ) + _value = directValue; + + return !!_value; + } + + + // = FeatureState + + /** describes the state of a feature + + In opposite to the FeatureStateEvent in css.frame, this one allows for multiple states to be specified at once. + With this, you can for instance specify that a toolbox item is checked, and has a certain title, at the same + time. + */ + struct FeatureState + { + bool bEnabled; + + std::optional bChecked; + std::optional bInvisible; + css::uno::Any aValue; + std::optional sTitle; + + FeatureState() : bEnabled(false) { } + }; + + + // = helper + + + struct ControllerFeature : public css::frame::DispatchInformation + { + sal_uInt16 nFeatureId; + }; + + + typedef ::std::map < OUString + , ControllerFeature + , ::std::less< OUString > + > SupportedFeatures; + + + class CompareFeatureById + { + const sal_Int32 m_nId; + public: + CompareFeatureById(sal_Int32 _nId) : m_nId(_nId) + {} + + bool operator()( const SupportedFeatures::value_type& _aType ) const + { + return m_nId == _aType.second.nFeatureId; + } + }; + + + struct FeatureListener + { + css::uno::Reference< css::frame::XStatusListener > + xListener; + sal_Int32 nId; + bool bForceBroadcast; + }; + + + class FindFeatureListener + { + const css::uno::Reference< css::frame::XStatusListener >& m_xListener; + public: + FindFeatureListener(const css::uno::Reference< css::frame::XStatusListener >& _xListener) + : m_xListener(_xListener) + {} + + bool operator()( const FeatureListener& lhs ) const + { + return lhs.xListener == m_xListener; + } + }; + + + typedef ::comphelper::SharedMutexBase OGenericUnoController_MBASE; + + typedef ::cppu::WeakComponentImplHelper< css::frame::XDispatch + , css::frame::XDispatchProviderInterceptor + , css::util::XModifyListener + , css::frame::XFrameActionListener + , css::lang::XInitialization + , css::lang::XServiceInfo + , css::frame::XDispatchInformationProvider + , css::frame::XController2 + , css::frame::XTitle + , css::frame::XTitleChangeBroadcaster + , css::awt::XUserInputInterception + > OGenericUnoController_Base; + + struct OGenericUnoController_Data; + + class DBACCESS_DLLPUBLIC OGenericUnoController + :public OGenericUnoController_MBASE + ,public OGenericUnoController_Base + ,public IController + { + private: + SupportedFeatures m_aSupportedFeatures; + ::comphelper::NamedValueCollection + m_aInitParameters; + + ::std::unique_ptr< OGenericUnoController_Data > + m_pData; + VclPtr m_pView; // our (VCL) "main window" + +#ifdef DBG_UTIL + bool m_bDescribingSupportedFeatures; +#endif + + protected: + + // attributes + struct DispatchTarget + { + css::util::URL aURL; + css::uno::Reference< css::frame::XStatusListener > xListener; + + DispatchTarget(const css::util::URL& rURL, const css::uno::Reference< css::frame::XStatusListener >& rRef) : aURL(rURL), xListener(rRef) { } + }; + + typedef std::map StateCache; + typedef std::vector Dispatch; + + ::std::deque< FeatureListener > + m_aFeaturesToInvalidate; + + ::osl::Mutex m_aFeatureMutex; // locked when features are append to or remove from deque + StateCache m_aStateCache; // save the current status of feature state + Dispatch m_arrStatusListener; // all our listeners where we dispatch status changes + OAsynchronousLink m_aAsyncInvalidateAll; + OAsynchronousLink m_aAsyncCloseTask; // called when a task should be closed + + css::uno::Reference< css::util::XURLTransformer > m_xUrlTransformer; // needed sometimes + css::uno::Reference< css::uno::XComponentContext > m_xContext; + ControllerFrame m_aCurrentFrame; + css::uno::Reference< css::frame::XDispatchProvider > m_xSlaveDispatcher; // for intercepting dispatches + css::uno::Reference< css::frame::XDispatchProvider > m_xMasterDispatcher; // ditto + css::uno::Reference< css::sdb::XDatabaseContext > m_xDatabaseContext; + css::uno::Reference< css::frame::XTitle > m_xTitleHelper; + + bool m_bPreview; + bool m_bReadOnly; + + bool m_bCurrentlyModified : 1; + bool m_bExternalTitle : 1; + + + // attribute access + using OGenericUnoController_MBASE::getMutex; + ::cppu::OBroadcastHelper& getBroadcastHelper() { return OGenericUnoController_Base::rBHelper; } + + + // methods + OGenericUnoController( const css::uno::Reference< css::uno::XComponentContext >& _rM ); + OGenericUnoController() = delete; + const ::comphelper::NamedValueCollection& + getInitParams() const { return m_aInitParameters; } + + // closes the task when possible + void closeTask(); + + // if getMenu returns a non empty string than this will be dispatched at the frame + virtual void loadMenu(const css::uno::Reference< css::frame::XFrame >& _xFrame); + + /** called when our menu has been loaded into our frame, can be used to load sub toolbars + + @param _xLayoutManager + The layout manager. + */ + virtual void onLoadedMenu(const css::uno::Reference< css::frame::XLayoutManager >& _xLayoutManager); + + // all the features which should be handled by this class + virtual void describeSupportedFeatures(); + + // state of a feature. 'feature' may be the handle of a css::util::URL somebody requested a dispatch interface for OR a toolbar slot. + virtual FeatureState GetState(sal_uInt16 nId) const; + // execute a feature + virtual void Execute(sal_uInt16 nId , const css::uno::Sequence< css::beans::PropertyValue>& aArgs); + + /** describes a feature supported by the controller + + Must not be called outside describeSupportedFeatures. + + @param _rCommandURL + the URL of the feature command + @param _nFeatureId + the id of the feature. Later references to this feature usually happen by id, not by + URL + @param _nCommandGroup + the command group of the feature. This is important for configuring the controller UI + by the user, see also CommandGroup. + */ + void implDescribeSupportedFeature( + const OUString& _rCommandURL, + sal_uInt16 _nFeatureId, + sal_Int16 _nCommandGroup = css::frame::CommandGroup::INTERNAL + ); + + /** returns if the feature is supported, otherwise + @param _nId + The ID of the feature. + */ + bool isFeatureSupported( sal_Int32 _nId ); + + // gets the URL which the given id is assigned to + css::util::URL getURLForId(sal_Int32 _nId) const; + + /** determines whether the given feature ID denotes a user-defined feature + + @see IController::registerCommandURL + */ + static bool isUserDefinedFeature( const sal_uInt16 nFeatureId ); + + /** determines whether the given feature URL denotes a user-defined feature + + @see IController::registerCommandURL + */ + bool isUserDefinedFeature( const OUString& _rFeatureURL ) const; + + // connect to a datasource + css::uno::Reference< css::sdbc::XConnection > connect( + const css::uno::Reference< css::sdbc::XDataSource>& _xDataSource + ); + + // connect to a datasource + css::uno::Reference< css::sdbc::XConnection > connect( + const OUString& _rsDataSourceName, + const OUString& _rContextInformation, + ::dbtools::SQLExceptionInfo* _pErrorInfo + ); + + void startConnectionListening(const css::uno::Reference< css::sdbc::XConnection >& _rxConnection); + void stopConnectionListening(const css::uno::Reference< css::sdbc::XConnection >& _rxConnection); + + /** return the container window of the top most frame + @return + The top most container window, nmay be . + */ + css::uno::Reference< css::awt::XWindow> getTopMostContainerWindow() const; + + // XInitialize will be called inside initialize + virtual void impl_initialize(); + + virtual OUString getPrivateTitle() const { return OUString(); } + + css::uno::Reference< css::frame::XTitle > impl_getTitleHelper_throw(bool bCreateIfNecessary = true); + virtual css::uno::Reference< css::frame::XModel > getPrivateModel() const + { + return css::uno::Reference< css::frame::XModel >(); + } + + virtual void startFrameListening( const css::uno::Reference< css::frame::XFrame >& _rxFrame ); + virtual void stopFrameListening( const css::uno::Reference< css::frame::XFrame >& _rxFrame ); + + void releaseNumberForComponent(); + + virtual ~OGenericUnoController() override; + + private: + void fillSupportedFeatures(); + + void InvalidateAll_Impl(); + void InvalidateFeature_Impl(); + + void ImplInvalidateFeature( sal_Int32 _nId, const css::uno::Reference< css::frame::XStatusListener >& _xListener, bool _bForceBroadcast ); + + void ImplBroadcastFeatureState(const OUString& _rFeature, const css::uno::Reference< css::frame::XStatusListener > & xListener, bool _bIgnoreCache); + + // link methods + DECL_DLLPRIVATE_LINK(OnAsyncInvalidateAll, void*, void); + DECL_DLLPRIVATE_LINK(OnAsyncCloseTask, void*, void); + + public: + const css::uno::Reference< css::uno::XComponentContext >& getORB() const { return m_xContext; } + ODataView* getView() const { return m_pView; } + weld::Window* getFrameWeld() const; + void setView( const VclPtr& i_rView ); + void clearView(); + // shows an error box if the SQLExceptionInfo is valid + void showError(const ::dbtools::SQLExceptionInfo& _rInfo); + + // if there is a css::util::URL translation for the id + // ('handle') then if xListener is NULL the change will be forwarded + // to all listeners to the given css::util::URL + // if there is a toolbar slot with the given id it is updated (the new state is determined via GetState) + // if _bForceBroadcast is sal_True, the current feature state is broadcasted no matter if it is the same as the cached state + void InvalidateFeature(sal_uInt16 nId, const css::uno::Reference< css::frame::XStatusListener > & xListener = nullptr, bool _bForceBroadcast = false); + + /** InvalidateAll invalidates all features currently known + */ + void InvalidateAll(); + // late construction + virtual bool Construct(vcl::Window* pParent); + + /** get the layout manager + @param _xFrame + The frame to ask for the layout manager. + @return + The layout manager of the frame, can be if the frame isn't initialized. + */ + static css::uno::Reference< css::frame::XLayoutManager > getLayoutManager(const css::uno::Reference< css::frame::XFrame >& _xFrame); + + // IController + virtual void executeUnChecked(const css::util::URL& _rCommand, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) override; + virtual void executeChecked(const css::util::URL& _rCommand, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) override; + virtual void executeUnChecked(sal_uInt16 _nCommandId, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) override; + virtual void executeChecked(sal_uInt16 _nCommandId, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) override; + virtual bool isCommandEnabled(sal_uInt16 _nCommandId) const override; + virtual bool isCommandEnabled(const OUString& _rCompleteCommandURL) const override; + virtual bool isDataSourceReadOnly() const override; + virtual css::uno::Reference< css::frame::XController > getXController() override; + virtual bool interceptUserInput( const NotifyEvent& _rEvent ) override; + + // misc + bool isCommandChecked(sal_uInt16 _nCommandId) const; + + // css::lang::XEventListener + virtual void SAL_CALL disposing(const css::lang::EventObject& Source) override; + + // css::util::XModifyListener + virtual void SAL_CALL modified(const css::lang::EventObject& aEvent) override; + + // XInterface + virtual void SAL_CALL acquire( ) noexcept override; + virtual void SAL_CALL release( ) noexcept override; + + // css::frame::XController2 + virtual css::uno::Reference< css::awt::XWindow > SAL_CALL getComponentWindow() override; + virtual OUString SAL_CALL getViewControllerName() override; + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getCreationArguments() override; + + virtual css::uno::Reference< css::ui::XSidebarProvider > SAL_CALL getSidebar() override; + + + // css::frame::XController + virtual void SAL_CALL attachFrame(const css::uno::Reference< css::frame::XFrame > & xFrame) override; + virtual sal_Bool SAL_CALL attachModel(const css::uno::Reference< css::frame::XModel > & xModel) override; + virtual sal_Bool SAL_CALL suspend(sal_Bool bSuspend) override = 0; + virtual css::uno::Any SAL_CALL getViewData() override; + virtual void SAL_CALL restoreViewData(const css::uno::Any& Data) override; + virtual css::uno::Reference< css::frame::XModel > SAL_CALL getModel() override; + virtual css::uno::Reference< css::frame::XFrame > SAL_CALL getFrame() override; + + // css::frame::XDispatch + virtual void SAL_CALL dispatch(const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue>& aArgs) override; + virtual void SAL_CALL addStatusListener(const css::uno::Reference< css::frame::XStatusListener > & aListener, const css::util::URL& aURL) override; + virtual void SAL_CALL removeStatusListener(const css::uno::Reference< css::frame::XStatusListener > & aListener, const css::util::URL& aURL) override; + + // css::frame::XDispatchProviderInterceptor + virtual css::uno::Reference< css::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider() override; + virtual void SAL_CALL setSlaveDispatchProvider(const css::uno::Reference< css::frame::XDispatchProvider > & _xNewProvider) override; + virtual css::uno::Reference< css::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider() override; + virtual void SAL_CALL setMasterDispatchProvider(const css::uno::Reference< css::frame::XDispatchProvider > & _xNewProvider) override; + + // css::frame::XDispatchProvider + virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL queryDispatch(const css::util::URL& aURL, const OUString& aTargetFrameName, sal_Int32 nSearchFlags) override; + virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches(const css::uno::Sequence< css::frame::DispatchDescriptor >& aDescripts) override; + + // css::lang::XComponent + virtual void SAL_CALL dispose() override; //LLA: need solar mutex {OGenericUnoController_COMPBASE::dispose(); } + virtual void SAL_CALL disposing() override; + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & aListener) override; + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & aListener) override; + + // css::frame::XFrameActionListener + virtual void SAL_CALL frameAction(const css::frame::FrameActionEvent& aEvent) override; + // lang::XInitialization + virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& aArguments ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override = 0; + virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + virtual css::uno::Sequence< OUString> SAL_CALL getSupportedServiceNames() override = 0; + + // XDispatchInformationProvider + virtual css::uno::Sequence< ::sal_Int16 > SAL_CALL getSupportedCommandGroups() override; + virtual css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL getConfigurableDispatchInformation( ::sal_Int16 ) override; + + // XTitle + virtual OUString SAL_CALL getTitle( ) override; + virtual void SAL_CALL setTitle( const OUString& sTitle ) override; + + // XTitleChangeBroadcaster + virtual void SAL_CALL addTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener ) override; + virtual void SAL_CALL removeTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener ) override; + + // XUserInputInterception + virtual void SAL_CALL addKeyHandler( const css::uno::Reference< css::awt::XKeyHandler >& xHandler ) override; + virtual void SAL_CALL removeKeyHandler( const css::uno::Reference< css::awt::XKeyHandler >& xHandler ) override; + virtual void SAL_CALL addMouseClickHandler( const css::uno::Reference< css::awt::XMouseClickHandler >& xHandler ) override; + virtual void SAL_CALL removeMouseClickHandler( const css::uno::Reference< css::awt::XMouseClickHandler >& xHandler ) override; + }; +} + +#endif // INCLUDED_DBACCESS_GENERICCONTROLLER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/default.rc b/include/default.rc new file mode 100644 index 000000000..5474d55c4 --- /dev/null +++ b/include/default.rc @@ -0,0 +1,64 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#define WIN32_LEAN_AND_MEAN +#include +#include "version.hrc" + + +// version information + + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION, SUBVERSION, MICROVERSION, VERVARIANT + PRODUCTVERSION VERSION, SUBVERSION, MICROVERSION, VERVARIANT + FILEFLAGSMASK 0x3F + FILEFLAGS +#if defined(DEBUG) + VS_FF_DEBUG | +#endif +#ifdef VER_PREL + VS_FF_PRERELEASE | +#endif + 0 + FILEOS VOS_NT_WINDOWS32 + FILETYPE VFT_APP + { + BLOCK "StringFileInfo" + { + BLOCK "040904E4" + { + // International StringTable + VALUE "CompanyName", PPS(RES_APP_VENDOR) "\0" + VALUE "ProductName", "LibreOffice\0" + VALUE "ProductVersion", PPS(VER_LEVEL) "\0" + VALUE "FileVersion", PPS(VER_LEVEL) "\0" + VALUE "OriginalFilename", PPS(ORG_NAME) "\0" + VALUE "InternalName", PPS(INTERNAL_NAME) "\0" + VALUE "LegalCopyright", S_CRIGHT " LibreOffice contributors. All rights reserved.\0" + ADDITIONAL_VERINFO1 + ADDITIONAL_VERINFO2 + ADDITIONAL_VERINFO3 + } + } + + BLOCK "VarFileInfo" + { + VALUE "Translation", 0x0409, 1252 + } + } diff --git a/include/desktop/crashreport.hxx b/include/desktop/crashreport.hxx new file mode 100644 index 000000000..403e31171 --- /dev/null +++ b/include/desktop/crashreport.hxx @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DESKTOP_CRASHREPORT_HXX +#define INCLUDED_DESKTOP_CRASHREPORT_HXX + +#include + +#include +#include + +#include + +// vector not sort the entries +#include +#include +#include +#include + +namespace google_breakpad +{ +class ExceptionHandler; +} + +/** + * Provides access to the crash reporter service. + * + * Valid keys are: + * * AdapterVendorId + * * AdapterDeviceId + * + */ +class +#if HAVE_FEATURE_BREAKPAD +// MSVC 2013 has undefined symbols for inline functions if it's exported +CRASHREPORT_DLLPUBLIC +#endif +/*class*/ CrashReporter +{ +public: + typedef enum {AddItem, Write, Create} tAddKeyHandling; +#if HAVE_FEATURE_BREAKPAD + static void addKeyValue(const OUString& rKey, const OUString& rValue, tAddKeyHandling AddKeyHandling); + + static void installExceptionHandler(); + static void removeExceptionHandler(); + + static void setActiveSfxObjectName(const OUString& rActiveSfxObjectName); + static OUString getActiveSfxObjectName(); + + static void logUnoCommand(const OUString& rUnoCommand); + static OUString getLoggedUnoCommands(); + + static bool crashReportInfoExists(); + + static bool readSendConfig(std::string& response); + + static bool IsDumpEnable(); + +private: + static osl::Mutex maMutex; + static osl::Mutex maActiveSfxObjectNameMutex; + static osl::Mutex maUnoLogCmdMutex; + static bool mbInit; + typedef struct _mpair + { + OUString first; + OUString second; + _mpair(const OUString& First, const OUString& Second) + { + first = First; + second = Second; + }; + } mpair; + + typedef std::vector vmaKeyValues; + static vmaKeyValues maKeyValues; // used to temporarily save entries before the old info has been uploaded + typedef std::deque vmaloggedUnoCommands; + static vmaloggedUnoCommands maloggedUnoCommands; + static OUString msActiveSfxObjectName; + + static std::unique_ptr mpExceptionHandler; + + static std::string getIniFileName(); + static void writeCommonInfo(); + static void writeSystemInfo(); + static void writeToFile(std::ios_base::openmode Openmode); + // when we create the ExceptionHandler we have no access to the user + // profile yet, so update when we have access + static void updateMinidumpLocation(); + +#else + // Add dummy methods for the non-breakpad case. That allows us to use + // // the code without linking to the lib and without adding HAVE_FEATURE_BREAKPAD + // // everywhere we want to log something to the crash report system. + inline static void addKeyValue(SAL_UNUSED_PARAMETER const OUString& /*rKey*/, SAL_UNUSED_PARAMETER const OUString& /*rValue*/, SAL_UNUSED_PARAMETER tAddKeyHandling /*AddKeyHandling*/) {}; + inline static void setActiveSfxObjectName(SAL_UNUSED_PARAMETER const OUString& /*rActiveSfxObjectName*/) {}; + inline static OUString getActiveSfxObjectName() + { + return OUString(); + } + inline static void logUnoCommand(SAL_UNUSED_PARAMETER const OUString& /*rUnoCommand*/) {}; + inline static OUString getLoggedUnoCommands() + { + return OUString(); + } +#endif // HAVE_FEATURE_BREAKPAD +}; + +#endif // INCLUDED_DESKTOP_CRASHREPORT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/desktop/dllapi.h b/include/desktop/dllapi.h new file mode 100644 index 000000000..5cf948ce0 --- /dev/null +++ b/include/desktop/dllapi.h @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DESKTOP_SOURCE_INC_DESKTOPDLLAPI_H +#define INCLUDED_DESKTOP_SOURCE_INC_DESKTOPDLLAPI_H + +#include +#include + +#if defined(DESKTOP_DLLIMPLEMENTATION) +#define DESKTOP_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define DESKTOP_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#if defined(CRASHREPORT_DLLIMPLEMENTATION) +#define CRASHREPORT_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define CRASHREPORT_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim: set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/desktop/exithelper.h b/include/desktop/exithelper.h new file mode 100644 index 000000000..b4f618783 --- /dev/null +++ b/include/desktop/exithelper.h @@ -0,0 +1,37 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DESKTOP_EXITHELPER_H +#define INCLUDED_DESKTOP_EXITHELPER_H + +enum EExitCodes +{ + /* e.g. used to force showing of the command line help */ + EXITHELPER_NO_ERROR = 0, + /* a uno exception was caught during startup */ + EXITHELPER_FATAL_ERROR = 77, + /* user force automatic restart after crash */ + EXITHELPER_CRASH_WITH_RESTART = 79, + /* the office restarts itself */ + EXITHELPER_NORMAL_RESTART = 81 +}; + +#endif // INCLUDED_DESKTOP_EXITHELPER_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/desktop/minidump.hxx b/include/desktop/minidump.hxx new file mode 100644 index 000000000..93c02f3e0 --- /dev/null +++ b/include/desktop/minidump.hxx @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DESKTOP_MINIDUMP_MINIDUMP_HXX +#define INCLUDED_DESKTOP_MINIDUMP_MINIDUMP_HXX + +#include + +#include + +namespace crashreport +{ +// when response = nullptr only make test +/** Read+Send, Test and send info from the Dump.ini . + + @param [in] iniPath Path-file to the read/test ini-file (UTF-8 on Windows) + @param [in] response=nullptr in this case made the Test only + @param [in] response!=nullptr in this case made the Read+Send + + @retval true Read+Send, Test was okay + @retval false Read+Send, Test is a error +*/ + +CRASHREPORT_DLLPUBLIC bool readConfig(const std::string& iniPath, std::string* response); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/XShapeDumper.hxx b/include/drawinglayer/XShapeDumper.hxx new file mode 100644 index 000000000..47f5b0c26 --- /dev/null +++ b/include/drawinglayer/XShapeDumper.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DRAWINGLAYER_XSHAPEDUMPER_HXX +#define INCLUDED_DRAWINGLAYER_XSHAPEDUMPER_HXX + +#include +#include + +namespace com::sun::star::drawing { class XShape; } +namespace com::sun::star::drawing { class XShapes; } +namespace com::sun::star::uno { template class Reference; } + +struct DRAWINGLAYER_DLLPUBLIC XShapeDumper +{ + XShapeDumper() = delete; + static OUString dump(const css::uno::Reference& xPageShapes, bool bDumpInteropProperties=false); + static OUString dump(const css::uno::Reference& xPageShapes, bool bDumpInteropProperties=false); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/animation/animationtiming.hxx b/include/drawinglayer/animation/animationtiming.hxx new file mode 100644 index 000000000..c92639b99 --- /dev/null +++ b/include/drawinglayer/animation/animationtiming.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ANIMATION_ANIMATIONTIMING_HXX +#define INCLUDED_DRAWINGLAYER_ANIMATION_ANIMATIONTIMING_HXX + +#include + +#include +#include + + +namespace drawinglayer::animation + { + + + class DRAWINGLAYER_DLLPUBLIC AnimationEntry + { + private: + AnimationEntry(const AnimationEntry&) = delete; + AnimationEntry& operator=(const AnimationEntry& rCandidate) = delete; + + public: + AnimationEntry(); + virtual ~AnimationEntry(); + virtual std::unique_ptr clone() const = 0; + + virtual bool operator==(const AnimationEntry& rCandidate) const = 0; + virtual double getDuration() const = 0; + virtual double getStateAtTime(double fTime) const = 0; + virtual double getNextEventTime(double fTime) const = 0; + }; + + + class DRAWINGLAYER_DLLPUBLIC AnimationEntryFixed final : public AnimationEntry + { + double mfDuration; + double mfState; + + public: + AnimationEntryFixed(double fDuration, double fState); + virtual ~AnimationEntryFixed() override; + virtual std::unique_ptr clone() const override; + + virtual bool operator==(const AnimationEntry& rCandidate) const override; + virtual double getDuration() const override; + virtual double getStateAtTime(double fTime) const override; + virtual double getNextEventTime(double fTime) const override; + }; + + + class DRAWINGLAYER_DLLPUBLIC AnimationEntryLinear final : public AnimationEntry + { + double mfDuration; + double mfFrequency; + double mfStart; + double mfStop; + + public: + AnimationEntryLinear(double fDuration, double fFrequency, double fStart, double fStop); + virtual ~AnimationEntryLinear() override; + virtual std::unique_ptr clone() const override; + + virtual bool operator==(const AnimationEntry& rCandidate) const override; + virtual double getDuration() const override; + virtual double getStateAtTime(double fTime) const override; + virtual double getNextEventTime(double fTime) const override; + }; + + + class DRAWINGLAYER_DLLPUBLIC AnimationEntryList : public AnimationEntry + { + protected: + using Entries = std::vector>; + + double mfDuration; + Entries maEntries; + + // helpers + Entries::size_type impGetIndexAtTime(double fTime, double &rfAddedTime) const; + + public: + AnimationEntryList(); + virtual ~AnimationEntryList() override; + virtual std::unique_ptr clone() const override; + + virtual bool operator==(const AnimationEntry& rCandidate) const override; + void append(const AnimationEntry& rCandidate); + virtual double getDuration() const override; + virtual double getStateAtTime(double fTime) const override; + virtual double getNextEventTime(double fTime) const override; + }; + + + class DRAWINGLAYER_DLLPUBLIC AnimationEntryLoop final : public AnimationEntryList + { + sal_uInt32 mnRepeat; + + public: + AnimationEntryLoop(sal_uInt32 nRepeat); + virtual ~AnimationEntryLoop() override; + virtual std::unique_ptr clone() const override; + + virtual bool operator==(const AnimationEntry& rCandidate) const override; + virtual double getDuration() const override; + virtual double getStateAtTime(double fTime) const override; + virtual double getNextEventTime(double fTime) const override; + }; + + +} // end of namespace drawinglayer::animation + + +#endif //INCLUDED_DRAWINGLAYER_ANIMATION_ANIMATIONTIMING_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/fillgradientattribute.hxx b/include/drawinglayer/attribute/fillgradientattribute.hxx new file mode 100644 index 000000000..50a87a685 --- /dev/null +++ b/include/drawinglayer/attribute/fillgradientattribute.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ +class BColor; +} + +namespace drawinglayer::attribute +{ +class ImpFillGradientAttribute; + +enum class GradientStyle +{ + Linear, + Axial, + Radial, + Elliptical, + Square, + Rect +}; + +class DRAWINGLAYER_DLLPUBLIC FillGradientAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpFillGradientAttribute; + +public: + /// constructors/assignmentoperator/destructor + FillGradientAttribute(GradientStyle eStyle, double fBorder, double fOffsetX, double fOffsetY, + double fAngle, const basegfx::BColor& rStartColor, + const basegfx::BColor& rEndColor, sal_uInt16 nSteps = 0); + FillGradientAttribute(); + FillGradientAttribute(const FillGradientAttribute&); + FillGradientAttribute(FillGradientAttribute&&); + FillGradientAttribute& operator=(const FillGradientAttribute&); + FillGradientAttribute& operator=(FillGradientAttribute&&); + ~FillGradientAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const FillGradientAttribute& rCandidate) const; + + // data read access + GradientStyle getStyle() const; + double getBorder() const; + double getOffsetX() const; + double getOffsetY() const; + double getAngle() const; + const basegfx::BColor& getStartColor() const; + const basegfx::BColor& getEndColor() const; + sal_uInt16 getSteps() const; +}; + +} // end of namespace drawinglayer::attribute + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/fillgraphicattribute.hxx b/include/drawinglayer/attribute/fillgraphicattribute.hxx new file mode 100644 index 000000000..976d7bd37 --- /dev/null +++ b/include/drawinglayer/attribute/fillgraphicattribute.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +class Graphic; + +namespace basegfx +{ +class B2DRange; +} + +namespace drawinglayer::attribute +{ +class ImpFillGraphicAttribute; + +class DRAWINGLAYER_DLLPUBLIC FillGraphicAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpFillGraphicAttribute; + +public: + /// constructors/assignmentoperator/destructor + FillGraphicAttribute(const Graphic& rGraphic, const basegfx::B2DRange& rGraphicRange, + bool bTiling, double fOffsetX = 0.0, double fOffsetY = 0.0); + FillGraphicAttribute(const FillGraphicAttribute&); + FillGraphicAttribute& operator=(const FillGraphicAttribute&); + ~FillGraphicAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const FillGraphicAttribute& rCandidate) const; + + // data read access + const Graphic& getGraphic() const; + const basegfx::B2DRange& getGraphicRange() const; + bool getTiling() const; + double getOffsetX() const; + double getOffsetY() const; +}; + +} // end of namespace drawinglayer::attribute + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/fillhatchattribute.hxx b/include/drawinglayer/attribute/fillhatchattribute.hxx new file mode 100644 index 000000000..a929b5715 --- /dev/null +++ b/include/drawinglayer/attribute/fillhatchattribute.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ +class BColor; +} + +namespace drawinglayer::attribute +{ +class ImpFillHatchAttribute; + +enum class HatchStyle +{ + Single, + Double, + Triple +}; + +class DRAWINGLAYER_DLLPUBLIC FillHatchAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpFillHatchAttribute; + +public: + /// constructors/assignmentoperator/destructor + FillHatchAttribute(HatchStyle eStyle, double fDistance, double fAngle, + const basegfx::BColor& rColor, sal_uInt32 nMinimalDiscreteDistance, + bool bFillBackground); + FillHatchAttribute(); + FillHatchAttribute(const FillHatchAttribute&); + FillHatchAttribute(FillHatchAttribute&&); + FillHatchAttribute& operator=(const FillHatchAttribute&); + FillHatchAttribute& operator=(FillHatchAttribute&&); + ~FillHatchAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const FillHatchAttribute& rCandidate) const; + + // data read access + HatchStyle getStyle() const; + double getDistance() const; + double getAngle() const; + const basegfx::BColor& getColor() const; + + // #i120230# If a minimal discrete distance is wanted (VCL used 3, + // this is the default for the global instance, too), set this + // unequal to zero. Zero means not to use it. If set bigger zero + // (should be at least two, one leads to a full plane filled with + // lines when Distance in discrete views is smaller than one) this + // will be used when the discrete value is less than the given one. + // This is used to 'emulate' old VCL behaviour which makes hatches + // look better by not making distances as small as needed, but + // keeping them on a minimal discrete value for more appealing + // visualisation. + sal_uInt32 getMinimalDiscreteDistance() const; + + bool isFillBackground() const; +}; + +} // end of namespace drawinglayer::attribute + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/fontattribute.hxx b/include/drawinglayer/attribute/fontattribute.hxx new file mode 100644 index 000000000..1a7250170 --- /dev/null +++ b/include/drawinglayer/attribute/fontattribute.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace drawinglayer::attribute +{ +class ImpFontAttribute; +} + +namespace drawinglayer::attribute +{ +/** FontAttribute class + + This attribute class is able to hold all parameters needed/used + to completely define the parametrisation of a text portion. + */ +class DRAWINGLAYER_DLLPUBLIC FontAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpFontAttribute; + +public: + /// TODO: pair kerning and CJK kerning + FontAttribute(const OUString& rFamilyName, const OUString& rStyleName, sal_uInt16 nWeight, + bool bSymbol = false, bool bVertical = false, bool bItalic = false, + bool bMonospaced = false, bool bOutline = false, bool bRTL = false, + bool bBiDiStrong = false); + FontAttribute(); + FontAttribute(const FontAttribute&); + FontAttribute(FontAttribute&&); + FontAttribute& operator=(const FontAttribute&); + FontAttribute& operator=(FontAttribute&&); + ~FontAttribute(); + + // compare operator + bool operator==(const FontAttribute& rCandidate) const; + + /// data read access + const OUString& getFamilyName() const; + const OUString& getStyleName() const; + sal_uInt16 getWeight() const; + bool getSymbol() const; + bool getVertical() const; + bool getItalic() const; + bool getOutline() const; + bool getRTL() const; + bool getBiDiStrong() const; + bool getMonospaced() const; +}; +} // end of namespace drawinglayer::attribute + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/lineattribute.hxx b/include/drawinglayer/attribute/lineattribute.hxx new file mode 100644 index 000000000..77828a15d --- /dev/null +++ b/include/drawinglayer/attribute/lineattribute.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include // for F_PI180 +#include +#include +#include + +namespace basegfx +{ +class BColor; +} + +namespace drawinglayer::attribute +{ +class ImpLineAttribute; +} + +namespace drawinglayer::attribute +{ +class DRAWINGLAYER_DLLPUBLIC LineAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpLineAttribute; + +public: + /// constructors/assignmentoperator/destructor + explicit LineAttribute(const basegfx::BColor& rColor, double fWidth = 0.0, + basegfx::B2DLineJoin aB2DLineJoin = basegfx::B2DLineJoin::Round, + css::drawing::LineCap aLineCap = css::drawing::LineCap_BUTT, + double fMiterMinimumAngle = basegfx::deg2rad(15.0)); + LineAttribute(); + LineAttribute(const LineAttribute&); + LineAttribute& operator=(const LineAttribute&); + ~LineAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const LineAttribute& rCandidate) const; + + // data read access + const basegfx::BColor& getColor() const; + double getWidth() const; + basegfx::B2DLineJoin getLineJoin() const; + css::drawing::LineCap getLineCap() const; + double getMiterMinimumAngle() const; +}; +} // end of namespace drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/linestartendattribute.hxx b/include/drawinglayer/attribute/linestartendattribute.hxx new file mode 100644 index 000000000..f894a335d --- /dev/null +++ b/include/drawinglayer/attribute/linestartendattribute.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace basegfx +{ +class B2DPolyPolygon; +} + +namespace drawinglayer::attribute +{ +class ImpLineStartEndAttribute; +} + +namespace drawinglayer::attribute +{ +class DRAWINGLAYER_DLLPUBLIC LineStartEndAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpLineStartEndAttribute; + +public: + /// constructors/assignmentoperator/destructor + LineStartEndAttribute(double fWidth, const basegfx::B2DPolyPolygon& rPolyPolygon, + bool bCentered); + LineStartEndAttribute(); + LineStartEndAttribute(const LineStartEndAttribute&); + LineStartEndAttribute& operator=(const LineStartEndAttribute&); + ~LineStartEndAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const LineStartEndAttribute& rCandidate) const; + + // data read access + double getWidth() const; + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const; + bool isCentered() const; + bool isActive() const; +}; + +} // end of namespace drawinglayer::attribute + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/materialattribute3d.hxx b/include/drawinglayer/attribute/materialattribute3d.hxx new file mode 100644 index 000000000..07c11e302 --- /dev/null +++ b/include/drawinglayer/attribute/materialattribute3d.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_MATERIALATTRIBUTE3D_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_MATERIALATTRIBUTE3D_HXX + +#include +#include + + +// predefines + +namespace drawinglayer::attribute { + class ImpMaterialAttribute3D; +} + +namespace basegfx { + class BColor; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC MaterialAttribute3D + { + public: + typedef o3tl::cow_wrapper ImplType; + + private: + ImplType mpMaterialAttribute3D; + + public: + // constructors/destructor + MaterialAttribute3D( + const basegfx::BColor& rColor, + const basegfx::BColor& rSpecular, + const basegfx::BColor& rEmission, + sal_uInt16 nSpecularIntensity); + MaterialAttribute3D(const basegfx::BColor& rColor); + MaterialAttribute3D(); + MaterialAttribute3D(const MaterialAttribute3D&); + ~MaterialAttribute3D(); + + // assignment operator + MaterialAttribute3D& operator=(const MaterialAttribute3D&); + + // compare operator + bool operator==(const MaterialAttribute3D& rCandidate) const; + + // data read access + const basegfx::BColor& getColor() const; + const basegfx::BColor& getSpecular() const; + const basegfx::BColor& getEmission() const; + sal_uInt16 getSpecularIntensity() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_MATERIALATTRIBUTE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrallattribute3d.hxx b/include/drawinglayer/attribute/sdrallattribute3d.hxx new file mode 100644 index 000000000..d0b1101aa --- /dev/null +++ b/include/drawinglayer/attribute/sdrallattribute3d.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRALLATTRIBUTE3D_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRALLATTRIBUTE3D_HXX + +#include + +#include +#include +#include +#include +#include + + +// predefines + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrLineFillShadowAttribute3D + { + private: + const SdrLineAttribute maLine; + const SdrFillAttribute maFill; + const SdrLineStartEndAttribute maLineStartEnd; + const SdrShadowAttribute maShadow; + const FillGradientAttribute maFillFloatTransGradient; + + public: + /// constructors/assignmentoperator/destructor + SdrLineFillShadowAttribute3D( + const SdrLineAttribute& rLine, + const SdrFillAttribute& rFill, + const SdrLineStartEndAttribute& rLineStartEnd, + const SdrShadowAttribute& rShadow, + const FillGradientAttribute& rFillFloatTransGradient); + SdrLineFillShadowAttribute3D(); + + // compare operator + bool operator==(const SdrLineFillShadowAttribute3D& rCandidate) const; + + // data read access + const SdrLineAttribute& getLine() const { return maLine; } + const SdrFillAttribute& getFill() const { return maFill; } + const SdrShadowAttribute& getShadow() const { return maShadow; } + const FillGradientAttribute& getFillFloatTransGradient() const { return maFillFloatTransGradient; } + }; + +} // end of namespace drawinglayer::overlay + + +#endif // INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRALLATTRIBUTE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrfillattribute.hxx b/include/drawinglayer/attribute/sdrfillattribute.hxx new file mode 100644 index 000000000..6ba140065 --- /dev/null +++ b/include/drawinglayer/attribute/sdrfillattribute.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRFILLATTRIBUTE_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRFILLATTRIBUTE_HXX + +#include +#include + + +// predefines + +namespace basegfx { + class BColor; +} + +namespace drawinglayer::attribute { + class ImpSdrFillAttribute; + class FillGradientAttribute; + class FillHatchAttribute; + class SdrFillGraphicAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrFillAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrFillAttribute > ImplType; + + private: + ImplType mpSdrFillAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrFillAttribute( + double fTransparence, + const basegfx::BColor& rColor, + const FillGradientAttribute& rGradient, + const FillHatchAttribute& rHatch, + const SdrFillGraphicAttribute& rFillGraphic); + SdrFillAttribute(bool bSlideBackgroundFill = false); + SdrFillAttribute(const SdrFillAttribute&); + SdrFillAttribute(SdrFillAttribute&&); + SdrFillAttribute& operator=(const SdrFillAttribute&); + SdrFillAttribute& operator=(SdrFillAttribute&&); + ~SdrFillAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // checks if the incarnation is slideBackgroundFill + bool isSlideBackgroundFill() const; + + // compare operator + bool operator==(const SdrFillAttribute& rCandidate) const; + + // data read access + double getTransparence() const; + const basegfx::BColor& getColor() const; + const FillGradientAttribute& getGradient() const; + const FillHatchAttribute& getHatch() const; + const SdrFillGraphicAttribute& getFillGraphic() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRFILLATTRIBUTE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrfillgraphicattribute.hxx b/include/drawinglayer/attribute/sdrfillgraphicattribute.hxx new file mode 100644 index 000000000..4a39313d1 --- /dev/null +++ b/include/drawinglayer/attribute/sdrfillgraphicattribute.hxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRFILLGRAPHICATTRIBUTE_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRFILLGRAPHICATTRIBUTE_HXX + +#include +#include + + +// predefines + +class Graphic; + +namespace basegfx { + class B2DRange; + class B2DVector; +} + +namespace drawinglayer::attribute { + class FillGraphicAttribute; + class ImpSdrFillGraphicAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrFillGraphicAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrFillGraphicAttribute > ImplType; + + private: + ImplType mpSdrFillGraphicAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrFillGraphicAttribute( + const Graphic& rFillGraphic, + const basegfx::B2DVector& rGraphicLogicSize, + const basegfx::B2DVector& rSize, + const basegfx::B2DVector& rOffset, + const basegfx::B2DVector& rOffsetPosition, + const basegfx::B2DVector& rRectPoint, + bool bTiling, + bool bStretch, + bool bLogSize); + SdrFillGraphicAttribute(); + SdrFillGraphicAttribute(const SdrFillGraphicAttribute&); + SdrFillGraphicAttribute(SdrFillGraphicAttribute&&); + SdrFillGraphicAttribute& operator=(const SdrFillGraphicAttribute&); + SdrFillGraphicAttribute& operator=(SdrFillGraphicAttribute&&); + ~SdrFillGraphicAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const SdrFillGraphicAttribute& rCandidate) const; + + // data read access + const Graphic& getFillGraphic() const; + const basegfx::B2DVector& getGraphicLogicSize() const; + const basegfx::B2DVector& getSize() const; + const basegfx::B2DVector& getOffset() const; + const basegfx::B2DVector& getOffsetPosition() const; + const basegfx::B2DVector& getRectPoint() const; + bool getTiling() const; + + // FillGraphicAttribute generator + FillGraphicAttribute createFillGraphicAttribute(const basegfx::B2DRange& rRange) const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRFILLGRAPHICATTRIBUTE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrglowattribute.hxx b/include/drawinglayer/attribute/sdrglowattribute.hxx new file mode 100644 index 000000000..d4045bbc1 --- /dev/null +++ b/include/drawinglayer/attribute/sdrglowattribute.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRGLOWATTRIBUTE_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRGLOWATTRIBUTE_HXX + +#include +#include + +namespace drawinglayer::attribute +{ +class DRAWINGLAYER_DLLPUBLIC SdrGlowAttribute +{ +private: + sal_Int32 m_nRadius = 0; + Color m_color; // Includes alpha! + +public: + SdrGlowAttribute(sal_Int32 nRadius, const Color& rColor); + SdrGlowAttribute(); + SdrGlowAttribute(const SdrGlowAttribute&); + SdrGlowAttribute(SdrGlowAttribute&&); + + bool operator==(const SdrGlowAttribute& rCandidate) const; + + SdrGlowAttribute& operator=(const SdrGlowAttribute&); + SdrGlowAttribute& operator=(SdrGlowAttribute&&); + + // data access + const Color& getColor() const { return m_color; } + sal_Int32 getRadius() const { return m_nRadius; } + bool isDefault() const { return m_nRadius == 0; } +}; + +} // end of namespace drawinglayer::attribute + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRGLOWATTRIBUTE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrlightattribute3d.hxx b/include/drawinglayer/attribute/sdrlightattribute3d.hxx new file mode 100644 index 000000000..b3c1fcaaa --- /dev/null +++ b/include/drawinglayer/attribute/sdrlightattribute3d.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLIGHTATTRIBUTE3D_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLIGHTATTRIBUTE3D_HXX + +#include +#include + + +// predefines + +namespace basegfx { + class BColor; + class B3DVector; +} + +namespace drawinglayer::attribute { + class ImpSdr3DLightAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC Sdr3DLightAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdr3DLightAttribute > ImplType; + + private: + ImplType mpSdr3DLightAttribute; + + public: + // constructors/destructor + Sdr3DLightAttribute( + const basegfx::BColor& rColor, + const basegfx::B3DVector& rDirection, + bool bSpecular); + Sdr3DLightAttribute(const Sdr3DLightAttribute&); + ~Sdr3DLightAttribute(); + + // assignment operator + Sdr3DLightAttribute& operator=(const Sdr3DLightAttribute&); + + // compare operator + bool operator==(const Sdr3DLightAttribute& rCandidate) const; + + // data read access + const basegfx::BColor& getColor() const; + const basegfx::B3DVector& getDirection() const; + bool getSpecular() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLIGHTATTRIBUTE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrlightingattribute3d.hxx b/include/drawinglayer/attribute/sdrlightingattribute3d.hxx new file mode 100644 index 000000000..ae2155a54 --- /dev/null +++ b/include/drawinglayer/attribute/sdrlightingattribute3d.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLIGHTINGATTRIBUTE3D_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLIGHTINGATTRIBUTE3D_HXX + +#include +#include + +#include + + +// predefines + +namespace basegfx { + class BColor; + class B3DVector; +} + +namespace drawinglayer::attribute { + class ImpSdrLightingAttribute; + class Sdr3DLightAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrLightingAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrLightingAttribute > ImplType; + + private: + ImplType mpSdrLightingAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrLightingAttribute( + const basegfx::BColor& rAmbientLight, + std::vector< Sdr3DLightAttribute >&& rLightVector); + SdrLightingAttribute(); + SdrLightingAttribute(const SdrLightingAttribute& rCandidate); + SdrLightingAttribute(SdrLightingAttribute&& rCandidate); + SdrLightingAttribute& operator=(const SdrLightingAttribute& rCandidate); + SdrLightingAttribute& operator=(SdrLightingAttribute&& rCandidate); + ~SdrLightingAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const SdrLightingAttribute& rCandidate) const; + + // data read access + const basegfx::BColor& getAmbientLightColor() const; + const ::std::vector< Sdr3DLightAttribute >& getLightVector() const; + + // color model solver + basegfx::BColor solveColorModel( + const basegfx::B3DVector& rNormalInEyeCoordinates, + const basegfx::BColor& rColor, const basegfx::BColor& rSpecular, + const basegfx::BColor& rEmission, sal_uInt16 nSpecularIntensity) const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLIGHTINGATTRIBUTE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrlineattribute.hxx b/include/drawinglayer/attribute/sdrlineattribute.hxx new file mode 100644 index 000000000..2fa9c39f0 --- /dev/null +++ b/include/drawinglayer/attribute/sdrlineattribute.hxx @@ -0,0 +1,89 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLINEATTRIBUTE_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLINEATTRIBUTE_HXX + +#include +#include +#include +#include +#include + + +// predefines + +namespace basegfx { + class BColor; +} + +namespace drawinglayer::attribute { + class ImpSdrLineAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrLineAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrLineAttribute > ImplType; + + private: + ImplType mpSdrLineAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrLineAttribute( + basegfx::B2DLineJoin eJoin, + double fWidth, + double fTransparence, + const basegfx::BColor& rColor, + css::drawing::LineCap eCap, + std::vector< double >&& rDotDashArray, + double fFullDotDashLen); + SdrLineAttribute(); + SdrLineAttribute(const SdrLineAttribute&); + SdrLineAttribute(SdrLineAttribute&&); + SdrLineAttribute& operator=(const SdrLineAttribute&); + SdrLineAttribute& operator=(SdrLineAttribute&&); + ~SdrLineAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const SdrLineAttribute& rCandidate) const; + + // data access + basegfx::B2DLineJoin getJoin() const; + double getWidth() const; + double getTransparence() const; + const basegfx::BColor& getColor() const; + const ::std::vector< double >& getDotDashArray() const; + double getFullDotDashLen() const; + css::drawing::LineCap getCap() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLINEATTRIBUTE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrlinestartendattribute.hxx b/include/drawinglayer/attribute/sdrlinestartendattribute.hxx new file mode 100644 index 000000000..afcf1fd6d --- /dev/null +++ b/include/drawinglayer/attribute/sdrlinestartendattribute.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLINESTARTENDATTRIBUTE_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLINESTARTENDATTRIBUTE_HXX + +#include +#include + + +// predefines + +namespace basegfx { + class B2DPolyPolygon; +} + +namespace drawinglayer::attribute { + class ImpSdrLineStartEndAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrLineStartEndAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrLineStartEndAttribute > ImplType; + + private: + ImplType mpSdrLineStartEndAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrLineStartEndAttribute( + const basegfx::B2DPolyPolygon& rStartPolyPolygon, + const basegfx::B2DPolyPolygon& rEndPolyPolygon, + double fStartWidth, + double fEndWidth, + bool bStartActive, + bool bEndActive, + bool bStartCentered, + bool bEndCentered); + SdrLineStartEndAttribute(); + SdrLineStartEndAttribute(const SdrLineStartEndAttribute&); + SdrLineStartEndAttribute(SdrLineStartEndAttribute&&); + SdrLineStartEndAttribute& operator=(const SdrLineStartEndAttribute&); + SdrLineStartEndAttribute& operator=(SdrLineStartEndAttribute&&); + ~SdrLineStartEndAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const SdrLineStartEndAttribute& rCandidate) const; + + // data read access + const basegfx::B2DPolyPolygon& getStartPolyPolygon() const; + const basegfx::B2DPolyPolygon& getEndPolyPolygon() const; + double getStartWidth() const; + double getEndWidth() const; + bool isStartActive() const; + bool isEndActive() const; + bool isStartCentered() const; + bool isEndCentered() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRLINESTARTENDATTRIBUTE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrobjectattribute3d.hxx b/include/drawinglayer/attribute/sdrobjectattribute3d.hxx new file mode 100644 index 000000000..0a2889d3e --- /dev/null +++ b/include/drawinglayer/attribute/sdrobjectattribute3d.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDROBJECTATTRIBUTE3D_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDROBJECTATTRIBUTE3D_HXX + +#include + +#include +#include +#include +#include +#include + + +// predefines + +namespace drawinglayer::attribute { + class ImpSdr3DObjectAttribute; + class MaterialAttribute3D; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC Sdr3DObjectAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdr3DObjectAttribute > ImplType; + + private: + ImplType mpSdr3DObjectAttribute; + + public: + // constructors/destructor + Sdr3DObjectAttribute( + css::drawing::NormalsKind aNormalsKind, + css::drawing::TextureProjectionMode aTextureProjectionX, + css::drawing::TextureProjectionMode aTextureProjectionY, + css::drawing::TextureKind2 aTextureKind, + css::drawing::TextureMode aTextureMode, + const MaterialAttribute3D& rMaterial, + bool bNormalsInvert, + bool bDoubleSided, + bool bShadow3D, + bool bTextureFilter, + bool bReducedLineGeometry); + Sdr3DObjectAttribute(const Sdr3DObjectAttribute&); + ~Sdr3DObjectAttribute(); + + // assignment operator + Sdr3DObjectAttribute& operator=(const Sdr3DObjectAttribute&); + + // compare operator + bool operator==(const Sdr3DObjectAttribute& rCandidate) const; + + // data read access + css::drawing::NormalsKind getNormalsKind() const; + css::drawing::TextureProjectionMode getTextureProjectionX() const; + css::drawing::TextureProjectionMode getTextureProjectionY() const; + css::drawing::TextureKind2 getTextureKind() const; + css::drawing::TextureMode getTextureMode() const; + const MaterialAttribute3D& getMaterial() const; + bool getNormalsInvert() const; + bool getDoubleSided() const; + bool getShadow3D() const; + bool getTextureFilter() const; + bool getReducedLineGeometry() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDROBJECTATTRIBUTE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrsceneattribute3d.hxx b/include/drawinglayer/attribute/sdrsceneattribute3d.hxx new file mode 100644 index 000000000..fa48207d3 --- /dev/null +++ b/include/drawinglayer/attribute/sdrsceneattribute3d.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRSCENEATTRIBUTE3D_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRSCENEATTRIBUTE3D_HXX + +#include + +#include +#include +#include + + +// predefines + +namespace drawinglayer::attribute { + class ImpSdrSceneAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrSceneAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrSceneAttribute > ImplType; + + private: + ImplType mpSdrSceneAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrSceneAttribute( + double fDistance, + double fShadowSlant, + css::drawing::ProjectionMode aProjectionMode, + css::drawing::ShadeMode aShadeMode, + bool bTwoSidedLighting); + SdrSceneAttribute(); + SdrSceneAttribute(const SdrSceneAttribute&); + SdrSceneAttribute(SdrSceneAttribute&&); + SdrSceneAttribute& operator=(const SdrSceneAttribute&); + SdrSceneAttribute& operator=(SdrSceneAttribute&&); + ~SdrSceneAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const SdrSceneAttribute& rCandidate) const; + + // data read access + double getShadowSlant() const; + css::drawing::ProjectionMode getProjectionMode() const; + css::drawing::ShadeMode getShadeMode() const; + bool getTwoSidedLighting() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRSCENEATTRIBUTE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/sdrshadowattribute.hxx b/include/drawinglayer/attribute/sdrshadowattribute.hxx new file mode 100644 index 000000000..ffe249498 --- /dev/null +++ b/include/drawinglayer/attribute/sdrshadowattribute.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRSHADOWATTRIBUTE_HXX +#define INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRSHADOWATTRIBUTE_HXX + +#include +#include + + +// predefines + +namespace basegfx { + class BColor; + class B2DVector; +} + +namespace drawinglayer::attribute { + class ImpSdrShadowAttribute; +} + + +namespace drawinglayer::attribute + { + class DRAWINGLAYER_DLLPUBLIC SdrShadowAttribute + { + public: + typedef o3tl::cow_wrapper< ImpSdrShadowAttribute > ImplType; + + private: + ImplType mpSdrShadowAttribute; + + public: + /// constructors/assignmentoperator/destructor + SdrShadowAttribute( + const basegfx::B2DVector& rOffset, + const basegfx::B2DVector& rSize, + double fTransparence, + sal_Int32 nBlur, + const basegfx::BColor& rColor); + SdrShadowAttribute(); + SdrShadowAttribute(const SdrShadowAttribute&); + SdrShadowAttribute(SdrShadowAttribute&&); + SdrShadowAttribute& operator=(const SdrShadowAttribute&); + SdrShadowAttribute& operator=(SdrShadowAttribute&&); + ~SdrShadowAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const SdrShadowAttribute& rCandidate) const; + + // data access + const basegfx::B2DVector& getOffset() const; + const basegfx::B2DVector& getSize() const; + double getTransparence() const; + sal_Int32 getBlur() const; + const basegfx::BColor& getColor() const; + }; + +} // end of namespace drawinglayer::attribute + + +#endif //INCLUDED_DRAWINGLAYER_ATTRIBUTE_SDRSHADOWATTRIBUTE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/attribute/strokeattribute.hxx b/include/drawinglayer/attribute/strokeattribute.hxx new file mode 100644 index 000000000..163a137cb --- /dev/null +++ b/include/drawinglayer/attribute/strokeattribute.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace drawinglayer::attribute +{ +class ImpStrokeAttribute; +} + +namespace drawinglayer::attribute +{ +class DRAWINGLAYER_DLLPUBLIC StrokeAttribute +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + ImplType mpStrokeAttribute; + +public: + /// constructors/assignmentoperator/destructor + explicit StrokeAttribute(std::vector&& rDotDashArray, double fFullDotDashLen = 0.0); + StrokeAttribute(); + StrokeAttribute(const StrokeAttribute&); + StrokeAttribute(StrokeAttribute&&); + StrokeAttribute& operator=(const StrokeAttribute&); + StrokeAttribute& operator=(StrokeAttribute&&); + ~StrokeAttribute(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + // compare operator + bool operator==(const StrokeAttribute& rCandidate) const; + + // data read access + const ::std::vector& getDotDashArray() const; + double getFullDotDashLen() const; +}; +} // end of namespace drawinglayer::attribute + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/converters.hxx b/include/drawinglayer/converters.hxx new file mode 100644 index 000000000..1fda7a2f8 --- /dev/null +++ b/include/drawinglayer/converters.hxx @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace drawinglayer +{ +BitmapEx DRAWINGLAYER_DLLPUBLIC +convertToBitmapEx(drawinglayer::primitive2d::Primitive2DContainer&& rSeq, + const geometry::ViewInformation2D& rViewInformation2D, sal_uInt32 nDiscreteWidth, + sal_uInt32 nDiscreteHeight, sal_uInt32 nMaxSquarePixels); + +// helper to convert any Primitive2DSequence to a good quality BitmapEx, +// using default parameters +BitmapEx DRAWINGLAYER_DLLPUBLIC convertPrimitive2DContainerToBitmapEx( + drawinglayer::primitive2d::Primitive2DContainer&& rSeq, const basegfx::B2DRange& rTargetRange, + const sal_uInt32 nMaximumQuadraticPixels = 500000, + const o3tl::Length eTargetUnit = o3tl::Length::mm100, + const std::optional& rTargetDPI = std::nullopt); + +} // end of namespace drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/drawinglayerdllapi.h b/include/drawinglayer/drawinglayerdllapi.h new file mode 100644 index 000000000..36a0d8abf --- /dev/null +++ b/include/drawinglayer/drawinglayerdllapi.h @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DRAWINGLAYER_DRAWINGLAYERDLLAPI_H +#define INCLUDED_DRAWINGLAYER_DRAWINGLAYERDLLAPI_H + +#include + +#if defined(DRAWINGLAYER_DLLIMPLEMENTATION) +#define DRAWINGLAYER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define DRAWINGLAYER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define DRAWINGLAYER_DLLPRIVATE SAL_DLLPRIVATE + +#if defined(DRAWINGLAYERCORE_DLLIMPLEMENTATION) +#define DRAWINGLAYERCORE_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define DRAWINGLAYERCORE_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/geometry/viewinformation2d.hxx b/include/drawinglayer/geometry/viewinformation2d.hxx new file mode 100644 index 000000000..2957b7daf --- /dev/null +++ b/include/drawinglayer/geometry/viewinformation2d.hxx @@ -0,0 +1,150 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +// predefines + +namespace drawinglayer::geometry +{ +class ImpViewInformation2D; +} + +namespace basegfx +{ +class B2DHomMatrix; +class B2DRange; +} + +namespace com::sun::star::beans +{ +struct PropertyValue; +} + +namespace com::sun::star::drawing +{ +class XDrawPage; +} + +namespace com::sun::star::uno +{ +template class Reference; +template class Sequence; +} + +namespace drawinglayer::geometry +{ +/** ViewInformation2D class + + This class holds all view-relevant information for a 2d geometry. + The most used data is for convenience offered directly using basegfx tooling classes. +*/ +class DRAWINGLAYERCORE_DLLPUBLIC ViewInformation2D +{ +public: + typedef o3tl::cow_wrapper ImplType; + +private: + /// pointer to private implementation class + ImplType mpViewInformation2D; + +public: + /** Constructor: Create a ViewInformation2D + + @param rObjectTransformation + The Transformation from Object to World coordinates (normally logic coordinates). + + @param rViewTransformation + The Transformation from World to View coordinates (normally logic coordinates + to discrete units, e.g. pixels). + + @param rViewport + The visible part of the view in World coordinates. If empty (getViewport().isEmpty()) + everything is visible. The data is in World coordinates. + + @param rxDrawPage + The currently displayed page. This information is needed e.g. due to existing PageNumber + fields which need to be interpreted. + + @param fViewTime + The time the view is defined for. Default is 0.0. This parameter is used e.g. for + animated objects + + @param rReducedDisplayQuality + */ + ViewInformation2D(const basegfx::B2DHomMatrix& rObjectTransformation, + const basegfx::B2DHomMatrix& rViewTransformation, + const basegfx::B2DRange& rViewport, + const css::uno::Reference& rxDrawPage, + double fViewTime, bool bReducedDisplayQuality = false); + + /// default (empty) constructor + ViewInformation2D(); + + /// copy constructor + ViewInformation2D(const ViewInformation2D&); + + ViewInformation2D(ViewInformation2D&&); + + /// destructor + ~ViewInformation2D(); + + /// assignment operator + ViewInformation2D& operator=(const ViewInformation2D&); + ViewInformation2D& operator=(ViewInformation2D&&); + + /// compare operators + bool operator==(const ViewInformation2D& rCandidate) const; + bool operator!=(const ViewInformation2D& rCandidate) const { return !operator==(rCandidate); } + + /// data access + const basegfx::B2DHomMatrix& getObjectTransformation() const; + const basegfx::B2DHomMatrix& getViewTransformation() const; + /// Empty viewport means everything is visible. + const basegfx::B2DRange& getViewport() const; + double getViewTime() const; + const css::uno::Reference& getVisualizedPage() const; + + /// On-demand prepared Object to View transformation and its inverse for convenience + const basegfx::B2DHomMatrix& getObjectToViewTransformation() const; + const basegfx::B2DHomMatrix& getInverseObjectToViewTransformation() const; + + /// On-demand prepared Viewport in discrete units for convenience + /// Empty viewport means everything is visible. + const basegfx::B2DRange& getDiscreteViewport() const; + + /** support reduced DisplayQuality, PropertyName is 'ReducedDisplayQuality'. This + is used e.g. to allow to lower display quality for OverlayPrimitives and + may lead to simpler decompositions in the local create2DDecomposition + implementations of the primitives + */ + bool getReducedDisplayQuality() const; +}; + +DRAWINGLAYERCORE_DLLPUBLIC ViewInformation2D +createViewInformation2D(const css::uno::Sequence& rViewParameters); + +} // end of namespace drawinglayer::geometry + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/geometry/viewinformation3d.hxx b/include/drawinglayer/geometry/viewinformation3d.hxx new file mode 100644 index 000000000..ca368a6c3 --- /dev/null +++ b/include/drawinglayer/geometry/viewinformation3d.hxx @@ -0,0 +1,162 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_GEOMETRY_VIEWINFORMATION3D_HXX +#define INCLUDED_DRAWINGLAYER_GEOMETRY_VIEWINFORMATION3D_HXX + +#include + +#include +#include + + +// predefines + +namespace drawinglayer::geometry { + class ImpViewInformation3D; +} + +namespace basegfx { + class B3DHomMatrix; +} + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::uno { template class Sequence; } + +namespace drawinglayer::geometry + { + /** ViewInformation3D class + + This class holds all view-relevant information for a 3d geometry. It works + together with UNO API definitions and supports holding a sequence of PropertyValues. + The most used data is for convenience offered directly using basegfx tooling classes. + It is an implementation to support the sequence of PropertyValues used in a + css::graphic::XPrimitive3D for C++ implementations working with those + */ + class DRAWINGLAYER_DLLPUBLIC ViewInformation3D + { + public: + typedef o3tl::cow_wrapper< ImpViewInformation3D, o3tl::ThreadSafeRefCountingPolicy > ImplType; + + private: + /// pointer to private implementation class + ImplType mpViewInformation3D; + + public: + /** Constructor: Create a ViewInformation3D + + @param rObjectTransformation + The Transformation from Object to World coordinates (normally logic coordinates). + + @param rOrientation + A part of the 3D ViewTransformation, the World to Camera coordinates transformation + which holds the camera coordinate system. + + @param rProjection + A part of the 3D ViewTransformation, the Camera to Device transformation which + transforms coordinates to a [0.0 .. 1.0] device range in X,Y and Z. Z may be used + as source for Z-Buffers. This transformation may be e.g. a parallel projection, + but also a perspective one and thus may use the last line of the matrix. + + @param rDeviceToView + A part of the 3D ViewTransformation, the Device to View transformation which normally + translates and scales from [0.0 .. 1.0] range in X,Y and Z to discrete position and + size. + + rOrientation, rProjection and rDeviceToView define the 3D transformation pipeline + and are normally used multiplied together to have a direct transformation from + World to View coordinates + + @param fViewTime + The time the view is defined for. Default is 0.0. This parameter is used e.g. for + animated objects + + @param rExtendedParameters + A sequence of property values which allows holding various other parameters besides + the obvious and needed ones above. For this constructor none of the other parameters + should be added as data. The constructor will parse the given parameters and if + data for the other parameters is given, the value in rExtendedParameters will + be preferred and overwrite the given parameter + */ + ViewInformation3D( + const basegfx::B3DHomMatrix& rObjectTransformation, + const basegfx::B3DHomMatrix& rOrientation, + const basegfx::B3DHomMatrix& rProjection, + const basegfx::B3DHomMatrix& rDeviceToView, + double fViewTime, + const css::uno::Sequence< css::beans::PropertyValue >& rExtendedParameters); + + /** Constructor: Create a ViewInformation3D + + @param rViewParameters + A sequence of property values which allows holding any combination of local and various + other parameters. This constructor is fed completely with a sequence of PropertyValues + which will be parsed to be able to offer the most used ones in a convenient way. + */ + explicit ViewInformation3D(const css::uno::Sequence< css::beans::PropertyValue >& rViewParameters); + + /// default (empty) constructor + ViewInformation3D(); + + /// copy constructor + ViewInformation3D(const ViewInformation3D&); + + ViewInformation3D(ViewInformation3D&&); + + /// destructor + ~ViewInformation3D(); + + // checks if the incarnation is default constructed + bool isDefault() const; + + /// assignment operator + ViewInformation3D& operator=(const ViewInformation3D&); + ViewInformation3D& operator=(ViewInformation3D&&); + + /// compare operators + bool operator==(const ViewInformation3D& rCandidate) const; + bool operator!=(const ViewInformation3D& rCandidate) const { return !operator==(rCandidate); } + + /// data access + const basegfx::B3DHomMatrix& getObjectTransformation() const; + const basegfx::B3DHomMatrix& getOrientation() const; + const basegfx::B3DHomMatrix& getProjection() const; + const basegfx::B3DHomMatrix& getDeviceToView() const; + double getViewTime() const; + + /// for convenience, the linear combination of the above four transformations is offered + const basegfx::B3DHomMatrix& getObjectToView() const; + + /** Get the uno::Sequence< beans::PropertyValue > which contains only ViewInformation + not offered directly + + Use this call if You only need ViewInformation which is not offered conveniently, + but only exists as PropertyValue. This is e.g. used to create partially updated + incarnations of ViewInformation3D without losing the only with PropertyValues + defined data. It does not contain a complete description. + */ + const css::uno::Sequence< css::beans::PropertyValue >& getExtendedInformationSequence() const; + }; + +} // end of namespace drawinglayer::geometry + + +#endif //INCLUDED_DRAWINGLAYER_GEOMETRY_VIEWINFORMATION3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/BufferedDecompositionPrimitive2D.hxx b/include/drawinglayer/primitive2d/BufferedDecompositionPrimitive2D.hxx new file mode 100644 index 000000000..8087a6544 --- /dev/null +++ b/include/drawinglayer/primitive2d/BufferedDecompositionPrimitive2D.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace drawinglayer::geometry +{ +class ViewInformation2D; +} + +namespace drawinglayer::primitive2d +{ +/** BufferedDecompositionPrimitive2D class + + Baseclass for all C++ implementations of css::graphic::XPrimitive2D + which want to buffer the decomposition result + + Buffering the decomposition is the most-used buffering and is thus used my most + primitive implementations which support a decomposition as base class. + + The buffering is done by holding the last decomposition in the local parameter + maBuffered2DDecomposition. The default implementation of get2DDecomposition checks + if maBuffered2DDecomposition is empty. If yes, it uses create2DDecomposition + to create the content. In all cases, maBuffered2DDecomposition is returned. + + For view-dependent primitives derived from Primitive2DBufferDecomposition more needs + to be done when the decomposition depends on parts of the parameter ViewInformation2D. + This defines a standard method for processing these: + + Implement a view-dependent get2DDecomposition doing the following steps: + (a) Locally extract needed parameters from ViewInformation2D to new, local parameters + (this may be a complete local copy of ViewInformation2D) + (b) If a buffered decomposition exists, ckeck if one of the new local parameters + differs from the corresponding locally remembered (as member) ones. If yes, + clear maBuffered2DDecomposition + (d) call baseclass::get2DDecomposition which will use create2DDecomposition + to fill maBuffered2DDecomposition if it's empty + (e) copy the new local parameters to the corresponding locally remembered ones + to identify if a new decomposition is needed at the next call + (f) return maBuffered2DDecomposition + */ +class DRAWINGLAYERCORE_DLLPUBLIC BufferedDecompositionPrimitive2D : public BasePrimitive2D +{ +private: + /// a sequence used for buffering the last create2DDecomposition() result + Primitive2DContainer maBuffered2DDecomposition; + + /// When a shadow wraps a list of primitives, this primitive wants to influence the transparency + /// of the shadow. + sal_uInt16 mnTransparenceForShadow = 0; + +protected: + /** access methods to maBuffered2DDecomposition. The usage of this methods may allow + later thread-safe stuff to be added if needed. Only to be used by getDecomposition() + implementations for buffering the last decomposition. + */ + const Primitive2DContainer& getBuffered2DDecomposition() const + { + return maBuffered2DDecomposition; + } + void setBuffered2DDecomposition(Primitive2DContainer&& rNew) + { + maBuffered2DDecomposition = std::move(rNew); + } + + /** method which is to be used to implement the local decomposition of a 2D primitive. */ + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const = 0; + +public: + // constructor/destructor + BufferedDecompositionPrimitive2D(); + + /** The getDecomposition default implementation will on demand use create2DDecomposition() if + maBuffered2DDecomposition is empty. It will set maBuffered2DDecomposition to this obtained decomposition + to buffer it. If the decomposition is also ViewInformation2D-dependent, this method needs to be + overridden and the ViewInformation2D for the last decomposition need to be remembered, too, and + be used in the next call to decide if the buffered decomposition may be reused or not. + */ + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; + + void setTransparenceForShadow(sal_uInt16 nTransparenceForShadow) + { + mnTransparenceForShadow = nTransparenceForShadow; + } + + sal_uInt16 getTransparenceForShadow() const { return mnTransparenceForShadow; } +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/CommonTypes.hxx b/include/drawinglayer/primitive2d/CommonTypes.hxx new file mode 100644 index 000000000..3e14b05da --- /dev/null +++ b/include/drawinglayer/primitive2d/CommonTypes.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace drawinglayer::primitive2d +{ +class BasePrimitive2D; +typedef rtl::Reference Primitive2DReference; +typedef css::uno::Sequence> Primitive2DSequence; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonColorPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonColorPrimitive2D.hxx new file mode 100644 index 000000000..25b0aad47 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonColorPrimitive2D.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonColorPrimitive2D class + + This primitive defines a tools::PolyPolygon filled with a single color. + This is one of the non-decomposable primitives, so a renderer + should process it. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonColorPrimitive2D final : public BasePrimitive2D +{ +private: + /// the tools::PolyPolygon geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the polygon fill color + basegfx::BColor maBColor; + +public: + /// constructor + PolyPolygonColorPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::BColor& rBColor); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::BColor& getBColor() const { return maBColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonGradientPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonGradientPrimitive2D.hxx new file mode 100644 index 000000000..9cdeee03f --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonGradientPrimitive2D.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonColorPrimitive2D class + + This primitive defines a tools::PolyPolygon filled with a gradient. The + decomosition will create a MaskPrimitive2D containing a + FillGradientPrimitive2D. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonGradientPrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the tools::PolyPolygon geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the definition range + basegfx::B2DRange maDefinitionRange; + + /// the gradient definition + attribute::FillGradientAttribute maFillGradient; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructors. The one without definition range will use output range as definition range + PolyPolygonGradientPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const attribute::FillGradientAttribute& rFillGradient); + PolyPolygonGradientPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::B2DRange& rDefinitionRange, + const attribute::FillGradientAttribute& rFillGradient); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } + const attribute::FillGradientAttribute& getFillGradient() const { return maFillGradient; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonGraphicPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonGraphicPrimitive2D.hxx new file mode 100644 index 000000000..82094a07c --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonGraphicPrimitive2D.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonGraphicPrimitive2D class + + This primitive defines a tools::PolyPolygon filled with bitmap data + (including transparence). The decomosition will create a MaskPrimitive2D + containing a FillGraphicPrimitive2D. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonGraphicPrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the tools::PolyPolygon geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the definition range + basegfx::B2DRange maDefinitionRange; + + /// the bitmap fill definition (may include tiling) + attribute::FillGraphicAttribute maFillGraphic; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + PolyPolygonGraphicPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::B2DRange& rDefinitionRange, + const attribute::FillGraphicAttribute& rFillGraphic); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } + const attribute::FillGraphicAttribute& getFillGraphic() const { return maFillGraphic; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonHairlinePrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonHairlinePrimitive2D.hxx new file mode 100644 index 000000000..1cab074fa --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonHairlinePrimitive2D.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonHairlinePrimitive2D class + + This primitive defines a multi-PolygonHairlinePrimitive2D and is + just for convenience. The definition is not different from the single + defined PolygonHairlinePrimitive2Ds. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonHairlinePrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the hairline geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the hairline color + basegfx::BColor maBColor; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolyPolygonHairlinePrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::BColor& rBColor); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::BColor& getBColor() const { return maBColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonHatchPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonHatchPrimitive2D.hxx new file mode 100644 index 000000000..960d2e600 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonHatchPrimitive2D.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonHatchPrimitive2D class + + This primitive defines a tools::PolyPolygon filled with a hatch. The + decomosition will create a MaskPrimitive2D containing a + FillHatchPrimitive2D. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonHatchPrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the tools::PolyPolygon geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the definition range + basegfx::B2DRange maDefinitionRange; + + /// the hatch background color (if used) + basegfx::BColor maBackgroundColor; + + /// the hatch definition + attribute::FillHatchAttribute maFillHatch; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructors. The one without definition range will use output range as definition range + PolyPolygonHatchPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::BColor& rBackgroundColor, + const attribute::FillHatchAttribute& rFillHatch); + PolyPolygonHatchPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::B2DRange& rDefinitionRange, + const basegfx::BColor& rBackgroundColor, + const attribute::FillHatchAttribute& rFillHatch); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } + const basegfx::BColor& getBackgroundColor() const { return maBackgroundColor; } + const attribute::FillHatchAttribute& getFillHatch() const { return maFillHatch; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonMarkerPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonMarkerPrimitive2D.hxx new file mode 100644 index 000000000..b2dc64630 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonMarkerPrimitive2D.hxx @@ -0,0 +1,82 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +// PolyPolygonMarkerPrimitive2D class + +/** PolyPolygonMarkerPrimitive2D class + + This primitive defines a multi-PolygonMarkerPrimitive2D and is + just for convenience. The definition is not different from the single + defined PolygonMarkerPrimitive2Ds. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonMarkerPrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the marker hairline geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the two colors + basegfx::BColor maRGBColorA; + basegfx::BColor maRGBColorB; + + /// the dash distance in 'pixels' + double mfDiscreteDashLength; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolyPolygonMarkerPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::BColor& rRGBColorA, + const basegfx::BColor& rRGBColorB, double fDiscreteDashLength); + + // data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::BColor& getRGBColorA() const { return maRGBColorA; } + const basegfx::BColor& getRGBColorB() const { return maRGBColorB; } + double getDiscreteDashLength() const { return mfDiscreteDashLength; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonSelectionPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonSelectionPrimitive2D.hxx new file mode 100644 index 000000000..59f1327f0 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonSelectionPrimitive2D.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonSelectionPrimitive2D class + + This primitive defines a tools::PolyPolygon which gets filled with a defined color + and a defined transparence, but also gets extended ('grown') by the given + discrete size (thus being a view-dependent primitive) + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonSelectionPrimitive2D final + : public DiscreteMetricDependentPrimitive2D +{ +private: + /// the tools::PolyPolygon geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the color + basegfx::BColor maColor; + + /// the transparence [0.0 .. 1.0] + double mfTransparence; + + /// the discrete grow size ('pixels'), only positive values allowed + double mfDiscreteGrow; + + /// draw polygons filled when fill is set + bool mbFill : 1; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolyPolygonSelectionPrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::BColor& rColor, double fTransparence, + double fDiscreteGrow, bool bFill); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const basegfx::BColor& getColor() const { return maColor; } + double getTransparence() const { return mfTransparence; } + double getDiscreteGrow() const { return mfDiscreteGrow; } + bool getFill() const { return mbFill; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolyPolygonStrokePrimitive2D.hxx b/include/drawinglayer/primitive2d/PolyPolygonStrokePrimitive2D.hxx new file mode 100644 index 000000000..94a58b466 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolyPolygonStrokePrimitive2D.hxx @@ -0,0 +1,82 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolyPolygonStrokePrimitive2D class + + This primitive defines a multi-PolygonStrokePrimitive2D and is + just for convenience. The definition is not different from the single + defined PolygonStrokePrimitive2Ds. + */ +class DRAWINGLAYER_DLLPUBLIC PolyPolygonStrokePrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the line geometry + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the line attributes like width, join and color + attribute::LineAttribute maLineAttribute; + + /// the line stroking (if used) + attribute::StrokeAttribute maStrokeAttribute; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolyPolygonStrokePrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const attribute::LineAttribute& rLineAttribute, + const attribute::StrokeAttribute& rStrokeAttribute); + + PolyPolygonStrokePrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, + const attribute::LineAttribute& rLineAttribute); + + /// data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } + const attribute::LineAttribute& getLineAttribute() const { return maLineAttribute; } + const attribute::StrokeAttribute& getStrokeAttribute() const { return maStrokeAttribute; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolygonHairlinePrimitive2D.hxx b/include/drawinglayer/primitive2d/PolygonHairlinePrimitive2D.hxx new file mode 100644 index 000000000..d05782786 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolygonHairlinePrimitive2D.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolygonHairlinePrimitive2D class + + This primitive defines a Hairline. Since hairlines are view-dependent, + this primitive is view-dependent, too. + + This is one of the non-decomposable primitives, so a renderer + should process it. + */ +class DRAWINGLAYER_DLLPUBLIC PolygonHairlinePrimitive2D final : public BasePrimitive2D +{ +private: + /// the hairline geometry + basegfx::B2DPolygon maPolygon; + + /// the hairline color + basegfx::BColor maBColor; + +public: + /// constructor + PolygonHairlinePrimitive2D(const basegfx::B2DPolygon& rPolygon, const basegfx::BColor& rBColor); + + /// data read access + const basegfx::B2DPolygon& getB2DPolygon() const { return maPolygon; } + const basegfx::BColor& getBColor() const { return maBColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolygonMarkerPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolygonMarkerPrimitive2D.hxx new file mode 100644 index 000000000..9bdcb5352 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolygonMarkerPrimitive2D.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolygonMarkerPrimitive2D class + + This primitive defines a two-colored marker hairline which is + dashed with the given dash length. Since hairlines are view-dependent, + this primitive is view-dependent, too. + + It will be decomposed to the needed PolygonHairlinePrimitive2D if + not handled directly by a renderer. + */ +class DRAWINGLAYER_DLLPUBLIC PolygonMarkerPrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the marker hairline geometry + basegfx::B2DPolygon maPolygon; + + /// the two colors + basegfx::BColor maRGBColorA; + basegfx::BColor maRGBColorB; + + /// the dash distance in 'pixels' + double mfDiscreteDashLength; + + /// decomposition is view-dependent, remember last InverseObjectToViewTransformation + basegfx::B2DHomMatrix maLastInverseObjectToViewTransformation; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolygonMarkerPrimitive2D(const basegfx::B2DPolygon& rPolygon, const basegfx::BColor& rRGBColorA, + const basegfx::BColor& rRGBColorB, double fDiscreteDashLength); + + /// data read access + const basegfx::B2DPolygon& getB2DPolygon() const { return maPolygon; } + const basegfx::BColor& getRGBColorA() const { return maRGBColorA; } + const basegfx::BColor& getRGBColorB() const { return maRGBColorB; } + double getDiscreteDashLength() const { return mfDiscreteDashLength; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// Override standard getDecomposition to be view-dependent here + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolygonStrokeArrowPrimitive2D.hxx b/include/drawinglayer/primitive2d/PolygonStrokeArrowPrimitive2D.hxx new file mode 100644 index 000000000..2577ffdfb --- /dev/null +++ b/include/drawinglayer/primitive2d/PolygonStrokeArrowPrimitive2D.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolygonStrokeArrowPrimitive2D class + + This primitive defines a PolygonStrokePrimitive2D, + possibly extended by start and end definitions, which are + normally used for arrows. + */ +class DRAWINGLAYER_DLLPUBLIC PolygonStrokeArrowPrimitive2D final : public PolygonStrokePrimitive2D +{ +private: + /// geometric definitions for line start and end + attribute::LineStartEndAttribute maStart; + attribute::LineStartEndAttribute maEnd; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolygonStrokeArrowPrimitive2D(const basegfx::B2DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute, + const attribute::StrokeAttribute& rStrokeAttribute, + const attribute::LineStartEndAttribute& rStart, + const attribute::LineStartEndAttribute& rEnd); + + /// constructor without stroking + PolygonStrokeArrowPrimitive2D(const basegfx::B2DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute, + const attribute::LineStartEndAttribute& rStart, + const attribute::LineStartEndAttribute& rEnd); + + /// data read access + const attribute::LineStartEndAttribute& getStart() const { return maStart; } + const attribute::LineStartEndAttribute& getEnd() const { return maEnd; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolygonStrokePrimitive2D.hxx b/include/drawinglayer/primitive2d/PolygonStrokePrimitive2D.hxx new file mode 100644 index 000000000..ab1566033 --- /dev/null +++ b/include/drawinglayer/primitive2d/PolygonStrokePrimitive2D.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** PolygonStrokePrimitive2D class + + This primitive defines a line with line width, line join, line color + and stroke attributes. It will be decomposed dependent on the definition + to the needed primitives, e.g. filled PolyPolygons for fat lines. + */ +class DRAWINGLAYER_DLLPUBLIC PolygonStrokePrimitive2D : public BufferedDecompositionPrimitive2D +{ +private: + /// the line geometry + basegfx::B2DPolygon maPolygon; + + /// the line attributes like width, join and color + attribute::LineAttribute maLineAttribute; + + /// the line stroking (if used) + attribute::StrokeAttribute maStrokeAttribute; + +protected: + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolygonStrokePrimitive2D(const basegfx::B2DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute, + const attribute::StrokeAttribute& rStrokeAttribute); + + /// constructor without stroking + PolygonStrokePrimitive2D(const basegfx::B2DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute); + + /// data read access + const basegfx::B2DPolygon& getB2DPolygon() const { return maPolygon; } + const attribute::LineAttribute& getLineAttribute() const { return maLineAttribute; } + const attribute::StrokeAttribute& getStrokeAttribute() const { return maStrokeAttribute; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/PolygonWavePrimitive2D.hxx b/include/drawinglayer/primitive2d/PolygonWavePrimitive2D.hxx new file mode 100644 index 000000000..72d875a5e --- /dev/null +++ b/include/drawinglayer/primitive2d/PolygonWavePrimitive2D.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +namespace drawinglayer::primitive2d +{ +/** PolygonWavePrimitive2D class + + This primitive defines a waveline based on a PolygonStrokePrimitive2D + where the wave is defined by wave width and wave length. + */ +class PolygonWavePrimitive2D final : public PolygonStrokePrimitive2D +{ +private: + /// wave definition + double mfWaveWidth; + double mfWaveHeight; + + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + PolygonWavePrimitive2D(const basegfx::B2DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute, + const attribute::StrokeAttribute& rStrokeAttribute, double fWaveWidth, + double fWaveHeight); + + /// constructor without stroking + PolygonWavePrimitive2D(const basegfx::B2DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute, double fWaveWidth, + double fWaveHeight); + + /// data read access + double getWaveWidth() const { return mfWaveWidth; } + double getWaveHeight() const { return mfWaveHeight; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace primitive2d::drawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/Primitive2DContainer.hxx b/include/drawinglayer/primitive2d/Primitive2DContainer.hxx new file mode 100644 index 000000000..2368ea45c --- /dev/null +++ b/include/drawinglayer/primitive2d/Primitive2DContainer.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +#include +#include + +namespace drawinglayer::geometry +{ +class ViewInformation2D; +} + +namespace drawinglayer::primitive2d +{ +class SAL_WARN_UNUSED DRAWINGLAYERCORE_DLLPUBLIC Primitive2DContainer final + : public std::deque, + public Primitive2DDecompositionVisitor +{ +public: + // use zero because we allocate a lot of empty containers + explicit Primitive2DContainer() + : deque(0) + { + } + explicit Primitive2DContainer(size_type count) + : deque(count) + { + } + virtual ~Primitive2DContainer() override; + Primitive2DContainer(const Primitive2DContainer& other) + : deque(other) + { + } + Primitive2DContainer(Primitive2DContainer&& other) noexcept + : deque(std::move(other)) + { + } + Primitive2DContainer(std::initializer_list init) + : deque(init) + { + } + Primitive2DContainer( + const css::uno::Sequence>&); + Primitive2DContainer(const std::deque>&); + + virtual void visit(const Primitive2DReference& rSource) override { append(rSource); } + virtual void visit(const Primitive2DContainer& rSource) override { append(rSource); } + virtual void visit(Primitive2DContainer&& rSource) override { append(std::move(rSource)); } + + void append(const Primitive2DReference&); + void append(const Primitive2DContainer& rSource); + void append(Primitive2DContainer&& rSource); + Primitive2DContainer& operator=(const Primitive2DContainer& r) + { + deque::operator=(r); + return *this; + } + Primitive2DContainer& operator=(Primitive2DContainer&& r) noexcept + { + deque::operator=(std::move(r)); + return *this; + } + bool operator==(const Primitive2DContainer& rB) const; + bool operator!=(const Primitive2DContainer& rB) const { return !operator==(rB); } + basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& aViewInformation) const; + Primitive2DContainer maybeInvert(bool bInvert = false); + + css::uno::Sequence> toSequence() const; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/Primitive2DVisitor.hxx b/include/drawinglayer/primitive2d/Primitive2DVisitor.hxx new file mode 100644 index 000000000..559a82c66 --- /dev/null +++ b/include/drawinglayer/primitive2d/Primitive2DVisitor.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace drawinglayer::primitive2d +{ +class Primitive2DContainer; + +// Visitor class for walking a tree of Primitive2DReference +class DRAWINGLAYERCORE_DLLPUBLIC Primitive2DDecompositionVisitor +{ +public: + virtual void visit(const Primitive2DReference&) = 0; + virtual void visit(const Primitive2DContainer&) = 0; + virtual void visit(Primitive2DContainer&&) = 0; + virtual ~Primitive2DDecompositionVisitor() {} +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/Tools.hxx b/include/drawinglayer/primitive2d/Tools.hxx new file mode 100644 index 000000000..3eaa322d9 --- /dev/null +++ b/include/drawinglayer/primitive2d/Tools.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/// get B2DRange from a given Primitive2DReference +basegfx::B2DRange DRAWINGLAYERCORE_DLLPUBLIC getB2DRangeFromPrimitive2DReference( + const Primitive2DReference& rCandidate, const geometry::ViewInformation2D& aViewInformation); + +/** compare two Primitive2DReferences for equality, including trying to get implementations (BasePrimitive2D) + and using compare operator + */ +bool DRAWINGLAYERCORE_DLLPUBLIC arePrimitive2DReferencesEqual(const Primitive2DReference& rA, + const Primitive2DReference& rB); + +/** compare two Primitive2DReferences for equality, including trying to get implementations (BasePrimitive2D) + and using compare operator + */ +bool DRAWINGLAYERCORE_DLLPUBLIC +arePrimitive2DReferencesEqual(const css::uno::Reference& rA, + const css::uno::Reference& rB); + +OUString DRAWINGLAYERCORE_DLLPUBLIC idToString(sal_uInt32 nId); + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/animatedprimitive2d.hxx b/include/drawinglayer/primitive2d/animatedprimitive2d.hxx new file mode 100644 index 000000000..61ff4d33e --- /dev/null +++ b/include/drawinglayer/primitive2d/animatedprimitive2d.hxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +// predefines +namespace drawinglayer::animation +{ +class AnimationEntry; +} + +namespace basegfx +{ +class B2DHomMatrix; +} + +namespace drawinglayer::primitive2d +{ +/** AnimatedSwitchPrimitive2D class + + This is the basic class for simple, animated primitives. The basic idea + is to have an animation definition (AnimationEntry) who's basic + functionality is to return a state value for any given animation time in + the range of [0.0 .. 1.0]. Depending on the state, the decomposition + calculates an index, which of the members of the child vector is to + be visualized. + + An example: For blinking, the Child vector should exist of two entries; + for values of [0.0 .. 0.5] the first, else the last entry will be used. + This mechanism is not limited to two entries, though. + */ +class DRAWINGLAYER_DLLPUBLIC AnimatedSwitchPrimitive2D : public GroupPrimitive2D +{ +private: + /** + The animation definition which allows translation of a point in time + to an animation state [0.0 .. 1.0]. This member contains a cloned + definition and is owned by this implementation. + */ + std::unique_ptr mpAnimationEntry; + + /** flag if this is a text or graphic animation. Necessary since SdrViews need to differentiate + between both types if they are on/off + */ + bool mbIsTextAnimation : 1; + +protected: + /** write access right for classes deriving from this who want to do special + things (e.g. optimization, buffering). + Caution: This is an exception from the read-only, non-modifiable paradigm + for primitives, so special preparations may be needed. Usually should + only be used for initialization (e.g. in a derived constructor) + */ + void setAnimationEntry(const animation::AnimationEntry& rNew); + +public: + /// constructor + AnimatedSwitchPrimitive2D(const animation::AnimationEntry& rAnimationEntry, + Primitive2DContainer&& aChildren, bool bIsTextAnimation); + + /// destructor - needed due to mpAnimationEntry + virtual ~AnimatedSwitchPrimitive2D() override; + + /// data read access + const animation::AnimationEntry& getAnimationEntry() const { return *mpAnimationEntry; } + bool isTextAnimation() const { return mbIsTextAnimation; } + bool isGraphicAnimation() const { return !isTextAnimation(); } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + /** Override getDecomposition() here since the decompose + depends on the point in time, so the default implementation is + not useful here, it needs to be handled locally + */ + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; +}; + +/** AnimatedBlinkPrimitive2D class + + Basically the same mechanism as in AnimatedSwitchPrimitive2D, but the + decomposition is specialized in delivering the children in the + range [0.0.. 0.5] and an empty sequence else + */ +class DRAWINGLAYER_DLLPUBLIC AnimatedBlinkPrimitive2D final : public AnimatedSwitchPrimitive2D +{ +public: + /// constructor + AnimatedBlinkPrimitive2D(const animation::AnimationEntry& rAnimationEntry, + Primitive2DContainer&& aChildren); + + /// create local decomposition + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +/** AnimatedInterpolatePrimitive2D class + + Specialized on multi-step animations based on matrix transformations. The + Child sequence will be embedded in a matrix transformation. That transformation + will be linearly combined from the decomposed values and the animation value + to allow a smooth animation. + */ +class DRAWINGLAYER_DLLPUBLIC AnimatedInterpolatePrimitive2D final : public AnimatedSwitchPrimitive2D +{ +private: + /// the transformations + std::vector maMatrixStack; + +public: + /// constructor + AnimatedInterpolatePrimitive2D(const std::vector& rmMatrixStack, + const animation::AnimationEntry& rAnimationEntry, + Primitive2DContainer&& aChildren); + + /// create local decomposition + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/backgroundcolorprimitive2d.hxx b/include/drawinglayer/primitive2d/backgroundcolorprimitive2d.hxx new file mode 100644 index 000000000..191fde1b8 --- /dev/null +++ b/include/drawinglayer/primitive2d/backgroundcolorprimitive2d.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +// BackgroundColorPrimitive2D class + +namespace drawinglayer::primitive2d +{ +/** BackgroundColorPrimitive2D class + + This primitive is defined to fill the whole visible Viewport with + the given color (and thus decomposes to a filled polygon). This + makes it a view-dependent primitive by definition. It only has + a valid decomposition if a valid Viewport is given in the + ViewInformation2D at decomposition time. + + It will try to buffer its last decomposition using maLastViewport + to detect changes in the get2DDecomposition call. + */ +class DRAWINGLAYER_DLLPUBLIC BackgroundColorPrimitive2D final + : public BufferedDecompositionPrimitive2D +{ +private: + /// the fill color to use + basegfx::BColor maBColor; + double mfTransparency; + + /// the last used viewInformation, used from getDecomposition for buffering + basegfx::B2DRange maLastViewport; + + /// create local decomposition + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + explicit BackgroundColorPrimitive2D(const basegfx::BColor& rBColor, double fTransparency = 0); + + /// data read access + const basegfx::BColor& getBColor() const { return maBColor; } + double getTransparency() const { return mfTransparency; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get B2Drange + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + /// Override standard getDecomposition call to be view-dependent here + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/baseprimitive2d.hxx b/include/drawinglayer/primitive2d/baseprimitive2d.hxx new file mode 100644 index 000000000..9e011bbea --- /dev/null +++ b/include/drawinglayer/primitive2d/baseprimitive2d.hxx @@ -0,0 +1,211 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace drawinglayer::geometry +{ +class ViewInformation2D; +} + +typedef comphelper::WeakComponentImplHelper + BasePrimitive2DImplBase; + +namespace drawinglayer::primitive2d +{ +/** BasePrimitive2D class + + Baseclass for all C++ implementations of css::graphic::XPrimitive2D + + This class is strongly virtual due to the lack of getPrimitiveID() implementation. + This is by purpose, this base class shall not be incarnated and be used directly as + a XPrimitive2D. + + It is noncopyable to make clear that a primitive is a read-only + instance and copying or changing values is not intended. The idea is to hold all data + needed for visualisation of this primitive in unchangeable form. + + It is derived from cppu::BaseMutex to have a Mutex at hand; in a base + implementation this may not be needed, but e.g. when buffering at last decomposition + in a local member, multiple threads may try to decompose at the same time, so locking + is needed to avoid race conditions seen from the UNO object implementation. + + A method to get a simplified representation is provided by get2DDecomposition. The + default implementation returns an empty sequence. The idea is that processors + using this primitive and do not know it, may get the decomposition and process + these instead. An example is e.g. a fat line, who's decomposition may contain + the geometric representation of that line using filled polygon primitives. When + the renderer knows how to handle fat lines, he may process this primitive directly; + if not he can use the decomposition. With this functionality, renderers may operate by + knowing only a small set of primitives. + + When a primitive does not implement get2DDecomposition, it is called a 'Basic Primitive' and + belongs to the set of primitives which a processor should be able to handle. Practice + will define this minimal sets of primitives. When defined and the concept is proved, + unique UNO APIs may be defined/implemented for these set to allow more intense work + with primitives using UNO. + + Current Basic 2D Primitives are: + + - BitmapPrimitive2D (bitmap data, evtl. with transparence) + - PointArrayPrimitive2D (single points) + - PolygonHairlinePrimitive2D (hairline curves/polygons) + - PolyPolygonColorPrimitive2D (colored polygons) + + UPDATE: MetafilePrimitive2D (VCL Metafile) is taken off this list since + it is implemented with the integration of CWS aw078 into DV300m69. + + All other implemented primitives have a defined decomposition and can thus be + decomposed down to this small set. + + A renderer implementing support for this minimal set of primitives can completely + render primitive-based visualisations. Of course, he also has to take states into account + which are represented by GroupPrimitive2D derivations, see groupprimitive2d.hxx + + To support getting the geometric BoundRect, getB2DRange is used. The default + implementation will use the get2DDecomposition result and merge a range from the + entries. Thus, an implementation is only necessary for the Basic Primitives, but + of course speedups are possible (and are used) by implementing the method at higher-level + primitives. + + For primitive identification, getPrimitiveID is used currently in this implementations + to allow a fast switch/case processing. This needs a unique identifier mechanism which + currently uses defines (see drawinglayer_primitivetypes2d.hxx). For UNO primitive API + it will be needed to add a unique descriptor (Name?) later to the API. + + This base implementation provides mappings from the methods from XPrimitive2D + (getDecomposition/getRange) to the appropriate methods in the C++ implementations + (get2DDecomposition/getB2DRange). The PropertyValue ViewParameters is converted to + the appropriate C++ implementation class ViewInformation2D. + + This base class does not implement any buffering; e.g. buffering the decomposition + and/or the range. These may be buffered anytime since the definition is that the primitive + is read-only and thus unchangeable. This implies that the decomposition and/or getting + the range will lead to the same result as last time, under the precondition that + the parameter ViewInformation2D is the same as the last one. This is usually the case + for view-independent primitives which are defined by not using ViewInformation2D + in their get2DDecomposition/getB2DRange implementations. +*/ +class DRAWINGLAYERCORE_DLLPUBLIC BasePrimitive2D : public salhelper::SimpleReferenceObject +{ + BasePrimitive2D(const BasePrimitive2D&) = delete; + BasePrimitive2D& operator=(const BasePrimitive2D&) = delete; + +public: + // constructor/destructor + BasePrimitive2D(); + virtual ~BasePrimitive2D() override; + + /** the ==operator is mainly needed to allow testing newly-created primitives against their last + incarnation which buffers/holds the made decompositions. The default implementation + uses getPrimitive2DID()-calls to test if it's the same ID at last. + Overridden implementations are then based on this implementation + */ + virtual bool operator==(const BasePrimitive2D& rPrimitive) const; + bool operator!=(const BasePrimitive2D& rPrimitive) const { return !operator==(rPrimitive); } + + /// The default implementation will use getDecomposition results to create the range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; + + /** provide unique ID for fast identifying of known primitive implementations in renderers. These use + the defines from drawinglayer_primitivetypes2d.hxx to define unique IDs. + */ + virtual sal_uInt32 getPrimitive2DID() const = 0; + + /// The default implementation will return an empty sequence + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const; + + // Methods from XPrimitive2D + + /** The getDecomposition implementation for UNO API will use getDecomposition from this implementation. It + will construct a ViewInformation2D from the ViewParameters for that purpose + */ + Primitive2DContainer + getDecomposition(const css::uno::Sequence& rViewParameters); + + /** The getRange implementation for UNO API will use getRange from this implementation. It + will construct a ViewInformation2D from the ViewParameters for that purpose + */ + css::geometry::RealRectangle2D + getRange(const css::uno::Sequence& rViewParameters); + + // XAccounting + virtual sal_Int64 estimateUsage(); +}; + +/** + Rather than make all the BasePrimitive2D classes bear the cost of being an UNO + object, we just wrap the top level BasePrimitive2D in this class when we need + to pass them over UNO +*/ +class DRAWINGLAYERCORE_DLLPUBLIC UnoPrimitive2D final : public BasePrimitive2DImplBase +{ + UnoPrimitive2D(const UnoPrimitive2D&) = delete; + UnoPrimitive2D& operator=(const UnoPrimitive2D&) = delete; + +public: + // constructor/destructor + UnoPrimitive2D(const rtl::Reference& rPrimitive) + : mxPrimitive(rPrimitive) + { + } + virtual ~UnoPrimitive2D() override; + + // Methods from XPrimitive2D + + /** The getDecomposition implementation for UNO API will use getDecomposition from this implementation. It + will construct a ViewInformation2D from the ViewParameters for that purpose + */ + virtual css::uno::Sequence<::css::uno::Reference<::css::graphic::XPrimitive2D>> SAL_CALL + getDecomposition(const css::uno::Sequence& rViewParameters) override; + + /** The getRange implementation for UNO API will use getRange from this implementation. It + will construct a ViewInformation2D from the ViewParameters for that purpose + */ + virtual css::geometry::RealRectangle2D SAL_CALL + getRange(const css::uno::Sequence& rViewParameters) override; + + // XAccounting + virtual sal_Int64 SAL_CALL estimateUsage() override; + + rtl::Reference const& getBasePrimitive2D() const { return mxPrimitive; } + +private: + rtl::Reference mxPrimitive; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/bitmapprimitive2d.hxx b/include/drawinglayer/primitive2d/bitmapprimitive2d.hxx new file mode 100644 index 000000000..46c0825af --- /dev/null +++ b/include/drawinglayer/primitive2d/bitmapprimitive2d.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace com::sun::star::awt +{ +class XBitmap; +} + +namespace drawinglayer::primitive2d +{ +/** BitmapPrimitive2D class + + This class is the central primitive for Bitmap-based primitives. + To keep it independent of Bitmap implementations, use UNO API + XBitmap object as wrapper due to formally used class Bitmap being + vcl-dependent and requiring linking against it. Use VCLUnoHelper + to convert awt::XBitmap <-> Bitmap + */ +class DRAWINGLAYER_DLLPUBLIC BitmapPrimitive2D final : public BasePrimitive2D +{ +private: + /// the Bitmap-data + css::uno::Reference maXBitmap; + + /** the object transformation from unit coordinates, defining + size, shear, rotate and position + */ + basegfx::B2DHomMatrix maTransform; + +public: + /// constructor + BitmapPrimitive2D(const css::uno::Reference& rXBitmap, + const basegfx::B2DHomMatrix& rTransform); + + /// data read access + const css::uno::Reference& getXBitmap() const { return maXBitmap; } + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + // XAccounting + virtual sal_Int64 estimateUsage() override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/borderlineprimitive2d.hxx b/include/drawinglayer/primitive2d/borderlineprimitive2d.hxx new file mode 100644 index 000000000..fe4580d07 --- /dev/null +++ b/include/drawinglayer/primitive2d/borderlineprimitive2d.hxx @@ -0,0 +1,146 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +enum class SvxBorderLineStyle : sal_Int16; + +namespace drawinglayer::primitive2d +{ +/** BorderLine class + Helper class holding the style definition for a single part of a full BorderLine definition. + Line extends are for start/end and for Left/Right, seen in vector direction. If + Left != Right that means the line has a diagonal start/end. + Think about it similar to a trapezoid, but not aligned to X-Axis and using the + perpendicular vector to the given one in a right-handed coordinate system. +*/ +class DRAWINGLAYER_DLLPUBLIC BorderLine +{ +private: + // line attribute containing Width, Color and others + drawinglayer::attribute::LineAttribute maLineAttribute; + + // line extends + double mfStartLeft; + double mfStartRight; + double mfEndLeft; + double mfEndRight; + + // if this is a gap, this is set to true + bool mbIsGap; + +public: + // Constructor for visible BorderLine segments + BorderLine(const drawinglayer::attribute::LineAttribute& rLineAttribute, + double fStartLeft = 0.0, double fStartRight = 0.0, double fEndLeft = 0.0, + double fEndRight = 0.0); + + // Constructor for gap BorderLine segments + BorderLine(double fWidth); + + ~BorderLine(); + + BorderLine(BorderLine const&) = default; + BorderLine(BorderLine&&) = default; + BorderLine& operator=(BorderLine const&) = default; + BorderLine& operator=(BorderLine&&) = default; + + const drawinglayer::attribute::LineAttribute& getLineAttribute() const + { + return maLineAttribute; + } + double getStartLeft() const { return mfStartLeft; } + double getStartRight() const { return mfStartRight; } + double getEndLeft() const { return mfEndLeft; } + double getEndRight() const { return mfEndRight; } + bool isGap() const { return mbIsGap; } + + /// compare operator + bool operator==(const BorderLine& rBorderLine) const; +}; + +/** BorderLinePrimitive2D class + + This is the basic primitive to build frames around objects, e.g. tables. + It defines a single or double line from Start to End using the LeftWidth, + Distance and RightWidth definitions. + The LineStart/End overlap is defined in the BorderLines definitions (see + class BorderLine above). +*/ +class DRAWINGLAYER_DLLPUBLIC BorderLinePrimitive2D final : public BufferedDecompositionPrimitive2D +{ +private: + /// the line definition + basegfx::B2DPoint maStart; + basegfx::B2DPoint maEnd; + + /// the single BorderLine style definition(s), one or three mostly used + std::vector maBorderLines; + + /// common style definitions + const drawinglayer::attribute::StrokeAttribute maStrokeAttribute; + + /// create local decomposition + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + + /// helper to get the full width from maBorderLines + double getFullWidth() const; + +public: + /// simplified constructor for BorderLine with single edge + BorderLinePrimitive2D(const basegfx::B2DPoint& rStart, const basegfx::B2DPoint& rEnd, + std::vector&& rBorderLines, + const drawinglayer::attribute::StrokeAttribute& rStrokeAttribute); + + /// data read access + const basegfx::B2DPoint& getStart() const { return maStart; } + const basegfx::B2DPoint& getEnd() const { return maEnd; } + const std::vector& getBorderLines() const { return maBorderLines; } + const drawinglayer::attribute::StrokeAttribute& getStrokeAttribute() const + { + return maStrokeAttribute; + } + + /// helper to decide if AntiAliasing should be used + bool isHorizontalOrVertical(const geometry::ViewInformation2D& rViewInformation) const; + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +/// helper to try to merge two instances of BorderLinePrimitive2D. If it was possible, +/// a merged version is in the returned Primitive2DReference. Lots of preconditions +/// have to be met to allow that, see implementation (and maybe even expand) +Primitive2DReference DRAWINGLAYER_DLLPUBLIC tryMergeBorderLinePrimitive2D( + const BorderLinePrimitive2D* pCandidateA, const BorderLinePrimitive2D* pCandidateB); + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/controlprimitive2d.hxx b/include/drawinglayer/primitive2d/controlprimitive2d.hxx new file mode 100644 index 000000000..015151cf8 --- /dev/null +++ b/include/drawinglayer/primitive2d/controlprimitive2d.hxx @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace com::sun::star::awt +{ +class XControl; +} +namespace com::sun::star::awt +{ +class XControlModel; +} + +namespace drawinglayer::primitive2d +{ +/** ControlPrimitive2D class + + Base class for ControlPrimitive handling. It decomposes to a + graphical representation (Bitmap data) of the control. This + representation is limited to a quadratic pixel maximum defined + in the application settings. + */ +class DRAWINGLAYER_DLLPUBLIC ControlPrimitive2D final : public BufferedDecompositionPrimitive2D +{ +private: + /// object's base data + basegfx::B2DHomMatrix maTransform; + css::uno::Reference mxControlModel; + + /// the created and cached awt::XControl + css::uno::Reference mxXControl; + + /// the last used scaling, used from getDecomposition for buffering + basegfx::B2DVector maLastViewScaling; + + /** used from getXControl() to create a local awt::XControl which is remembered in mxXControl + and from thereon always used and returned by getXControl() + */ + void createXControl(); + + /// single local decompositions, used from create2DDecomposition() + Primitive2DReference + createBitmapDecomposition(const geometry::ViewInformation2D& rViewInformation) const; + Primitive2DReference createPlaceholderDecomposition() const; + + /// local decomposition + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + ControlPrimitive2D(const basegfx::B2DHomMatrix& rTransform, + const css::uno::Reference& rxControlModel); + + /** constructor with an additional XControl as parameter to allow to hand it over at incarnation time + if it exists. This will avoid to create a 2nd one on demand in createXControl() + and thus double the XControls. + */ + ControlPrimitive2D(const basegfx::B2DHomMatrix& rTransform, + const css::uno::Reference& rxControlModel, + const css::uno::Reference& rxXControl); + + /// data read access + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + const css::uno::Reference& getControlModel() const + { + return mxControlModel; + } + + /** mxControl access. This will on demand create the awt::XControl using createXControl() + if it does not exist. It may already have been created or even handed over at + incarnation + */ + const css::uno::Reference& getXControl() const; + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + /// Override standard getDecomposition to be view-dependent here + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/discretebitmapprimitive2d.hxx b/include/drawinglayer/primitive2d/discretebitmapprimitive2d.hxx new file mode 100644 index 000000000..cbdb21ad9 --- /dev/null +++ b/include/drawinglayer/primitive2d/discretebitmapprimitive2d.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +// DiscreteBitmapPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** DiscreteBitmapPrimitive2D class + + This class defines a view-dependent BitmapPrimitive which has a + logic position for the top-left position and is always to be + painted in 1:1 pixel resolution. It will never be sheared, rotated + or scaled with the view. + */ + class DRAWINGLAYER_DLLPUBLIC DiscreteBitmapPrimitive2D final : public ObjectAndViewTransformationDependentPrimitive2D + { + private: + /// the RGBA Bitmap-data + BitmapEx maBitmapEx; + + /** the top-left object position */ + basegfx::B2DPoint maTopLeft; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + DiscreteBitmapPrimitive2D( + const BitmapEx& rBitmapEx, + const basegfx::B2DPoint& rTopLeft); + + /// data read access + const BitmapEx& getBitmapEx() const { return maBitmapEx; } + const basegfx::B2DPoint& getTopLeft() const { return maTopLeft; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/discreteshadowprimitive2d.hxx b/include/drawinglayer/primitive2d/discreteshadowprimitive2d.hxx new file mode 100644 index 000000000..435ab9825 --- /dev/null +++ b/include/drawinglayer/primitive2d/discreteshadowprimitive2d.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + + +// DiscreteShadowPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** DiscreteShadow data class + + */ + class DRAWINGLAYER_DLLPUBLIC DiscreteShadow + { + private: + /// the original shadow BitmapEx in a special form + BitmapEx maBitmapEx; + + /// buffered extracted parts of CombinedShadow for easier usage + BitmapEx maTopLeft; + BitmapEx maTop; + BitmapEx maTopRight; + BitmapEx maRight; + BitmapEx maBottomRight; + BitmapEx maBottom; + BitmapEx maBottomLeft; + BitmapEx maLeft; + + public: + /// constructor + explicit DiscreteShadow(const BitmapEx& rBitmapEx); + + /// data read access + const BitmapEx& getBitmapEx() const { return maBitmapEx; } + + /// compare operator + bool operator==(const DiscreteShadow& rCompare) const + { + return getBitmapEx() == rCompare.getBitmapEx(); + } + + /// helper accesses which create on-demand needed segments + const BitmapEx& getTopLeft() const; + const BitmapEx& getTop() const; + const BitmapEx& getTopRight() const; + const BitmapEx& getRight() const; + const BitmapEx& getBottomRight() const; + const BitmapEx& getBottom() const; + const BitmapEx& getBottomLeft() const; + const BitmapEx& getLeft() const; + }; + + /** DiscreteShadowPrimitive2D class + + */ + class DRAWINGLAYER_DLLPUBLIC DiscreteShadowPrimitive2D final : public DiscreteMetricDependentPrimitive2D + { + private: + // the object transformation of the rectangular object + basegfx::B2DHomMatrix maTransform; + + // the bitmap shadow data + DiscreteShadow maDiscreteShadow; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + DiscreteShadowPrimitive2D( + const basegfx::B2DHomMatrix& rTransform, + const DiscreteShadow& rDiscreteShadow); + + /// data read access + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + const DiscreteShadow& getDiscreteShadow() const { return maDiscreteShadow; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx b/include/drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx new file mode 100644 index 000000000..687efb1d8 --- /dev/null +++ b/include/drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + + +// define ranges for other libraries + +#define PRIMITIVE2D_ID_RANGE_DRAWINGLAYER (0 << 16) +#define PRIMITIVE2D_ID_RANGE_SVX (1 << 16) +#define PRIMITIVE2D_ID_RANGE_SD (2 << 16) +#define PRIMITIVE2D_ID_RANGE_SW (3 << 16) +#define PRIMITIVE2D_ID_RANGE_SC (4 << 16) + + +// local primitives + +#define PRIMITIVE2D_ID_TRANSPARENCEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 0) +#define PRIMITIVE2D_ID_ANIMATEDSWITCHPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 1) +#define PRIMITIVE2D_ID_ANIMATEDBLINKPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 2) +#define PRIMITIVE2D_ID_ANIMATEDINTERPOLATEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 3) +#define PRIMITIVE2D_ID_BACKGROUNDCOLORPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 4) +#define PRIMITIVE2D_ID_BITMAPPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 5) +#define PRIMITIVE2D_ID_CONTROLPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 6) +#define PRIMITIVE2D_ID_EMBEDDED3DPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 7) +#define PRIMITIVE2D_ID_FILLGRAPHICPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 8) +#define PRIMITIVE2D_ID_FILLGRADIENTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 9) +#define PRIMITIVE2D_ID_FILLHATCHPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 10) +#define PRIMITIVE2D_ID_GRAPHICPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 11) +#define PRIMITIVE2D_ID_GRIDPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 12) +#define PRIMITIVE2D_ID_GROUPPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 13) +#define PRIMITIVE2D_ID_HELPLINEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 14) +#define PRIMITIVE2D_ID_MARKERARRAYPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 15) +#define PRIMITIVE2D_ID_MASKPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 16) +#define PRIMITIVE2D_ID_MEDIAPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 17) +#define PRIMITIVE2D_ID_METAFILEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 18) +#define PRIMITIVE2D_ID_MODIFIEDCOLORPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 19) +#define PRIMITIVE2D_ID_POLYGONHAIRLINEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 20) +#define PRIMITIVE2D_ID_POLYGONMARKERPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 21) +#define PRIMITIVE2D_ID_POLYGONSTROKEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 22) +#define PRIMITIVE2D_ID_POLYGONSTROKEARROWPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 23) +#define PRIMITIVE2D_ID_POLYPOLYGONSTROKEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 24) +#define PRIMITIVE2D_ID_POLYPOLYGONSTROKEARROWPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 25) +#define PRIMITIVE2D_ID_POLYPOLYGONCOLORPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 26) +#define PRIMITIVE2D_ID_POLYPOLYGONGRADIENTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 27) +#define PRIMITIVE2D_ID_POLYPOLYGONHATCHPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 28) +#define PRIMITIVE2D_ID_POLYPOLYGONGRAPHICPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 29) +#define PRIMITIVE2D_ID_SCENEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 30) +#define PRIMITIVE2D_ID_SHADOWPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 31) +#define PRIMITIVE2D_ID_TEXTSIMPLEPORTIONPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 32) +#define PRIMITIVE2D_ID_TEXTDECORATEDPORTIONPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 33) +#define PRIMITIVE2D_ID_TRANSFORMPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 34) +#define PRIMITIVE2D_ID_UNIFIEDTRANSPARENCEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 35) +#define PRIMITIVE2D_ID_POINTARRAYPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 36) +#define PRIMITIVE2D_ID_TEXTHIERARCHYFIELDPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 37) +#define PRIMITIVE2D_ID_TEXTHIERARCHYLINEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 38) +#define PRIMITIVE2D_ID_TEXTHIERARCHYPARAGRAPHPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 39) +#define PRIMITIVE2D_ID_TEXTHIERARCHYBLOCKPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 40) +#define PRIMITIVE2D_ID_TEXTHIERARCHYEDITPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 41) +#define PRIMITIVE2D_ID_POLYGONWAVEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 42) +#define PRIMITIVE2D_ID_WRONGSPELLPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 43) +#define PRIMITIVE2D_ID_TEXTEFFECTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 44) +#define PRIMITIVE2D_ID_TEXTHIERARCHYBULLETPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 45) +#define PRIMITIVE2D_ID_POLYPOLYGONHAIRLINEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 46) +#define PRIMITIVE2D_ID_EXECUTEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 47) +#define PRIMITIVE2D_ID_PAGEPREVIEWPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 48) +#define PRIMITIVE2D_ID_STRUCTURETAGPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 49) +#define PRIMITIVE2D_ID_BORDERLINEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 50) +#define PRIMITIVE2D_ID_POLYPOLYGONMARKERPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 51) +#define PRIMITIVE2D_ID_HITTESTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 52) +#define PRIMITIVE2D_ID_INVERTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 53) +#define PRIMITIVE2D_ID_DISCRETEBITMAPPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 54) +#define PRIMITIVE2D_ID_WALLPAPERBITMAPPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 55) +#define PRIMITIVE2D_ID_TEXTLINEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 56) +#define PRIMITIVE2D_ID_TEXTCHARACTERSTRIKEOUTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 57) +#define PRIMITIVE2D_ID_TEXTGEOMETRYSTRIKEOUTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 58) +#define PRIMITIVE2D_ID_EPSPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 59) +#define PRIMITIVE2D_ID_DISCRETESHADOWPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 60) +#define PRIMITIVE2D_ID_HIDDENGEOMETRYPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 61) +#define PRIMITIVE2D_ID_SVGLINEARGRADIENTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 62) +#define PRIMITIVE2D_ID_SVGRADIALGRADIENTPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 63) +#define PRIMITIVE2D_ID_SVGLINEARATOMPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 64) +#define PRIMITIVE2D_ID_SVGRADIALATOMPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 65) +#define PRIMITIVE2D_ID_CROPPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 66) +#define PRIMITIVE2D_ID_PATTERNFILLPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 67) +#define PRIMITIVE2D_ID_OBJECTINFOPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 68) +#define PRIMITIVE2D_ID_POLYPOLYGONSELECTIONPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 69) +#define PRIMITIVE2D_ID_PAGEHIERARCHYPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 70) +#define PRIMITIVE2D_ID_GLOWPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 71) +#define PRIMITIVE2D_ID_SOFTEDGEPRIMITIVE2D (PRIMITIVE2D_ID_RANGE_DRAWINGLAYER| 72) +// When you add a new primitive, please update the drawinglayer::primitive2d::idToString() function +// in drawinglayer/source/primitive2d/Tools.cxx. + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/embedded3dprimitive2d.hxx b/include/drawinglayer/primitive2d/embedded3dprimitive2d.hxx new file mode 100644 index 000000000..959b38592 --- /dev/null +++ b/include/drawinglayer/primitive2d/embedded3dprimitive2d.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + + +// Embedded3DPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** Embedded3DPrimitive2D class + + This is a helper primitive which allows embedding of single 3D + primitives to the 2D primitive logic. It will get the scene it's + involved and thus the 3D transformation. With this information it + is able to provide 2D range data for a 3D primitive. + + This primitive will not be visualized and decomposes to a yellow + 2D rectangle to visualize that this should never be visualized + */ + class DRAWINGLAYER_DLLPUBLIC Embedded3DPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// the sequence of 3d primitives + primitive3d::Primitive3DContainer mxChildren3D; + + /// the 2D scene object transformation + basegfx::B2DHomMatrix maObjectTransformation; + + /// the 3D transformations + geometry::ViewInformation3D maViewInformation3D; + + /** if the embedded 3D primitives contain shadow, these parameters are needed + to extract the shadow which is a sequence of 2D primitives and may expand + the 2D range. Since every single 3D object in a scene may individually + have shadow or not, these values need to be provided and prepared. The shadow + distance itself (a 2D transformation) is part of the 3D shadow definition + */ + basegfx::B3DVector maLightNormal; + double mfShadowSlant; + basegfx::B3DRange maScene3DRange; + + /// the primitiveSequence for on-demand created shadow primitives (see mbShadow3DChecked) + Primitive2DContainer maShadowPrimitives; + + /// #i96669# add simple range buffering for this primitive + basegfx::B2DRange maB2DRange; + + /** flag if given 3D geometry is already checked for shadow definitions and 2d shadows + are created in maShadowPrimitives + */ + bool mbShadow3DChecked : 1; + + /// private helpers + bool impGetShadow3D() const; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + Embedded3DPrimitive2D( + const primitive3d::Primitive3DContainer& rxChildren3D, + const basegfx::B2DHomMatrix& rObjectTransformation, + const geometry::ViewInformation3D& rViewInformation3D, + const basegfx::B3DVector& rLightNormal, + double fShadowSlant, + const basegfx::B3DRange& rScene3DRange); + + /// data read access + const primitive3d::Primitive3DContainer& getChildren3D() const { return mxChildren3D; } + const basegfx::B2DHomMatrix& getObjectTransformation() const { return maObjectTransformation; } + const geometry::ViewInformation3D& getViewInformation3D() const { return maViewInformation3D; } + const basegfx::B3DVector& getLightNormal() const { return maLightNormal; } + double getShadowSlant() const { return mfShadowSlant; } + const basegfx::B3DRange& getScene3DRange() const { return maScene3DRange; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/epsprimitive2d.hxx b/include/drawinglayer/primitive2d/epsprimitive2d.hxx new file mode 100644 index 000000000..7aa72b6ce --- /dev/null +++ b/include/drawinglayer/primitive2d/epsprimitive2d.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ + /** EpsPrimitive2D class */ + class EpsPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// the geometry definition + basegfx::B2DHomMatrix maEpsTransform; + + /// the Eps content definition + GfxLink maGfxLink; + + /// the replacement content definition + GDIMetaFile maMetaFile; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + EpsPrimitive2D( + const basegfx::B2DHomMatrix& rEpsTransform, + const GfxLink& rGfxLink, + const GDIMetaFile& rMetaFile); + + /// data read access + const basegfx::B2DHomMatrix& getEpsTransform() const { return maEpsTransform; } + const GfxLink& getGfxLink() const { return maGfxLink; } + const GDIMetaFile& getMetaFile() const { return maMetaFile; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get B2Drange + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/fillgradientprimitive2d.hxx b/include/drawinglayer/primitive2d/fillgradientprimitive2d.hxx new file mode 100644 index 000000000..9fe2fbcbc --- /dev/null +++ b/include/drawinglayer/primitive2d/fillgradientprimitive2d.hxx @@ -0,0 +1,114 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +// predefines + +namespace basegfx { class B2DPolygon; } +namespace drawinglayer::texture { struct B2DHomMatrixAndBColor; } + + +// FillGradientPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** FillGradientPrimitive2D class + + This class defines a gradient filling for a rectangular area. The + Range is defined by the Transformation, the gradient by the FillGradientAttribute. + + The decomposition will deliver the decomposed gradient, e.g. for an ellipse + gradient the various ellipses in various color steps will be created. + + I have added functionality to create both versions of filled decompositions: + Those who overlap and non-overlapping ones. The overlapping version is the + default one since it works with and without AntiAliasing. The non-overlapping + version is used in the MetafilePrimitive2D decomposition when the old XOR + paint was recorded. + */ + class DRAWINGLAYER_DLLPUBLIC FillGradientPrimitive2D : public BufferedDecompositionPrimitive2D + { + private: + /// the geometrically visible area + basegfx::B2DRange maOutputRange; + + /// the area the gradient definition is based on + /// in the simplest case identical to OutputRange + basegfx::B2DRange maDefinitionRange; + + /// the gradient definition + attribute::FillGradientAttribute maFillGradient; + + /// local helpers + void generateMatricesAndColors( + std::vector< drawinglayer::texture::B2DHomMatrixAndBColor >& rEntries, + basegfx::BColor& rOuterColor) const; + void createOverlappingFill( + Primitive2DContainer& rContainer, + const std::vector< drawinglayer::texture::B2DHomMatrixAndBColor >& rEntries, + const basegfx::BColor& rOuterColor, + const basegfx::B2DPolygon& rUnitPolygon) const; + void createNonOverlappingFill( + Primitive2DContainer& rContainer, + const std::vector< drawinglayer::texture::B2DHomMatrixAndBColor >& rEntries, + const basegfx::BColor& rOuterColor, + const basegfx::B2DPolygon& rUnitPolygon) const; + + protected: + /// local helper + void createFill(Primitive2DContainer& rContainer, bool bOverlapping) const; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructors. The one without definition range will use output range as definition range + FillGradientPrimitive2D( + const basegfx::B2DRange& rOutputRange, + const attribute::FillGradientAttribute& rFillGradient); + FillGradientPrimitive2D( + const basegfx::B2DRange& rOutputRange, + const basegfx::B2DRange& rDefinitionRange, + const attribute::FillGradientAttribute& rFillGradient); + + /// data read access + const basegfx::B2DRange& getOutputRange() const { return maOutputRange; } + const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } + const attribute::FillGradientAttribute& getFillGradient() const { return maFillGradient; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/fillgraphicprimitive2d.hxx b/include/drawinglayer/primitive2d/fillgraphicprimitive2d.hxx new file mode 100644 index 000000000..51d49df30 --- /dev/null +++ b/include/drawinglayer/primitive2d/fillgraphicprimitive2d.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + + +// FillbitmapPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** FillGraphicPrimitive2D class + + This class defines a bitmap filling for a rectangular area. The + Range is defined by the Transformation, the fill by the FillGraphicAttribute. + There, the fill consists of a Bitmap (not transparent) defining the fill data + and a Point/Vector pair defining the relative position/size [0.0 .. 1.0] + inside the area where the bitmap is positioned. A flag defines then if this + is tiled or not. + + Renderers should handle this primitive; it has a geometrically correct + decomposition, but on pixel outputs the areas where the tiled pieces are + aligned tend to show up (one overlapping or empty pixel) + */ + class DRAWINGLAYER_DLLPUBLIC FillGraphicPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// the geometric definition + basegfx::B2DHomMatrix maTransformation; + + /// the fill attributes + attribute::FillGraphicAttribute maFillGraphic; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + FillGraphicPrimitive2D( + const basegfx::B2DHomMatrix& rTransformation, + const attribute::FillGraphicAttribute& rFillGraphic); + + /// data read access + const basegfx::B2DHomMatrix& getTransformation() const { return maTransformation; } + const attribute::FillGraphicAttribute& getFillGraphic() const { return maFillGraphic; } + + /// compare operator + virtual bool operator==( const BasePrimitive2D& rPrimitive ) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/fillhatchprimitive2d.hxx b/include/drawinglayer/primitive2d/fillhatchprimitive2d.hxx new file mode 100644 index 000000000..03bc12139 --- /dev/null +++ b/include/drawinglayer/primitive2d/fillhatchprimitive2d.hxx @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + + +// FillHatchPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** FillHatchPrimitive2D class + + This class defines a hatch filling for a rectangular area. The + Range is defined by the Transformation, the hatch by the FillHatchAttribute. + If the background is to be filled, a flag in FillHatchAttribute is set and + the BColor defines the background color. + + #i120230# This primitive is now evtl. metric dependent due to the value + MinimalDiscreteDistance in the FillHatchAttribute if the value is not zero. + This is used for a more appealing, VCL-like visualisation by not letting the + distances get too small between lines. + + The decomposition will deliver the hatch lines. + */ + class FillHatchPrimitive2D final : public DiscreteMetricDependentPrimitive2D + { + private: + /// the geometrically visible area + basegfx::B2DRange maOutputRange; + + /// the area the gradient definition is based on + /// in the simplest case identical to OutputRange + basegfx::B2DRange maDefinitionRange; + + /// the hatch definition + attribute::FillHatchAttribute maFillHatch; + + /// hatch background color (if used) + basegfx::BColor maBColor; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructors. The one without definition range will use output range as definition range + FillHatchPrimitive2D( + const basegfx::B2DRange& rOutputRange, + const basegfx::BColor& rBColor, + const attribute::FillHatchAttribute& rFillHatch); + FillHatchPrimitive2D( + const basegfx::B2DRange& rOutputRange, + const basegfx::B2DRange& rDefinitionRange, + const basegfx::BColor& rBColor, + const attribute::FillHatchAttribute& rFillHatch); + + /// data read access + const basegfx::B2DRange& getOutputRange() const { return maOutputRange; } + const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } + const attribute::FillHatchAttribute& getFillHatch() const { return maFillHatch; } + const basegfx::BColor& getBColor() const { return maBColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/glowprimitive2d.hxx b/include/drawinglayer/primitive2d/glowprimitive2d.hxx new file mode 100644 index 000000000..7dd65e725 --- /dev/null +++ b/include/drawinglayer/primitive2d/glowprimitive2d.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace drawinglayer::primitive2d +{ +class DRAWINGLAYER_DLLPUBLIC GlowPrimitive2D final : public GroupPrimitive2D +{ +private: + /// the Glow color to which all geometry is to be forced; includes alpha + Color maGlowColor; + + /// the Glow size, in logical units (100ths of mm) + double mfGlowRadius; + +public: + /// constructor + GlowPrimitive2D(const Color& rGlowColor, double fRadius, Primitive2DContainer&& rChildren); + + /// data read access + const Color& getGlowColor() const { return maGlowColor; } + double getGlowRadius() const { return mfGlowRadius; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/graphicprimitive2d.hxx b/include/drawinglayer/primitive2d/graphicprimitive2d.hxx new file mode 100644 index 000000000..9bce4b8c0 --- /dev/null +++ b/include/drawinglayer/primitive2d/graphicprimitive2d.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** GraphicPrimitive2D class + + Primitive to hold graphics defined by GraphicObject and GraphicAttr + combination. This includes MetaFiles and diverse pixel-oriented graphic + formats. It even includes animated GIFs, Croppings and other changes + defined in GraphicAttr. + + This makes the decomposition contain a wide variety of possibilities, + too. From a simple BitmapPrimitive over AnimatedSwitchPrimitive2D, + MetafilePrimitive2D (with and without embedding in a masking when e.g. + the Metafile is bigger than the geometry) and embeddings in + TransformPrimitive2D and MaskPrimitive2D for croppings. + + The primitive geometry area is defined by Transform. + */ +class DRAWINGLAYER_DLLPUBLIC GraphicPrimitive2D final : public BufferedDecompositionPrimitive2D +{ +private: + /// the geometric definition + basegfx::B2DHomMatrix maTransform; + + /// the GraphicObject with all its content possibilities + GraphicObject maGraphicObject; + + /// The GraphicAttr with all its modification possibilities + GraphicAttr maGraphicAttr; + + /// local decomposition + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor(s) + GraphicPrimitive2D(const basegfx::B2DHomMatrix& rTransform, const GraphicObject& rGraphicObject, + const GraphicAttr& rGraphicAttr); + GraphicPrimitive2D(const basegfx::B2DHomMatrix& rTransform, + const GraphicObject& rGraphicObject); + + /// data read access + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + const GraphicObject& getGraphicObject() const { return maGraphicObject; } + const GraphicAttr& getGraphicAttr() const { return maGraphicAttr; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/gridprimitive2d.hxx b/include/drawinglayer/primitive2d/gridprimitive2d.hxx new file mode 100644 index 000000000..3c2bf595a --- /dev/null +++ b/include/drawinglayer/primitive2d/gridprimitive2d.hxx @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + + +// GridPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** GridPrimitive2D class + + This primitive is specialized to Grid visualisation. The graphic definition + (Transform) contains the whole grid area, but will of course be combined + with the visible area (Viewport) when decomposed. Also a resolution-dependent + point reduction is used to not create too much grid visualisation data. This + makes this primitive highly view-dependent and it dynamically buffers + the last decomposition dependent from the Viewport used. + */ + class DRAWINGLAYER_DLLPUBLIC GridPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// The geometry definition for the grid area + basegfx::B2DHomMatrix maTransform; + + /// grid layout definitions + double mfWidth; + double mfHeight; + double mfSmallestViewDistance; + double mfSmallestSubdivisionViewDistance; + sal_uInt32 mnSubdivisionsX; + sal_uInt32 mnSubdivisionsY; + + /// Grid color for single-pixel grid points + basegfx::BColor maBColor; + + /// The Bitmap (with transparence) for grid cross points + BitmapEx maCrossMarker; + + /** the last used object to view transformtion and the last Viewport, + used from getDecomposition for decide buffering + */ + basegfx::B2DHomMatrix maLastObjectToViewTransformation; + basegfx::B2DRange maLastViewport; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + GridPrimitive2D( + const basegfx::B2DHomMatrix& rTransform, + double fWidth, + double fHeight, + double fSmallestViewDistance, + double fSmallestSubdivisionViewDistance, + sal_uInt32 nSubdivisionsX, + sal_uInt32 nSubdivisionsY, + const basegfx::BColor& rBColor, + const BitmapEx& rCrossMarker); + + /// data read access + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + double getWidth() const { return mfWidth; } + double getHeight() const { return mfHeight; } + double getSmallestViewDistance() const { return mfSmallestViewDistance; } + double getSmallestSubdivisionViewDistance() const { return mfSmallestSubdivisionViewDistance; } + sal_uInt32 getSubdivisionsX() const { return mnSubdivisionsX; } + sal_uInt32 getSubdivisionsY() const { return mnSubdivisionsY; } + const basegfx::BColor& getBColor() const { return maBColor; } + const BitmapEx& getCrossMarker() const { return maCrossMarker; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get 2d range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/groupprimitive2d.hxx b/include/drawinglayer/primitive2d/groupprimitive2d.hxx new file mode 100644 index 000000000..b34bef834 --- /dev/null +++ b/include/drawinglayer/primitive2d/groupprimitive2d.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +// GroupPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** GroupPrimitive2D class + + Baseclass for all grouping 2D primitives + + The grouping primitive in its basic form is capable of holding + a child primitive content and returns it on decomposition on default. + It is used for two main purposes, but more may apply: + + - to transport extended information, e.g. for text classification, + see e.g. TextHierarchy*Primitive2D implementations. Since they + decompose to their child content, renderers not aware/interested + in that extra information will just ignore these primitives + + - to encapsulate common geometry, e.g. the ShadowPrimitive2D implements + applying a generic shadow to a child sequence by adding the needed + offset and color stuff in the decomposition + + In most cases the decomposition is straightforward, so by default + this primitive will not buffer the result and is not derived from + BufferedDecompositionPrimitive2D, but from BasePrimitive2D. + + A renderer has to take GroupPrimitive2D derivations into account which + are used to hold a state. + + Current Basic 2D StatePrimitives are: + + - TransparencePrimitive2D (objects with freely defined transparence) + - InvertPrimitive2D (for XOR) + - MaskPrimitive2D (for masking) + - ModifiedColorPrimitive2D (for a stack of color modifications) + - TransformPrimitive2D (for a transformation stack) + */ + class DRAWINGLAYER_DLLPUBLIC GroupPrimitive2D : public BasePrimitive2D + { + private: + /// the children. Declared private since this shall never be changed at all after construction + Primitive2DContainer maChildren; + + public: + /// constructor + explicit GroupPrimitive2D(Primitive2DContainer&& aChildren); + + /// data read access + const Primitive2DContainer& getChildren() const { return maChildren; } + + void getChildren(Primitive2DDecompositionVisitor& rVisitor) const { rVisitor.visit(maChildren); } + + /// compare operator + virtual bool operator==( const BasePrimitive2D& rPrimitive ) const override; + + /// local decomposition. Implementation will just return children + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + // XAccounting + virtual sal_Int64 estimateUsage() override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/helplineprimitive2d.hxx b/include/drawinglayer/primitive2d/helplineprimitive2d.hxx new file mode 100644 index 000000000..075715b9b --- /dev/null +++ b/include/drawinglayer/primitive2d/helplineprimitive2d.hxx @@ -0,0 +1,106 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + + +// HelplinePrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** HelplineStyle2D definition + + The available styles of Helplines + */ + enum class HelplineStyle2D + { + Point, + Line + }; + + /** HelplinePrimitive2D class + + This primitive provides a view-dependent helpline definition. The Helpline + is defined by a line equation (Point and vector) and a style. When the style + is a line, dependent from Viewport the visible part of that Helpline is + constructed. For Point, a cross is constructed. This primitive is highly + view-dependent. + + The visualisation uses the two given colors to create a dashed line with + the given dash length. + */ + class DRAWINGLAYER_DLLPUBLIC HelplinePrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// Helpline geometry definition + basegfx::B2DPoint maPosition; + basegfx::B2DVector maDirection; + HelplineStyle2D meStyle; + + /// Helpline style definition + basegfx::BColor maRGBColA; + basegfx::BColor maRGBColB; + double mfDiscreteDashLength; + + /** the last used object to view transformtion and the last Viewport, + used from getDecomposition for decide buffering + */ + basegfx::B2DHomMatrix maLastObjectToViewTransformation; + basegfx::B2DRange maLastViewport; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + HelplinePrimitive2D( + const basegfx::B2DPoint& rPosition, + const basegfx::B2DVector& rDirection, + HelplineStyle2D eStyle, + const basegfx::BColor& rRGBColA, + const basegfx::BColor& aRGBColB, + double fDiscreteDashLength); + + /// data read access + const basegfx::B2DPoint& getPosition() const { return maPosition; } + const basegfx::B2DVector& getDirection() const { return maDirection; } + HelplineStyle2D getStyle() const { return meStyle; } + const basegfx::BColor& getRGBColA() const { return maRGBColA; } + const basegfx::BColor& getRGBColB() const { return maRGBColB; } + double getDiscreteDashLength() const { return mfDiscreteDashLength; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx b/include/drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx new file mode 100644 index 000000000..3a13d2ab4 --- /dev/null +++ b/include/drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace drawinglayer::primitive2d +{ + // This primitive is used to represent geometry for non-visible objects, + // e.g. a PresObj's outline. To still be able to use primitives for HitTest + // functionality, the 2d decompositions will produce an as much as possible + // simplified line geometry encapsulated in this primitive when there is no + // line geometry. In a further enhanced version this may change to 'if neither + // filled nor lines' creation criteria. The whole primitive decomposes to nothing, + // so no one not knowing it will be influenced. Only helper processors for hit test + // (and maybe BoundRect extractors) will use it and its children subcontent. + class DRAWINGLAYER_DLLPUBLIC HiddenGeometryPrimitive2D final : public GroupPrimitive2D + { + public: + explicit HiddenGeometryPrimitive2D(Primitive2DContainer&& aChildren); + + // despite returning an empty decomposition since it's no visualisation data, + // range calculation is intended to use hidden geometry, so + // the local implementation will return the children's range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// local decomposition. Implementation will return empty Primitive2DSequence + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + + // provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/invertprimitive2d.hxx b/include/drawinglayer/primitive2d/invertprimitive2d.hxx new file mode 100644 index 000000000..ccafd5156 --- /dev/null +++ b/include/drawinglayer/primitive2d/invertprimitive2d.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace drawinglayer::primitive2d +{ + /** InvertPrimitive2D class + + This is a helper class which encapsulates geometry that should be + painted XOR, e.g. old cursor visualisations. It decomposes to + its content, so when not supporting it, the contained geometry + will be visualized normally. + Unfortunately this is still needed, but hard to support on various + systems. XOR painting needs read access to the target, so modern + graphic systems tend to not support it anymore. + */ + class DRAWINGLAYER_DLLPUBLIC InvertPrimitive2D final : public GroupPrimitive2D + { + public: + /// constructor + explicit InvertPrimitive2D(Primitive2DContainer&& aChildren); + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/markerarrayprimitive2d.hxx b/include/drawinglayer/primitive2d/markerarrayprimitive2d.hxx new file mode 100644 index 000000000..40f6236cf --- /dev/null +++ b/include/drawinglayer/primitive2d/markerarrayprimitive2d.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +// MarkerArrayPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** MarkerArrayPrimitive2D class + + This primitive defines an array of markers. Their size is defined + in pixels and independent from the view transformation which makes + this primitive highly view-dependent. It is also transformation + invariant, so that the bitmap is always visualized unscaled and + unrotated. + It is used e.g. for grid position visualisation. The given Bitmap + (with transparence) is defined to be visible centered at each of the given + positions. + It decomposes to the needed number of BitmapPrimitive2D's, so it would + be efficient to handle it directly in a renderer. + */ + class DRAWINGLAYER_DLLPUBLIC MarkerArrayPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// the positions for the marker + std::vector< basegfx::B2DPoint > maPositions; + + /// the marker definition to visualize + BitmapEx maMarker; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + MarkerArrayPrimitive2D( + std::vector< basegfx::B2DPoint >&& rPositions, + const BitmapEx& rMarker); + + /// data read access + const std::vector< basegfx::B2DPoint >& getPositions() const { return maPositions; } + const BitmapEx& getMarker() const { return maMarker; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/maskprimitive2d.hxx b/include/drawinglayer/primitive2d/maskprimitive2d.hxx new file mode 100644 index 000000000..e2d8c0e65 --- /dev/null +++ b/include/drawinglayer/primitive2d/maskprimitive2d.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** MaskPrimitive2D class + + This is the central masking primitive. It's a grouping + primitive and contains a tools::PolyPolygon which defines the visible + area. Only visualisation parts of the Child primitive sequence + inside of the mask tools::PolyPolygon is defined to be visible. + + This primitive should be handled by a renderer. If it is not handled, + it decomposes to its Child content, and thus the visualisation would + contain no clips. + + The geometry range of this primitive is completely defined by the Mask + tools::PolyPolygon since by definition nothing outside of the mask is visible. + */ + class DRAWINGLAYER_DLLPUBLIC MaskPrimitive2D final : public GroupPrimitive2D + { + private: + /// the mask PolyPolygon + basegfx::B2DPolyPolygon maMask; + + public: + /// constructor + MaskPrimitive2D( + const basegfx::B2DPolyPolygon& rMask, + Primitive2DContainer&& aChildren); + + /// data read access + const basegfx::B2DPolyPolygon& getMask() const { return maMask; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/mediaprimitive2d.hxx b/include/drawinglayer/primitive2d/mediaprimitive2d.hxx new file mode 100644 index 000000000..084b6728a --- /dev/null +++ b/include/drawinglayer/primitive2d/mediaprimitive2d.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** MediaPrimitive2D class + + This is a unified primitive for Media visualisation, e.g. animations + or sounds. It's geometry is defined by Transform. For convenience, + it also contains a discrete border size (aka Pixels) which will be added + if used. This makes it a view-dependent primitive. It also gets a filled + background and the decomposition will try to create a graphic representation + if the content (defined by the URL), e.g. a still frame for animated stuff. + */ + class DRAWINGLAYER_DLLPUBLIC MediaPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// the geometry definition + basegfx::B2DHomMatrix maTransform; + + /// the content definition + OUString maURL; + + /// style: background color + basegfx::BColor maBackgroundColor; + + /// discrete border (in 'pixels') + sal_uInt32 mnDiscreteBorder; + + const Graphic maSnapshot; + + /// local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + MediaPrimitive2D( + const basegfx::B2DHomMatrix& rTransform, + const OUString& rURL, + const basegfx::BColor& rBackgroundColor, + sal_uInt32 nDiscreteBorder, + const Graphic &rSnapshot); + + /// data read access + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + const basegfx::BColor& getBackgroundColor() const { return maBackgroundColor; } + sal_uInt32 getDiscreteBorder() const { return mnDiscreteBorder; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/metafileprimitive2d.hxx b/include/drawinglayer/primitive2d/metafileprimitive2d.hxx new file mode 100644 index 000000000..c6caded90 --- /dev/null +++ b/include/drawinglayer/primitive2d/metafileprimitive2d.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + + +// MetafilePrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** MetafilePrimitive2D class + + This is the MetaFile representing primitive. It's geometry is defined + by MetaFileTransform. The content (defined by MetaFile) will be scaled + to the geometric definition by using PrefMapMode and PrefSize of the + Metafile. + + It has shown that this not always guarantees that all Metafile content + is inside the geometric definition, but this primitive defines that this + is the case to allow a getB2DRange implementation. If it cannot be + guaranteed that the Metafile is inside the geometric definition, it should + be embedded to a MaskPrimitive2D. + + This primitive has no decomposition yet, so when not supported by a renderer, + it will not be visualized. + + In the future, a decomposition implementation would be appreciated and would + have many advantages; Metafile would no longer have to be rendered by + sub-systems and a standard way for converting Metafiles would exist. + */ + class DRAWINGLAYER_DLLPUBLIC MetafilePrimitive2D final : public BufferedDecompositionPrimitive2D, public MetafileAccessor + { + private: + /// the geometry definition + basegfx::B2DHomMatrix maMetaFileTransform; + + /// the content definition + GDIMetaFile maMetaFile; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + public: + /// constructor + MetafilePrimitive2D( + const basegfx::B2DHomMatrix& rMetaFileTransform, + const GDIMetaFile& rMetaFile); + + /// data read access + const basegfx::B2DHomMatrix& getTransform() const { return maMetaFileTransform; } + const GDIMetaFile& getMetaFile() const { return maMetaFile; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// from MetafileAccessor + virtual void accessMetafile(GDIMetaFile& rTargetMetafile) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/modifiedcolorprimitive2d.hxx b/include/drawinglayer/primitive2d/modifiedcolorprimitive2d.hxx new file mode 100644 index 000000000..167ed054f --- /dev/null +++ b/include/drawinglayer/primitive2d/modifiedcolorprimitive2d.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** ModifiedColorPrimitive2D class + + This primitive is a grouping primitive and allows to define + how the colors of its child content shall be modified for + visualisation. This can be (and is) used e.g. for generic shadow + visualisation by forcing all color usages of the contained + sub-content to the shadow color. + + For the possibilities of color modifications, please refer + to the basegfx::BColorModifier definitions in basegfx. For + processing there is tooling in basegfx to build a stack of + BColorModifierSharedPtrs to always be able to process the correct + colors. + + If a renderer does not handle this primitive, the content will + be visualized unchanged. + */ + class DRAWINGLAYER_DLLPUBLIC ModifiedColorPrimitive2D final : public GroupPrimitive2D + { + private: + /// The ColorModifier to use + basegfx::BColorModifierSharedPtr maColorModifier; + + public: + /// constructor + ModifiedColorPrimitive2D( + Primitive2DContainer&& aChildren, + const basegfx::BColorModifierSharedPtr& rColorModifier); + + /// data read access + const basegfx::BColorModifierSharedPtr& getColorModifier() const { return maColorModifier; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/objectinfoprimitive2d.hxx b/include/drawinglayer/primitive2d/objectinfoprimitive2d.hxx new file mode 100644 index 000000000..9df931a96 --- /dev/null +++ b/include/drawinglayer/primitive2d/objectinfoprimitive2d.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace drawinglayer::primitive2d +{ + /** ObjectInfoPrimitive2D class + + Info hierarchy helper class to hold contents like Name, Title and + Description which are valid for the child content, e.g. created for + primitives based on DrawingLayer objects or SVG parts. It decomposes + to its content, so all direct renderers may ignore it. May e.g. + be used when re-creating graphical content from a sequence of primitives + */ + class DRAWINGLAYER_DLLPUBLIC ObjectInfoPrimitive2D final : public GroupPrimitive2D + { + private: + OUString maName; + OUString maTitle; + OUString maDesc; + + public: + /// constructor + ObjectInfoPrimitive2D( + Primitive2DContainer&& aChildren, + const OUString& rName, + const OUString& rTitle, + const OUString& rDesc); + + /// data read access + const OUString& getName() const { return maName; } + const OUString& getTitle() const { return maTitle; } + const OUString& getDesc() const { return maDesc; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/pagehierarchyprimitive2d.hxx b/include/drawinglayer/primitive2d/pagehierarchyprimitive2d.hxx new file mode 100644 index 000000000..8b6a08aa7 --- /dev/null +++ b/include/drawinglayer/primitive2d/pagehierarchyprimitive2d.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace drawinglayer::primitive2d +{ + /** PageHierarchyPrimitive2D class + + This primitive encapsulates text lines. + */ + class DRAWINGLAYER_DLLPUBLIC PageHierarchyPrimitive2D final : public GroupPrimitive2D + { + private: + public: + /// constructor + explicit PageHierarchyPrimitive2D(Primitive2DContainer&& aChildren); + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/pagepreviewprimitive2d.hxx b/include/drawinglayer/primitive2d/pagepreviewprimitive2d.hxx new file mode 100644 index 000000000..6ee147557 --- /dev/null +++ b/include/drawinglayer/primitive2d/pagepreviewprimitive2d.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace com::sun::star::drawing { class XDrawPage; } + + +namespace drawinglayer::primitive2d +{ + /** PagePreviewPrimitive2D class + + This primitive is needed to have the correct XDrawPage as ViewInformation for decomposing + the page contents (given as PageContent here) if these contain e.g. + view-dependent (in this case XDrawPage-dependent) text fields like PageNumber. If You want + those primitives to be visualized correctly, Your renderer needs to locally correct its + ViewInformation2D to reference the new XDrawPage. + */ + class DRAWINGLAYER_DLLPUBLIC PagePreviewPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /** the XDrawPage visualized by this primitive. When we go forward with primitives + this will not only be used by the renderers to provide the correct decompose + graphic attribute context, but also to completely create the page's sub-content. + */ + const css::uno::Reference< css::drawing::XDrawPage > mxDrawPage; + + /// the PageContent + Primitive2DContainer maPageContent; + + /// the own geometry + basegfx::B2DHomMatrix maTransform; + + /// content width and height + double mfContentWidth; + double mfContentHeight; + + /// local decomposition. Implementation will just return children + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + PagePreviewPrimitive2D( + const css::uno::Reference< css::drawing::XDrawPage >& rxDrawPage, + const basegfx::B2DHomMatrix& rTransform, + double fContentWidth, + double fContentHeight, + Primitive2DContainer&& rPageContent); + + /// data read access + const css::uno::Reference< css::drawing::XDrawPage >& getXDrawPage() const { return mxDrawPage; } + const Primitive2DContainer& getPageContent() const { return maPageContent; } + const basegfx::B2DHomMatrix& getTransform() const { return maTransform; } + double getContentWidth() const { return mfContentWidth; } + double getContentHeight() const { return mfContentHeight; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// own getB2DRange + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/patternfillprimitive2d.hxx b/include/drawinglayer/primitive2d/patternfillprimitive2d.hxx new file mode 100644 index 000000000..9da0e44e5 --- /dev/null +++ b/include/drawinglayer/primitive2d/patternfillprimitive2d.hxx @@ -0,0 +1,104 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** PatternFillPrimitive2D class + + This primitive allows filling a given tools::PolyPolygon with a pattern + defined by a sequence of primitives which are mapped to the unit range. + The pattern is defined using a reference range which defines a rectangular + area relative to the tools::PolyPolygon (in unit coordinates) which is virtually + infinitely repeated. + */ + class DRAWINGLAYER_DLLPUBLIC PatternFillPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + const basegfx::B2DPolyPolygon maMask; + const Primitive2DContainer maChildren; + const basegfx::B2DRange maReferenceRange; + + /// values holding the discrete buffer size + sal_uInt32 mnDiscreteWidth; + sal_uInt32 mnDiscreteHeight; + + /// helper that is capable to calculate the needed discrete buffer size for + /// eventually buffered content + void calculateNeededDiscreteBufferSize( + sal_uInt32& rWidth, + sal_uInt32& rHeight, + const geometry::ViewInformation2D& rViewInformation) const; + + /// helper which creates the content - checks if clipping is needed and eventually + /// creates buffered content to speed up rendering + Primitive2DContainer createContent(const geometry::ViewInformation2D& rViewInformation) const; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + PatternFillPrimitive2D( + const basegfx::B2DPolyPolygon& rMask, + Primitive2DContainer&& rChildren, + const basegfx::B2DRange& rReferenceRange); + + /// data read access + const basegfx::B2DPolyPolygon& getMask() const { return maMask; } + const Primitive2DContainer& getChildren() const { return maChildren; } + const basegfx::B2DRange& getReferenceRange() const { return maReferenceRange; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// overload to react on evtl. buffered content + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + // XAccounting + virtual sal_Int64 estimateUsage() override; + + /// helper which creates the content - checks if clipping is needed and eventually + /// creates buffered content to speed up rendering + BitmapEx createTileImage(sal_uInt32 nWidth, sal_uInt32 nHeight) const; + + /// helper that is capable to calculate the needed discrete buffer size for + /// eventually buffered content + void getTileSize( + sal_uInt32& rWidth, + sal_uInt32& rHeight, + const geometry::ViewInformation2D& rViewInformation) const; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/pointarrayprimitive2d.hxx b/include/drawinglayer/primitive2d/pointarrayprimitive2d.hxx new file mode 100644 index 000000000..a2eb5f611 --- /dev/null +++ b/include/drawinglayer/primitive2d/pointarrayprimitive2d.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + + +// PointArrayPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** PointArrayPrimitive2D class + + This primitive defines single,discrete 'pixels' for the given + positions in the given color. This makes it view-dependent since + the logic size of a 'pixel' depends on the view transformation. + + This is one of the non-decomposable primitives, so a renderer + should process it (Currently it is only used for grid visualisation, + but this may change). + */ + class PointArrayPrimitive2D final : public BasePrimitive2D + { + private: + /// the array of positions + std::vector< basegfx::B2DPoint > maPositions; + + /// the color to use + basegfx::BColor maRGBColor; + + /// #i96669# add simple range buffering for this primitive + basegfx::B2DRange maB2DRange; + + public: + /// constructor + PointArrayPrimitive2D( + std::vector< basegfx::B2DPoint >&& rPositions, + const basegfx::BColor& rRGBColor); + + /// data read access + const std::vector< basegfx::B2DPoint >& getPositions() const { return maPositions; } + const basegfx::BColor& getRGBColor() const { return maRGBColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/primitivetools2d.hxx b/include/drawinglayer/primitive2d/primitivetools2d.hxx new file mode 100644 index 000000000..97e4f770e --- /dev/null +++ b/include/drawinglayer/primitive2d/primitivetools2d.hxx @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** DiscreteMetricDependentPrimitive2D class + + tooling class for BufferedDecompositionPrimitive2D based classes which are view-dependent + regarding the size of a discrete unit. The implementation of get2DDecomposition + guards the buffered local decomposition and ensures that a create2DDecomposition + implementation may use an up-to-date DiscreteUnit accessible using getDiscreteUnit() + */ + class DRAWINGLAYER_DLLPUBLIC DiscreteMetricDependentPrimitive2D : public BufferedDecompositionPrimitive2D + { + private: + /** the last used fDiscreteUnit definitions for decomposition. Since this + is checked and updated from get2DDecomposition() it will be current and + usable in create2DDecomposition() + */ + double mfDiscreteUnit; + + public: + /// constructor + DiscreteMetricDependentPrimitive2D() + : mfDiscreteUnit(0.0) + { + } + + /// data read access + double getDiscreteUnit() const { return mfDiscreteUnit; } + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; + + /** ViewportDependentPrimitive2D class + + tooling class for BufferedDecompositionPrimitive2D based classes which are view-dependent + regarding the viewport. The implementation of get2DDecomposition + guards the buffered local decomposition and ensures that a create2DDecomposition + implementation may use an up-to-date Viewport accessible using getViewport() + */ + class DRAWINGLAYER_DLLPUBLIC ViewportDependentPrimitive2D : public BufferedDecompositionPrimitive2D + { + private: + /** the last used Viewport definition for decomposition. Since this + is checked and updated from get2DDecomposition() it will be current and + usable in create2DDecomposition() + */ + basegfx::B2DRange maViewport; + + public: + /// constructor + ViewportDependentPrimitive2D() + { + } + + /// data read access + const basegfx::B2DRange& getViewport() const { return maViewport; } + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; + + /** ViewTransformationDependentPrimitive2D class + + tooling class for BufferedDecompositionPrimitive2D based classes which are view-dependent + regarding the complete Viewtransformation. The implementation of get2DDecomposition + guards the buffered local decomposition and ensures that a create2DDecomposition + implementation may use an up-to-date ViewTransformation accessible using getViewTransformation() + */ + class DRAWINGLAYER_DLLPUBLIC ViewTransformationDependentPrimitive2D : public BufferedDecompositionPrimitive2D + { + private: + /** the last used ViewTransformation definition for decomposition. Since this + is checked and updated from get2DDecomposition() it will be current and + usable in create2DDecomposition() + */ + basegfx::B2DHomMatrix maViewTransformation; + + public: + /// constructor + ViewTransformationDependentPrimitive2D() + { + } + + /// data read access + const basegfx::B2DHomMatrix& getViewTransformation() const { return maViewTransformation; } + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; + + /** ObjectAndViewTransformationDependentPrimitive2D class + + tooling class for BufferedDecompositionPrimitive2D based classes which are view-dependent + and Object-Transform dependent. The implementation of get2DDecomposition + guards the buffered local decomposition and ensures that a create2DDecomposition + implementation may use an up-to-date ViewTransformation accessible using getViewTransformation() + and an object transformation via getObjectTransformation() + */ + class DRAWINGLAYER_DLLPUBLIC ObjectAndViewTransformationDependentPrimitive2D : public BufferedDecompositionPrimitive2D + { + private: + /** the last used ViewTransformation and the last ObjectTransformation + definition for decomposition. Since this is checked and updated from + get2DDecomposition() it will be current and usable in create2DDecomposition() + */ + basegfx::B2DHomMatrix maViewTransformation; + basegfx::B2DHomMatrix maObjectTransformation; + + public: + /// constructor + ObjectAndViewTransformationDependentPrimitive2D() + { + } + + /// data read access + const basegfx::B2DHomMatrix& getViewTransformation() const { return maViewTransformation; } + const basegfx::B2DHomMatrix& getObjectTransformation() const { return maObjectTransformation; } + + /// Override standard getDecomposition to be view-dependent here + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/sceneprimitive2d.hxx b/include/drawinglayer/primitive2d/sceneprimitive2d.hxx new file mode 100644 index 000000000..3fc027fcb --- /dev/null +++ b/include/drawinglayer/primitive2d/sceneprimitive2d.hxx @@ -0,0 +1,147 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ + /** ScenePrimitive2D class + + This primitive defines a 3D scene as a 2D primitive and is the anchor point + for a 3D visualisation. The decomposition is view-dependent and will try to + re-use already rendered 3D content. + + The rendering is done using the default-3D renderer from basegfx which supports + AntiAliasing. + + The 2D primitive's geometric range is defined completely by the + ObjectTransformation combined with evtl. 2D shadows from the 3D objects. The + shadows of 3D objects are 2D polygons, projected with the 3D transformation. + + This is the class a renderer may process directly when he wants to implement + an own (e.g. system-specific) 3D renderer. + */ + class DRAWINGLAYER_DLLPUBLIC ScenePrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// the 3D geometry definition + primitive3d::Primitive3DContainer mxChildren3D; + + /// 3D scene attribute set + attribute::SdrSceneAttribute maSdrSceneAttribute; + + /// lighting attribute set + attribute::SdrLightingAttribute maSdrLightingAttribute; + + /// object transformation for scene for 2D definition + basegfx::B2DHomMatrix maObjectTransformation; + + /// scene transformation set and object transformation + geometry::ViewInformation3D maViewInformation3D; + + /// the primitiveSequence for on-demand created shadow primitives (see mbShadow3DChecked) + Primitive2DContainer maShadowPrimitives; + + /** flag if given 3D geometry is already checked for shadow definitions and 2d shadows + are created in maShadowPrimitives + */ + bool mbShadow3DChecked : 1; + + /// the last used NewDiscreteSize and NewUnitVisiblePart definitions for decomposition + double mfOldDiscreteSizeX; + double mfOldDiscreteSizeY; + basegfx::B2DRange maOldUnitVisiblePart; + + /** the last created BitmapEx, e.g. for fast HitTest. This does not really need + memory since BitmapEx is internally RefCounted + */ + BitmapEx maOldRenderedBitmap; + + /// private helpers + bool impGetShadow3D() const; + void calculateDiscreteSizes( + const geometry::ViewInformation2D& rViewInformation, + basegfx::B2DRange& rDiscreteRange, + basegfx::B2DRange& rVisibleDiscreteRange, + basegfx::B2DRange& rUnitVisibleRange) const; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// public helpers + /** Geometry extractor. Shadow will be added as in create2DDecomposition, but + the 3D content is not converted to a bitmap visualisation but to projected 2D geometry. This + helper is useful e.g. for Contour extraction or HitTests. + */ + Primitive2DContainer getGeometry2D() const; + Primitive2DContainer getShadow2D() const; + + /** Fast HitTest which uses the last buffered BitmapEx from the last + rendered area if available. The return value describes if the check + could be done with the current information, so do NOT use o_rResult + when it returns false. o_rResult will be changed on return true and + then contains a definitive answer if content of this scene is hit or + not. On return false, it is normally necessary to use the geometric + HitTest (see CutFindProcessor usages). The given HitPoint + has to be in logic coordinates in scene's ObjectCoordinateSystem. + */ + bool tryToCheckLastVisualisationDirectHit(const basegfx::B2DPoint& rLogicHitPoint, bool& o_rResult) const; + + /// constructor + ScenePrimitive2D( + const primitive3d::Primitive3DContainer& rxChildren3D, + const attribute::SdrSceneAttribute& rSdrSceneAttribute, + const attribute::SdrLightingAttribute& rSdrLightingAttribute, + const basegfx::B2DHomMatrix& rObjectTransformation, + const geometry::ViewInformation3D& rViewInformation3D); + + /// data read access + const primitive3d::Primitive3DContainer& getChildren3D() const { return mxChildren3D; } + const attribute::SdrSceneAttribute& getSdrSceneAttribute() const { return maSdrSceneAttribute; } + const attribute::SdrLightingAttribute& getSdrLightingAttribute() const { return maSdrLightingAttribute; } + const basegfx::B2DHomMatrix& getObjectTransformation() const { return maObjectTransformation; } + const geometry::ViewInformation3D& getViewInformation3D() const { return maViewInformation3D; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + + /// get local decomposition. Override since this decomposition is view-dependent + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/sdrdecompositiontools2d.hxx b/include/drawinglayer/primitive2d/sdrdecompositiontools2d.hxx new file mode 100644 index 000000000..408abe952 --- /dev/null +++ b/include/drawinglayer/primitive2d/sdrdecompositiontools2d.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +// predefines + +namespace basegfx { + class B2DPolyPolygon; + class B2DHomMatrix; +} + + +namespace drawinglayer::primitive2d +{ + // helpers to create HitTestPrimitives Line + Primitive2DReference DRAWINGLAYER_DLLPUBLIC createHiddenGeometryPrimitives2D( + const basegfx::B2DHomMatrix& rMatrix); + + Primitive2DReference DRAWINGLAYER_DLLPUBLIC createHiddenGeometryPrimitives2D( + const basegfx::B2DPolyPolygon& rPolygon); + + Primitive2DReference DRAWINGLAYER_DLLPUBLIC createHiddenGeometryPrimitives2D( + bool bFilled, + const basegfx::B2DRange& rRange); + + Primitive2DReference DRAWINGLAYER_DLLPUBLIC createHiddenGeometryPrimitives2D( + bool bFilled, + const basegfx::B2DRange& rRange, + const basegfx::B2DHomMatrix& rMatrix); + + Primitive2DReference DRAWINGLAYER_DLLPUBLIC createHiddenGeometryPrimitives2D( + bool bFilled, + const basegfx::B2DPolyPolygon& rPolygon, + const basegfx::B2DHomMatrix& rMatrix); + +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/shadowprimitive2d.hxx b/include/drawinglayer/primitive2d/shadowprimitive2d.hxx new file mode 100644 index 000000000..7df83a395 --- /dev/null +++ b/include/drawinglayer/primitive2d/shadowprimitive2d.hxx @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** ShadowPrimitive2D class + + This primitive defines a generic shadow geometry construction + for 2D objects. It decomposes to a TransformPrimitive2D embedded + into a ModifiedColorPrimitive2D. + + It's for primitive usage convenience, so that not everyone has + to implement the generic shadow construction by himself. + + The same geometry as sequence of primitives is used as geometry and + as shadow. Since these are RefCounted Uno-Api objects, no extra objects + are needed for the shadow itself; all the local decompositions of the + original geometry can be reused from the renderer for shadow visualisation. + */ + class DRAWINGLAYER_DLLPUBLIC ShadowPrimitive2D final : public GroupPrimitive2D + { + private: + /// the shadow transformation, normally just an offset + basegfx::B2DHomMatrix maShadowTransform; + + /// the shadow color to which all geometry is to be forced + basegfx::BColor maShadowColor; + + /// the blur radius of the shadow + double mfShadowBlur; + + + public: + /// constructor + ShadowPrimitive2D( + const basegfx::B2DHomMatrix& rShadowTransform, + const basegfx::BColor& rShadowColor, + double fShadowBlur, + Primitive2DContainer&& aChildren); + + /// data read access + const basegfx::B2DHomMatrix& getShadowTransform() const { return maShadowTransform; } + const basegfx::BColor& getShadowColor() const { return maShadowColor; } + double getShadowBlur() const { return mfShadowBlur; } + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// create decomposition + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/softedgeprimitive2d.hxx b/include/drawinglayer/primitive2d/softedgeprimitive2d.hxx new file mode 100644 index 000000000..90ada61f7 --- /dev/null +++ b/include/drawinglayer/primitive2d/softedgeprimitive2d.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace drawinglayer::primitive2d +{ +class DRAWINGLAYER_DLLPUBLIC SoftEdgePrimitive2D final : public GroupPrimitive2D +{ +private: + /// Soft edge size, in logical units (100ths of mm) + double mfRadius; + mutable bool mbInMaskGeneration = false; + +public: + SoftEdgePrimitive2D(double fRadius, Primitive2DContainer&& aChildren); + + double getRadius() const { return mfRadius; } + + void setMaskGeneration(bool bVal = true) const { mbInMaskGeneration = bVal; } + + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + virtual void + get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, + const geometry::ViewInformation2D& rViewInformation) const override; + + virtual sal_uInt32 getPrimitive2DID() const override; +}; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/structuretagprimitive2d.hxx b/include/drawinglayer/primitive2d/structuretagprimitive2d.hxx new file mode 100644 index 000000000..40ad422c2 --- /dev/null +++ b/include/drawinglayer/primitive2d/structuretagprimitive2d.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** StructureTagPrimitive2D class + + This class is used to provide simple support for adding grouped + pdf writer structured element information like used in sd from + unomodel.cxx where a ViewObjectContactRedirector is used to add + such information for diverse objects. + This primitive encapsulates these and the VCLPdfRenderer uses it + to apply the needed infos directly to the pdf export in a compatible + way. + If a renderer ignores this, it just decomposes to its child + content. + */ + class DRAWINGLAYER_DLLPUBLIC StructureTagPrimitive2D final : public GroupPrimitive2D + { + private: + /// the PDF structure element this grouping represents + vcl::PDFWriter::StructElement maStructureElement; + + /// flag for background object + bool mbBackground; + /// flag for image (OBJ_GRAF) + bool mbIsImage; + /// anchor structure element (Writer) + sal_Int32 m_nAnchorStructureElementId; + + public: + /// constructor + StructureTagPrimitive2D( + const vcl::PDFWriter::StructElement& rStructureElement, + bool bBackground, + bool bIsImage, + Primitive2DContainer&& aChildren, + sal_Int32 nAnchorStructureElementId = -1); + + /// data read access + const vcl::PDFWriter::StructElement& getStructureElement() const { return maStructureElement; } + bool isBackground() const { return mbBackground; } + bool isImage() const { return mbIsImage; } + bool isTaggedSdrObject() const; + sal_Int32 GetAnchorStructureElementId() const { return m_nAnchorStructureElementId; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/svggradientprimitive2d.hxx b/include/drawinglayer/primitive2d/svggradientprimitive2d.hxx new file mode 100644 index 000000000..66c68fdaf --- /dev/null +++ b/include/drawinglayer/primitive2d/svggradientprimitive2d.hxx @@ -0,0 +1,369 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + + +// SvgGradientEntry class + +namespace drawinglayer::primitive2d +{ + /// a single GradientStop defining a color and opacity at a distance + class SvgGradientEntry + { + private: + double mfOffset; + basegfx::BColor maColor; + double mfOpacity; + + public: + SvgGradientEntry(double fOffset, const basegfx::BColor& rColor, double fOpacity) + : mfOffset(fOffset), + maColor(rColor), + mfOpacity(fOpacity) + { + } + + double getOffset() const { return mfOffset; } + const basegfx::BColor& getColor() const { return maColor; } + double getOpacity() const { return mfOpacity; } + + bool operator==(const SvgGradientEntry& rCompare) const + { + return (getOffset() == rCompare.getOffset() + && getColor() == rCompare.getColor() + && getOpacity() == rCompare.getOpacity()); + } + + bool operator<(const SvgGradientEntry& rCompare) const + { + return getOffset() < rCompare.getOffset(); + } + }; + + typedef ::std::vector< SvgGradientEntry > SvgGradientEntryVector; + + // SvgGradientHelper class + + enum class SpreadMethod + { + Pad, + Reflect, + Repeat + }; + + /* helper for linear and radial gradient, both get derived from this + to share common definitions and functionality + **/ + class SvgGradientHelper + { + private: + /// the extra gradient transform + basegfx::B2DHomMatrix maGradientTransform; + + /// geometric definition, the geometry to be filled + basegfx::B2DPolyPolygon maPolyPolygon; + + /// the gradient definition + SvgGradientEntryVector maGradientEntries; + + // internal helper for case SpreadMethod::Reflect + SvgGradientEntryVector maMirroredGradientEntries; + + /// start and/or center point + basegfx::B2DPoint maStart; + + /// how to spread + SpreadMethod maSpreadMethod; + + bool mbPreconditionsChecked : 1; + bool mbCreatesContent : 1; + bool mbSingleEntry : 1; + bool mbFullyOpaque : 1; + + // true = interpret in unit coordinate system -> object aspect ratio will scale result + // false = interpret in object coordinate system -> object aspect ratio will not scale result + // (related to SVG's gradientUnits (userSpaceOnUse|objectBoundingBox) + bool mbUseUnitCoordinates : 1; + + /// local helpers + const SvgGradientEntryVector& getMirroredGradientEntries() const; + void createMirroredGradientEntries(); + const SvgGradientEntry& FindEntryLessOrEqual(sal_Int32& rInt, const double fFrac) const; + const SvgGradientEntry& FindEntryMore(sal_Int32& rInt,const double fFrac) const; + + protected: + /// local helpers + void createSingleGradientEntryFill(Primitive2DContainer& rContainer) const; + virtual void createAtom( + Primitive2DContainer& rTargetColor, + Primitive2DContainer& rTargetOpacity, + const SvgGradientEntry& rFrom, + const SvgGradientEntry& rTo, + sal_Int32 nOffsetFrom, + sal_Int32 nOffsetTo) const = 0; + void createRun( + Primitive2DContainer& rTargetColor, + Primitive2DContainer& rTargetOpacity, + double fStart, + double fEnd) const; + virtual void checkPreconditions(); + void createResult( + Primitive2DContainer& rContainer, + Primitive2DContainer aTargetColor, + Primitive2DContainer aTargetOpacity, + const basegfx::B2DHomMatrix& rUnitGradientToObject, + bool bInvert = false) const; + bool getCreatesContent() const { return mbCreatesContent; } + bool getSingleEntry() const { return mbSingleEntry; } + void setSingleEntry() { mbSingleEntry = true; } + bool getPreconditionsChecked() const { return mbPreconditionsChecked; } + bool getFullyOpaque() const { return mbFullyOpaque; } + + public: + /// constructor + SvgGradientHelper( + const basegfx::B2DHomMatrix& rGradientTransform, + const basegfx::B2DPolyPolygon& rPolyPolygon, + SvgGradientEntryVector&& rGradientEntries, + const basegfx::B2DPoint& rStart, + bool bUseUnitCoordinates, + SpreadMethod aSpreadMethod); + virtual ~SvgGradientHelper(); + + /// data read access + const basegfx::B2DHomMatrix& getGradientTransform() const { return maGradientTransform; } + const basegfx::B2DPolyPolygon& getPolyPolygon() const { return maPolyPolygon; } + const SvgGradientEntryVector& getGradientEntries() const { return maGradientEntries; } + const basegfx::B2DPoint& getStart() const { return maStart; } + bool getUseUnitCoordinates() const { return mbUseUnitCoordinates; } + SpreadMethod getSpreadMethod() const { return maSpreadMethod; } + + /// compare operator + bool operator==(const SvgGradientHelper& rSvgGradientHelper) const; + }; + + /// the basic linear gradient primitive + class DRAWINGLAYER_DLLPUBLIC SvgLinearGradientPrimitive2D final : public BufferedDecompositionPrimitive2D, public SvgGradientHelper + { + private: + /// the end point for linear gradient + basegfx::B2DPoint maEnd; + + /// local helpers + virtual void createAtom( + Primitive2DContainer& rTargetColor, + Primitive2DContainer& rTargetOpacity, + const SvgGradientEntry& rFrom, + const SvgGradientEntry& rTo, + sal_Int32 nOffsetFrom, + sal_Int32 nOffsetTo) const override; + virtual void checkPreconditions() override; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + SvgLinearGradientPrimitive2D( + const basegfx::B2DHomMatrix& rGradientTransform, + const basegfx::B2DPolyPolygon& rPolyPolygon, + SvgGradientEntryVector&& rGradientEntries, + const basegfx::B2DPoint& rStart, + const basegfx::B2DPoint& rEnd, + bool bUseUnitCoordinates, + SpreadMethod aSpreadMethod); + virtual ~SvgLinearGradientPrimitive2D() override; + + /// data read access + const basegfx::B2DPoint& getEnd() const { return maEnd; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + /// the basic radial gradient primitive + class DRAWINGLAYER_DLLPUBLIC SvgRadialGradientPrimitive2D final : public BufferedDecompositionPrimitive2D, public SvgGradientHelper + { + private: + /// the geometric definition + double mfRadius; + + /// Focal only used when focal is set at all, see constructors + basegfx::B2DPoint maFocal; + basegfx::B2DVector maFocalVector; + double maFocalLength; + + bool mbFocalSet : 1; + + /// local helpers + virtual void createAtom( + Primitive2DContainer& rTargetColor, + Primitive2DContainer& rTargetOpacity, + const SvgGradientEntry& rFrom, + const SvgGradientEntry& rTo, + sal_Int32 nOffsetFrom, + sal_Int32 nOffsetTo) const override; + virtual void checkPreconditions() override; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + SvgRadialGradientPrimitive2D( + const basegfx::B2DHomMatrix& rGradientTransform, + const basegfx::B2DPolyPolygon& rPolyPolygon, + SvgGradientEntryVector&& rGradientEntries, + const basegfx::B2DPoint& rStart, + double fRadius, + bool bUseUnitCoordinates, + SpreadMethod aSpreadMethod, + const basegfx::B2DPoint* pFocal); + virtual ~SvgRadialGradientPrimitive2D() override; + + /// data read access + double getRadius() const { return mfRadius; } + const basegfx::B2DPoint& getFocal() const { return maFocal; } + bool isFocalSet() const { return mbFocalSet; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + // SvgLinearAtomPrimitive2D class + + /* basic primitive for a single linear GradientRun in unit coordinates. + It's derived from DiscreteMetricDependentPrimitive2D to allow view-dependent + decompositions allowing reduced color steps + **/ + class SvgLinearAtomPrimitive2D final : public DiscreteMetricDependentPrimitive2D + { + private: + /// the geometric definition in unit coordinates + basegfx::BColor maColorA; + basegfx::BColor maColorB; + double mfOffsetA; + double mfOffsetB; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + SvgLinearAtomPrimitive2D( + const basegfx::BColor& aColorA, double fOffsetA, + const basegfx::BColor& aColorB, double fOffsetB); + + /// data read access + const basegfx::BColor& getColorA() const { return maColorA; } + const basegfx::BColor& getColorB() const { return maColorB; } + double getOffsetA() const { return mfOffsetA; } + double getOffsetB() const { return mfOffsetB; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + // SvgRadialAtomPrimitive2D class + + /* basic primitive for a single radial GradientRun in unit coordinates. + It's derived from DiscreteMetricDependentPrimitive2D to allow view-dependent + decompositions allowing reduced color steps + **/ + class SvgRadialAtomPrimitive2D final : public DiscreteMetricDependentPrimitive2D + { + private: + /// the geometric definition in unit coordinates + basegfx::BColor maColorA; + basegfx::BColor maColorB; + double mfScaleA; + double mfScaleB; + + // helper to hold translation vectors when given (for focal) + struct VectorPair + { + basegfx::B2DVector maTranslateA; + basegfx::B2DVector maTranslateB; + + VectorPair(const basegfx::B2DVector& rTranslateA, const basegfx::B2DVector& rTranslateB) + : maTranslateA(rTranslateA), + maTranslateB(rTranslateB) + { + } + }; + + /// Only used when focal is set + std::unique_ptr mpTranslate; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + SvgRadialAtomPrimitive2D( + const basegfx::BColor& aColorA, double fScaleA, const basegfx::B2DVector& rTranslateA, + const basegfx::BColor& aColorB, double fScaleB, const basegfx::B2DVector& rTranslateB); + SvgRadialAtomPrimitive2D( + const basegfx::BColor& aColorA, double fScaleA, + const basegfx::BColor& aColorB, double fScaleB); + virtual ~SvgRadialAtomPrimitive2D() override; + + /// data read access + const basegfx::BColor& getColorA() const { return maColorA; } + const basegfx::BColor& getColorB() const { return maColorB; } + double getScaleA() const { return mfScaleA; } + double getScaleB() const { return mfScaleB; } + bool isTranslateSet() const { return (nullptr != mpTranslate); } + basegfx::B2DVector getTranslateA() const { if(mpTranslate) return mpTranslate->maTranslateA; return basegfx::B2DVector(); } + basegfx::B2DVector getTranslateB() const { if(mpTranslate) return mpTranslate->maTranslateB; return basegfx::B2DVector(); } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/textbreakuphelper.hxx b/include/drawinglayer/primitive2d/textbreakuphelper.hxx new file mode 100644 index 000000000..d7dbeabb3 --- /dev/null +++ b/include/drawinglayer/primitive2d/textbreakuphelper.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace drawinglayer::primitive2d { class TextSimplePortionPrimitive2D; } + + +namespace drawinglayer::primitive2d +{ + enum class BreakupUnit + { + Character, + Word + }; + + class DRAWINGLAYER_DLLPUBLIC TextBreakupHelper + { + private: + const TextSimplePortionPrimitive2D& mrSource; + Primitive2DContainer mxResult; + TextLayouterDevice maTextLayouter; + basegfx::utils::B2DHomMatrixBufferedOnDemandDecompose maDecTrans; + + bool mbNoDXArray : 1; + + /// create a portion from nIndex to nLength and append to rTempResult + void breakupPortion(Primitive2DContainer& rTempResult, sal_Int32 nIndex, sal_Int32 nLength, bool bWordLineMode); + + /// breakup complete primitive + void breakup(BreakupUnit aBreakupUnit); + + protected: + /// allow user callback to allow changes to the new TextTransformation. Default + /// does nothing. Retval defines if a primitive gets created, e.g. return false + /// to suppress creation + virtual bool allowChange(sal_uInt32 nCount, basegfx::B2DHomMatrix& rNewTransform, sal_uInt32 nIndex, sal_uInt32 nLength); + + /// allow read access to evtl. useful local parts + const TextLayouterDevice& getTextLayouter() const { return maTextLayouter; } + const TextSimplePortionPrimitive2D& getSource() const { return mrSource; } + + public: + TextBreakupHelper(const TextSimplePortionPrimitive2D& rSource); + virtual ~TextBreakupHelper(); + + /// get result + Primitive2DContainer extractResult(BreakupUnit aBreakupUnit = BreakupUnit::Character); + }; + +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/textdecoratedprimitive2d.hxx b/include/drawinglayer/primitive2d/textdecoratedprimitive2d.hxx new file mode 100644 index 000000000..1a4d821c7 --- /dev/null +++ b/include/drawinglayer/primitive2d/textdecoratedprimitive2d.hxx @@ -0,0 +1,124 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +namespace basegfx::utils { + class B2DHomMatrixBufferedOnDemandDecompose; +} + +namespace drawinglayer::primitive2d +{ + /** TextDecoratedPortionPrimitive2D class + + This primitive expands the TextSimplePortionPrimitive2D by common + decorations used in the office. It can be decomposed and will create + a TextSimplePortionPrimitive2D and all the contained decorations (if used) + as geometry. + */ + class DRAWINGLAYER_DLLPUBLIC TextDecoratedPortionPrimitive2D final : public TextSimplePortionPrimitive2D + { + private: + /// decoration definitions + basegfx::BColor maOverlineColor; + basegfx::BColor maTextlineColor; + TextLine meFontOverline; + TextLine meFontUnderline; + TextStrikeout meTextStrikeout; + TextEmphasisMark meTextEmphasisMark; + TextRelief meTextRelief; + + bool mbUnderlineAbove : 1; + bool mbWordLineMode : 1; + bool mbEmphasisMarkAbove : 1; + bool mbEmphasisMarkBelow : 1; + bool mbShadow : 1; + + /// helper methods + void impCreateGeometryContent( + Primitive2DContainer& rTarget, + basegfx::utils::B2DHomMatrixBufferedOnDemandDecompose const & rDecTrans, + const OUString& rText, + sal_Int32 nTextPosition, + sal_Int32 nTextLength, + const ::std::vector< double >& rDXArray, + const attribute::FontAttribute& rFontAttribute) const; + + /// local decomposition. + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + TextDecoratedPortionPrimitive2D( + /// TextSimplePortionPrimitive2D parameters + const basegfx::B2DHomMatrix& rNewTransform, + const OUString& rText, + sal_Int32 nTextPosition, + sal_Int32 nTextLength, + std::vector< double >&& rDXArray, + const attribute::FontAttribute& rFontAttribute, + const css::lang::Locale& rLocale, + const basegfx::BColor& rFontColor, + const Color& rFillColor, + + /// local parameters + const basegfx::BColor& rOverlineColor, + const basegfx::BColor& rTextlineColor, + TextLine eFontOverline = TEXT_LINE_NONE, + TextLine eFontUnderline = TEXT_LINE_NONE, + bool bUnderlineAbove = false, + TextStrikeout eTextStrikeout = TEXT_STRIKEOUT_NONE, + bool bWordLineMode = false, + TextEmphasisMark eTextEmphasisMark = TEXT_FONT_EMPHASIS_MARK_NONE, + bool bEmphasisMarkAbove = true, + bool bEmphasisMarkBelow = false, + TextRelief eTextRelief = TEXT_RELIEF_NONE, + bool bShadow = false); + + /// data read access + TextLine getFontOverline() const { return meFontOverline; } + TextLine getFontUnderline() const { return meFontUnderline; } + TextStrikeout getTextStrikeout() const { return meTextStrikeout; } + TextEmphasisMark getTextEmphasisMark() const { return meTextEmphasisMark; } + TextRelief getTextRelief() const { return meTextRelief; } + const basegfx::BColor& getOverlineColor() const { return maOverlineColor; } + const basegfx::BColor& getTextlineColor() const { return maTextlineColor; } + bool getUnderlineAbove() const { return mbUnderlineAbove; } + bool getWordLineMode() const { return mbWordLineMode; } + bool getEmphasisMarkAbove() const { return mbEmphasisMarkAbove; } + bool getEmphasisMarkBelow() const { return mbEmphasisMarkBelow; } + bool getShadow() const { return mbShadow; } + + /// compare operator + virtual bool operator==( const BasePrimitive2D& rPrimitive ) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/textenumsprimitive2d.hxx b/include/drawinglayer/primitive2d/textenumsprimitive2d.hxx new file mode 100644 index 000000000..1017888d1 --- /dev/null +++ b/include/drawinglayer/primitive2d/textenumsprimitive2d.hxx @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace drawinglayer::primitive2d +{ + /** TextLine definition + + This is used for both underline and overline + */ + enum TextLine + { + TEXT_LINE_NONE, + TEXT_LINE_SINGLE, + TEXT_LINE_DOUBLE, + TEXT_LINE_DOTTED, + TEXT_LINE_DASH, + TEXT_LINE_LONGDASH, + TEXT_LINE_DASHDOT, + TEXT_LINE_DASHDOTDOT, + TEXT_LINE_SMALLWAVE, + TEXT_LINE_WAVE, + TEXT_LINE_DOUBLEWAVE, + TEXT_LINE_BOLD, + TEXT_LINE_BOLDDOTTED, + TEXT_LINE_BOLDDASH, + TEXT_LINE_BOLDLONGDASH, + TEXT_LINE_BOLDDASHDOT, + TEXT_LINE_BOLDDASHDOTDOT, + TEXT_LINE_BOLDWAVE + }; + + /** helper to convert LineStyle */ + TextLine DRAWINGLAYER_DLLPUBLIC mapFontLineStyleToTextLine(FontLineStyle eLineStyle); + FontLineStyle DRAWINGLAYER_DLLPUBLIC mapTextLineToFontLineStyle(TextLine eLineStyle); + + /** FontStrikeout definition */ + enum TextStrikeout + { + TEXT_STRIKEOUT_NONE, + TEXT_STRIKEOUT_SINGLE, + TEXT_STRIKEOUT_DOUBLE, + TEXT_STRIKEOUT_BOLD, + TEXT_STRIKEOUT_SLASH, + TEXT_STRIKEOUT_X + }; + + /** helper to convert FontStrikeout */ + TextStrikeout DRAWINGLAYER_DLLPUBLIC mapFontStrikeoutToTextStrikeout(::FontStrikeout eFontStrikeout); + ::FontStrikeout DRAWINGLAYER_DLLPUBLIC mapTextStrikeoutToFontStrikeout(TextStrikeout eFontStrikeout); + + /** TextEmphasisMark definition */ + enum TextEmphasisMark + { + TEXT_FONT_EMPHASIS_MARK_NONE, + TEXT_FONT_EMPHASIS_MARK_DOT, + TEXT_FONT_EMPHASIS_MARK_CIRCLE, + TEXT_FONT_EMPHASIS_MARK_DISC, + TEXT_FONT_EMPHASIS_MARK_ACCENT + }; + + /** TextRelief definition */ + enum TextRelief + { + TEXT_RELIEF_NONE, + TEXT_RELIEF_EMBOSSED, + TEXT_RELIEF_ENGRAVED + }; + +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/texthierarchyprimitive2d.hxx b/include/drawinglayer/primitive2d/texthierarchyprimitive2d.hxx new file mode 100644 index 000000000..00972a284 --- /dev/null +++ b/include/drawinglayer/primitive2d/texthierarchyprimitive2d.hxx @@ -0,0 +1,179 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** TextHierarchyLinePrimitive2D class + + Text format hierarchy helper class. It decomposes to its + content, so all direct renderers may ignore it. If You need + to know more about line hierarchies You may react on it and + also need to take care that the source of data uses it. + + This primitive encapsulates text lines. + */ + class DRAWINGLAYER_DLLPUBLIC TextHierarchyLinePrimitive2D final : public GroupPrimitive2D + { + private: + public: + /// constructor + explicit TextHierarchyLinePrimitive2D(Primitive2DContainer&& aChildren); + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + /** TextHierarchyBulletPrimitive2D class + + This primitive encapsulates text bullets. + */ + class DRAWINGLAYER_DLLPUBLIC TextHierarchyBulletPrimitive2D final : public GroupPrimitive2D + { + private: + public: + /// constructor + explicit TextHierarchyBulletPrimitive2D(Primitive2DContainer&& aChildren); + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + /** TextHierarchyParagraphPrimitive2D class + + This primitive encapsulates text paragraphs. + */ + class DRAWINGLAYER_DLLPUBLIC TextHierarchyParagraphPrimitive2D final : public GroupPrimitive2D + { + private: + // outline level of the encapsulated paragraph data. + // -1 means no level, >= 0 is the level + sal_Int16 mnOutlineLevel; + + public: + /// constructor + explicit TextHierarchyParagraphPrimitive2D( + Primitive2DContainer&& aChildren, + sal_Int16 nOutlineLevel = -1); + + /// data read access + sal_Int16 getOutlineLevel() const { return mnOutlineLevel; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + /** TextHierarchyBlockPrimitive2D class + + This primitive encapsulates text blocks. + */ + class DRAWINGLAYER_DLLPUBLIC TextHierarchyBlockPrimitive2D final : public GroupPrimitive2D + { + private: + public: + /// constructor + explicit TextHierarchyBlockPrimitive2D(Primitive2DContainer&& aChildren); + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + /** FieldType definition */ + enum FieldType + { + /** unspecified. If more info is needed for a FieldType, + create a new type and its handling + */ + FIELD_TYPE_COMMON, + + /** uses "FIELD_SEQ_BEGIN;PageField" -> special handling */ + FIELD_TYPE_PAGE, + + /** uses URL as string -> special handling */ + FIELD_TYPE_URL + }; + + /** TextHierarchyFieldPrimitive2D class + + This primitive encapsulates text fields. + Also: This type uses a type enum to transport the encapsulated field + type. Also added is a String which is type-dependent. E.g. for URL + fields, it contains the URL. + */ + class DRAWINGLAYER_DLLPUBLIC TextHierarchyFieldPrimitive2D final : public GroupPrimitive2D + { + private: + /// field type definition + FieldType meType; + + /// field data as name/value pairs (dependent of field type definition) + std::vector< std::pair< OUString, OUString>> meNameValue; + + public: + /// constructor + TextHierarchyFieldPrimitive2D( + Primitive2DContainer&& aChildren, + const FieldType& rFieldType, + const std::vector< std::pair< OUString, OUString>>* pNameValue = nullptr); + + /// data read access + FieldType getType() const { return meType; } + OUString getValue(const OUString& rName) const; + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; + + /** TextHierarchyEditPrimitive2D class + + #i97628# + Primitive to encapsulate text from an active text edit; some + renderers need to suppress this output due to painting the + edited text in e.g. an OutlinerEditView. It's derived from + GroupPrimitive2D, so the implicit decomposition will use the + content. To suppress, this primitive needs to be parsed by + the renderer without taking any action. + */ + class DRAWINGLAYER_DLLPUBLIC TextHierarchyEditPrimitive2D final : public GroupPrimitive2D + { + private: + public: + /// constructor + explicit TextHierarchyEditPrimitive2D(Primitive2DContainer&& aChildren); + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/textlayoutdevice.hxx b/include/drawinglayer/primitive2d/textlayoutdevice.hxx new file mode 100644 index 000000000..93587769c --- /dev/null +++ b/include/drawinglayer/primitive2d/textlayoutdevice.hxx @@ -0,0 +1,127 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include + +// predefines +class VirtualDevice; +class GDIMetaFile; +enum class DrawTextFlags; +namespace vcl +{ +class Font; +} +namespace tools +{ +class Rectangle; +} +namespace drawinglayer::attribute +{ +class FontAttribute; +} +namespace com::sun::star::lang +{ +struct Locale; +} + +// access to one global impTimedRefDev incarnation in namespace drawinglayer::primitive + +namespace drawinglayer::primitive2d +{ +/** TextLayouterDevice class + + This helper class exists to isolate all accesses to VCL + text formatting/handling functionality for primitive implementations. + When in the future FontHandling may move to an own library independent + from VCL, primitives will be prepared. + */ +class DRAWINGLAYER_DLLPUBLIC TextLayouterDevice +{ + /// internally used VirtualDevice + SolarMutexGuard maSolarGuard; + VirtualDevice& mrDevice; + +public: + /// constructor/destructor + TextLayouterDevice(); + ~TextLayouterDevice() COVERITY_NOEXCEPT_FALSE; + + /// tooling methods + void setFont(const vcl::Font& rFont); + void setFontAttribute(const attribute::FontAttribute& rFontAttribute, double fFontScaleX, + double fFontScaleY, const css::lang::Locale& rLocale); + + double getTextHeight() const; + double getOverlineHeight() const; + double getOverlineOffset() const; + double getUnderlineHeight() const; + double getUnderlineOffset() const; + double getStrikeoutOffset() const; + + double getTextWidth(const OUString& rText, sal_uInt32 nIndex, sal_uInt32 nLength) const; + + void getTextOutlines(basegfx::B2DPolyPolygonVector&, const OUString& rText, sal_uInt32 nIndex, + sal_uInt32 nLength, const ::std::vector& rDXArray) const; + + basegfx::B2DRange getTextBoundRect(const OUString& rText, sal_uInt32 nIndex, + sal_uInt32 nLength) const; + + double getFontAscent() const; + double getFontDescent() const; + + void addTextRectActions(const tools::Rectangle& rRectangle, const OUString& rText, + DrawTextFlags nStyle, GDIMetaFile& rGDIMetaFile) const; + + ::std::vector getTextArray(const OUString& rText, sal_uInt32 nIndex, + sal_uInt32 nLength) const; + + ::std::vector getCaretPositions(const OUString& rText, sal_uInt32 nIndex, + sal_uInt32 nLength) const; +}; + +// helper methods for vcl font handling + +/** Create a VCL-Font based on the definitions in FontAttribute + and the given FontScaling. The FontScaling defines the FontHeight + (fFontScaleY) and the FontWidth (fFontScaleX). The combination of + both defines FontStretching, where no stretching happens at + fFontScaleY == fFontScaleX + */ +vcl::Font DRAWINGLAYER_DLLPUBLIC getVclFontFromFontAttribute( + const attribute::FontAttribute& rFontAttribute, double fFontScaleX, double fFontScaleY, + double fFontRotation, const css::lang::Locale& rLocale); + +/** Generate FontAttribute DataSet derived from the given VCL-Font. + The FontScaling with fFontScaleY, fFontScaleX relationship (see + above) will be set in return parameter o_rSize to allow further + processing + */ +attribute::FontAttribute DRAWINGLAYER_DLLPUBLIC getFontAttributeFromVclFont( + basegfx::B2DVector& o_rSize, const vcl::Font& rFont, bool bRTL, bool bBiDiStrong); + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/textprimitive2d.hxx b/include/drawinglayer/primitive2d/textprimitive2d.hxx new file mode 100644 index 000000000..1c23edafd --- /dev/null +++ b/include/drawinglayer/primitive2d/textprimitive2d.hxx @@ -0,0 +1,184 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace drawinglayer::primitive2d +{ +/** TextSimplePortionPrimitive2D class + + This is the basic primitive for representing a text portion. It contains + all needed information. If it is not handled by a renderer, its decomposition + will provide the text tools::PolyPolygon outlines as filled polygons, correctly + transformed. + + To get better text quality, it is suggested to handle this primitive directly + in a renderer. In that case, e.g. hintings on the system can be supported. + + @param maTextTransform + The text transformation contains the text start position (always baselined) + as translation, the FontSize as scale (where width relative to height defines + font scaling and width == height means no font scaling) and the font rotation + and shear. + When shear is used and a renderer does not support it, it may be better to use + the decomposition which will do everything correctly. Same is true for mirroring + which would be expressed as negative scalings. + + @param rText + The text to be used. Only a part may be used, but a bigger part of the string + may be necessary for correct layouting (e.g. international) + + @param aTextPosition + The index to the first character to use from rText + + @param aTextLength + The number of characters to use from rText + + @param rDXArray + The distances between the characters. This parameter may be empty, in that case + the renderer is responsible to do something useful. If it is given, it has to be of + the size aTextLength. Its values are in logical coordinates and describe the + distance for each character to use. This is independent from the font width which + is given with maTextTransform. The first value is the offset to use from the start + point in FontCoordinateSystem X-Direction (given by maTextTransform) to the start + point of the second character + + @param rFontAttribute + The font definition + + @param rLocale + The locale to use + + @param rFontColor + The font color to use + + @param bFilled + + @param nWidthToFill + + @param rTextFillColor + Text background color (has nothing to do with bFilled and nWidthToFill) + + */ +class DRAWINGLAYER_DLLPUBLIC TextSimplePortionPrimitive2D : public BufferedDecompositionPrimitive2D +{ +private: + /// text transformation (FontCoordinateSystem) + basegfx::B2DHomMatrix maTextTransform; + + /// The text, used from maTextPosition up to maTextPosition + maTextLength + OUString maText; + + /// The index from where on maText is used + sal_Int32 mnTextPosition; + + /// The length for maText usage, starting from maTextPosition + sal_Int32 mnTextLength; + + /// The DX array in logic units + std::vector maDXArray; + + /// The font definition + attribute::FontAttribute maFontAttribute; + + /// The Locale for the text + css::lang::Locale maLocale; + + /// font color + basegfx::BColor maFontColor; + + // Whether to fill a given width with the text + bool mbFilled; + + // the width to fill + tools::Long mnWidthToFill; + + /// The fill color of the text + Color maTextFillColor; + + /// #i96669# internal: add simple range buffering for this primitive + basegfx::B2DRange maB2DRange; + +protected: + /// local decomposition. + virtual void + create2DDecomposition(Primitive2DContainer& rContainer, + const geometry::ViewInformation2D& rViewInformation) const override; + +public: + /// constructor + TextSimplePortionPrimitive2D(const basegfx::B2DHomMatrix& rNewTransform, const OUString& rText, + sal_Int32 nTextPosition, sal_Int32 nTextLength, + std::vector&& rDXArray, + const attribute::FontAttribute& rFontAttribute, + const css::lang::Locale& rLocale, + const basegfx::BColor& rFontColor, bool bFilled = false, + tools::Long nWidthToFill = 0, + const Color& rTextFillColor = COL_TRANSPARENT); + + /** get text outlines as polygons and their according ObjectTransformation. Handles all + the necessary VCL outline extractions, scaling adaptations and other stuff. + */ + void getTextOutlinesAndTransformation(basegfx::B2DPolyPolygonVector& rTarget, + basegfx::B2DHomMatrix& rTransformation) const; + + /// data read access + const basegfx::B2DHomMatrix& getTextTransform() const { return maTextTransform; } + const OUString& getText() const { return maText; } + sal_Int32 getTextPosition() const { return mnTextPosition; } + sal_Int32 getTextLength() const { return mnTextLength; } + const ::std::vector& getDXArray() const { return maDXArray; } + const attribute::FontAttribute& getFontAttribute() const { return maFontAttribute; } + const css::lang::Locale& getLocale() const { return maLocale; } + const basegfx::BColor& getFontColor() const { return maFontColor; } + const Color& getTextFillColor() const { return maTextFillColor; } + bool isFilled() const { return mbFilled; } + tools::Long getWidthToFill() const { return mnWidthToFill; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange + getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; +}; + +/// small helper to have a compare operator for Locale +bool DRAWINGLAYER_DLLPUBLIC LocalesAreEqual(const css::lang::Locale& rA, + const css::lang::Locale& rB); + +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/transformprimitive2d.hxx b/include/drawinglayer/primitive2d/transformprimitive2d.hxx new file mode 100644 index 000000000..c1b620fc7 --- /dev/null +++ b/include/drawinglayer/primitive2d/transformprimitive2d.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + + +namespace drawinglayer::primitive2d +{ + /** TransformPrimitive2D class + + This is one of the basic grouping primitives and it provides + embedding a sequence of primitives (a geometry) into a + transformation. All renderers have to handle this, usually by + building a current transformation stack (linear combination) + and applying this to all to-be-rendered geometry. If not handling + this, the output will be mostly wrong since this primitive is + widely used. + + It does transform by embedding an existing geometry into a + transformation as Child-content. This allows re-usage of the + refcounted Uno-Api primitives and their existing, buffered + decompositions. + + It could e.g. be used to show a single object geometry in 1000 + different, transformed states without the need to create those + thousand primitive contents. + */ + class DRAWINGLAYER_DLLPUBLIC TransformPrimitive2D final : public GroupPrimitive2D + { + private: + // the transformation to apply to the child geometry + basegfx::B2DHomMatrix maTransformation; + + public: + /// constructor + TransformPrimitive2D( + const basegfx::B2DHomMatrix& rTransformation, + Primitive2DContainer&& rChildren); + + /// data read access + const basegfx::B2DHomMatrix& getTransformation() const { return maTransformation; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// get range + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/transparenceprimitive2d.hxx b/include/drawinglayer/primitive2d/transparenceprimitive2d.hxx new file mode 100644 index 000000000..14658abe3 --- /dev/null +++ b/include/drawinglayer/primitive2d/transparenceprimitive2d.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace drawinglayer::primitive2d +{ + /** TransparencePrimitive2D class + + This is the basic primitive for applying freely defined transparence + to freely defined content. The basic idea is to associate a content + which is defined as a sequence of primitives and hold as child content + in the GroupPrimitive2D with a transparence channel also defined as a sequence + of primitives and hold in the transparence member. + + The basic definition is to use the transparence content as transparence-Mask by + interpreting the transparence-content not as RGB, but as Luminance transparence mask + using the common RGB_to_luminance definition as e.g. used by VCL. + + The defining geometry is the Range of the child primitive sequence, + this means the renderers will/shall use this geometric information for + rendering, not the transparent one. The transparent one should/will be clipped + accordingly. + */ + class DRAWINGLAYER_DLLPUBLIC TransparencePrimitive2D final : public GroupPrimitive2D + { + private: + /// The transparence-Mask who's RGB-Values are interpreted as Luminance + Primitive2DContainer maTransparence; + + public: + /** constructor + + @param rChildren + The content which is defined to have a transparency. The + range of this primitive is defined by this content + + @param rTransparence + The definition of the Transparence-channel for this primitive. It + will be interpreted as mask by interpreting as gray values + using the common RGB_to_luminance definitions + */ + TransparencePrimitive2D( + Primitive2DContainer&& rChildren, + Primitive2DContainer&& aTransparence); + + /// data read access + const Primitive2DContainer& getTransparence() const { return maTransparence; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/unifiedtransparenceprimitive2d.hxx b/include/drawinglayer/primitive2d/unifiedtransparenceprimitive2d.hxx new file mode 100644 index 000000000..b5a75f295 --- /dev/null +++ b/include/drawinglayer/primitive2d/unifiedtransparenceprimitive2d.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace drawinglayer::primitive2d +{ + /** UnifiedTransparencePrimitive2D class + + This primitive encapsulates a child hierarchy and defines + that it shall be visualized with the given transparency. That + transparency is unique for all contained geometry, so that + e.g. overlapping polygons in the child geometry will not show + regions of combined transparency, but be all rendered with the + defined, single transparency. + */ + class DRAWINGLAYER_DLLPUBLIC UnifiedTransparencePrimitive2D final : public GroupPrimitive2D + { + private: + /// the unified transparence + double mfTransparence; + + public: + /// constructor + UnifiedTransparencePrimitive2D( + Primitive2DContainer&& rChildren, + double fTransparence); + + /// data read access + double getTransparence() const { return mfTransparence; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// own getB2DRange implementation to include transparent geometries to BoundRect calculations + virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const override; + + /// create decomposition + virtual void get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive2d/wrongspellprimitive2d.hxx b/include/drawinglayer/primitive2d/wrongspellprimitive2d.hxx new file mode 100644 index 000000000..559e9e191 --- /dev/null +++ b/include/drawinglayer/primitive2d/wrongspellprimitive2d.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + + +// WrongSpellPrimitive2D class + +namespace drawinglayer::primitive2d +{ + /** WrongSpellPrimitive2D class + + This is a helper primitive to hold evtl. WrongSpell visualisations + in the sequence of primitives. The primitive holds this information + separated from the TextPortions to where it belongs to, to expand the + TextSimplePortionPrimitive2D more as needed. + + A renderer who does not want to visualize this (if contained at all) + can detect and ignore this primitive. If its decomposition is used, + it will be visualized as red wavelines. + + The geometric definition defines a line on the X-Axis (no Y-coordinates) + which will when transformed by Transformation, create the coordinate data. + */ + class DRAWINGLAYER_DLLPUBLIC WrongSpellPrimitive2D final : public BufferedDecompositionPrimitive2D + { + private: + /// geometry definition + basegfx::B2DHomMatrix maTransformation; + double mfStart; + double mfStop; + + /// color (usually red) + basegfx::BColor maColor; + + /// create local decomposition + virtual void create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const override; + + public: + /// constructor + WrongSpellPrimitive2D( + const basegfx::B2DHomMatrix& rTransformation, + double fStart, + double fStop, + const basegfx::BColor& rColor); + + /// data read access + const basegfx::B2DHomMatrix& getTransformation() const { return maTransformation; } + double getStart() const { return mfStart; } + double getStop() const { return mfStop; } + const basegfx::BColor& getColor() const { return maColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive2D& rPrimitive) const override; + + /// provide unique ID + virtual sal_uInt32 getPrimitive2DID() const override; + }; +} // end of namespace drawinglayer::primitive2d + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/Tools.hxx b/include/drawinglayer/primitive3d/Tools.hxx new file mode 100644 index 000000000..4f0d4967e --- /dev/null +++ b/include/drawinglayer/primitive3d/Tools.hxx @@ -0,0 +1,21 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include + +namespace drawinglayer::primitive3d +{ +OUString DRAWINGLAYER_DLLPUBLIC idToString(sal_uInt32 nId); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/baseprimitive3d.hxx b/include/drawinglayer/primitive3d/baseprimitive3d.hxx new file mode 100644 index 000000000..f1a4c5e4d --- /dev/null +++ b/include/drawinglayer/primitive3d/baseprimitive3d.hxx @@ -0,0 +1,210 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_BASEPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_BASEPRIMITIVE3D_HXX + +#include + +#include +#include +#include +#include +#include + + +/** defines for DeclPrimitive3DIDBlock and ImplPrimitive3DIDBlock + Added to be able to simply change identification stuff later, e.g. add + an identification string and/or ID to the interface and to the implementation + ATM used to declare implement getPrimitive3DID() + */ + +#define DeclPrimitive3DIDBlock() \ + virtual sal_uInt32 getPrimitive3DID() const override; + +#define ImplPrimitive3DIDBlock(TheClass, TheID) \ + sal_uInt32 TheClass::getPrimitive3DID() const { return TheID; } + + +// predefines + +namespace drawinglayer::geometry { + class ViewInformation3D; +} + +namespace drawinglayer::primitive3d { + /// typedefs for basePrimitive3DImplBase, Primitive3DContainer and Primitive3DReference + typedef cppu::WeakComponentImplHelper< css::graphic::XPrimitive3D > BasePrimitive3DImplBase; + typedef css::uno::Reference< css::graphic::XPrimitive3D > Primitive3DReference; + + class SAL_WARN_UNUSED DRAWINGLAYER_DLLPUBLIC Primitive3DContainer : public std::deque< Primitive3DReference > + { + public: + explicit Primitive3DContainer() {} + explicit Primitive3DContainer( size_type count ) : deque(count) {} + Primitive3DContainer( const Primitive3DContainer& other ) : deque(other) {} + Primitive3DContainer( Primitive3DContainer&& other ) noexcept : deque(std::move(other)) {} + Primitive3DContainer( std::initializer_list init ) : deque(init) {} + template + Primitive3DContainer(Iter first, Iter last) : deque(first, last) {} + + void append(const Primitive3DContainer& rSource); + Primitive3DContainer& operator=(const Primitive3DContainer& r) { deque::operator=(r); return *this; } + Primitive3DContainer& operator=(Primitive3DContainer&& r) noexcept { deque::operator=(std::move(r)); return *this; } + bool operator==(const Primitive3DContainer& rB) const; + bool operator!=(const Primitive3DContainer& rB) const { return !operator==(rB); } + basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& aViewInformation) const; + }; +} + + +// basePrimitive3D class + +namespace drawinglayer::primitive3d + { + /** BasePrimitive3D class + + Baseclass for all C++ implementations of css::graphic::XPrimitive2D + + The description/functionality is identical with the 2D case in baseprimitive2d.hxx, + please see there for detailed information. + + Current Basic 3D Primitives are: + + - PolygonHairlinePrimitive3D (for 3D hairlines) + - PolyPolygonMaterialPrimitive3D (for 3D filled plane polygons) + + That's all for 3D! + */ + class DRAWINGLAYER_DLLPUBLIC BasePrimitive3D + : protected cppu::BaseMutex, + public BasePrimitive3DImplBase + { + BasePrimitive3D(const BasePrimitive3D&) = delete; + BasePrimitive3D& operator=( const BasePrimitive3D& ) = delete; + public: + // constructor/destructor + BasePrimitive3D(); + virtual ~BasePrimitive3D() override; + + /** the ==operator is mainly needed to allow testing newly-created high level primitives against their last + incarnation which buffers/holds the decompositions. The default implementation + uses getPrimitive3DID()-calls to test if it's the same ID at last. + Overridden implementation are then based on this implementation. + */ + virtual bool operator==( const BasePrimitive3D& rPrimitive ) const; + bool operator!=( const BasePrimitive3D& rPrimitive ) const { return !operator==(rPrimitive); } + + /** This method is for places where using the C++ implementation directly is possible. The subprocessing + and range merging is more efficient when working directly on basegfx::B3DRange. The default implementation + will use getDecomposition results to create the range + */ + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const; + + /** provide unique ID for fast identifying of known primitive implementations in renderers. These use + the defines from primitivetypes3d.hxx to define unique IDs. + */ + virtual sal_uInt32 getPrimitive3DID() const = 0; + + /// The default implementation returns an empty sequence + virtual Primitive3DContainer get3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const; + + + // Methods from XPrimitive3D + + + /** The getDecomposition implementation for UNO API will use getDecomposition from this implementation. It + will get the ViewInformation from the ViewParameters for that purpose + */ + virtual css::uno::Sequence< ::css::uno::Reference< ::css::graphic::XPrimitive3D > > SAL_CALL getDecomposition( const css::uno::Sequence< css::beans::PropertyValue >& rViewParameters ) override; + + /** the getRange default implementation will use getDecomposition to create the range information from merging + getRange results from the single local decomposition primitives. + */ + virtual css::geometry::RealRectangle3D SAL_CALL getRange( const css::uno::Sequence< css::beans::PropertyValue >& rViewParameters ) override; + }; + +} // end of namespace drawinglayer::primitive2d + + +// BufferedDecompositionPrimitive3D class + +namespace drawinglayer::primitive3d + { + /** BufferedDecompositionPrimitive3D class + + Baseclass for all C++ implementations of css::graphic::XPrimitive2D + + The description/functionality is identical with the 2D case in baseprimitive2d.hxx, + please see there for detailed information + */ + class DRAWINGLAYER_DLLPUBLIC BufferedDecompositionPrimitive3D + : public BasePrimitive3D + { + private: + /// a sequence used for buffering the last create3DDecomposition() result + Primitive3DContainer maBuffered3DDecomposition; + + protected: + /** access methods to maBuffered3DDecomposition. The usage of this methods may allow + later thread-safe stuff to be added if needed. Only to be used by getDecomposition() + implementations for buffering the last decomposition. + */ + const Primitive3DContainer& getBuffered3DDecomposition() const { return maBuffered3DDecomposition; } + void setBuffered3DDecomposition(const Primitive3DContainer& rNew) { maBuffered3DDecomposition = rNew; } + + /** method which is to be used to implement the local decomposition of a 2D primitive. The default + implementation will just return an empty decomposition + */ + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const; + + public: + // constructor + BufferedDecompositionPrimitive3D(); + + /** The getDecomposition default implementation will on demand use create3DDecomposition() if + maBuffered3DDecomposition is empty. It will set maBuffered3DDecomposition to this obtained decomposition + to buffer it. If the decomposition is also ViewInformation-dependent, this method needs to be + overridden and the ViewInformation for the last decomposition needs to be remembered, too, and + be used in the next call to decide if the buffered decomposition may be reused or not. + */ + virtual Primitive3DContainer get3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + }; + +} // end of namespace drawinglayer::primitive3d + + +// tooling + +namespace drawinglayer::primitive3d + { + /// get B3DRange from a given Primitive3DReference + basegfx::B3DRange DRAWINGLAYER_DLLPUBLIC getB3DRangeFromPrimitive3DReference(const Primitive3DReference& rCandidate, const geometry::ViewInformation3D& aViewInformation); + + /** compare two Primitive2DReferences for equality, including trying to get implementations (BasePrimitive2D) + and using compare operator + */ + bool DRAWINGLAYER_DLLPUBLIC arePrimitive3DReferencesEqual(const Primitive3DReference& rA, const Primitive3DReference& rB); + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_BASEPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/drawinglayer_primitivetypes3d.hxx b/include/drawinglayer/primitive3d/drawinglayer_primitivetypes3d.hxx new file mode 100644 index 000000000..54141823e --- /dev/null +++ b/include/drawinglayer/primitive3d/drawinglayer_primitivetypes3d.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_DRAWINGLAYER_PRIMITIVETYPES3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_DRAWINGLAYER_PRIMITIVETYPES3D_HXX + + +// define ranges for other libraries + +#define PRIMITIVE3D_ID_RANGE_DRAWINGLAYER (0 << 16) + + +// local primitives + +#define PRIMITIVE3D_ID_GROUPPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 0) +#define PRIMITIVE3D_ID_HATCHTEXTUREPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 1) +#define PRIMITIVE3D_ID_MODIFIEDCOLORPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 2) +#define PRIMITIVE3D_ID_POLYGONHAIRLINEPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 3) +#define PRIMITIVE3D_ID_POLYGONSTROKEPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 4) +#define PRIMITIVE3D_ID_POLYGONTUBEPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 5) +#define PRIMITIVE3D_ID_POLYPOLYGONMATERIALPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 6) +#define PRIMITIVE3D_ID_SDRCUBEPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 7) +#define PRIMITIVE3D_ID_SDREXTRUDEPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 8) +#define PRIMITIVE3D_ID_SDRLATHEPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 9) +#define PRIMITIVE3D_ID_SDRPOLYPOLYGONPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 10) +#define PRIMITIVE3D_ID_SDRSPHEREPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 11) +#define PRIMITIVE3D_ID_SHADOWPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 12) +#define PRIMITIVE3D_ID_UNIFIEDTRANSPARENCETEXTUREPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 13) +#define PRIMITIVE3D_ID_GRADIENTTEXTUREPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 14) +#define PRIMITIVE3D_ID_BITMAPTEXTUREPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 15) +#define PRIMITIVE3D_ID_TRANSPARENCETEXTUREPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 16) +#define PRIMITIVE3D_ID_TRANSFORMPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 17) +#define PRIMITIVE3D_ID_HIDDENGEOMETRYPRIMITIVE3D (PRIMITIVE3D_ID_RANGE_DRAWINGLAYER| 18) + + +#endif // INCLUDED_DRAWINGLAYER_PRIMITIVE3D_DRAWINGLAYER_PRIMITIVETYPES3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/groupprimitive3d.hxx b/include/drawinglayer/primitive3d/groupprimitive3d.hxx new file mode 100644 index 000000000..d77bb0db9 --- /dev/null +++ b/include/drawinglayer/primitive3d/groupprimitive3d.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_GROUPPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_GROUPPRIMITIVE3D_HXX + +#include + +#include + + +namespace drawinglayer::primitive3d + { + /** GroupPrimitive3D class + + Baseclass for all grouping 3D primitives + + The description/functionality is identical with the 2D case in groupprimitive2d.hxx, + please see there for detailed information. + + Current Basic 3D StatePrimitives are: + + - ModifiedColorPrimitive3D (for a stack of color modifications) + - ShadowPrimitive3D (for 3D objects with shadow; this is a special case + since the shadow of a 3D primitive is a 2D primitive set) + - TexturePrimitive3D (with the following variations) + - GradientTexturePrimitive3D (for 3D gradient fill) + - BitmapTexturePrimitive3D (for 3D Bitmap fill) + - TransparenceTexturePrimitive3D (for 3D transparence) + - HatchTexturePrimitive3D (for 3D hatch fill) + - TransformPrimitive3D (for a transformation stack) + */ + class DRAWINGLAYER_DLLPUBLIC GroupPrimitive3D : public BasePrimitive3D + { + private: + /// the children. Declared private since this shall never be changed at all after construction + Primitive3DContainer maChildren; + + public: + /// constructor + explicit GroupPrimitive3D(const Primitive3DContainer& rChildren); + + /// data read access + const Primitive3DContainer& getChildren() const { return maChildren; } + + /// compare operator + virtual bool operator==( const BasePrimitive3D& rPrimitive ) const override; + + /// local decomposition. Implementation will just return children + virtual Primitive3DContainer get3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_GROUPPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/modifiedcolorprimitive3d.hxx b/include/drawinglayer/primitive3d/modifiedcolorprimitive3d.hxx new file mode 100644 index 000000000..d33fba13d --- /dev/null +++ b/include/drawinglayer/primitive3d/modifiedcolorprimitive3d.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_MODIFIEDCOLORPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_MODIFIEDCOLORPRIMITIVE3D_HXX + +#include + +#include +#include + + +namespace drawinglayer::primitive3d + { + /** ModifiedColorPrimitive3D class + + This primitive is a grouping primitive and allows to define + how the colors of its child content shall be modified for + visualisation. Please see the ModifiedColorPrimitive2D + description for more info. + */ + class DRAWINGLAYER_DLLPUBLIC ModifiedColorPrimitive3D final : public GroupPrimitive3D + { + private: + /// The ColorModifier to use + basegfx::BColorModifierSharedPtr maColorModifier; + + public: + /// constructor + ModifiedColorPrimitive3D( + const Primitive3DContainer& rChildren, + const basegfx::BColorModifierSharedPtr& rColorModifier); + + /// data read access + const basegfx::BColorModifierSharedPtr& getColorModifier() const { return maColorModifier; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_MODIFIEDCOLORPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/polygonprimitive3d.hxx b/include/drawinglayer/primitive3d/polygonprimitive3d.hxx new file mode 100644 index 000000000..76f4a8fe7 --- /dev/null +++ b/include/drawinglayer/primitive3d/polygonprimitive3d.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_POLYGONPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_POLYGONPRIMITIVE3D_HXX + +#include + +#include +#include +#include +#include +#include + + +namespace drawinglayer::primitive3d + { + /** PolygonHairlinePrimitive3D class + + This primitive defines a Hairline in 3D. Since hairlines are view-dependent, + this primitive is view-dependent, too. + + This is one of the non-decomposable 3D primitives, so a renderer + should process it. + */ + class DRAWINGLAYER_DLLPUBLIC PolygonHairlinePrimitive3D : public BasePrimitive3D + { + private: + /// the hairline geometry + basegfx::B3DPolygon maPolygon; + + /// the hairline color + basegfx::BColor maBColor; + + public: + /// constructor + PolygonHairlinePrimitive3D( + const basegfx::B3DPolygon& rPolygon, + const basegfx::BColor& rBColor); + + /// data read access + const basegfx::B3DPolygon& getB3DPolygon() const { return maPolygon; } + const basegfx::BColor& getBColor() const { return maBColor; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +namespace drawinglayer::primitive3d + { + /** PolygonStrokePrimitive3D class + + This primitive defines a 3D line with line width, line join, line color + and stroke attributes. It will be decomposed dependent on the definition + to the needed primitives, e.g. filled Tubes for fat lines. + */ + class PolygonStrokePrimitive3D final : public BufferedDecompositionPrimitive3D + { + private: + /// the line geometry + basegfx::B3DPolygon maPolygon; + + /// the line attributes like width, join and color + attribute::LineAttribute maLineAttribute; + + /// the line stroking (if used) + attribute::StrokeAttribute maStrokeAttribute; + + /// local decomposition. + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + public: + /// constructor + PolygonStrokePrimitive3D( + const basegfx::B3DPolygon& rPolygon, + const attribute::LineAttribute& rLineAttribute, + const attribute::StrokeAttribute& rStrokeAttribute); + + /// data read access + const basegfx::B3DPolygon& getB3DPolygon() const { return maPolygon; } + const attribute::LineAttribute& getLineAttribute() const { return maLineAttribute; } + const attribute::StrokeAttribute& getStrokeAttribute() const { return maStrokeAttribute; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_POLYGONPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/polypolygonprimitive3d.hxx b/include/drawinglayer/primitive3d/polypolygonprimitive3d.hxx new file mode 100644 index 000000000..bc229840e --- /dev/null +++ b/include/drawinglayer/primitive3d/polypolygonprimitive3d.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_POLYPOLYGONPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_POLYPOLYGONPRIMITIVE3D_HXX + +#include + +#include +#include +#include + + +namespace drawinglayer::primitive3d + { + /** PolyPolygonMaterialPrimitive3D class + + This primitive defines a planar 3D tools::PolyPolygon filled with a single color. + This is one of the non-decomposable primitives, so a renderer + should process it. + + It is assumed here that the PolyPolgon is a single plane in 3D. + */ + class DRAWINGLAYER_DLLPUBLIC PolyPolygonMaterialPrimitive3D final : public BasePrimitive3D + { + private: + /// the tools::PolyPolygon geometry + basegfx::B3DPolyPolygon maPolyPolygon; + + /// the fill parameters + attribute::MaterialAttribute3D maMaterial; + + bool mbDoubleSided : 1; + + public: + /// constructor + PolyPolygonMaterialPrimitive3D( + const basegfx::B3DPolyPolygon& rPolyPolygon, + const attribute::MaterialAttribute3D& rMaterial, + bool bDoubleSided); + + /// data read access + const basegfx::B3DPolyPolygon& getB3DPolyPolygon() const { return maPolyPolygon; } + const attribute::MaterialAttribute3D& getMaterial() const { return maMaterial; } + bool getDoubleSided() const { return mbDoubleSided; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_POLYPOLYGONPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrcubeprimitive3d.hxx b/include/drawinglayer/primitive3d/sdrcubeprimitive3d.hxx new file mode 100644 index 000000000..65a72366a --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrcubeprimitive3d.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRCUBEPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRCUBEPRIMITIVE3D_HXX + +#include + +#include + + +namespace drawinglayer::primitive3d + { + /** SdrCubePrimitive3D class + + This 3D primitive expands the SdrPrimitive3D to a 3D cube definition. + The cube is implicitly in unit coordinates and the given transformation + defines its geometry in space. + */ + class DRAWINGLAYER_DLLPUBLIC SdrCubePrimitive3D final : public SdrPrimitive3D + { + /// local decomposition. + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + public: + /// constructor + SdrCubePrimitive3D( + const basegfx::B3DHomMatrix& rTransform, + const basegfx::B2DVector& rTextureSize, + const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, + const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute); + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRCUBEPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx b/include/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx new file mode 100644 index 000000000..4caa0c819 --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrextrudelathetools3d.hxx @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDELATHETOOLS3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDELATHETOOLS3D_HXX + +#include + +#include +#include +#include + + +// predefines + +namespace drawinglayer::geometry { + class ViewInformation3D; +} + + +namespace drawinglayer::primitive3d + { + /** SliceType3D definition */ + enum SliceType3D + { + SLICETYPE3D_REGULAR, // normal geometry Slice3D + SLICETYPE3D_FRONTCAP, // front cap + SLICETYPE3D_BACKCAP // back cap + }; + + /// class to hold one Slice3D + class DRAWINGLAYER_DLLPUBLIC Slice3D final + { + basegfx::B3DPolyPolygon maPolyPolygon; + SliceType3D maSliceType; + + public: + Slice3D( + const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::B3DHomMatrix& aTransform, + SliceType3D aSliceType = SLICETYPE3D_REGULAR) + : maPolyPolygon(basegfx::utils::createB3DPolyPolygonFromB2DPolyPolygon(rPolyPolygon)), + maSliceType(aSliceType) + { + maPolyPolygon.transform(aTransform); + } + + // data access + const basegfx::B3DPolyPolygon& getB3DPolyPolygon() const { return maPolyPolygon; } + SliceType3D getSliceType() const { return maSliceType; } + }; + + /// typedef for a group of Slice3Ds + typedef ::std::vector< Slice3D > Slice3DVector; + + /// helpers for creation + void DRAWINGLAYER_DLLPUBLIC createLatheSlices( + Slice3DVector& rSliceVector, + const basegfx::B2DPolyPolygon& rSource, + double fBackScale, + double fDiagonal, + double fRotation, + sal_uInt32 nSteps, + bool bCharacterMode, + bool bCloseFront, + bool bCloseBack); + + void DRAWINGLAYER_DLLPUBLIC createExtrudeSlices( + Slice3DVector& rSliceVector, + const basegfx::B2DPolyPolygon& rSource, + double fBackScale, + double fDiagonal, + double fDepth, + bool bCharacterMode, + bool bCloseFront, + bool bCloseBack); + + /// helpers for geometry extraction + basegfx::B3DPolyPolygon DRAWINGLAYER_DLLPUBLIC extractHorizontalLinesFromSlice(const Slice3DVector& rSliceVector, bool bCloseHorLines); + basegfx::B3DPolyPolygon DRAWINGLAYER_DLLPUBLIC extractVerticalLinesFromSlice(const Slice3DVector& rSliceVector); + + void DRAWINGLAYER_DLLPUBLIC extractPlanesFromSlice( + ::std::vector< basegfx::B3DPolyPolygon >& rFill, + const Slice3DVector& rSliceVector, + bool bCreateNormals, + bool bSmoothNormals, + bool bSmoothLids, + bool bClosed, + double fSmoothNormalsMix, + double fSmoothLidsMix, + bool bCreateTextureCoordinates, + const basegfx::B2DHomMatrix& rTexTransform); + + void DRAWINGLAYER_DLLPUBLIC createReducedOutlines( + const geometry::ViewInformation3D& rViewInformation, + const basegfx::B3DHomMatrix& rObjectTransform, + const basegfx::B3DPolygon& rLoopA, + const basegfx::B3DPolygon& rLoopB, + basegfx::B3DPolyPolygon& rTarget); + +} // end of namespace drawinglayer::overlay + + +#endif //_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDELATHETOOLS3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrextrudeprimitive3d.hxx b/include/drawinglayer/primitive3d/sdrextrudeprimitive3d.hxx new file mode 100644 index 000000000..860f4f72b --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrextrudeprimitive3d.hxx @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDEPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDEPRIMITIVE3D_HXX + +#include + +#include +#include +#include +#include + + +namespace drawinglayer::primitive3d + { + /** SdrExtrudePrimitive3D class + + This 3D primitive expands the SdrPrimitive3D to a 3D extrude definition. + The given 2D tools::PolyPolygon geometry is imagined as lying on the XY-plane in 3D + and gets extruded in Z-Direction by Depth. + + Various possibilities e.g. for creating diagonals (edge roudings in 3D) + and similar are given. + + The decomposition will create all necessary 3D planes for visualisation. + */ + class DRAWINGLAYER_DLLPUBLIC SdrExtrudePrimitive3D final : public SdrPrimitive3D + { + private: + /// geometry helper for slices + basegfx::B2DPolyPolygon maCorrectedPolyPolygon; + Slice3DVector maSlices; + + /// primitive geometry data + basegfx::B2DPolyPolygon maPolyPolygon; + double mfDepth; + double mfDiagonal; + double mfBackScale; + + /// decomposition data when ReducedLineGeometry is used, see get3DDecomposition + std::optional mpLastRLGViewInformation; + + bool mbSmoothNormals : 1; // Plane self + bool mbSmoothLids : 1; // Front/back + bool mbCharacterMode : 1; + bool mbCloseFront : 1; + bool mbCloseBack : 1; + + /// create slices + void impCreateSlices(); + + /// get (evtl. create) slices + const Slice3DVector& getSlices() const; + + /// local decomposition. + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + public: + /// constructor + SdrExtrudePrimitive3D( + const basegfx::B3DHomMatrix& rTransform, + const basegfx::B2DVector& rTextureSize, + const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, + const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute, + const basegfx::B2DPolyPolygon& rPolyPolygon, + double fDepth, + double fDiagonal, + double fBackScale, + bool bSmoothNormals, + bool bSmoothLids, + bool bCharacterMode, + bool bCloseFront, + bool bCloseBack); + virtual ~SdrExtrudePrimitive3D() override; + + /// data read access + const basegfx::B2DPolyPolygon& getPolyPolygon() const { return maPolyPolygon; } + double getDepth() const { return mfDepth; } + double getDiagonal() const { return mfDiagonal; } + double getBackScale() const { return mfBackScale; } + bool getSmoothNormals() const { return mbSmoothNormals; } + bool getSmoothLids() const { return mbSmoothLids; } + bool getCharacterMode() const { return mbCharacterMode; } + bool getCloseFront() const { return mbCloseFront; } + bool getCloseBack() const { return mbCloseBack; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// Overridden to allow for reduced line mode to decide if to buffer decomposition or not + virtual Primitive3DContainer get3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDREXTRUDEPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrlatheprimitive3d.hxx b/include/drawinglayer/primitive3d/sdrlatheprimitive3d.hxx new file mode 100644 index 000000000..779d92e17 --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrlatheprimitive3d.hxx @@ -0,0 +1,128 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRLATHEPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRLATHEPRIMITIVE3D_HXX + +#include + +#include +#include +#include +#include + + +namespace drawinglayer::primitive3d + { + /** SdrLathePrimitive3D class + + This 3D primitive expands the SdrPrimitive3D to a 3D rotation definition. + The given 2D tools::PolyPolygon geometry is imagined as lying on the XY-plane in 3D + and gets rotated around the Y-Axis. + + Various possibilities e.g. for creating diagonals (edge roudings in 3D) + and similar are given. + + The decomposition will create all necessary 3D planes for visualisation. + */ + class DRAWINGLAYER_DLLPUBLIC SdrLathePrimitive3D final : public SdrPrimitive3D + { + private: + /// geometry helper for slices + basegfx::B2DPolyPolygon maCorrectedPolyPolygon; + Slice3DVector maSlices; + + /// primitive geometry data + basegfx::B2DPolyPolygon maPolyPolygon; + sal_uInt32 mnHorizontalSegments; + sal_uInt32 mnVerticalSegments; + double mfDiagonal; + double mfBackScale; + double mfRotation; + + /// decomposition data when ReducedLineGeometry is used, see get3DDecomposition + std::optional mpLastRLGViewInformation; + + bool mbSmoothNormals : 1; // Plane self + bool mbSmoothLids : 1; // Front/back + bool mbCharacterMode : 1; + bool mbCloseFront : 1; + bool mbCloseBack : 1; + + /// create slices + void impCreateSlices(); + + /// get (evtl. create) slices + const Slice3DVector& getSlices() const; + + /// local decomposition. + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + public: + /// constructor + SdrLathePrimitive3D( + const basegfx::B3DHomMatrix& rTransform, + const basegfx::B2DVector& rTextureSize, + const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, + const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute, + const basegfx::B2DPolyPolygon& rPolyPolygon, + sal_uInt32 nHorizontalSegments, + sal_uInt32 nVerticalSegments, + double fDiagonal, + double fBackScale, + double fRotation, + bool bSmoothNormals, + bool bSmoothLids, + bool bCharacterMode, + bool bCloseFront, + bool bCloseBack); + virtual ~SdrLathePrimitive3D() override; + + /// data read access + const basegfx::B2DPolyPolygon& getPolyPolygon() const { return maPolyPolygon; } + sal_uInt32 getHorizontalSegments() const { return mnHorizontalSegments; } + sal_uInt32 getVerticalSegments() const { return mnVerticalSegments; } + double getDiagonal() const { return mfDiagonal; } + double getBackScale() const { return mfBackScale; } + double getRotation() const { return mfRotation; } + bool getSmoothNormals() const { return mbSmoothNormals; } + bool getSmoothLids() const { return mbSmoothLids; } + bool getCharacterMode() const { return mbCharacterMode; } + bool getCloseFront() const { return mbCloseFront; } + bool getCloseBack() const { return mbCloseBack; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// Overridden to allow for reduced line mode to decide if to buffer decomposition or not + virtual Primitive3DContainer get3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRLATHEPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrpolypolygonprimitive3d.hxx b/include/drawinglayer/primitive3d/sdrpolypolygonprimitive3d.hxx new file mode 100644 index 000000000..922414cf6 --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrpolypolygonprimitive3d.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPOLYPOLYGONPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPOLYPOLYGONPRIMITIVE3D_HXX + +#include + +#include + + +namespace drawinglayer::primitive3d + { + /** SdrPolyPolygonPrimitive3D class + + This 3D primitive defines a PolyPolgon in space which may have + Line- and FillStyles and extra 3D surface attributes. It is assumed + that the given 3D PolyPolgon (which may contain texture and normal + information) is planar in 3D. + + The decomposition will include all needed 3D data for visualisation, + including FatLines and fill styles. + */ + class DRAWINGLAYER_DLLPUBLIC SdrPolyPolygonPrimitive3D final : public SdrPrimitive3D + { + private: + /// the planar polyPolygon evtl with normals and texture coordinates + basegfx::B3DPolyPolygon maPolyPolygon3D; + + /// local decomposition. + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + public: + /// constructor + SdrPolyPolygonPrimitive3D( + const basegfx::B3DPolyPolygon& rPolyPolygon3D, + const basegfx::B3DHomMatrix& rTransform, + const basegfx::B2DVector& rTextureSize, + const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, + const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute); + + /// data access + const basegfx::B3DPolyPolygon& getPolyPolygon3D() const { return maPolyPolygon3D; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPOLYPOLYGONPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrprimitive3d.hxx b/include/drawinglayer/primitive3d/sdrprimitive3d.hxx new file mode 100644 index 000000000..bd8991f78 --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrprimitive3d.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPRIMITIVE3D_HXX + +#include + +#include +#include +#include +#include +#include +#include + + +namespace drawinglayer +{ + /** SdrPrimitive3D class + + Base class for the more complicated geometric primitives, so + derive from buffered primitive to allow overriding of + create3DDecomposition there. + */ + namespace primitive3d + { + class DRAWINGLAYER_DLLPUBLIC SdrPrimitive3D : public BufferedDecompositionPrimitive3D + { + private: + /// object surface attributes + basegfx::B3DHomMatrix maTransform; + basegfx::B2DVector maTextureSize; + attribute::SdrLineFillShadowAttribute3D maSdrLFSAttribute; + attribute::Sdr3DObjectAttribute maSdr3DObjectAttribute; + + protected: + /** Standard implementation for primitive3D which + will use maTransform as range and expand by evtl. line width / 2 + */ + basegfx::B3DRange getStandard3DRange() const; + + /** implementation for primitive3D which + will use given Slice3Ds and expand by evtl. line width / 2 + */ + basegfx::B3DRange get3DRangeFromSlices(const Slice3DVector& rSlices) const; + + public: + /// constructor + SdrPrimitive3D( + const basegfx::B3DHomMatrix& rTransform, + const basegfx::B2DVector& rTextureSize, + const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, + const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute); + + /// data read access + const basegfx::B3DHomMatrix& getTransform() const { return maTransform; } + const basegfx::B2DVector& getTextureSize() const { return maTextureSize; } + const attribute::SdrLineFillShadowAttribute3D& getSdrLFSAttribute() const { return maSdrLFSAttribute; } + const attribute::Sdr3DObjectAttribute& getSdr3DObjectAttribute() const { return maSdr3DObjectAttribute; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + }; + } // end of namespace primitive3d +} // end of namespace drawinglayer + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/sdrsphereprimitive3d.hxx b/include/drawinglayer/primitive3d/sdrsphereprimitive3d.hxx new file mode 100644 index 000000000..af9090c3f --- /dev/null +++ b/include/drawinglayer/primitive3d/sdrsphereprimitive3d.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRSPHEREPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRSPHEREPRIMITIVE3D_HXX + +#include + +#include + + +namespace drawinglayer::primitive3d + { + /** SdrSpherePrimitive3D class + + This 3D primitive expands the SdrPrimitive3D to a 3D sphere definition. + The sphere is implicitly in unit coordinates and the given transformation + defines its geometry in space. + */ + class DRAWINGLAYER_DLLPUBLIC SdrSpherePrimitive3D final : public SdrPrimitive3D + { + private: + /// additional geometry definitions + sal_uInt32 mnHorizontalSegments; + sal_uInt32 mnVerticalSegments; + + /// local decomposition. + virtual Primitive3DContainer create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const override; + + public: + /// constructor + SdrSpherePrimitive3D( + const basegfx::B3DHomMatrix& rTransform, + const basegfx::B2DVector& rTextureSize, + const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, + const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute, + sal_uInt32 nHorizontalSegments, + sal_uInt32 nVerticalSegments); + + /// data read access + sal_uInt32 getHorizontalSegments() const { return mnHorizontalSegments; } + sal_uInt32 getVerticalSegments() const { return mnVerticalSegments; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRSPHEREPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/primitive3d/transformprimitive3d.hxx b/include/drawinglayer/primitive3d/transformprimitive3d.hxx new file mode 100644 index 000000000..a99ea27e8 --- /dev/null +++ b/include/drawinglayer/primitive3d/transformprimitive3d.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_TRANSFORMPRIMITIVE3D_HXX +#define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_TRANSFORMPRIMITIVE3D_HXX + +#include + +#include +#include + + +namespace drawinglayer::primitive3d + { + /** TransformPrimitive3D class + + This is one of the basic grouping 3D primitives and it provides + embedding a sequence of primitives (a geometry) into a + 3D transformation. + + Please see the description for TransformPrimitive2D since these + primitives are pretty similar. + */ + class DRAWINGLAYER_DLLPUBLIC TransformPrimitive3D final : public GroupPrimitive3D + { + private: + // the 3D transformation to apply + basegfx::B3DHomMatrix maTransformation; + + public: + /// constructor + TransformPrimitive3D( + const basegfx::B3DHomMatrix& rTransformation, + const Primitive3DContainer& rChildren); + + /// data read access + const basegfx::B3DHomMatrix& getTransformation() const { return maTransformation; } + + /// compare operator + virtual bool operator==(const BasePrimitive3D& rPrimitive) const override; + + /// get range + virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const override; + + /// provide unique ID + DeclPrimitive3DIDBlock() + }; + +} // end of namespace drawinglayer::primitive3d + + +#endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_TRANSFORMPRIMITIVE3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/baseprocessor2d.hxx b/include/drawinglayer/processor2d/baseprocessor2d.hxx new file mode 100644 index 000000000..7ab718630 --- /dev/null +++ b/include/drawinglayer/processor2d/baseprocessor2d.hxx @@ -0,0 +1,200 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_BASEPROCESSOR2D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_BASEPROCESSOR2D_HXX + +#include + +#include +#include +#include + + +namespace drawinglayer::processor2d + { + /** BaseProcessor2D class + + Base class for all C++ implementations of instances which process + primitives. + + Instances which process primitives can be renderers, but also stuff + for HitTests, BoundRect calculations and/or animation processing. The + main usage are renderers, but they are supposed to handle any primitive + processing. + + The base implementation is constructed with a ViewInformation2D which + is accessible throughout the processor implementations. The idea is + to construct any processor with a given ViewInformation2D. To be able + to handle primitives which need to change the current transformation + (as e.g. TransformPrimitive2D) it is allowed for the processor implementation + to change its local value using updateViewInformation. + + The basic processing method is process(..) which gets handed over the + sequence of primitives to process. For convenience of the C++ implementations, + the default implementation of process(..) maps all accesses to primitives to + single calls to processBasePrimitive2D(..) where the primitive in question is + already casted to the C++ implementation class. + + The process(..) implementation makes a complete iteration over the given + sequence of primitives. If the Primitive is not derived from BasePrimitive2D + and thus not part of the C++ implementations, it converts ViewInformation2D + to the corresponding API implementation (a uno::Sequence< beans::PropertyValue >) + and recursively calls the method process(..) at the primitive with the decomposition + derived from that primitive. This is the preparation to handle unknown implementations + of the css::graphic::XPrimitive2D interface in the future. + + So, to implement a basic processor, it is necessary to override and implement the + processBasePrimitive2D(..) method. A minimal renderer has to support the + Basic Primitives (see baseprimitive2d.hxx) and the Grouping Primitives (see + groupprimitive2d.hxx). These are (currently): + + Basic Primitives: + + - BitmapPrimitive2D (bitmap data, possibly with transparency) + - PointArrayPrimitive2D (single points) + - PolygonHairlinePrimitive2D (hairline curves/polygons) + - PolyPolygonColorPrimitive2D (colored polygons) + + Grouping Primitives: + + - TransparencePrimitive2D (objects with freely defined transparence) + - InvertPrimitive2D (for XOR) + - MaskPrimitive2D (for masking) + - ModifiedColorPrimitive2D (for a stack of color modifications) + - TransformPrimitive2D (for a transformation stack) + + A processor doing so is a minimal processor. Of course a processor may + handle any higher-level primitive (that has a decomposition implementation) + for more direct data access or performance reasons, too. + + The main part of a processBasePrimitive2D implementation is a switch..case + construct, looking like the following: + + void foo::processBasePrimitive2D(const BasePrimitive2D& rCandidate) + { + switch(rCandidate.getPrimitive2DID()) + { + case PRIMITIVE2D_ID_??? : + { + // process PRIMITIVE2D_ID_??? here... + + ... + + break; + } + + ... + + default : + { + // process recursively + process(rCandidate.get2DDecomposition(getViewInformation2D())); + break; + } + } + } + + The default case makes the processor work with all complex primitives + by recursively using their decomposition. + + You can also add a case for ignoring primitives by using: + + case PRIMITIVE2D_ID_...IGNORE.A.. : + case PRIMITIVE2D_ID_...IGNORE.B.. : + case PRIMITIVE2D_ID_...IGNORE.C.. : + { + // ignore these primitives by neither processing nor + // recursively processing their decomposition + break; + } + + Another useful case is embedding the processing of a complex primitive by + bracketing it with some actions: + + case PRIMITIVE2D_ID_SOME_TEXT : + { + // encapsulate e.g. with changing local variables, e.g. + // sometimes it's good to know if a basic primitive is + // part of a text, especially when not handling the text + // self but by purpose want to handle the decomposed + // geometries in the processor + startText(); + process(rCandidate.get2DDecomposition(getViewInformation2D())); + endText(); + break; + } + + As an example a processor collecting the outlines of a sequence of primitives + only needs to handle some Basic Primitives and create outline and collect + outline polygons e.g. for primitives with area like BitmapPrimitive2D (a + rectangle) and PolyPolygonColorPrimitive2D. When also handling the Grouping + Primitives MaskPrimitive2D (e.g. ignoring its content, using the mask polyPolygon) + and TransformPrimitive2D (to have the correct local transformation), a processor + creating the outline can be written using just four (4) primitives. As a tipp, it can + be helpful to add many for the purpose not interesting higher level primitives + to not force their decomposition to be created and/or parsed. + */ + class DRAWINGLAYER_DLLPUBLIC BaseProcessor2D : public drawinglayer::primitive2d::Primitive2DDecompositionVisitor + { + private: + /// The ViewInformation2D itself. It's private to isolate accesses to it + geometry::ViewInformation2D maViewInformation2D; + + protected: + /* access method to allow the implementations to change the current + ViewInformation2D if needed. This allows isolating these accesses + later if needed + */ + void updateViewInformation(const geometry::ViewInformation2D& rViewInformation2D) + { + maViewInformation2D = rViewInformation2D; + } + + /* as tooling, the process() implementation takes over API handling and calls this + virtual render method when the primitive implementation is BasePrimitive2D-based. + Default implementation does nothing + */ + virtual void processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate); + + void process(const primitive2d::BasePrimitive2D& rCandidate); + + // Primitive2DDecompositionVisitor + virtual void visit(const primitive2d::Primitive2DReference&) override final; + virtual void visit(const primitive2d::Primitive2DContainer&) override final; + virtual void visit(primitive2d::Primitive2DContainer&&) override final; + + public: + /// constructor/destructor + explicit BaseProcessor2D(const geometry::ViewInformation2D& rViewInformation); + virtual ~BaseProcessor2D(); + + /// the central processing method + void process(const primitive2d::Primitive2DContainer& rSource); + + /// data read access + const geometry::ViewInformation2D& getViewInformation2D() const { return maViewInformation2D; } + }; + +} // end of namespace drawinglayer::processor2d + + +#endif //INCLUDED_DRAWINGLAYER_PROCESSOR2D_BASEPROCESSOR2D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/contourextractor2d.hxx b/include/drawinglayer/processor2d/contourextractor2d.hxx new file mode 100644 index 000000000..53158cc21 --- /dev/null +++ b/include/drawinglayer/processor2d/contourextractor2d.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_CONTOUREXTRACTOR2D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_CONTOUREXTRACTOR2D_HXX + +#include + +#include +#include + + +namespace drawinglayer::processor2d + { + /** ContourExtractor2D class + + A processor who extracts the contour of the primitives fed to it + in the single local PolyPolygon + */ + class DRAWINGLAYER_DLLPUBLIC ContourExtractor2D final : public BaseProcessor2D + { + private: + /// the extracted contour + basegfx::B2DPolyPolygonVector maExtractedContour; + + bool mbExtractFillOnly : 1; + + /// tooling methods + void processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate) override; + + public: + explicit ContourExtractor2D( + const geometry::ViewInformation2D& rViewInformation, + bool bExtractFillOnly); + + virtual ~ContourExtractor2D() override; + + const basegfx::B2DPolyPolygonVector& getExtractedContour() const { return maExtractedContour; } + }; + +} // end of namespace drawinglayer::processor2d + + +#endif // INCLUDED_DRAWINGLAYER_PROCESSOR2D_CONTOUREXTRACTOR2D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/hittestprocessor2d.hxx b/include/drawinglayer/processor2d/hittestprocessor2d.hxx new file mode 100644 index 000000000..5638f6889 --- /dev/null +++ b/include/drawinglayer/processor2d/hittestprocessor2d.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_HITTESTPROCESSOR2D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_HITTESTPROCESSOR2D_HXX + +#include +#include +#include + +namespace basegfx { class B2DPolygon; } +namespace basegfx { class B2DPolyPolygon; } +namespace drawinglayer::primitive2d { class ScenePrimitive2D; } + +namespace drawinglayer::processor2d + { + /** HitTestProcessor2D class + + This processor implements a HitTest with the fed primitives, + given tolerance and extras + */ + class DRAWINGLAYER_DLLPUBLIC HitTestProcessor2D final : public BaseProcessor2D + { + private: + /// discrete HitTest position + basegfx::B2DPoint maDiscreteHitPosition; + + /// discrete HitTolerance + double mfDiscreteHitTolerance; + + /// stack of HitPrimitives, taken care of during HitTest run + primitive2d::Primitive2DContainer maHitStack; + + /// flag if HitStack shall be collected as part of the result, default is false + bool mbCollectHitStack : 1; + + /// Boolean to flag if a hit was found. If yes, fast exit is taken + bool mbHit : 1; + + /// flag to concentrate on text hits only + bool mbHitTextOnly : 1; + + /// tooling methods + void processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate) override; + bool checkHairlineHitWithTolerance( + const basegfx::B2DPolygon& rPolygon, + double fDiscreteHitTolerance) const; + bool checkFillHitWithTolerance( + const basegfx::B2DPolyPolygon& rPolyPolygon, + double fDiscreteHitTolerance) const; + void check3DHit(const primitive2d::ScenePrimitive2D& rCandidate); + + public: + HitTestProcessor2D( + const geometry::ViewInformation2D& rViewInformation, + const basegfx::B2DPoint& rLogicHitPosition, + double fLogicHitTolerance, + bool bHitTextOnly); + virtual ~HitTestProcessor2D() override; + + /// switch on collecting primitives for a found hit on maHitStack, default is off + void collectHitStack(bool bCollect) { mbCollectHitStack = bCollect; } + + /// get HitStack of primitives, first is the one that created the hit, last is the + /// top-most + const primitive2d::Primitive2DContainer& getHitStack() const { return maHitStack; } + + /// data read access + const basegfx::B2DPoint& getDiscreteHitPosition() const { return maDiscreteHitPosition; } + double getDiscreteHitTolerance() const { return mfDiscreteHitTolerance; } + bool getCollectHitStack() const { return mbCollectHitStack; } + bool getHit() const { return mbHit; } + bool getHitTextOnly() const { return mbHitTextOnly; } + }; + +} // end of namespace drawinglayer::processor2d + +#endif // INCLUDED_DRAWINGLAYER_PROCESSOR2D_HITTESTPROCESSOR2D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/linegeometryextractor2d.hxx b/include/drawinglayer/processor2d/linegeometryextractor2d.hxx new file mode 100644 index 000000000..a2a388dd1 --- /dev/null +++ b/include/drawinglayer/processor2d/linegeometryextractor2d.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_LINEGEOMETRYEXTRACTOR2D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_LINEGEOMETRYEXTRACTOR2D_HXX + +#include + +#include +#include +#include + + +namespace drawinglayer::processor2d + { + /** LineGeometryExtractor2D class + + This processor can extract the line geometry from fed primitives. The + hairlines and the fill geometry from fat lines are separated. + */ + class DRAWINGLAYER_DLLPUBLIC LineGeometryExtractor2D final : public BaseProcessor2D + { + private: + basegfx::B2DPolygonVector maExtractedHairlines; + basegfx::B2DPolyPolygonVector maExtractedLineFills; + + bool mbInLineGeometry : 1; + + /// tooling methods + void processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate) override; + + public: + LineGeometryExtractor2D(const geometry::ViewInformation2D& rViewInformation); + virtual ~LineGeometryExtractor2D() override; + + const basegfx::B2DPolygonVector& getExtractedHairlines() const { return maExtractedHairlines; } + const basegfx::B2DPolyPolygonVector& getExtractedLineFills() const { return maExtractedLineFills; } + }; + +} // end of namespace drawinglayer::processor2d + + +#endif // INCLUDED_DRAWINGLAYER_PROCESSOR2D_LINEGEOMETRYEXTRACTOR2D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/objectinfoextractor2d.hxx b/include/drawinglayer/processor2d/objectinfoextractor2d.hxx new file mode 100644 index 000000000..f7dc1d146 --- /dev/null +++ b/include/drawinglayer/processor2d/objectinfoextractor2d.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_OBJECTINFOEXTRACTOR2D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_OBJECTINFOEXTRACTOR2D_HXX + +#include +#include + +namespace drawinglayer::primitive2d { class ObjectInfoPrimitive2D; } + +namespace drawinglayer::processor2d + { + /** ObjectInfoPrimitiveExtractor2D class + + A processor to find the first incarnation of ObjectInfoPrimitive2D + in a given hierarchy + */ + class DRAWINGLAYER_DLLPUBLIC ObjectInfoPrimitiveExtractor2D final : public BaseProcessor2D + { + private: + /// the target + const primitive2d::ObjectInfoPrimitive2D* mpFound; + + /// tooling methods + void processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate) override; + + public: + ObjectInfoPrimitiveExtractor2D(const geometry::ViewInformation2D& rViewInformation); + virtual ~ObjectInfoPrimitiveExtractor2D() override; + + const primitive2d::ObjectInfoPrimitive2D* getResult() const { return mpFound; } + }; + +} // end of namespace drawinglayer::processor2d + +#endif // INCLUDED_DRAWINGLAYER_PROCESSOR2D_OBJECTINFOEXTRACTOR2D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/processor2dtools.hxx b/include/drawinglayer/processor2d/processor2dtools.hxx new file mode 100644 index 000000000..86ad2562e --- /dev/null +++ b/include/drawinglayer/processor2d/processor2dtools.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_PROCESSOR2DTOOLS_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_PROCESSOR2DTOOLS_HXX + +#include +#include + +namespace drawinglayer::geometry { class ViewInformation2D; } +namespace drawinglayer::processor2d { class BaseProcessor2D; } + +class OutputDevice; + +namespace drawinglayer::processor2d + { + /** create the best available pixel based BaseProcessor2D + (which may be system-dependent) + + @param rTargetOutDev + The target OutputDevice + + @param rViewInformation2D + The ViewInformation to use + + @return + the created BaseProcessor2D (ownership change) + */ + DRAWINGLAYER_DLLPUBLIC std::unique_ptr createPixelProcessor2DFromOutputDevice( + OutputDevice& rTargetOutDev, + const drawinglayer::geometry::ViewInformation2D& rViewInformation2D); + + /** create a BaseProcessor2D dependent on some states of the + given OutputDevice. If metafile is recorded, the needed + VclMetafileProcessor2D will be created. If a pixel renderer + is requested, the best one is incarnated + + @param rTargetOutDev + The target OutputDevice + + @param rViewInformation2D + The ViewInformation to use + + @return + the created BaseProcessor2D (ownership change) + */ + DRAWINGLAYER_DLLPUBLIC std::unique_ptr createProcessor2DFromOutputDevice( + OutputDevice& rTargetOutDev, + const drawinglayer::geometry::ViewInformation2D& rViewInformation2D); + + +} // end of namespace drawinglayer::processor2d + +#endif //INCLUDED_DRAWINGLAYER_PROCESSOR2D_PROCESSOR2DTOOLS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/processorfromoutputdevice.hxx b/include/drawinglayer/processor2d/processorfromoutputdevice.hxx new file mode 100644 index 000000000..f5ba9da79 --- /dev/null +++ b/include/drawinglayer/processor2d/processorfromoutputdevice.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_PROCESSORFROMOUTPUTDEVICE_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_PROCESSORFROMOUTPUTDEVICE_HXX + +#include +#include + +class OutputDevice; + +namespace drawinglayer::processor2d { + class BaseProcessor2D; +} + +namespace drawinglayer::geometry { class ViewInformation2D; } + +namespace drawinglayer::processor2d + { + // create a mating VCL-Processor for given OutputDevice. This includes + // looking for MetaFile-recording. The returned renderer changes owner, + // deletion is duty of the caller + DRAWINGLAYER_DLLPUBLIC std::unique_ptr createBaseProcessor2DFromOutputDevice( + OutputDevice& rTargetOutDev, + const drawinglayer::geometry::ViewInformation2D& rViewInformation2D); + +} // end of namespace drawinglayer::processor2d + +#endif // INCLUDED_DRAWINGLAYER_PROCESSOR2D_PROCESSORFROMOUTPUTDEVICE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor2d/textaspolygonextractor2d.hxx b/include/drawinglayer/processor2d/textaspolygonextractor2d.hxx new file mode 100644 index 000000000..42e2376f0 --- /dev/null +++ b/include/drawinglayer/processor2d/textaspolygonextractor2d.hxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR2D_TEXTASPOLYGONEXTRACTOR2D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR2D_TEXTASPOLYGONEXTRACTOR2D_HXX + +#include + +#include +#include +#include +#include +#include + + +namespace drawinglayer::processor2d + { + /// helper data structure for returning the result + struct DRAWINGLAYER_DLLPUBLIC TextAsPolygonDataNode + { + private: + basegfx::B2DPolyPolygon maB2DPolyPolygon; + basegfx::BColor maBColor; + bool mbIsFilled; + + public: + TextAsPolygonDataNode( + const basegfx::B2DPolyPolygon& rB2DPolyPolygon, + const basegfx::BColor& rBColor, + bool bIsFilled) + : maB2DPolyPolygon(rB2DPolyPolygon), + maBColor(rBColor), + mbIsFilled(bIsFilled) + { + } + + // data read access + const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maB2DPolyPolygon; } + const basegfx::BColor& getBColor() const { return maBColor; } + bool getIsFilled() const { return mbIsFilled; } + }; + + /// typedef for a vector of that helper data + typedef ::std::vector< TextAsPolygonDataNode > TextAsPolygonDataNodeVector; + + /** TextAsPolygonExtractor2D class + + This processor extracts text in the fed primitives to filled polygons + */ + class DRAWINGLAYER_DLLPUBLIC TextAsPolygonExtractor2D final : public BaseProcessor2D + { + private: + // extraction target + TextAsPolygonDataNodeVector maTarget; + + // the modifiedColorPrimitive stack + basegfx::BColorModifierStack maBColorModifierStack; + + // flag if we are in a decomposed text + sal_uInt32 mnInText; + + // tooling methods + void processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate) override; + + public: + explicit TextAsPolygonExtractor2D(const geometry::ViewInformation2D& rViewInformation); + virtual ~TextAsPolygonExtractor2D() override; + + // data read access + const TextAsPolygonDataNodeVector& getTarget() const { return maTarget; } + }; + +} // end of namespace drawinglayer::processor2d + + +#endif // INCLUDED_DRAWINGLAYER_PROCESSOR2D_TEXTASPOLYGONEXTRACTOR2D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor3d/baseprocessor3d.hxx b/include/drawinglayer/processor3d/baseprocessor3d.hxx new file mode 100644 index 000000000..b70e38ee9 --- /dev/null +++ b/include/drawinglayer/processor3d/baseprocessor3d.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR3D_BASEPROCESSOR3D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR3D_BASEPROCESSOR3D_HXX + +#include + +#include +#include + + +namespace drawinglayer::processor3d + { + /** BaseProcessor3D class + + Baseclass for all C++ implementations of instances which process + primitives. + + Please have a look at baseprocessor2d.hxx for more comments. + */ + class DRAWINGLAYER_DLLPUBLIC BaseProcessor3D + { + private: + geometry::ViewInformation3D maViewInformation3D; + + protected: + void updateViewInformation(const geometry::ViewInformation3D& rViewInformation3D) + { + maViewInformation3D = rViewInformation3D; + } + + /* as tooling, the process() implementation takes over API handling and calls this + virtual render method when the primitive implementation is BasePrimitive3D-based. + Default implementation does nothing + */ + virtual void processBasePrimitive3D(const primitive3d::BasePrimitive3D& rCandidate); + + public: + explicit BaseProcessor3D(const geometry::ViewInformation3D& rViewInformation); + virtual ~BaseProcessor3D(); + + // the central processing method + void process(const primitive3d::Primitive3DContainer& rSource); + + // data access + const geometry::ViewInformation3D& getViewInformation3D() const { return maViewInformation3D; } + }; + +} // end of namespace drawinglayer::processor3d + + +#endif //_DRAWINGLAYER_PROCESSOR3D_BASEPROCESSOR3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/processor3d/cutfindprocessor3d.hxx b/include/drawinglayer/processor3d/cutfindprocessor3d.hxx new file mode 100644 index 000000000..b237e9c68 --- /dev/null +++ b/include/drawinglayer/processor3d/cutfindprocessor3d.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_DRAWINGLAYER_PROCESSOR3D_CUTFINDPROCESSOR3D_HXX +#define INCLUDED_DRAWINGLAYER_PROCESSOR3D_CUTFINDPROCESSOR3D_HXX + +#include +#include + +#include + +namespace drawinglayer::processor3d + { + /** CutFindProcessor class + + This processor extracts all cuts of 3D plane geometries in the fed primitives + with the given cut vector, based on the ViewInformation3D given. + */ + class DRAWINGLAYER_DLLPUBLIC CutFindProcessor final : public BaseProcessor3D + { + private: + /// the start and stop point for the cut vector + basegfx::B3DPoint maFront; + basegfx::B3DPoint maBack; + + /// the found cut points + ::std::vector< basegfx::B3DPoint > maResult; + + /* #i102956# the transformation change from TransformPrimitive3D processings + needs to be remembered to be able to transform found cuts to the + basic coordinate system the processor starts with + */ + basegfx::B3DHomMatrix maCombinedTransform; + + bool mbAnyHit : 1; + + /* as tooling, the process() implementation takes over API handling and calls this + virtual render method when the primitive implementation is BasePrimitive3D-based. + */ + virtual void processBasePrimitive3D(const primitive3d::BasePrimitive3D& rCandidate) override; + + public: + CutFindProcessor(const geometry::ViewInformation3D& rViewInformation, + const basegfx::B3DPoint& rFront, + const basegfx::B3DPoint& rBack, + bool bAnyHit); + + /// data read access + const ::std::vector< basegfx::B3DPoint >& getCutPoints() const { return maResult; } + }; + +} // end of namespace drawinglayer::processor3d + + +#endif //INCLUDED_DRAWINGLAYER_PROCESSOR3D_CUTFINDPROCESSOR3D_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/drawinglayer/tools/primitive2dxmldump.hxx b/include/drawinglayer/tools/primitive2dxmldump.hxx new file mode 100644 index 000000000..9dc06e7b6 --- /dev/null +++ b/include/drawinglayer/tools/primitive2dxmldump.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_DRAWINGLAYER_TOOLS_PRIMITIVE2DXMLDUMP_HXX +#define INCLUDED_DRAWINGLAYER_TOOLS_PRIMITIVE2DXMLDUMP_HXX + +#include +#include +#include +#include +#include +#include + +namespace tools { class XmlWriter; } + +namespace drawinglayer +{ + +class DRAWINGLAYER_DLLPUBLIC Primitive2dXmlDump final +{ +private: + std::vector maFilter; + void decomposeAndWrite(const drawinglayer::primitive2d::Primitive2DContainer& rPrimitive2DSequence, tools::XmlWriter& rWriter); + +public: + Primitive2dXmlDump(); + ~Primitive2dXmlDump(); + + /** Dumps the input primitive sequence to xml into a file or memory stream and parses the xml for testing. + * + * if rStreamName is set, then the xml content will be dumped into a file, + * otherwise if the rStreamName is empty, then the content will be dumped + * into a memory stream. + * + */ + xmlDocUniquePtr dumpAndParse(const drawinglayer::primitive2d::Primitive2DContainer& aPrimitive2DSequence, const OUString& rStreamName = OUString()); + + /** Dumps the input primitive sequence to xml into a file. */ + void dump(const drawinglayer::primitive2d::Primitive2DContainer& rPrimitive2DSequence, const OUString& rStreamName); + +}; + +} + +#endif // INCLUDED_DRAWINGLAYER_TOOLS_PRIMITIVE2DXMLDUMP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/AccessibleComponentBase.hxx b/include/editeng/AccessibleComponentBase.hxx new file mode 100644 index 000000000..80b0c2b95 --- /dev/null +++ b/include/editeng/AccessibleComponentBase.hxx @@ -0,0 +1,109 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_ACCESSIBLECOMPONENTBASE_HXX +#define INCLUDED_EDITENG_ACCESSIBLECOMPONENTBASE_HXX + +#include +#include + +namespace com::sun::star::accessibility +{ +class XAccessible; +} + +namespace accessibility +{ +/** @descr + This base class provides (will provide) a base implementation of the + XAccessibleComponent and the + XAccessibleExtendedComponent for all shapes. For + more detailed documentation about the methods refer to the interface + descriptions of XAccessible, + XAccessibleContext, XInterface, + XServiceInfo, and XTypeProvider. +*/ +class EDITENG_DLLPUBLIC AccessibleComponentBase + : public css::accessibility::XAccessibleExtendedComponent +{ +public: + //===== internal ======================================================== + AccessibleComponentBase(); + virtual ~AccessibleComponentBase(); + + //===== XAccessibleComponent ================================================ + + /** The default implementation uses the result of + getBounds to determine whether the given point lies + inside this object. + */ + virtual sal_Bool SAL_CALL containsPoint(const css::awt::Point& aPoint) override; + + /** The default implementation returns an empty reference. + */ + virtual css::uno::Reference + SAL_CALL getAccessibleAtPoint(const css::awt::Point& aPoint) override; + + /** The default implementation returns an empty rectangle. + */ + virtual css::awt::Rectangle SAL_CALL getBounds() override; + + /** The default implementation uses the result of + getBounds to determine the location. + */ + virtual css::awt::Point SAL_CALL getLocation() override; + + /** The default implementation returns an empty position, i.e. the + * result of the default constructor of css::awt::Point. + */ + virtual css::awt::Point SAL_CALL getLocationOnScreen() override; + + /** The default implementation uses the result of + getBounds to determine the size. + */ + virtual css::awt::Size SAL_CALL getSize() override; + + /** The default implementation does nothing. + */ + virtual void SAL_CALL grabFocus() override; + + /** Returns black as the default foreground color. + */ + virtual sal_Int32 SAL_CALL getForeground() override; + + /** Returns white as the default background color. + */ + virtual sal_Int32 SAL_CALL getBackground() override; + + //===== XAccessibleExtendedComponent ==================================== + virtual css::uno::Reference SAL_CALL getFont() override; + virtual OUString SAL_CALL getTitledBorderText() override; + virtual OUString SAL_CALL getToolTipText() override; + + //===== XTypeProvider =================================================== + + /// @throws css::uno::RuntimeException + virtual css::uno::Sequence SAL_CALL getTypes(); +}; + +} // end of namespace accessibility + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/AccessibleContextBase.hxx b/include/editeng/AccessibleContextBase.hxx new file mode 100644 index 000000000..69ef3151c --- /dev/null +++ b/include/editeng/AccessibleContextBase.hxx @@ -0,0 +1,341 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_ACCESSIBLECONTEXTBASE_HXX +#define INCLUDED_EDITENG_ACCESSIBLECONTEXTBASE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::accessibility { class XAccessibleStateSet; } +namespace com::sun::star::accessibility { class XAccessibleRelationSet; } +namespace com::sun::star::accessibility { struct AccessibleEventObject; } +namespace utl { class AccessibleStateSetHelper; } + +namespace accessibility { + +/** @descr + This base class provides an implementation of the + AccessibleContext service. Apart from the + XXAccessible and XAccessibleContextContext + interfaces it supports the XServiceInfo interface. +*/ +class EDITENG_DLLPUBLIC AccessibleContextBase + : public cppu::BaseMutex, + public cppu::WeakComponentImplHelper< + css::accessibility::XAccessible, + css::accessibility::XAccessibleContext, + css::accessibility::XAccessibleEventBroadcaster, + css::lang::XServiceInfo + > +{ +public: + + //===== internal ======================================================== + + /** The origin of the accessible name or description. + */ + enum StringOrigin { + ManuallySet, + FromShape, + AutomaticallyCreated, + NotSet + }; + + AccessibleContextBase ( + css::uno::Reference< css::accessibility::XAccessible> xParent, + const sal_Int16 aRole); + virtual ~AccessibleContextBase() override; + + + /** Call all accessibility event listeners to inform them about the + specified event. + @param aEventId + Id of the event type. + @param rNewValue + New value of the modified attribute. Pass empty structure if + not applicable. + @param rOldValue + Old value of the modified attribute. Pass empty structure if + not applicable. + */ + void CommitChange (sal_Int16 aEventId, + const css::uno::Any& rNewValue, + const css::uno::Any& rOldValue); + + /** Set a new description and, provided that the new name differs from + the old one, broadcast an accessibility event. + @param rsDescription + The new description. + @param eDescriptionOrigin + The origin of the description. This is used to determine + whether the given description overrules the existing one. An + origin with a lower numerical value overrides one with a higher + value. + @throws css::uno::RuntimeException + */ + void SetAccessibleDescription ( + const OUString& rsDescription, + StringOrigin eDescriptionOrigin); + + /** Set a new description and, provided that the new name differs from + the old one, broadcast an accessibility event. + @param rsName + The new name. + @param eNameOrigin + The origin of the name. This is used to determine whether the + given name overrules the existing one. An origin with a lower + numerical value overrides one with a higher value. + @throws css::uno::RuntimeException + */ + void SetAccessibleName ( + const OUString& rsName, + StringOrigin eNameOrigin); + + /** Set the specified state (turn it on) and send events to all + listeners to inform them of the change. + + @param aState + The state to turn on. + + @return + If the specified state changed its value due to this call + is returned, otherwise . + */ + virtual bool SetState (sal_Int16 aState); + + /** Reset the specified state (turn it off) and send events to all + listeners to inform them of the change. + + @param aState + The state to turn off. + + @return + If the specified state changed its value due to this call + is returned, otherwise . + */ + virtual bool ResetState (sal_Int16 aState); + + /** Return the state of the specified state. + + @param aState + The state for which to return its value. + + @return + A value of indicates that the state is set. A + value indicates an unset state. + */ + bool GetState (sal_Int16 aState); + + /** Replace the current relation set with the specified one. Send + events for relations that are not in both sets. + + @param rRelationSet + The new relation set that replaces the old one. + + @throws css::uno::RuntimeException + */ + void SetRelationSet ( + const css::uno::Reference< css::accessibility::XAccessibleRelationSet>& rxRelationSet); + + + //===== XAccessible ===================================================== + + /// Return the XAccessibleContext. + virtual css::uno::Reference< css::accessibility::XAccessibleContext> SAL_CALL + getAccessibleContext() override; + + + //===== XAccessibleContext ============================================== + + /// Return the number of currently visible children. + virtual sal_Int32 SAL_CALL + getAccessibleChildCount() override; + + /// Return the specified child or throw exception. + virtual css::uno::Reference< css::accessibility::XAccessible> SAL_CALL + getAccessibleChild (sal_Int32 nIndex) override; + + /// Return a reference to the parent. + virtual css::uno::Reference< css::accessibility::XAccessible> SAL_CALL + getAccessibleParent() override; + + /// Return this objects index among the parents children. + virtual sal_Int32 SAL_CALL + getAccessibleIndexInParent() override; + + /// Return this object's role. + virtual sal_Int16 SAL_CALL + getAccessibleRole() override; + + /// Return this object's description. + virtual OUString SAL_CALL + getAccessibleDescription() override; + + /// Return the object's current name. + virtual OUString SAL_CALL + getAccessibleName() override; + + /// Return NULL to indicate that an empty relation set. + virtual css::uno::Reference< css::accessibility::XAccessibleRelationSet> SAL_CALL + getAccessibleRelationSet() override; + + /// Return the set of current states. + virtual css::uno::Reference< css::accessibility::XAccessibleStateSet> SAL_CALL + getAccessibleStateSet() override; + + /** Return the parents locale or throw exception if this object has no + parent yet/anymore. + */ + virtual css::lang::Locale SAL_CALL + getLocale() override; + + //===== XAccessibleEventBroadcaster ======================================== + + virtual void SAL_CALL + addAccessibleEventListener ( + const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener) override; + + virtual void SAL_CALL + removeAccessibleEventListener ( + const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener) override; + + + //===== XServiceInfo ==================================================== + + /** Returns an identifier for the implementation of this object. + */ + virtual OUString SAL_CALL + getImplementationName() override; + + /** Return whether the specified service is supported by this class. + */ + virtual sal_Bool SAL_CALL + supportsService (const OUString& sServiceName) override; + + /** Returns a list of all supported services. In this case that is just + the AccessibleContext service. + */ + virtual css::uno::Sequence< OUString> SAL_CALL + getSupportedServiceNames() override; + + + //===== XTypeProvider =================================================== + + /** Returns an implementation id. + */ + virtual css::uno::Sequence SAL_CALL + getImplementationId() override; + + /** Check whether or not the object has been disposed (or is in the + state of being disposed). + + @return TRUE, if the object is disposed or in the course + of being disposed. Otherwise, FALSE is returned. + */ + bool IsDisposed() const; + +protected: + /** The state set. + */ + rtl::Reference<::utl::AccessibleStateSetHelper> mxStateSet; + + /** The relation set. Relations can be set or removed by calling the + AddRelation and RemoveRelation methods. + */ + css::uno::Reference< css::accessibility::XAccessibleRelationSet> mxRelationSet; + + // This method is called from the component helper base class while disposing. + virtual void SAL_CALL disposing() override; + + /** Create the accessible object's name. This method may be called more + than once for a single object. + @return + The returned string is a unique (among the accessible object's + siblings) name. + @throws css::uno::RuntimeException + */ + virtual OUString CreateAccessibleName(); + + void FireEvent (const css::accessibility::AccessibleEventObject& aEvent); + + /** Check whether or not the object has been disposed (or is in the + state of being disposed). If that is the case then + DisposedException is thrown to inform the (indirect) caller of the + foul deed. + @throws css::lang::DisposedException + */ + void ThrowIfDisposed(); + + /** sets the role as returned by XaccessibleContext::getAccessibleRole + +

    Caution: This is only to be used in the construction phase (means within + the ctor or late ctor), never when the object is still alive and part + of an Accessibility hierarchy.

    + */ + void SetAccessibleRole( sal_Int16 _nRole ); + +private: + /// Reference to the parent object. + css::uno::Reference< css::accessibility::XAccessible> mxParent; + + /** Description of this object. This is not a constant because it can + be set from the outside. Furthermore, it changes according to the + draw page's display mode. + */ + OUString msDescription; + + /** The origin of the description is used to determine whether new + descriptions given to the SetAccessibleDescription is ignored or + whether that replaces the old value in msDescription. + */ + StringOrigin meDescriptionOrigin; + + /** Name of this object. It changes according the draw page's + display mode. + */ + OUString msName; + + /** The origin of the name is used to determine whether new + name given to the SetAccessibleName is ignored or + whether that replaces the old value in msName. + */ + StringOrigin meNameOrigin; + + /** client id in the AccessibleEventNotifier queue + */ + sal_uInt32 mnClientId; + + /** This is the role of this object. + */ + sal_Int16 maRole; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/AccessibleEditableTextPara.hxx b/include/editeng/AccessibleEditableTextPara.hxx new file mode 100644 index 000000000..d81cc6cd5 --- /dev/null +++ b/include/editeng/AccessibleEditableTextPara.hxx @@ -0,0 +1,388 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_ACCESSIBLEEDITABLETEXTPARA_HXX +#define INCLUDED_EDITENG_ACCESSIBLEEDITABLETEXTPARA_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +class SvxViewForwarder; +class MapMode; +class SvxAccessibleTextAdapter; +class SvxAccessibleTextEditViewAdapter; +namespace accessibility { class AccessibleImageBullet; } +namespace utl { class AccessibleStateSetHelper; } + +namespace accessibility +{ + typedef ::comphelper::WeakComponentImplHelper< css::accessibility::XAccessible, + css::accessibility::XAccessibleContext, + css::accessibility::XAccessibleComponent, + css::accessibility::XAccessibleEditableText, + css::accessibility::XAccessibleEventBroadcaster, + css::accessibility::XAccessibleTextAttributes, + css::accessibility::XAccessibleHypertext, + css::accessibility::XAccessibleMultiLineText, + css::lang::XServiceInfo > AccessibleTextParaInterfaceBase; + + /** This class implements the actual text paragraphs for the EditEngine/Outliner UAA + */ + class UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) AccessibleEditableTextPara final : public AccessibleTextParaInterfaceBase, private ::comphelper::OCommonAccessibleText + { + + // override OCommonAccessibleText methods + virtual OUString implGetText() override; + virtual css::lang::Locale implGetLocale() override; + virtual void implGetSelection( sal_Int32& nStartIndex, sal_Int32& nEndIndex ) override; + virtual void implGetParagraphBoundary( const OUString& rtext, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ) override; + virtual void implGetLineBoundary( const OUString& rtext, css::i18n::Boundary& rBoundary, sal_Int32 nIndex ) override; + + public: + /// Create accessible object for given parent + // #i27138# + // - add parameter <_pParaManager> (default value NULL) + // This has to be the instance of , which + // created and manages this accessible paragraph. + AccessibleEditableTextPara ( css::uno::Reference< css::accessibility::XAccessible > xParent, + const AccessibleParaManager* _pParaManager = nullptr ); + + virtual ~AccessibleEditableTextPara () override; + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface (const css::uno::Type & rType) override; + + // XAccessible + virtual css::uno::Reference< css::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) override; + + // XAccessibleContext + virtual sal_Int32 SAL_CALL getAccessibleChildCount() override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleParent() override; + virtual sal_Int32 SAL_CALL getAccessibleIndexInParent() override; + virtual sal_Int16 SAL_CALL getAccessibleRole() override; + /// Maximal length of text returned by getAccessibleDescription() + enum { MaxDescriptionLen = 40 }; + virtual OUString SAL_CALL getAccessibleDescription() override; + virtual OUString SAL_CALL getAccessibleName() override; + virtual css::uno::Reference< css::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet() override; + virtual css::uno::Reference< css::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet() override; + virtual css::lang::Locale SAL_CALL getLocale() override; + + // XAccessibleEventBroadcaster + virtual void SAL_CALL addAccessibleEventListener( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener ) override; + virtual void SAL_CALL removeAccessibleEventListener( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener ) override; + + // XAccessibleComponent + virtual sal_Bool SAL_CALL containsPoint( const css::awt::Point& aPoint ) override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const css::awt::Point& aPoint ) override; + virtual css::awt::Rectangle SAL_CALL getBounds( ) override; + virtual css::awt::Point SAL_CALL getLocation( ) override; + virtual css::awt::Point SAL_CALL getLocationOnScreen( ) override; + virtual css::awt::Size SAL_CALL getSize( ) override; + virtual void SAL_CALL grabFocus( ) override; + virtual sal_Int32 SAL_CALL getForeground( ) override; + virtual sal_Int32 SAL_CALL getBackground( ) override; + + // XAccessibleText (this comes implicitly inherited by XAccessibleEditableText AND by XAccessibleMultiLineText) + virtual sal_Int32 SAL_CALL getCaretPosition() override; + virtual sal_Bool SAL_CALL setCaretPosition( sal_Int32 nIndex ) override; + virtual sal_Unicode SAL_CALL getCharacter( sal_Int32 nIndex ) override; + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getCharacterAttributes( sal_Int32 nIndex, const css::uno::Sequence< OUString >& aRequestedAttributes ) override; + virtual css::awt::Rectangle SAL_CALL getCharacterBounds( sal_Int32 nIndex ) override; + virtual sal_Int32 SAL_CALL getCharacterCount() override; + virtual sal_Int32 SAL_CALL getIndexAtPoint( const css::awt::Point& aPoint ) override; + virtual OUString SAL_CALL getSelectedText() override; + virtual sal_Int32 SAL_CALL getSelectionStart() override; + virtual sal_Int32 SAL_CALL getSelectionEnd() override; + virtual sal_Bool SAL_CALL setSelection( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + virtual OUString SAL_CALL getText() override; + virtual OUString SAL_CALL getTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + /// Does not support AccessibleTextType::SENTENCE (missing feature in EditEngine) + virtual css::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + /// Does not support AccessibleTextType::SENTENCE (missing feature in EditEngine) + virtual css::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + /// Does not support AccessibleTextType::SENTENCE (missing feature in EditEngine) + virtual css::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + virtual sal_Bool SAL_CALL copyText( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + virtual sal_Bool SAL_CALL scrollSubstringTo( sal_Int32 nStartIndex, sal_Int32 nEndIndex, css::accessibility::AccessibleScrollType aScrollType) override; + + // XAccessibleEditableText + virtual sal_Bool SAL_CALL cutText( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + virtual sal_Bool SAL_CALL pasteText( sal_Int32 nIndex ) override; + virtual sal_Bool SAL_CALL deleteText( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + virtual sal_Bool SAL_CALL insertText( const OUString& sText, sal_Int32 nIndex ) override; + virtual sal_Bool SAL_CALL replaceText( sal_Int32 nStartIndex, sal_Int32 nEndIndex, const OUString& sReplacement ) override; + virtual sal_Bool SAL_CALL setAttributes( sal_Int32 nStartIndex, sal_Int32 nEndIndex, const css::uno::Sequence< css::beans::PropertyValue >& aAttributeSet ) override; + virtual sal_Bool SAL_CALL setText( const OUString& sText ) override; + + // XAccessibleTextAttributes + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getDefaultAttributes( const css::uno::Sequence< OUString >& RequestedAttributes ) override; + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getRunAttributes( ::sal_Int32 Index, const css::uno::Sequence< OUString >& RequestedAttributes ) override; + + // XAccessibleHypertext + virtual ::sal_Int32 SAL_CALL getHyperLinkCount( ) override; + virtual css::uno::Reference< css::accessibility::XAccessibleHyperlink > SAL_CALL getHyperLink( ::sal_Int32 nLinkIndex ) override; + virtual ::sal_Int32 SAL_CALL getHyperLinkIndex( ::sal_Int32 nCharIndex ) override; + + // XAccessibleMultiLineText + virtual ::sal_Int32 SAL_CALL getLineNumberAtIndex( ::sal_Int32 nIndex ) override; + virtual css::accessibility::TextSegment SAL_CALL getTextAtLineNumber( ::sal_Int32 nLineNo ) override; + virtual css::accessibility::TextSegment SAL_CALL getTextAtLineWithCaret( ) override; + virtual ::sal_Int32 SAL_CALL getNumberOfLineWithCaret( ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService (const OUString& sServiceName) override; + virtual css::uno::Sequence< OUString> SAL_CALL getSupportedServiceNames() override; + + /** Set the current index in the accessibility parent + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + void SetIndexInParent( sal_Int32 nIndex ); + + /** Get the current index in the accessibility parent + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + sal_Int32 GetIndexInParent() const { return mnIndexInParent; } + + /** Set the current paragraph number + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + void SetParagraphIndex( sal_Int32 nIndex ); + + /** Query the current paragraph number (0 - nParas-1) + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + sal_Int32 GetParagraphIndex() const { return mnParagraphIndex; } + + /** Set the edit engine offset + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + void SetEEOffset( const Point& rOffset ); + + /** Set the EditEngine offset + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + void SetEditSource( SvxEditSourceAdapter* pEditSource ); + + /** Dispose this object + + Notifies and deregisters the listeners, drops all references. + */ + void Dispose(); + + /// Calls all Listener objects to tell them the change. Don't hold locks when calling this! + void FireEvent(const sal_Int16 nEventId, const css::uno::Any& rNewValue = css::uno::Any(), const css::uno::Any& rOldValue = css::uno::Any() ) const; + + /// Sets the given state on the internal state set and fires STATE_CHANGE event. Don't hold locks when calling this! + void SetState( const sal_Int16 nStateId ); + /// Unsets the given state on the internal state set and fires STATE_CHANGE event. Don't hold locks when calling this! + void UnSetState( const sal_Int16 nStateId ); + + static tools::Rectangle LogicToPixel( const tools::Rectangle& rRect, const MapMode& rMapMode, SvxViewForwarder const & rForwarder ); + + SvxEditSourceAdapter& GetEditSource() const; + + /** Query the SvxTextForwarder for EditEngine access. + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + SvxAccessibleTextAdapter& GetTextForwarder() const; + + /** Query the SvxViewForwarder for EditEngine access. + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + SvxViewForwarder& GetViewForwarder() const; + + /** Query whether a GetEditViewForwarder( sal_False ) will return a forwarder + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + bool HaveEditView() const; + + /** Query the SvxEditViewForwarder for EditEngine access. + + @attention This method does not lock the SolarMutex, + leaving that to the calling code. This is because only + there potential deadlock situations can be resolved. Thus, + make sure SolarMutex is locked when calling this. + */ + SvxAccessibleTextEditViewAdapter& GetEditViewForwarder( bool bCreate = false ) const; + + /** Send a TEXT_CHANGED event for this paragraph + + This method internally caters for calculating text + differences, and sends the appropriate Anys in the + Accessibility::TEXT_CHANGED event + */ + void TextChanged(); + + private: + AccessibleEditableTextPara( const AccessibleEditableTextPara& ) = delete; + AccessibleEditableTextPara& operator= ( const AccessibleEditableTextPara& ) = delete; + + /** Calculate character range of similar attributes + + @param nStartIndex + Therein, the start of the character range with the same attributes is returned + + @param nEndIndex + Therein, the end (exclusively) of the character range with the same attributes is returned + + @param nIndex + The character index at where to look for similar character attributes + + @return false, if the method was not able to determine the range + */ + bool GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, sal_Int32 nIndex ); + + int getNotifierClientId() const { return mnNotifierClientId; } + + /// Do we have children? This is the case for image bullets + bool HaveChildren(); + + const Point& GetEEOffset() const { return maEEOffset; } + + // Get text from forwarder + OUString GetTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ); + sal_Int32 GetTextLen() const; + + /** Get the current selection of this paragraph + + @return sal_False, if nothing in this paragraph is selected + */ + bool GetSelection(sal_Int32& nStartPos, sal_Int32& nEndPos ); + + /** create selection from Accessible selection. + + */ + ESelection MakeSelection( sal_Int32 nStartEEIndex, sal_Int32 nEndEEIndex ); + ESelection MakeSelection( sal_Int32 nEEIndex ); + ESelection MakeCursor( sal_Int32 nEEIndex ); + + // check whether index value is within permitted range + + /// Check whether 0<=nIndex<=n-1 + void CheckIndex( sal_Int32 nIndex ); + /// Check whether 0<=nIndex<=n + void CheckPosition( sal_Int32 nIndex ); + /// Check whether 0<=nStart<=n and 0<=nEnd<=n + void CheckRange( sal_Int32 nStart, sal_Int32 nEnd ); + + void _correctValues( css::uno::Sequence< css::beans::PropertyValue >& rValues ); + sal_Int32 SkipField(sal_Int32 nIndex, bool bForward); + // get overlapped field, extend return string. Only extend forward for now + void ExtendByField( css::accessibility::TextSegment& Segment ); + OUString GetFieldTypeNameAtIndex(sal_Int32 nIndex); + // the paragraph index in the edit engine (guarded by solar mutex) + sal_Int32 mnParagraphIndex; + + // our current index in the parent (guarded by solar mutex) + sal_Int32 mnIndexInParent; + + // the current edit source (guarded by solar mutex) + SvxEditSourceAdapter* mpEditSource; + + // the possible child (for image bullets, guarded by solar mutex) + typedef WeakCppRef < css::accessibility::XAccessible, AccessibleImageBullet > WeakBullet; + WeakBullet maImageBullet; + + // the last string used for an Accessibility::TEXT_CHANGED event (guarded by solar mutex) + OUString maLastTextString; + + // the offset of the underlying EditEngine from the shape/cell (guarded by solar mutex) + Point maEEOffset; + + // the current state set (updated from SetState/UnSetState and guarded by solar mutex) + rtl::Reference< ::utl::AccessibleStateSetHelper > mxStateSet; + + /// The shape we're the accessible for (unguarded) + css::uno::Reference< css::accessibility::XAccessible > mxParent; + + /// Our listeners (guarded by maMutex) + int mnNotifierClientId; +private: + // Text paragraphs should provide FLOWS_TO and FLOWS_FROM relations (#i27138#) + // the paragraph manager, which created this instance - is NULL, if + // instance isn't created by AccessibleParaManager. + // Needed for method to retrieve predecessor + // paragraph and the successor paragraph. + const AccessibleParaManager* mpParaManager; + }; + +} // end of namespace accessibility + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/AccessibleParaManager.hxx b/include/editeng/AccessibleParaManager.hxx new file mode 100644 index 000000000..0eceac19c --- /dev/null +++ b/include/editeng/AccessibleParaManager.hxx @@ -0,0 +1,272 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_ACCESSIBLEPARAMANAGER_HXX +#define INCLUDED_EDITENG_ACCESSIBLEPARAMANAGER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::accessibility { class XAccessible; } + +class SvxEditSourceAdapter; + +namespace accessibility +{ + class AccessibleEditableTextPara; + + /** Helper class for weak object references plus implementation + + This class combines a weak reference (to facilitate automatic + object disposal if user drops last reference) and hard + reference to the c++ class (for fast access and bypassing of + the UNO interface) + */ + template < class UnoType, class CppType > class WeakCppRef + { + public: + + typedef UnoType UnoInterfaceType; + typedef CppType InterfaceType; + + WeakCppRef() : maWeakRef(), maUnsafeRef( nullptr ) {} + + WeakCppRef(rtl::Reference const & rImpl): + maWeakRef(rImpl.get()), + maUnsafeRef(rImpl.get()) + { + } + + // get object with c++ object and hard reference (which + // prevents the c++ object from destruction during use) + rtl::Reference get() const { + css::uno::Reference ref(maWeakRef); + return ref.is() ? maUnsafeRef : rtl::Reference(); + } + + // default copy constructor and assignment will do + // WeakCppRef( const WeakCppRef& ); + // WeakCppRef& operator= ( const WeakCppRef& ); + + private: + + // the interface, hold weakly + css::uno::WeakReference< UnoInterfaceType > maWeakRef; + + // hard ref to c++ class, _only_ valid if maWeakRef.is() is true + InterfaceType* maUnsafeRef; + }; + + + /** This class manages the paragraphs of an AccessibleTextHelper + + To facilitate automatic deletion of paragraphs no longer used, + this class uses the WeakCppRef helper to hold the objects weakly. + */ + class UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) AccessibleParaManager + { + public: + typedef WeakCppRef < css::accessibility::XAccessible, AccessibleEditableTextPara > WeakPara; + typedef ::std::pair< WeakPara, css::awt::Rectangle > WeakChild; + typedef ::std::pair< css::uno::Reference< + css::accessibility::XAccessible > , css::awt::Rectangle > Child; + typedef ::std::vector< WeakChild > VectorOfChildren; + typedef ::std::vector< sal_Int16 > VectorOfStates; + + AccessibleParaManager(); + ~AccessibleParaManager(); + + /** Sets a vector of additional accessible states. + + The states are passed to every created child object + (text paragraph). The state values are defined in + css::accessibility::AccessibleStateType. + */ + void SetAdditionalChildStates( VectorOfStates&& rChildStates ); + + /** Set the number of paragraphs + + @param nNumPara + The total number of paragraphs the EditEngine currently + has (_not_ the number of currently visible children) + */ + void SetNum( sal_Int32 nNumParas ); + + /** Get the number of paragraphs currently possible */ + sal_Int32 GetNum() const; + + // iterators + VectorOfChildren::iterator begin(); + VectorOfChildren::iterator end(); + + /// Set focus to given child + void SetFocus( sal_Int32 nChild ); + + void FireEvent( sal_Int32 nPara, + const sal_Int16 nEventId ) const; + + static bool IsReferencable(rtl::Reference const & aChild); + bool IsReferencable( sal_Int32 nChild ) const; + static void ShutdownPara( const WeakChild& rChild ); + + Child CreateChild( sal_Int32 nChild, + const css::uno::Reference< css::accessibility::XAccessible >& xFrontEnd, + SvxEditSourceAdapter& rEditSource, + sal_Int32 nParagraphIndex ); + + WeakChild GetChild( sal_Int32 nParagraphIndex ) const; + bool HasCreatedChild( sal_Int32 nParagraphIndex ) const; + + // forwarder to all paragraphs + /// Make all children active and editable (or off) + void SetActive( bool bActive = true ); + /// Set state of all children + void SetState( const sal_Int16 nStateId ); + /// Unset state of all children + void UnSetState( const sal_Int16 nStateId ); + /// Set offset to edit engine for all children + void SetEEOffset ( const Point& rOffset ); + /// Dispose all living children + void Dispose (); + + // forwarder to given paragraphs + + /** Release the given range of paragraphs + + All ranges have the meaning [start,end), similar to STL + + @param nStartPara + Index of paragraph to start with releasing + + @param nEndPara + Index of first paragraph to stop with releasing + */ + void Release( sal_Int32 nStartPara, sal_Int32 nEndPara ); + + /** Fire event for the given range of paragraphs + + All ranges have the meaning [start,end), similar to STL + + @param nStartPara + Index of paragraph to start with event firing + + @param nEndPara + Index of first paragraph to stop with event firing + */ + void FireEvent( sal_Int32 nStartPara, + sal_Int32 nEndPara, + const sal_Int16 nEventId, + const css::uno::Any& rNewValue = css::uno::Any(), + const css::uno::Any& rOldValue = css::uno::Any() ) const; + + /** Functor adapter for ForEach template + + Adapts giving functor such that only the paragraph objects + are accessed and the fact that our children are held + weakly is hidden + + The functor must provide the following method: + void operator() ( AccessibleEditablePara& ) + + */ + template < typename Functor > class WeakChildAdapter + { + public: + WeakChildAdapter( Functor& rFunctor ) : mrFunctor(rFunctor) {} + void operator()( const WeakChild& rPara ) + { + // retrieve hard reference from weak one + auto aHardRef( rPara.first.get() ); + + if( aHardRef.is() ) + mrFunctor( *aHardRef ); + } + + private: + Functor& mrFunctor; + }; + + /** Adapter for unary member functions + + Since STL's binder don't work with const& arguments (and + BOOST's neither, at least on MSVC), have to provide our + own adapter for unary member functions. + + Create with pointer to member function of + AccessibleEditableTextPara and the corresponding argument. + */ + template < typename Argument > class MemFunAdapter + { + public: + typedef void (::accessibility::AccessibleEditableTextPara::*FunctionPointer)( Argument ); + + MemFunAdapter( FunctionPointer aFunPtr, Argument aArg ) : maFunPtr(aFunPtr), maArg(aArg) {} + void operator()( const WeakChild& rPara ) + { + // retrieve hard reference from weak one + auto aHardRef( rPara.first.get() ); + + if( aHardRef.is() ) + (*aHardRef.*maFunPtr)( maArg ); + } + + private: + FunctionPointer maFunPtr; + Argument maArg; + }; + + private: + /// Set state on given child + void SetState( sal_Int32 nChild, const sal_Int16 nStateId ); + /// Unset state on given child + void UnSetState( sal_Int32 nChild, const sal_Int16 nStateId ); + /// Init child with default state (as stored in previous SetFocus and SetActive calls) + void InitChild( AccessibleEditableTextPara& rChild, + SvxEditSourceAdapter& rEditSource, + sal_Int32 nChild, + sal_Int32 nParagraphIndex ) const; + + // vector the size of the paragraph number of the underlying EditEngine + VectorOfChildren maChildren; + + /// Additional states that will be set at every created child object. + VectorOfStates maChildStates; + + // cache EE offset for child creation + Point maEEOffset; + + // which child currently has the focus (-1 for none) + sal_Int32 mnFocusedChild; + + // whether children are active and editable + bool mbActive; + }; + +} // end of namespace accessibility + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/AccessibleSelectionBase.hxx b/include/editeng/AccessibleSelectionBase.hxx new file mode 100644 index 000000000..25746ddc5 --- /dev/null +++ b/include/editeng/AccessibleSelectionBase.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_ACCESSIBLESELECTIONBASE_HXX +#define INCLUDED_EDITENG_ACCESSIBLESELECTIONBASE_HXX + +#include +#include + +namespace accessibility +{ +/** @descr + This base class provides a base implementation of the + XAccessibleSelection interface. + The following methods have to be implemented if this + class is used: + + implGetMutex, + implGetAccessibleContext, + implIsSelected, + implSelect, +*/ + class EDITENG_DLLPUBLIC AccessibleSelectionBase : public ::comphelper::OCommonAccessibleSelection, + public css::accessibility::XAccessibleSelection + { + protected: + + virtual ::osl::Mutex& implGetMutex() = 0; + + public: + + // XAccessibleSelection - default implementations + virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) override; + virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) override; + virtual void SAL_CALL clearAccessibleSelection( ) override; + virtual void SAL_CALL selectAllAccessibleChildren( ) override; + virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) override; + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) override; + virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) override; + + public: + + AccessibleSelectionBase(); + virtual ~AccessibleSelectionBase(); + }; + +} + +#endif // INCLUDED_EDITENG_ACCESSIBLESELECTIONBASE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/AccessibleStaticTextBase.hxx b/include/editeng/AccessibleStaticTextBase.hxx new file mode 100644 index 000000000..2f2095f07 --- /dev/null +++ b/include/editeng/AccessibleStaticTextBase.hxx @@ -0,0 +1,233 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_ACCESSIBLESTATICTEXTBASE_HXX +#define INCLUDED_EDITENG_ACCESSIBLESTATICTEXTBASE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::accessibility { class XAccessible; } + +class SvxEditSource; + +namespace accessibility +{ + + class AccessibleStaticTextBase_Impl; + + typedef ::cppu::ImplHelper2< + css::accessibility::XAccessibleText, + css::accessibility::XAccessibleTextAttributes > AccessibleStaticTextBase_BASE; + + /** Helper class for objects containing EditEngine/Outliner text + + This class implements the XAccessibleText interface for static + text, somewhat similar to the children of the + AccessibleTextHelper class. Currently, there are no children, + i.e. the whole text is presented in one big chunk. This might + change in the future, if a need for image bullets should + arise. These, by convention, would be represented as children + of the text. + + You have to implement the SvxEditSource, SvxTextForwarder, + SvxViewForwarder and SvxEditViewForwarder interfaces in order + to enable your object to cooperate with this + class. SvxTextForwarder encapsulates the fact that text + objects do not necessarily have an EditEngine at their + disposal, SvxViewForwarder and SvxEditViewForwarder do the + same for the document and the edit view. The three mentioned + forwarder objects are not stored by the AccessibleTextHelper, + but fetched every time from the SvxEditSource. So you are best + off making your SvxEditSource::Get*Forwarder methods cache the + current forwarder. + + As this class is intended for static (i.e. non-changing) text + only, no event broadcasting is necessary. You must handle + visibility by yourself, the bounding boxes returned by + getCharacterBounds() are relative to your accessibility + object. + + @attention All public non-UNO methods (those are the uppercase + ones) must not be called with any mutex hold, except when + calling from the main thread (with holds the solar mutex), + unless stated otherwise. This is because they themselves might + need the solar mutex in addition to the object mutex, and the + ordering of the locking must be: first solar mutex, then + object mutex. Furthermore, state change events might be fired + internally. + + @derive Use this class as a base for objects containing static + edit engine text. To avoid overwriting every interface method + to intercept derived object defunc state, just set NULL as the + edit source. Every interface method will then properly throw + an exception. + */ + class EDITENG_DLLPUBLIC AccessibleStaticTextBase : public AccessibleStaticTextBase_BASE + { + + public: + /** Create accessible text object for given edit source + + @param pEditSource + The edit source to use. Object ownership is transferred + from the caller to the callee. The object listens on the + SvxEditSource for object disposal, so no provisions have + to be taken if the caller destroys the data (e.g. the + model) contained in the given SvxEditSource. + + */ + explicit AccessibleStaticTextBase( ::std::unique_ptr< SvxEditSource > && pEditSource ); + + virtual ~AccessibleStaticTextBase(); + + private: + AccessibleStaticTextBase( const AccessibleStaticTextBase& ) = delete; + AccessibleStaticTextBase& operator= ( const AccessibleStaticTextBase& ) = delete; + + public: + + /** Set the current edit source + + @attention You are required to have the solar mutex + locked, when calling this method. Thus, the method should + only be called from the main office thread. + + The EditSource set here is required to broadcast out the + following hints: SfxHintId::EditSourceParasMoved, + SfxHintId::EditSourceSelectionChanged, SfxHintId::TextModified, + SfxHintId::TextParaInserted, SfxHintId::TextParaRemoved, + SfxHintId::TextHeightChanged, + SfxHintId::TextViewScrolled. Otherwise, not all state changes + will get noticed by the accessibility object. Further + more, when the corresponding core object or the model is + dying, either the edit source must be set to NULL or it + has to broadcast a SfxHintId::Dying hint. + + This class does not have a dispose method, since it is not + a UNO component. Nevertheless, it holds C++ references to + several core objects, so you should issue a + SetEditSource(::std::unique_ptr()) in + your dispose() method. + + @param pEditSource + The new edit source to set. Object ownership is transferred + from the caller to the callee. + */ + void SetEditSource( ::std::unique_ptr< SvxEditSource > && pEditSource ); + + /** Set the event source + + @attention When setting a reference here, you should call + Dispose() when you as the owner are disposing, since until + then this object will hold that reference + + @param rInterface + The interface that should be set as the source for + accessibility events sent by this object. + */ + void SetEventSource( const css::uno::Reference< css::accessibility::XAccessible >& rInterface ); + + /** Set offset of EditEngine from parent + + @attention You are required to have the solar mutex + locked, when calling this method. Thus, the method should + only be called from the main office thread. + + If the origin of the underlying EditEngine does + not correspond to the upper left corner of the object + using this class, you have to specify the offset. + + @param rPoint + The offset in screen coordinates (i.e. pixel) + */ + void SetOffset( const Point& rPoint ); + + /** Drop all references and enter disposed state + + This method drops all references to external objects (also + the event source reference set via SetEventSource()) and + sets the object into the disposed state (i.e. the methods + return default values or throw a uno::DisposedException + exception). + */ + void Dispose(); + + // XAccessibleText interface implementation + virtual sal_Int32 SAL_CALL getCaretPosition() override; + virtual sal_Bool SAL_CALL setCaretPosition( sal_Int32 nIndex ) override; + virtual sal_Unicode SAL_CALL getCharacter( sal_Int32 nIndex ) override; + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getCharacterAttributes( sal_Int32 nIndex, const css::uno::Sequence< OUString >& aRequestedAttributes ) override; + virtual css::awt::Rectangle SAL_CALL getCharacterBounds( sal_Int32 nIndex ) override; + virtual sal_Int32 SAL_CALL getCharacterCount() override; + virtual sal_Int32 SAL_CALL getIndexAtPoint( const css::awt::Point& aPoint ) override; + virtual OUString SAL_CALL getSelectedText() override; + virtual sal_Int32 SAL_CALL getSelectionStart() override; + virtual sal_Int32 SAL_CALL getSelectionEnd() override; + /// This will only work with a functional SvxEditViewForwarder, i.e. an EditEngine/Outliner in edit mode + virtual sal_Bool SAL_CALL setSelection( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + virtual OUString SAL_CALL getText() override; + virtual OUString SAL_CALL getTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + /// Does not support AccessibleTextType::SENTENCE (missing feature in EditEngine) + virtual css::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + /// Does not support AccessibleTextType::SENTENCE (missing feature in EditEngine) + virtual css::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + /// Does not support AccessibleTextType::SENTENCE (missing feature in EditEngine) + virtual css::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) override; + /// This will only work with a functional SvxEditViewForwarder, i.e. an EditEngine/Outliner in edit mode + virtual sal_Bool SAL_CALL copyText( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) override; + virtual sal_Bool SAL_CALL scrollSubstringTo( sal_Int32 nStartIndex, sal_Int32 nEndIndex, css::accessibility::AccessibleScrollType aScrollType) override; + + // XAccessibleTextAttributes + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getDefaultAttributes( const css::uno::Sequence< OUString >& RequestedAttributes ) override; + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getRunAttributes( sal_Int32 Index, const css::uno::Sequence< OUString >& RequestedAttributes ) override; + + // child-related methods from XAccessibleContext + /// @throws css::uno::RuntimeException + virtual sal_Int32 SAL_CALL getAccessibleChildCount(); + /// @throws css::lang::IndexOutOfBoundsException + /// @throws css::uno::RuntimeException + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ); + + // child-related methods from XAccessibleComponent + /// @throws css::uno::RuntimeException + virtual css::uno::Reference< css::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const css::awt::Point& aPoint ); + + protected: + tools::Rectangle GetParagraphBoundingBox() const; + + private: + + /// @dyn + const std::unique_ptr< AccessibleStaticTextBase_Impl > mpImpl; + + }; + +} // end of namespace accessibility + +#endif // INCLUDED_EDITENG_ACCESSIBLESTATICTEXTBASE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/CustomPropertyField.hxx b/include/editeng/CustomPropertyField.hxx new file mode 100644 index 000000000..38f3119a0 --- /dev/null +++ b/include/editeng/CustomPropertyField.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_EDITENG_CUSTOMPROPERTYFIELD_HXX +#define INCLUDED_EDITENG_CUSTOMPROPERTYFIELD_HXX + +#include + +#include + +#include + +namespace com::sun::star::document { class XDocumentProperties; } + + +namespace editeng +{ + +class EDITENG_DLLPUBLIC CustomPropertyField final : public SvxFieldData +{ +private: + OUString msName; + OUString msCurrentPresentation; + +public: + explicit CustomPropertyField(OUString aName, OUString aCurrentPresentation); + + virtual ~CustomPropertyField() override; + + virtual sal_Int32 GetClassId() const override { return css::text::textfield::Type::DOCINFO_CUSTOM; } + + virtual std::unique_ptr Clone() const override; + virtual bool operator==(const SvxFieldData&) const override; + + virtual MetaAction* createBeginComment() const override; + + OUString GetFormatted(css::uno::Reference const & xDocumentProperties); + + OUString const & GetName() const + { + return msName; + } + + OUString const & GetCurrentPresentation() const + { + return msCurrentPresentation; + } +}; + +} // end editeng namespace + +#endif // INCLUDED_EDITENG_CUSTOMPROPERTYFIELD_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/SpellPortions.hxx b/include/editeng/SpellPortions.hxx new file mode 100644 index 000000000..75f625438 --- /dev/null +++ b/include/editeng/SpellPortions.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_SPELLPORTIONS_HXX +#define INCLUDED_EDITENG_SPELLPORTIONS_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::linguistic2 { + class XSpellAlternatives; +} + +namespace com::sun::star::linguistic2 { class XProofreader; } + +namespace svx{ +/** contains a portion of text that has the same language attributes applied + and belongs to the same script type. + */ +struct SpellPortion +{ + /** contains the text of the portion. + */ + OUString sText; + /** for wrong words this reference is filled with the error information otherwise + it's an empty reference + */ + css::uno::Reference< css::linguistic2::XSpellAlternatives> xAlternatives; + /** provides access to the grammar checker interface + */ + css::uno::Reference< css::linguistic2::XProofreader > xGrammarChecker; + /** contains the proposed dialog title if the proof reading component provides one. + */ + OUString sDialogTitle; + /** contains the grammar error information + */ + css::linguistic2::SingleProofreadingError aGrammarError; + /** contains the language applied to the text. It has to match the script type. + */ + LanguageType eLanguage; + /** Marks the portion as field, footnote symbol or any other special content that + should be protected against unintentional deletion. + */ + bool bIsField; + /** Marks the portion hidden content that should not be touched by spell checking + and not be removed like redlines. The creator of the portions has to take care + for them. + */ + bool bIsHidden; + /** determines whether the error type is a grammar error + */ + bool bIsGrammarError; + /** marks portion as to-be-ignored. This is a return parameter. + */ + bool bIgnoreThisError; + + SpellPortion() : + eLanguage(LANGUAGE_DONTKNOW), + bIsField(false), + bIsHidden(false), + bIsGrammarError(false), + bIgnoreThisError(false) + { + aGrammarError.nErrorStart = aGrammarError.nErrorLength = aGrammarError.nErrorType = 0; + } +}; +typedef std::vector SpellPortions; +}//namespace svx +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/Trie.hxx b/include/editeng/Trie.hxx new file mode 100644 index 000000000..e6ee659c3 --- /dev/null +++ b/include/editeng/Trie.hxx @@ -0,0 +1,39 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_EDITENG_TRIE_HXX +#define INCLUDED_EDITENG_TRIE_HXX + +#include +#include +#include +#include + +namespace editeng +{ +struct TrieNode; + +class EDITENG_DLLPUBLIC Trie final +{ +private: + std::unique_ptr mRoot; + +public: + Trie(); + ~Trie(); + + void insert(const OUString& sInputString) const; + void findSuggestions(const OUString& sWordPart, std::vector& rSuggestionList) const; + size_t size() const; +}; +} + +#endif // INCLUDED_EDITENG_TRIE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/UnoForbiddenCharsTable.hxx b/include/editeng/UnoForbiddenCharsTable.hxx new file mode 100644 index 000000000..625198dad --- /dev/null +++ b/include/editeng/UnoForbiddenCharsTable.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOFORBIDDENCHARSTABLE_HXX +#define INCLUDED_EDITENG_UNOFORBIDDENCHARSTABLE_HXX + +#include +#include +#include +#include +#include + +class SvxForbiddenCharactersTable; + +class EDITENG_DLLPUBLIC SvxUnoForbiddenCharsTable : public cppu::WeakImplHelper< + css::i18n::XForbiddenCharacters, + css::linguistic2::XSupportedLocales> +{ +protected: + /** this virtual function is called if the forbidden characters are changed */ + virtual void onChange(); + + std::shared_ptr mxForbiddenChars; + +public: + SvxUnoForbiddenCharsTable(std::shared_ptr xForbiddenChars); + virtual ~SvxUnoForbiddenCharsTable() override; + + // XForbiddenCharacters + virtual css::i18n::ForbiddenCharacters SAL_CALL getForbiddenCharacters( const css::lang::Locale& rLocale ) override; + virtual sal_Bool SAL_CALL hasForbiddenCharacters( const css::lang::Locale& rLocale ) override; + virtual void SAL_CALL setForbiddenCharacters( const css::lang::Locale& rLocale, const css::i18n::ForbiddenCharacters& rForbiddenCharacters ) override; + virtual void SAL_CALL removeForbiddenCharacters( const css::lang::Locale& rLocale ) override; + + // XSupportedLocales + virtual css::uno::Sequence< css::lang::Locale > SAL_CALL getLocales( ) override; + virtual sal_Bool SAL_CALL hasLocale( const css::lang::Locale& aLocale ) override; +}; + +#endif // INCLUDED_EDITENG_UNOFORBIDDENCHARSTABLE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/acorrcfg.hxx b/include/editeng/acorrcfg.hxx new file mode 100644 index 000000000..900cc2601 --- /dev/null +++ b/include/editeng/acorrcfg.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_ACORRCFG_HXX +#define INCLUDED_EDITENG_ACORRCFG_HXX + +#include +#include +#include + +class SvxAutoCorrect; +class SvxAutoCorrCfg; + +class SvxBaseAutoCorrCfg final : public utl::ConfigItem +{ +private: + SvxAutoCorrCfg& rParent; + static css::uno::Sequence GetPropertyNames(); + + virtual void ImplCommit() override; + +public: + SvxBaseAutoCorrCfg(SvxAutoCorrCfg& rParent); + virtual ~SvxBaseAutoCorrCfg() override; + + void Load(bool bInit); + virtual void Notify( const css::uno::Sequence& aPropertyNames) override; + using ConfigItem::SetModified; +}; + +class SvxSwAutoCorrCfg final : public utl::ConfigItem +{ +private: + SvxAutoCorrCfg& rParent; + static css::uno::Sequence GetPropertyNames(); + + virtual void ImplCommit() override; + +public: + SvxSwAutoCorrCfg(SvxAutoCorrCfg& rParent); + virtual ~SvxSwAutoCorrCfg() override; + + void Load(bool bInit); + virtual void Notify( const css::uno::Sequence& aPropertyNames) override; + using ConfigItem::SetModified; +}; +/*-------------------------------------------------------------------- + Description: Configuration for Auto Correction + --------------------------------------------------------------------*/ +class EDITENG_DLLPUBLIC SvxAutoCorrCfg final +{ + friend class SvxBaseAutoCorrCfg; + friend class SvxSwAutoCorrCfg; + + std::unique_ptr pAutoCorrect; + + SvxBaseAutoCorrCfg aBaseConfig; + SvxSwAutoCorrCfg aSwConfig; + + // Flags for Autotext: + bool bFileRel; + bool bNetRel; + // Help tip for Autotext as you type + bool bAutoTextTip; + bool bAutoTextPreview; + bool bAutoFmtByInput; + bool bSearchInAllCategories; + +public: + void SetModified() + { + aBaseConfig.SetModified(); + aSwConfig.SetModified(); + } + void Commit() + { + aBaseConfig.Commit(); + aSwConfig.Commit(); + } + + SvxAutoCorrect* GetAutoCorrect() { return pAutoCorrect.get(); } + const SvxAutoCorrect* GetAutoCorrect() const { return pAutoCorrect.get(); } + // the pointer is transferred to the possession of the ConfigItems! + void SetAutoCorrect( SvxAutoCorrect* ); + + bool IsAutoFormatByInput() const { return bAutoFmtByInput; } + void SetAutoFormatByInput( bool bSet ) { bAutoFmtByInput = bSet;aSwConfig.SetModified();} + + bool IsSaveRelFile() const { return bFileRel; } + void SetSaveRelFile( bool bSet ) { bFileRel = bSet; aSwConfig.SetModified(); } + + bool IsSaveRelNet() const { return bNetRel; } + void SetSaveRelNet( bool bSet ) { bNetRel = bSet; aSwConfig.SetModified();} + + bool IsAutoTextTip() const { return bAutoTextTip; } + void SetAutoTextTip(bool bSet ) { bAutoTextTip = bSet;aSwConfig.SetModified();} + + bool IsSearchInAllCategories() const { return bSearchInAllCategories;} + + SvxAutoCorrCfg(); + ~SvxAutoCorrCfg(); + static SvxAutoCorrCfg& Get(); +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/adjustitem.hxx b/include/editeng/adjustitem.hxx new file mode 100644 index 000000000..e27939077 --- /dev/null +++ b/include/editeng/adjustitem.hxx @@ -0,0 +1,143 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_ADJUSTITEM_HXX +#define INCLUDED_EDITENG_ADJUSTITEM_HXX + +#include +#include +#include +#include + +// class SvxAdjustItem --------------------------------------------------- + +/* +[Description] +This item describes the row orientation. +*/ +constexpr sal_uInt16 ADJUST_LASTBLOCK_VERSION = 0x0001; + +class EDITENG_DLLPUBLIC SvxAdjustItem final : public SfxEnumItemInterface +{ + bool bLeft : 1; + bool bRight : 1; + bool bCenter : 1; + bool bBlock : 1; + + // only active when bBlock + bool bOneBlock : 1; + bool bLastCenter : 1; + bool bLastBlock : 1; + +public: + static SfxPoolItem* CreateDefault(); + + SvxAdjustItem( const SvxAdjust eAdjst /*= SvxAdjust::Left*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + virtual sal_uInt16 GetValueCount() const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetEnumValue() const override; + virtual void SetEnumValue( sal_uInt16 nNewVal ) override; + virtual SvxAdjustItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + void SetOneWord( const SvxAdjust eType ) + { + bOneBlock = eType == SvxAdjust::Block; + } + + void SetLastBlock( const SvxAdjust eType ) + { + bLastBlock = eType == SvxAdjust::Block; + bLastCenter = eType == SvxAdjust::Center; + } + + void SetAdjust( const SvxAdjust eType ) + { + bLeft = eType == SvxAdjust::Left; + bRight = eType == SvxAdjust::Right; + bCenter = eType == SvxAdjust::Center; + bBlock = eType == SvxAdjust::Block; + } + + SvxAdjust GetLastBlock() const + { + SvxAdjust eRet = SvxAdjust::Left; + + if ( bLastBlock ) + eRet = SvxAdjust::Block; + else if( bLastCenter ) + eRet = SvxAdjust::Center; + return eRet; + } + + SvxAdjust GetOneWord() const + { + SvxAdjust eRet = SvxAdjust::Left; + + if ( bBlock && bOneBlock ) + eRet = SvxAdjust::Block; + return eRet; + } + + SvxAdjust GetAdjust() const + { + SvxAdjust eRet = SvxAdjust::Left; + + if ( bRight ) + eRet = SvxAdjust::Right; + else if ( bCenter ) + eRet = SvxAdjust::Center; + else if ( bBlock ) + eRet = SvxAdjust::Block; + return eRet; + } + + sal_Int8 GetAsFlags() const + { + sal_Int8 nFlags = 0; + if ( bOneBlock ) + nFlags |= 0x0001; + if ( bLastCenter ) + nFlags |= 0x0002; + if ( bLastBlock ) + nFlags |= 0x0004; + return nFlags; + } + + void SetAsFlags(sal_Int8 nFlags) + { + bOneBlock = 0 != (nFlags & 0x0001); + bLastCenter = 0 != (nFlags & 0x0002); + bLastBlock = 0 != (nFlags & 0x0004); + } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/autokernitem.hxx b/include/editeng/autokernitem.hxx new file mode 100644 index 000000000..798aab04b --- /dev/null +++ b/include/editeng/autokernitem.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_AUTOKERNITEM_HXX +#define INCLUDED_EDITENG_AUTOKERNITEM_HXX + +#include +#include + +// class SvxAutoKernItem ------------------------------------------------- + +/* + [Description] + Attribute for Pair-Kerning. +*/ + +class EDITENG_DLLPUBLIC SvxAutoKernItem final : public SfxBoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxAutoKernItem( const bool bAutoKern /*= false*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxAutoKernItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/blinkitem.hxx b/include/editeng/blinkitem.hxx new file mode 100644 index 000000000..4a4af0e62 --- /dev/null +++ b/include/editeng/blinkitem.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_BLINKITEM_HXX +#define INCLUDED_EDITENG_BLINKITEM_HXX + +#include +#include +#include + +// class SvxBlinkItem ------------------------------------------------- + +/* + [Description] + This item describes, whether to flash. +*/ + +class EDITENG_DLLPUBLIC SvxBlinkItem final : public SfxBoolItem +{ +public: + SvxBlinkItem( const bool bBlink /*= false*/, const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxBlinkItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/borderline.hxx b/include/editeng/borderline.hxx new file mode 100644 index 000000000..6cf1c4512 --- /dev/null +++ b/include/editeng/borderline.hxx @@ -0,0 +1,246 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_BORDERLINE_HXX +#define INCLUDED_EDITENG_BORDERLINE_HXX + +#include + +#include +#include +#include +#include +#include + +class IntlWrapper; + +// Line width defaults in twips +// Thin matches Excel's default values +// See tdf#48622 for the discussion leading to these defaults. +class SvxBorderLineWidth +{ +public: + static const sal_Int16 Hairline = 1; // 0.05pt + static const sal_Int16 VeryThin = 10; // 0.5pt + static const sal_Int16 Thin = 15; // 0.75pt + static const sal_Int16 Medium = 30; // 1.5pt + static const sal_Int16 Thick = 45; // 2.25pt + static const sal_Int16 ExtraThick = 90; // 4.5pt +}; + +// Abstracts over values from css::table::BorderLineStyle +enum class SvxBorderLineStyle : sal_Int16 +{ + /** No border line + */ + NONE = css::table::BorderLineStyle::NONE, + + /** Solid border line. + */ + SOLID = css::table::BorderLineStyle::SOLID, + + /** Dotted border line. + */ + DOTTED = css::table::BorderLineStyle::DOTTED, + + /** Dashed border line. + */ + DASHED = css::table::BorderLineStyle::DASHED, + + /** Double border line. Widths of the lines and the gap are all equal, + and vary equally with the total width. + */ + DOUBLE = css::table::BorderLineStyle::DOUBLE, + + /** Double border line with a thin line outside and a thick line + inside separated by a small gap. + */ + THINTHICK_SMALLGAP = css::table::BorderLineStyle::THINTHICK_SMALLGAP, + + /** Double border line with a thin line outside and a thick line + inside separated by a medium gap. + */ + THINTHICK_MEDIUMGAP = css::table::BorderLineStyle::THINTHICK_MEDIUMGAP, + + /** Double border line with a thin line outside and a thick line + inside separated by a large gap. + */ + THINTHICK_LARGEGAP = css::table::BorderLineStyle::THINTHICK_LARGEGAP, + + /** Double border line with a thick line outside and a thin line + inside separated by a small gap. + */ + THICKTHIN_SMALLGAP = css::table::BorderLineStyle::THICKTHIN_SMALLGAP, + + /** Double border line with a thick line outside and a thin line + inside separated by a medium gap. + */ + THICKTHIN_MEDIUMGAP = css::table::BorderLineStyle::THICKTHIN_MEDIUMGAP, + + /** Double border line with a thick line outside and a thin line + inside separated by a large gap. + */ + THICKTHIN_LARGEGAP = css::table::BorderLineStyle::THICKTHIN_LARGEGAP, + + /** 3D embossed border line. + */ + EMBOSSED = css::table::BorderLineStyle::EMBOSSED, + + /** 3D engraved border line. + */ + ENGRAVED = css::table::BorderLineStyle::ENGRAVED, + + /** Outset border line. + */ + OUTSET = css::table::BorderLineStyle::OUTSET, + + /** Inset border line. + */ + INSET = css::table::BorderLineStyle::INSET, + + /** Finely dashed border line. + */ + FINE_DASHED = css::table::BorderLineStyle::FINE_DASHED, + + /** Double border line consisting of two fixed thin lines separated by a + variable gap. + */ + DOUBLE_THIN = css::table::BorderLineStyle::DOUBLE_THIN, + + /** Line consisting of a repetition of one dash and one dot. */ + DASH_DOT = css::table::BorderLineStyle::DASH_DOT, + + /** Line consisting of a repetition of one dash and 2 dots. */ + DASH_DOT_DOT = css::table::BorderLineStyle::DASH_DOT_DOT, + + /** Maximum valid border line style value. + */ + BORDER_LINE_STYLE_MAX = css::table::BorderLineStyle::BORDER_LINE_STYLE_MAX, +}; + +namespace editeng +{ + +// convert border style between Word formats and LO +SvxBorderLineStyle EDITENG_DLLPUBLIC ConvertBorderStyleFromWord(int); +/// convert border width in twips between Word formats and LO +double EDITENG_DLLPUBLIC ConvertBorderWidthToWord(SvxBorderLineStyle, double); +double EDITENG_DLLPUBLIC ConvertBorderWidthFromWord(SvxBorderLineStyle, + double, int); + +class EDITENG_DLLPUBLIC SvxBorderLine final +{ + tools::Long m_nWidth; + tools::Long m_nMult; + tools::Long m_nDiv; + Color (*m_pColorOutFn)(Color); + Color (*m_pColorInFn)(Color); + Color (*m_pColorGapFn)(Color); + BorderWidthImpl m_aWidthImpl; + Color aColor; + SvxBorderLineStyle m_nStyle; + bool m_bMirrorWidths; + bool m_bUseLeftTop; + +public: + SvxBorderLine( const Color *pCol = nullptr, + tools::Long nWidth = 0, + SvxBorderLineStyle nStyle = SvxBorderLineStyle::SOLID, + Color (*pColorOutFn)( Color ) = &darkColor, + Color (*pColorInFn)( Color ) = &darkColor ); + + const Color& GetColor() const { return aColor; } + Color GetColorOut( bool bLeftOrTop = true ) const; + Color GetColorIn( bool bLeftOrTop = true ) const; + bool HasGapColor() const { return m_pColorGapFn != nullptr; } + Color GetColorGap() const; + + void SetWidth( tools::Long nWidth ); + /** Guess the style and width from the three lines widths values. + + When the value of nStyle is SvxBorderLine::DOUBLE, the style set will be guessed + using the three values to match the best possible style among the following: + - SvxBorderLine::DOUBLE + - SvxBorderLine::THINTHICK_SMALLGAP + - SvxBorderLine::THINTHICK_MEDIUMGAP + - SvxBorderLine::THINTHICK_LARGEGAP + - SvxBorderLine::THICKTHIN_SMALLGAP + - SvxBorderLine::THICKTHIN_MEDIUMGAP + - SvxBorderLine::THICKTHIN_LARGEGAP + + If no styles matches the width, then the width is set to 0. + + There is one known case that could fit several styles: \a nIn = \a nDist = 0.75 pt, + \a nOut = 1.5 pt. This case fits SvxBorderLine::THINTHICK_SMALLGAP and + SvxBorderLine::THINTHICK_MEDIUMGAP with a 1.5 pt width and + SvxBorderLine::THINTHICK_LARGEGAP with a 0.75 pt width. The same case happens + also for thick-thin styles. + + \param nStyle the border style used to guess the width. + \param nIn the width of the inner line in 1th pt + \param nOut the width of the outer line in 1th pt + \param nDist the width of the gap between the lines in 1th pt + */ + void GuessLinesWidths( SvxBorderLineStyle nStyle, sal_uInt16 nOut, sal_uInt16 nIn = 0, sal_uInt16 nDist = 0 ); + + // TODO Hacky method to mirror lines in only a few cases + void SetMirrorWidths() { m_bMirrorWidths = true; } + tools::Long GetWidth( ) const { return m_nWidth; } + sal_uInt16 GetOutWidth() const; + sal_uInt16 GetInWidth() const; + sal_uInt16 GetDistance() const; + + SvxBorderLineStyle GetBorderLineStyle() const { return m_nStyle; } + + void SetColor( const Color &rColor ) { aColor = rColor; } + void SetBorderLineStyle( SvxBorderLineStyle nNew ); + void ScaleMetrics( tools::Long nMult, tools::Long nDiv ); + + bool operator==( const SvxBorderLine &rCmp ) const; + + OUString GetValueString( MapUnit eSrcUnit, MapUnit eDestUnit, + const IntlWrapper* pIntl, + bool bMetricStr = false ) const; + + bool HasPriority( const SvxBorderLine& rOtherLine ) const; + + bool isEmpty() const { + return m_aWidthImpl.IsEmpty() + || m_nStyle == SvxBorderLineStyle::NONE + || m_nWidth == 0; + } + bool isDouble() const { return m_aWidthImpl.IsDouble(); } + sal_uInt16 GetScaledWidth() const { return GetOutWidth() + GetInWidth() + GetDistance(); } + + static Color darkColor( Color aMain ); + static Color lightColor( Color aMain ); + + static Color threeDLightColor( Color aMain ); + static Color threeDMediumColor( Color aMain ); + static Color threeDDarkColor( Color aMain ); + + static BorderWidthImpl getWidthImpl( SvxBorderLineStyle nStyle ); +}; + +EDITENG_DLLPUBLIC bool operator!=( const SvxBorderLine& rLeft, const SvxBorderLine& rRight ); + +} // namespace editeng + +#endif + diff --git a/include/editeng/boxitem.hxx b/include/editeng/boxitem.hxx new file mode 100644 index 000000000..786821c02 --- /dev/null +++ b/include/editeng/boxitem.hxx @@ -0,0 +1,271 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_BOXITEM_HXX +#define INCLUDED_EDITENG_BOXITEM_HXX + +#include +#include +#include +#include +#include + + +namespace editeng { class SvxBorderLine; } + +// class SvxBoxItem ------------------------------------------------------ + +/* [Description] + + This item describes a border attribute + (all four edges and the inward distance) +*/ +enum class SvxBoxItemLine +{ + TOP, BOTTOM, LEFT, RIGHT, LAST = RIGHT +}; + +/** +This version causes SvxBoxItem to store the 4 cell spacing distances separately +when serializing to stream. +*/ +constexpr sal_uInt16 BOX_4DISTS_VERSION = 1; +/** +This version causes SvxBoxItem to store the styles for its border lines when +serializing to stream. +*/ +constexpr sal_uInt16 BOX_BORDER_STYLE_VERSION = 2; + +class EDITENG_DLLPUBLIC SvxBoxItem final : public SfxPoolItem +{ + std::unique_ptr + pTop, + pBottom, + pLeft, + pRight; + sal_Int16 nTopDist, + nBottomDist, + nLeftDist, + nRightDist; + bool bRemoveAdjCellBorder; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxBoxItem( const sal_uInt16 nId ); + SvxBoxItem( const SvxBoxItem &rCpy ); + virtual ~SvxBoxItem() override; + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxBoxItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + const editeng::SvxBorderLine* GetTop() const { return pTop.get(); } + const editeng::SvxBorderLine* GetBottom() const { return pBottom.get(); } + const editeng::SvxBorderLine* GetLeft() const { return pLeft.get(); } + const editeng::SvxBorderLine* GetRight() const { return pRight.get(); } + + const editeng::SvxBorderLine* GetLine( SvxBoxItemLine nLine ) const; + + //The Pointers are being copied! + void SetLine( const editeng::SvxBorderLine* pNew, SvxBoxItemLine nLine ); + + sal_Int16 GetDistance( SvxBoxItemLine nLine, bool bAllowNegative = false ) const; + sal_uInt16 GetSmallestDistance() const; + + bool IsRemoveAdjacentCellBorder() const { return bRemoveAdjCellBorder; } + + void SetDistance( sal_Int16 nNew, SvxBoxItemLine nLine ); + inline void SetAllDistances( sal_Int16 nNew ); + + void SetRemoveAdjacentCellBorder( bool bSet ) { bRemoveAdjCellBorder = bSet; } + + // Line width plus Space plus inward distance + // bEvenIfNoLine = TRUE -> Also return distance, when no Line is set + sal_uInt16 CalcLineWidth( SvxBoxItemLine nLine ) const; + sal_Int16 CalcLineSpace( SvxBoxItemLine nLine, bool bEvenIfNoLine = false, bool bAllowNegative = false ) const; + bool HasBorder( bool bTreatPaddingAsBorder ) const; + static css::table::BorderLine2 SvxLineToLine( const editeng::SvxBorderLine* pLine, bool bConvert ); + static bool LineToSvxLine(const css::table::BorderLine& rLine, editeng::SvxBorderLine& rSvxLine, bool bConvert); + static bool LineToSvxLine(const css::table::BorderLine2& rLine, editeng::SvxBorderLine& rSvxLine, bool bConvert); + + virtual boost::property_tree::ptree dumpAsJSON() const override; + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +inline void SvxBoxItem::SetAllDistances(sal_Int16 const nNew) +{ + nTopDist = nBottomDist = nLeftDist = nRightDist = nNew; +} + +// class SvxBoxInfoItem -------------------------------------------------- + +/* [Description] + + Another item for the border. This item has only limited functionality. + On one hand, the general Dialog is told by the item which options it + should offer. On the other hand, this attribute may be used to + transported the borderline for the inner horizontal and vertical lines. +*/ + +enum class SvxBoxInfoItemLine +{ + HORI, VERT, LAST = VERT +}; + +enum class SvxBoxInfoItemValidFlags +{ + NONE = 0x00, + TOP = 0x01, + BOTTOM = 0x02, + LEFT = 0x04, + RIGHT = 0x08, + HORI = 0x10, + VERT = 0x20, + DISTANCE = 0x40, + DISABLE = 0x80, + ALL = 0xff +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +class EDITENG_DLLPUBLIC SvxBoxInfoItem final : public SfxPoolItem +{ + std::unique_ptr pHori; //inner horizontal Line + std::unique_ptr pVert; //inner vertical Line + + bool mbEnableHor; /// true = Enable inner horizontal line. + bool mbEnableVer; /// true = Enable inner vertical line. + + /* + Currently only for StarWriter: distance inward from SvxBoxItem. If the + distance is requested, then the field for the distance from the dialog be + activated. nDefDist is regarded as a default value. If any line is + turned on or will be turned on it must this distance be set to default. + bMinDist indicates whether the user can go below this value or not. + With NDIST is the current distance from the app transported back and + forth to the dialogue. + */ + + bool bDist :1; // TRUE, Unlock Distance. + bool bMinDist :1; // TRUE, Going below minimum Distance is prohibited + + SvxBoxInfoItemValidFlags nValidFlags; + sal_uInt16 nDefDist; // The default or minimum distance. + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxBoxInfoItem( const sal_uInt16 nId ); + SvxBoxInfoItem( const SvxBoxInfoItem &rCpy ); + virtual ~SvxBoxInfoItem() override; + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual SvxBoxInfoItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + const editeng::SvxBorderLine* GetHori() const { return pHori.get(); } + const editeng::SvxBorderLine* GetVert() const { return pVert.get(); } + + //The Pointers are being copied! + void SetLine( const editeng::SvxBorderLine* pNew, SvxBoxInfoItemLine nLine ); + + bool IsTable() const { return mbEnableHor && mbEnableVer; } + void SetTable( bool bNew ) { mbEnableHor = mbEnableVer = bNew; } + + bool IsHorEnabled() const { return mbEnableHor; } + void EnableHor( bool bEnable ) { mbEnableHor = bEnable; } + bool IsVerEnabled() const { return mbEnableVer; } + void EnableVer( bool bEnable ) { mbEnableVer = bEnable; } + + bool IsDist() const { return bDist; } + void SetDist( bool bNew ) { bDist = bNew; } + bool IsMinDist() const { return bMinDist; } + void SetMinDist( bool bNew ) { bMinDist = bNew; } + sal_uInt16 GetDefDist() const { return nDefDist; } + void SetDefDist( sal_uInt16 nNew ) { nDefDist = nNew; } + + bool IsValid( SvxBoxInfoItemValidFlags nValid ) const + { return bool( nValidFlags & nValid ); } + void SetValid( SvxBoxInfoItemValidFlags nValid, bool bValid = true ) + { + if (bValid) + nValidFlags |= nValid; + else + nValidFlags &= ~nValid; + } + void ResetFlags(); + + virtual boost::property_tree::ptree dumpAsJSON() const override; +}; + +namespace editeng +{ + +void EDITENG_DLLPUBLIC BorderDistanceFromWord(bool bFromEdge, sal_Int32& nMargin, + sal_Int32& nBorderDistance, sal_Int32 nBorderWidth); + +struct EDITENG_DLLPUBLIC WordPageMargins final +{ + sal_uInt16 nLeft = 0; + sal_uInt16 nRight = 0; + sal_uInt16 nTop = 0; + sal_uInt16 nBottom = 0; +}; + +struct EDITENG_DLLPUBLIC WordBorderDistances final +{ + bool bFromEdge = false; + sal_uInt16 nLeft = 0; + sal_uInt16 nRight = 0; + sal_uInt16 nTop = 0; + sal_uInt16 nBottom = 0; +}; + +// Heuristics to decide if we need to use "from edge" offset of borders. All sizes in twips +void EDITENG_DLLPUBLIC BorderDistancesToWord(const SvxBoxItem& rBox, const WordPageMargins& rMargins, + WordBorderDistances& rDistances); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/brushitem.hxx b/include/editeng/brushitem.hxx new file mode 100644 index 000000000..850ff7d10 --- /dev/null +++ b/include/editeng/brushitem.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_BRUSHITEM_HXX +#define INCLUDED_EDITENG_BRUSHITEM_HXX + +#include +#include +#include +#include + +// class SvxBrushItem ---------------------------------------------------- + +class Graphic; +class GraphicObject; + +constexpr sal_uInt16 BRUSH_GRAPHIC_VERSION = 0x0001; + +enum SvxGraphicPosition +{ + GPOS_NONE, + GPOS_LT, GPOS_MT, GPOS_RT, + GPOS_LM, GPOS_MM, GPOS_RM, + GPOS_LB, GPOS_MB, GPOS_RB, + GPOS_AREA, GPOS_TILED +}; + +class EDITENG_DLLPUBLIC SvxBrushItem final : public SfxPoolItem +{ + Color aColor; + Color aFilterColor; + sal_Int32 nShadingValue; + mutable std::unique_ptr xGraphicObject; + sal_Int8 nGraphicTransparency; //contains a percentage value which is + //copied to the GraphicObject when necessary + OUString maStrLink; + OUString maStrFilter; + SvxGraphicPosition eGraphicPos; + mutable bool bLoadAgain; + + void ApplyGraphicTransparency_Impl(); + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxBrushItem( sal_uInt16 nWhich ); + SvxBrushItem( const Color& rColor, sal_uInt16 nWhich ); + + SvxBrushItem( const Graphic& rGraphic, + SvxGraphicPosition ePos, sal_uInt16 nWhich ); + SvxBrushItem( const GraphicObject& rGraphicObj, + SvxGraphicPosition ePos, sal_uInt16 nWhich ); + SvxBrushItem( OUString rLink, OUString aFilter, + SvxGraphicPosition ePos, sal_uInt16 nWhich ); + SvxBrushItem( const SvxBrushItem& ); + SvxBrushItem(SvxBrushItem&&); + + virtual ~SvxBrushItem() override; + +public: + // check if it's used + bool isUsed() const; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual SvxBrushItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + const Color& GetColor() const { return aColor; } + Color& GetColor() { return aColor; } + void SetColor( const Color& rCol) { aColor = rCol; } + + const Color& GetFiltColor() const { return aFilterColor; } + Color& GetFiltColor() { return aFilterColor; } + void SetFiltColor( const Color& rCol) { aFilterColor = rCol; } + + SvxGraphicPosition GetGraphicPos() const { return eGraphicPos; } + + sal_Int32 GetShadingValue() const { return nShadingValue; } + const Graphic* GetGraphic(OUString const & referer = OUString()/*TODO*/) const; + const GraphicObject* GetGraphicObject(OUString const & referer = OUString()/*TODO*/) const; + const OUString& GetGraphicLink() const { return maStrLink; } + const OUString& GetGraphicFilter() const { return maStrFilter; } + + // get graphic transparency in percent + sal_Int8 getGraphicTransparency() const { return nGraphicTransparency; } + void setGraphicTransparency(sal_Int8 nNew); + + void SetGraphicPos( SvxGraphicPosition eNew ); + void SetGraphic( const Graphic& rNew ); + void SetGraphicObject( const GraphicObject& rNewObj ); + void SetGraphicLink( const OUString& rNew ); + void SetGraphicFilter( const OUString& rNew ); + + static sal_Int8 TransparencyToPercent(sal_Int32 nTrans); + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif // INCLUDED_EDITENG_BRUSHITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/bulletitem.hxx b/include/editeng/bulletitem.hxx new file mode 100644 index 000000000..4e736b776 --- /dev/null +++ b/include/editeng/bulletitem.hxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_BULLETITEM_HXX +#define INCLUDED_EDITENG_BULLETITEM_HXX + +#include +#include +#include +#include +#include + + +/** + * these must match the values in css::style::NumberingType + */ +enum class SvxBulletStyle +{ + ABC_BIG = 0, + ABC_SMALL = 1, + ROMAN_BIG = 2, + ROMAN_SMALL = 3, + N123 = 4, + NONE = 5, + BULLET = 6, + BMP = 128 +}; + +// class SvxBulletItem --------------------------------------------------- + +class EDITENG_DLLPUBLIC SvxBulletItem final : public SfxPoolItem +{ + vcl::Font aFont; + std::unique_ptr + pGraphicObject; + OUString aPrevText; + OUString aFollowText; + sal_uInt16 nStart; + SvxBulletStyle nStyle; + tools::Long nWidth; + sal_uInt16 nScale; + sal_Unicode cSymbol; + +public: + explicit SvxBulletItem( sal_uInt16 nWhich ); + SvxBulletItem( const SvxBulletItem& ); + virtual ~SvxBulletItem() override; + + virtual SvxBulletItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + OUString GetFullText() const; + + tools::Long GetWidth() const { return nWidth; } + const vcl::Font& GetFont() const { return aFont; } + + const GraphicObject& GetGraphicObject() const; + void SetGraphicObject( const GraphicObject& rGraphicObject ); + + void SetSymbol( sal_Unicode c) { cSymbol = c; } + + void SetStart( sal_uInt16 nNew ) { nStart = nNew; } + void SetWidth( tools::Long nNew ) { nWidth = nNew; } + void SetStyle( SvxBulletStyle nNew ) { nStyle = nNew; } + void SetFont( const vcl::Font& rNew) { aFont = rNew; } + void SetScale( sal_uInt16 nNew ) { nScale = nNew; } + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + void CopyValidProperties( const SvxBulletItem& rCopyFrom ); +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/charhiddenitem.hxx b/include/editeng/charhiddenitem.hxx new file mode 100644 index 000000000..ed72e08dc --- /dev/null +++ b/include/editeng/charhiddenitem.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CHARHIDDENITEM_HXX +#define INCLUDED_EDITENG_CHARHIDDENITEM_HXX + +#include +#include +#include + +// class SvxCharHiddenItem ------------------------------------------------- +/* [Description] + + This item marks text as hidden +*/ + +class EDITENG_DLLPUBLIC SvxCharHiddenItem final : public SfxBoolItem +{ +public: + SvxCharHiddenItem( const bool bHidden /*= false*/, const sal_uInt16 nId ); + + virtual SvxCharHiddenItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/charreliefitem.hxx b/include/editeng/charreliefitem.hxx new file mode 100644 index 000000000..78b57fa7d --- /dev/null +++ b/include/editeng/charreliefitem.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CHARRELIEFITEM_HXX +#define INCLUDED_EDITENG_CHARRELIEFITEM_HXX + +#include +#include +#include + +// class SvxCharRotateItem ---------------------------------------------- + +/* [Description] + + This item defines a character relief and has currently the values + emboss, relief. +*/ + +class EDITENG_DLLPUBLIC SvxCharReliefItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxCharReliefItem( FontRelief eValue /*= FontRelief::NONE*/, + const sal_uInt16 nId ); + + virtual SvxCharReliefItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetValueCount() const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/charrotateitem.hxx b/include/editeng/charrotateitem.hxx new file mode 100644 index 000000000..49fb3f345 --- /dev/null +++ b/include/editeng/charrotateitem.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CHARROTATEITEM_HXX +#define INCLUDED_EDITENG_CHARROTATEITEM_HXX + +#include +#include +#include + + // class SvxTextRotateItem ---------------------------------------------- + + /* [Description] + + This item defines a text rotation value. Currently + text can only be rotated 90,0 and 270,0 degrees. + + */ + +class EDITENG_DLLPUBLIC SvxTextRotateItem : public SfxUInt16Item +{ +public: + SvxTextRotateItem(Degree10 nValue, const sal_uInt16 nId); + + virtual SvxTextRotateItem* Clone(SfxItemPool *pPool = nullptr) const override; + + virtual bool GetPresentation(SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper&) const override; + + virtual bool QueryValue(css::uno::Any& rVal, sal_uInt8 nMemberId = 0) const override; + virtual bool PutValue(const css::uno::Any& rVal, sal_uInt8 nMemberId) override; + + Degree10 GetValue() const { return Degree10(SfxUInt16Item::GetValue()); } + void SetValue(Degree10 val) { SfxUInt16Item::SetValue(val.get()); } + + // our currently only degree values + void SetTopToBottom() { SetValue(2700_deg10); } + void SetBottomToTop() { SetValue(900_deg10); } + bool IsTopToBottom() const { return 2700_deg10 == GetValue(); } + bool IsBottomToTop() const { return 900_deg10 == GetValue(); } + bool IsVertical() const { return IsTopToBottom() || IsBottomToTop(); } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + + +// class SvxCharRotateItem ---------------------------------------------- + +/* [Description] + + This item defines a character rotation value (0,1 degree). Currently + character can only be rotated 90,0 and 270,0 degrees. + The flag FitToLine defines only a UI-Information - + if true it must also create a SvxCharScaleItem. + +*/ + +class EDITENG_DLLPUBLIC SvxCharRotateItem final : public SvxTextRotateItem +{ + bool bFitToLine; +public: + static SfxPoolItem* CreateDefault(); + + SvxCharRotateItem( Degree10 nValue /*= 0*/, + bool bFitIntoLine /*= false*/, + const sal_uInt16 nId ); + + virtual SvxCharRotateItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool operator==( const SfxPoolItem& ) const override; + + bool IsFitToLine() const { return bFitToLine; } + void SetFitToLine( bool b ) { bFitToLine = b; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/charscaleitem.hxx b/include/editeng/charscaleitem.hxx new file mode 100644 index 000000000..fff4fa8ef --- /dev/null +++ b/include/editeng/charscaleitem.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CHARSCALEITEM_HXX +#define INCLUDED_EDITENG_CHARSCALEITEM_HXX + +#include +#include + +// class SvxCharScaleItem ---------------------------------------------- + +/* [Description] + + This item defines a character scaling factor as percent value. + A value of 100 is identical to 100% and means normal width + A value of 50 is identical to 50% and means 1/2 width. + +*/ + +class EDITENG_DLLPUBLIC SvxCharScaleWidthItem final : public SfxUInt16Item +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxCharScaleWidthItem( sal_uInt16 nValue /*= 100*/, + const sal_uInt16 nId ); + + virtual SvxCharScaleWidthItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/cmapitem.hxx b/include/editeng/cmapitem.hxx new file mode 100644 index 000000000..d0b4bff25 --- /dev/null +++ b/include/editeng/cmapitem.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CMAPITEM_HXX +#define INCLUDED_EDITENG_CMAPITEM_HXX + +#include +#include +#include + +// class SvxCaseMapItem -------------------------------------------------- + +/* [Description] + + This item describe the font type (uppercase, small caps ,...). +*/ + +class EDITENG_DLLPUBLIC SvxCaseMapItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxCaseMapItem( const SvxCaseMap eMap /*= SvxCaseMap::NotMapped*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + SfxEnumItem + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxCaseMapItem* Clone( SfxItemPool *pPool = nullptr ) const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetValueCount() const override; + + // enum cast + SvxCaseMap GetCaseMap() const { return GetValue(); } + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/colritem.hxx b/include/editeng/colritem.hxx new file mode 100644 index 000000000..cbd52844b --- /dev/null +++ b/include/editeng/colritem.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_COLRITEM_HXX +#define INCLUDED_EDITENG_COLRITEM_HXX + +#include +#include +#include + +#define VERSION_USEAUTOCOLOR 1 + +/// Represents theme metadata for a (tools) Color. +class EDITENG_DLLPUBLIC SvxThemeColor +{ + sal_Int16 maThemeIndex; + /// Luminance Modulation: 100th percentage, defaults to 100%. + sal_Int16 mnLumMod; + /// Luminance Offset: 100th percentage, defaults to 0%. + sal_Int16 mnLumOff; + +public: + explicit SvxThemeColor(); + bool operator==(const SvxThemeColor& rThemeColor) const; + + sal_Int16 GetThemeIndex() const + { + return maThemeIndex; + } + + void SetThemeIndex(sal_Int16 nIndex) + { + maThemeIndex = nIndex; + } + + void SetLumMod(sal_Int16 nLumMod) { mnLumMod = nLumMod; } + + sal_Int16 GetLumMod() const { return mnLumMod; } + + void SetLumOff(sal_Int16 nLumOff) { mnLumOff = nLumOff; } + + sal_Int16 GetLumOff() const { return mnLumOff; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const; +}; + +/** SvxColorItem item describes a color. +*/ +class EDITENG_DLLPUBLIC SvxColorItem final : public SfxPoolItem +{ +private: + Color mColor; + SvxThemeColor maThemeColor; + sal_Int16 maTintShade; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxColorItem(const sal_uInt16 nId); + SvxColorItem(const Color& aColor, const sal_uInt16 nId); + virtual ~SvxColorItem() override; + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==(const SfxPoolItem& rPoolItem) const override; + virtual bool QueryValue(css::uno::Any& rVal, sal_uInt8 nMemberId = 0) const override; + virtual bool PutValue(const css::uno::Any& rVal, sal_uInt8 nMemberId) override; + + virtual bool GetPresentation(SfxItemPresentation ePres, + MapUnit eCoreMetric, MapUnit ePresMetric, + OUString &rText, const IntlWrapper& rIntlWrapper) const override; + + virtual SvxColorItem* Clone(SfxItemPool* pPool = nullptr) const override; + SvxColorItem(SvxColorItem const &) = default; // SfxPoolItem copy function dichotomy + + const Color& GetValue() const + { + return mColor; + } + void SetValue(const Color& rNewColor); + + sal_Int16 GetTintOrShade() const + { + return maTintShade; + } + + void SetTintOrShade(sal_Int16 nTintOrShade) + { + maTintShade = nTintOrShade; + } + + SvxThemeColor& GetThemeColor() { return maThemeColor; } + + const SvxThemeColor& GetThemeColor() const { return maThemeColor; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/contouritem.hxx b/include/editeng/contouritem.hxx new file mode 100644 index 000000000..9c67384fc --- /dev/null +++ b/include/editeng/contouritem.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CONTOURITEM_HXX +#define INCLUDED_EDITENG_CONTOURITEM_HXX + +#include +#include + +// class SvxContourItem -------------------------------------------------- + +/* [Description] + This item describes, if contour is employed. +*/ + +class EDITENG_DLLPUBLIC SvxContourItem final : public SfxBoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxContourItem( const bool bContoured /*= false*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxContourItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/crossedoutitem.hxx b/include/editeng/crossedoutitem.hxx new file mode 100644 index 000000000..5d8b18fe2 --- /dev/null +++ b/include/editeng/crossedoutitem.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_CROSSEDOUTITEM_HXX +#define INCLUDED_EDITENG_CROSSEDOUTITEM_HXX + +#include +#include +#include + +// class SvxCrossedOutItem ----------------------------------------------- + +/* [Description] + This item describes, whether and how it is striked out. +*/ + +class EDITENG_DLLPUBLIC SvxCrossedOutItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxCrossedOutItem( const FontStrikeout eSt /*= STRIKEOUT_NONE*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxCrossedOutItem* Clone( SfxItemPool *pPool = nullptr ) const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetValueCount() const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + using SfxEnumItem::SetValue; + + virtual bool HasBoolValue() const override; + virtual bool GetBoolValue() const override; + virtual void SetBoolValue( bool bVal ) override; + + SvxCrossedOutItem(SvxCrossedOutItem const &) = default; // SfxPoolItem copy function dichotomy + + // enum cast + FontStrikeout GetStrikeout() const + { return GetValue(); } +}; + +#endif // INCLUDED_EDITENG_CROSSEDOUTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editdata.hxx b/include/editeng/editdata.hxx new file mode 100644 index 000000000..1762fd86e --- /dev/null +++ b/include/editeng/editdata.hxx @@ -0,0 +1,359 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +// MyEDITDATA, wegen exportiertem EditData +#ifndef INCLUDED_EDITENG_EDITDATA_HXX +#define INCLUDED_EDITENG_EDITDATA_HXX + +#include +#include +#include +#include +#include + +class SfxPoolItem; +template class SvParser; +class SvxFieldItem; +enum class HtmlTokenId : sal_Int16; + +enum class EETextFormat { Text = 0x20, Rtf, Html = 0x32, Xml }; +enum class EEHorizontalTextDirection { Default, L2R, R2L }; +enum class EESelectionMode { Std, Hidden }; + // EESelectionMode::Hidden can be used to completely hide the selection. This is useful e.g. when you want show the selection + // only as long as your window (which the edit view works on) has the focus +enum class EESpellState { Ok, NoSpeller, ErrorFound }; +enum class EEAnchorMode { + TopLeft, TopHCenter, TopRight, + VCenterLeft, VCenterHCenter, VCenterRight, + BottomLeft, BottomHCenter, BottomRight }; + +enum class EERemoveParaAttribsMode { RemoveAll, RemoveCharItems, RemoveNone }; + +#define EE_PARA_NOT_FOUND SAL_MAX_INT32 +#define EE_PARA_APPEND SAL_MAX_INT32 +#define EE_PARA_ALL SAL_MAX_INT32 +#define EE_PARA_MAX_COUNT SAL_MAX_INT32 + +#define EE_INDEX_NOT_FOUND SAL_MAX_INT32 +#define EE_TEXTPOS_ALL SAL_MAX_INT32 +#define EE_TEXTPOS_MAX_COUNT SAL_MAX_INT32 + +EDITENG_DLLPUBLIC extern const size_t EE_APPEND; + +// Error messages for Read / Write Method +#define EE_READWRITE_WRONGFORMAT ErrCode(ErrCodeArea::Svx, 1) + +#define EDITUNDO_REMOVECHARS 100 +#define EDITUNDO_CONNECTPARAS 101 +#define EDITUNDO_MOVEPARAGRAPHS 103 +#define EDITUNDO_INSERTFEATURE 104 +#define EDITUNDO_SPLITPARA 105 +#define EDITUNDO_INSERTCHARS 106 +#define EDITUNDO_DELCONTENT 107 +#define EDITUNDO_DELETE 108 +#define EDITUNDO_CUT 109 +#define EDITUNDO_PASTE 110 +#define EDITUNDO_INSERT 111 +#define EDITUNDO_MOVEPARAS 113 +#define EDITUNDO_PARAATTRIBS 114 +#define EDITUNDO_ATTRIBS 115 +#define EDITUNDO_DRAGANDDROP 116 +#define EDITUNDO_READ 117 +#define EDITUNDO_STYLESHEET 118 +#define EDITUNDO_REPLACEALL 119 +#define EDITUNDO_RESETATTRIBS 121 +#define EDITUNDO_INDENTBLOCK 122 +#define EDITUNDO_UNINDENTBLOCK 123 +#define EDITUNDO_MARKSELECTION 124 +#define EDITUNDO_TRANSLITERATE 125 + +#define EDITUNDO_USER 200 + +struct EPosition +{ + sal_Int32 nPara; + sal_Int32 nIndex; + + EPosition() + : nPara( EE_PARA_NOT_FOUND ) + , nIndex( EE_INDEX_NOT_FOUND ) + { } + + EPosition( sal_Int32 nPara_, sal_Int32 nPos_ ) + : nPara( nPara_ ) + , nIndex( nPos_ ) + { } +}; + +template +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, EPosition const& pos) +{ + return stream << "EPosition(" << pos.nPara << ',' << pos.nIndex << ")"; +} + +struct ESelection +{ + sal_Int32 nStartPara; + sal_Int32 nStartPos; + sal_Int32 nEndPara; + sal_Int32 nEndPos; + + ESelection() : nStartPara( 0 ), nStartPos( 0 ), nEndPara( 0 ), nEndPos( 0 ) {} + + ESelection( sal_Int32 nStPara, sal_Int32 nStPos, + sal_Int32 nEPara, sal_Int32 nEPos ) + : nStartPara( nStPara ) + , nStartPos( nStPos ) + , nEndPara( nEPara ) + , nEndPos( nEPos ) + { } + + ESelection( sal_Int32 nPara, sal_Int32 nPos ) + : nStartPara( nPara ) + , nStartPos( nPos ) + , nEndPara( nPara ) + , nEndPos( nPos ) + { } + + void Adjust(); + bool operator==( const ESelection& rS ) const; + bool operator!=( const ESelection& rS ) const { return !operator==(rS); } + bool operator<( const ESelection& rS ) const; + bool operator>( const ESelection& rS ) const; + bool IsZero() const; + bool HasRange() const; +}; + +template +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, ESelection const& sel) +{ + return stream << "ESelection(" << sel.nStartPara << ',' << sel.nStartPos << "," << sel.nEndPara << "," << sel.nEndPos << ")"; +} + +inline bool ESelection::HasRange() const +{ + return ( nStartPara != nEndPara ) || ( nStartPos != nEndPos ); +} + +inline bool ESelection::IsZero() const +{ + return ( ( nStartPara == 0 ) && ( nStartPos == 0 ) && + ( nEndPara == 0 ) && ( nEndPos == 0 ) ); +} + +inline bool ESelection::operator==( const ESelection& rS ) const +{ + return ( ( nStartPara == rS.nStartPara ) && ( nStartPos == rS.nStartPos ) && + ( nEndPara == rS.nEndPara ) && ( nEndPos == rS.nEndPos ) ); +} + +inline bool ESelection::operator<( const ESelection& rS ) const +{ + // The selection must be adjusted. + // => Only check if end of 'this' < Start of rS + return ( nEndPara < rS.nStartPara ) || + ( ( nEndPara == rS.nStartPara ) && ( nEndPos < rS.nStartPos ) && !operator==( rS ) ); +} + +inline bool ESelection::operator>( const ESelection& rS ) const +{ + // The selection must be adjusted. + // => Only check if end of 'this' < Start of rS + return ( nStartPara > rS.nEndPara ) || + ( ( nStartPara == rS.nEndPara ) && ( nStartPos > rS.nEndPos ) && !operator==( rS ) ); +} + +inline void ESelection::Adjust() +{ + bool bSwap = false; + if ( nStartPara > nEndPara ) + bSwap = true; + else if ( ( nStartPara == nEndPara ) && ( nStartPos > nEndPos ) ) + bSwap = true; + + if ( bSwap ) + { + sal_Int32 nSPar = nStartPara; sal_Int32 nSPos = nStartPos; + nStartPara = nEndPara; nStartPos = nEndPos; + nEndPara = nSPar; nEndPos = nSPos; + } +} + +struct EDITENG_DLLPUBLIC EFieldInfo +{ + std::unique_ptr pFieldItem; + OUString aCurrentText; + EPosition aPosition; + + EFieldInfo(); + EFieldInfo( const SvxFieldItem& rFieldItem, sal_Int32 nPara, sal_Int32 nPos ); + ~EFieldInfo(); + + EFieldInfo( const EFieldInfo& ); + EFieldInfo& operator= ( const EFieldInfo& ); +}; + +enum class RtfImportState { + Start, End, // only pParser, nPara, nIndex + NextToken, UnknownAttr, // nToken+nTokenValue + SetAttr, // pAttrs + InsertText, // aText + InsertPara, // - + }; +enum class HtmlImportState { + Start, End, // only pParser, nPara, nIndex + NextToken, // nToken + SetAttr, // pAttrs + InsertText, // aText + InsertPara, InsertField // - + }; + +struct HtmlImportInfo +{ + SvParser* pParser; + ESelection aSelection; + HtmlImportState eState; + + HtmlTokenId nToken; + + OUString aText; + + HtmlImportInfo( HtmlImportState eState, SvParser* pPrsrs, const ESelection& rSel ); + ~HtmlImportInfo(); +}; + +struct RtfImportInfo +{ + SvParser* pParser; + ESelection aSelection; + RtfImportState eState; + + int nToken; + short nTokenValue; + + RtfImportInfo( RtfImportState eState, SvParser* pPrsrs, const ESelection& rSel ); +}; + +struct ParagraphInfos +{ + ParagraphInfos() + : nFirstLineHeight( 0 ) + , nFirstLineTextHeight ( 0 ) + , nFirstLineMaxAscent( 0 ) + , bValid( false ) + {} + + sal_uInt16 nFirstLineHeight; + sal_uInt16 nFirstLineTextHeight; + sal_uInt16 nFirstLineMaxAscent; + + bool bValid; // A query during formatting is not valid! +}; + +struct EECharAttrib +{ + const SfxPoolItem* pAttr; + + sal_Int32 nStart; + sal_Int32 nEnd; + EECharAttrib(sal_Int32 nSt, sal_Int32 nE, const SfxPoolItem* pA = nullptr) + : pAttr(pA) + , nStart(nSt) + , nEnd(nE) + { + } +}; + +struct MoveParagraphsInfo +{ + sal_Int32 nStartPara; + sal_Int32 nEndPara; + sal_Int32 nDestPara; + + MoveParagraphsInfo( sal_Int32 nS, sal_Int32 nE, sal_Int32 nD ) + { nStartPara = nS; nEndPara = nE; nDestPara = nD; } +}; + +struct PasteOrDropInfos +{ + sal_Int32 nStartPara; + sal_Int32 nEndPara; + + PasteOrDropInfos() : nStartPara(-1), nEndPara(-1) {} +}; + +enum EENotifyType +{ + /// EditEngine text was modified + EE_NOTIFY_TEXTMODIFIED, + + /// A paragraph was inserted into the EditEngine + EE_NOTIFY_PARAGRAPHINSERTED, + + /// A paragraph was removed from the EditEngine + EE_NOTIFY_PARAGRAPHREMOVED, + + /// Multiple paragraphs have been removed from the EditEngine + EE_NOTIFY_PARAGRAPHSMOVED, + + /// The height of at least one paragraph has changed + EE_NOTIFY_TextHeightChanged, + + /// The view area of the EditEngine scrolled + EE_NOTIFY_TEXTVIEWSCROLLED, + + /// The selection and/or the cursor position has changed + EE_NOTIFY_TEXTVIEWSELECTIONCHANGED, + + /// The EditEngine is in a valid state again. Process pending notifications. + EE_NOTIFY_PROCESSNOTIFICATIONS, + + EE_NOTIFY_TEXTVIEWSELECTIONCHANGED_ENDD_PARA +}; + +struct EENotify +{ + EENotifyType eNotificationType; + + sal_Int32 nParagraph; // only valid in PARAGRAPHINSERTED/EE_NOTIFY_PARAGRAPHREMOVED + + sal_Int32 nParam1; + sal_Int32 nParam2; + + EENotify( EENotifyType eType ) + { eNotificationType = eType; nParagraph = EE_PARA_NOT_FOUND; nParam1 = 0; nParam2 = 0; } +}; + +namespace editeng +{ + +struct LanguageSpan +{ + LanguageType nLang = LANGUAGE_DONTKNOW; + sal_Int32 nStart = -1; + sal_Int32 nEnd = -1; +}; + +} + +#endif // INCLUDED_EDITENG_EDITDATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editeng.hxx b/include/editeng/editeng.hxx new file mode 100644 index 000000000..a0ce29ca2 --- /dev/null +++ b/include/editeng/editeng.hxx @@ -0,0 +1,655 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// MyEDITENG, due to exported EditEng +#ifndef INCLUDED_EDITENG_EDITENG_HXX +#define INCLUDED_EDITENG_EDITENG_HXX + +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +template class Link; + +namespace com::sun::star { + namespace linguistic2 { + class XSpellChecker1; + class XHyphenator; + } + namespace datatransfer { + class XTransferable; + } + namespace lang { + struct Locale; + } +} + +namespace svx { +struct SpellPortion; +typedef std::vector SpellPortions; +} + +class SfxUndoManager; +namespace basegfx { class B2DPolyPolygon; } +namespace editeng { + struct MisspellRanges; +} + +class ImpEditEngine; +class EditView; +class OutputDevice; +class SvxFont; +class SfxItemPool; +class SfxStyleSheet; +class SfxStyleSheetPool; +class SvxSearchItem; +class SvxFieldItem; +class MapMode; +class Color; +namespace vcl { class Font; } +class KeyEvent; +class Size; +class Point; +namespace tools { class Rectangle; } +class SvStream; +namespace vcl { class Window; } +class SvKeyValueIterator; +class SvxForbiddenCharactersTable; +class SvxNumberFormat; +class SvxFieldData; +class ContentNode; +class ParaPortion; +class EditSelection; +class EditPaM; +class EditLine; +class InternalEditStatus; +class EditSelectionEngine; +class EditDoc; +class Range; +struct EPaM; +class DeletedNodeInfo; +class ParaPortionList; +enum class CharCompressType; +enum class TransliterationFlags; +class LinkParamNone; + +/** values for: + SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ); +*/ +enum class EditEngineAttribs { + All, /// returns all attributes even when they are not set + OnlyHard /// returns only attributes hard set on portions +}; + +/** values for: + SfxItemSet GetAttribs( sal_Int32 nPara, sal_Int32 nStart, sal_Int32 nEnd, sal_uInt8 nFlags = 0xFF ) const; +*/ +enum class GetAttribsFlags +{ + NONE = 0x00, + STYLESHEET = 0x01, + PARAATTRIBS = 0x02, + CHARATTRIBS = 0x04, + ALL = 0x07, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +enum class SetAttribsMode { + NONE, WholeWord, Edge +}; + +class EDITENG_DLLPUBLIC EditEngine +{ + friend class EditView; + friend class ImpEditView; + friend class Outliner; + friend class TextChainingUtils; + + +public: + typedef std::vector ViewsType; + + EditSelection InsertText( + css::uno::Reference const & rxDataObj, + const OUString& rBaseURL, const EditPaM& rPaM, bool bUseSpecial); + +private: + std::unique_ptr pImpEditEngine; + + EditEngine( const EditEngine& ) = delete; + EditEngine& operator=( const EditEngine& ) = delete; + EDITENG_DLLPRIVATE bool PostKeyEvent( const KeyEvent& rKeyEvent, EditView* pView, vcl::Window const * pFrameWin ); + + EDITENG_DLLPRIVATE void CursorMoved(const ContentNode* pPrevNode); + EDITENG_DLLPRIVATE void CheckIdleFormatter(); + EDITENG_DLLPRIVATE bool IsIdleFormatterActive() const; + EDITENG_DLLPRIVATE ParaPortion* FindParaPortion(ContentNode const * pNode); + EDITENG_DLLPRIVATE const ParaPortion* FindParaPortion(ContentNode const * pNode) const; + EDITENG_DLLPRIVATE const ParaPortion* GetPrevVisPortion(const ParaPortion* pCurPortion) const; + + EDITENG_DLLPRIVATE css::uno::Reference< + css::datatransfer::XTransferable> + CreateTransferable(const EditSelection& rSelection); + + EDITENG_DLLPRIVATE EditPaM EndOfWord(const EditPaM& rPaM); + + EDITENG_DLLPRIVATE EditPaM GetPaM(const Point& aDocPos, bool bSmart = true); + + EDITENG_DLLPRIVATE EditSelection SelectWord( + const EditSelection& rCurSelection, + sal_Int16 nWordType = css::i18n::WordType::ANYWORD_IGNOREWHITESPACES); + + EDITENG_DLLPRIVATE tools::Long GetXPos( + const ParaPortion* pParaPortion, const EditLine* pLine, sal_Int32 nIndex, bool bPreferPortionStart = false) const; + + EDITENG_DLLPRIVATE Range GetLineXPosStartEnd( + const ParaPortion* pParaPortion, const EditLine* pLine) const; + + EDITENG_DLLPRIVATE InternalEditStatus& GetInternalEditStatus(); + + EDITENG_DLLPRIVATE void HandleBeginPasteOrDrop(PasteOrDropInfos& rInfos); + EDITENG_DLLPRIVATE void HandleEndPasteOrDrop(PasteOrDropInfos& rInfos); + EDITENG_DLLPRIVATE bool HasText() const; + EDITENG_DLLPRIVATE const EditSelectionEngine& GetSelectionEngine() const; + EDITENG_DLLPRIVATE void SetInSelectionMode(bool b); + +protected: + + +public: + EditEngine( SfxItemPool* pItemPool ); + virtual ~EditEngine(); + + const SfxItemSet& GetEmptyItemSet() const; + + void SetDefTab( sal_uInt16 nDefTab ); + + void SetRefDevice( OutputDevice* pRefDef ); + OutputDevice* GetRefDevice() const; + + void SetRefMapMode( const MapMode& rMapMode ); + MapMode const & GetRefMapMode() const; + + /// Change the update mode per bUpdate and potentially trigger FormatAndUpdate. + /// bRestoring is used for LOK to update cursor visibility, specifically, + /// when true, it means we are restoring the update mode after internally + /// disabling it (f.e. during SetText to set/delete default text in Impress). + /// @return previous value of update + bool SetUpdateLayout(bool bUpdate, bool bRestoring = false); + bool IsUpdateLayout() const; + + void SetBackgroundColor( const Color& rColor ); + Color const & GetBackgroundColor() const; + Color GetAutoColor() const; + void EnableAutoColor( bool b ); + void ForceAutoColor( bool b ); + bool IsForceAutoColor() const; + + void InsertView(EditView* pEditView, size_t nIndex = EE_APPEND); + EditView* RemoveView( EditView* pEditView ); + void RemoveView(size_t nIndex); + EditView* GetView(size_t nIndex = 0) const; + size_t GetViewCount() const; + bool HasView( EditView* pView ) const; + EditView* GetActiveView() const; + void SetActiveView(EditView* pView); + + void SetPaperSize( const Size& rSize ); + const Size& GetPaperSize() const; + + void SetVertical( bool bVertical ); + bool IsEffectivelyVertical() const; + bool IsTopToBottom() const; + bool GetVertical() const; + void SetRotation(TextRotation nRotation); + TextRotation GetRotation() const; + + void SetTextColumns(sal_Int16 nColumns, sal_Int32 nSpacing); + + void SetFixedCellHeight( bool bUseFixedCellHeight ); + + void SetDefaultHorizontalTextDirection( EEHorizontalTextDirection eHTextDir ); + EEHorizontalTextDirection GetDefaultHorizontalTextDirection() const; + + SvtScriptType GetScriptType( const ESelection& rSelection ) const; + editeng::LanguageSpan GetLanguage(const EditPaM& rPaM) const; + editeng::LanguageSpan GetLanguage( sal_Int32 nPara, sal_Int32 nPos ) const; + + void TransliterateText( const ESelection& rSelection, TransliterationFlags nTransliterationMode ); + EditSelection TransliterateText( const EditSelection& rSelection, TransliterationFlags nTransliterationMode ); + + void SetAsianCompressionMode( CharCompressType nCompression ); + + void SetKernAsianPunctuation( bool bEnabled ); + + void SetAddExtLeading( bool b ); + + void SetPolygon( const basegfx::B2DPolyPolygon& rPolyPolygon ); + void SetPolygon( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::B2DPolyPolygon* pLinePolyPolygon); + void ClearPolygon(); + + const Size& GetMinAutoPaperSize() const; + void SetMinAutoPaperSize( const Size& rSz ); + + const Size& GetMaxAutoPaperSize() const; + void SetMaxAutoPaperSize( const Size& rSz ); + + void SetMinColumnWrapHeight(tools::Long nVal); + + OUString GetText( LineEnd eEnd = LINEEND_LF ) const; + OUString GetText( const ESelection& rSelection ) const; + sal_Int32 GetTextLen() const; + sal_uInt32 GetTextHeight() const; + sal_uInt32 GetTextHeightNTP() const; + sal_uInt32 CalcTextWidth(); + + OUString GetText( sal_Int32 nParagraph ) const; + sal_Int32 GetTextLen( sal_Int32 nParagraph ) const; + sal_uInt32 GetTextHeight( sal_Int32 nParagraph ) const; + + sal_Int32 GetParagraphCount() const; + + sal_Int32 GetLineCount( sal_Int32 nParagraph ) const; + sal_Int32 GetLineLen( sal_Int32 nParagraph, sal_Int32 nLine ) const; + void GetLineBoundaries( /*out*/sal_Int32& rStart, /*out*/sal_Int32& rEnd, sal_Int32 nParagraph, sal_Int32 nLine ) const; + sal_Int32 GetLineNumberAtIndex( sal_Int32 nPara, sal_Int32 nIndex ) const; + sal_uInt32 GetLineHeight( sal_Int32 nParagraph ); + tools::Rectangle GetParaBounds( sal_Int32 nPara ); + ParagraphInfos GetParagraphInfos( sal_Int32 nPara ); + sal_Int32 FindParagraph( tools::Long nDocPosY ); + EPosition FindDocPosition( const Point& rDocPos ) const; + tools::Rectangle GetCharacterBounds( const EPosition& rPos ) const; + + OUString GetWord(sal_Int32 nPara, sal_Int32 nIndex); + + ESelection GetWord( const ESelection& rSelection, sal_uInt16 nWordType ) const; + + void Clear(); + void SetText( const OUString& rStr ); + + std::unique_ptr CreateTextObject(); + std::unique_ptr GetEmptyTextObject() const; + std::unique_ptr CreateTextObject( sal_Int32 nPara, sal_Int32 nParas = 1 ); + std::unique_ptr CreateTextObject( const ESelection& rESelection ); + void SetText( const EditTextObject& rTextObject ); + + void RemoveParagraph(sal_Int32 nPara); + void InsertParagraph(sal_Int32 nPara, const EditTextObject& rTxtObj, const bool bAppend = false); + void InsertParagraph(sal_Int32 nPara, const OUString& rText); + + void SetText(sal_Int32 nPara, const OUString& rText); + + virtual void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& rSet ); + const SfxItemSet& GetParaAttribs( sal_Int32 nPara ) const; + + /// Set attributes from rSet an all characters of nPara. + void SetCharAttribs(sal_Int32 nPara, const SfxItemSet& rSet); + void GetCharAttribs( sal_Int32 nPara, std::vector& rLst ) const; + + SfxItemSet GetAttribs( sal_Int32 nPara, sal_Int32 nStart, sal_Int32 nEnd, GetAttribsFlags nFlags = GetAttribsFlags::ALL ) const; + SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ); + + bool HasParaAttrib( sal_Int32 nPara, sal_uInt16 nWhich ) const; + const SfxPoolItem& GetParaAttrib( sal_Int32 nPara, sal_uInt16 nWhich ) const; + template + const T& GetParaAttrib( sal_Int32 nPara, TypedWhichId nWhich ) const + { + return static_cast(GetParaAttrib(nPara, sal_uInt16(nWhich))); + } + + vcl::Font GetStandardFont( sal_Int32 nPara ); + SvxFont GetStandardSvxFont( sal_Int32 nPara ); + + void RemoveAttribs( const ESelection& rSelection, bool bRemoveParaAttribs, sal_uInt16 nWhich ); + + void ShowParagraph( sal_Int32 nParagraph, bool bShow ); + + SfxUndoManager& GetUndoManager(); + SfxUndoManager* SetUndoManager(SfxUndoManager* pNew); + void UndoActionStart( sal_uInt16 nId ); + void UndoActionStart(sal_uInt16 nId, const ESelection& rSel); + void UndoActionEnd(); + bool IsInUndo() const; + + void EnableUndo( bool bEnable ); + bool IsUndoEnabled() const; + + /** returns the value last used for bTryMerge while calling ImpEditEngine::InsertUndo + This is currently used in a bad but needed hack to get undo actions merged in the + OutlineView in impress. Do not use it unless you want to sell your soul too! */ + bool HasTriedMergeOnLastAddUndo() const; + + void ClearModifyFlag(); + void SetModified(); + bool IsModified() const; + + void SetModifyHdl( const Link& rLink ); + Link const & GetModifyHdl() const; + + bool IsInSelectionMode() const; + + void StripPortions(); + void GetPortions( sal_Int32 nPara, std::vector& rList ); + + tools::Long GetFirstLineStartX( sal_Int32 nParagraph ); + Point GetDocPosTopLeft( sal_Int32 nParagraph ); + Point GetDocPos( const Point& rPaperPos ) const; + bool IsTextPos( const Point& rPaperPos, sal_uInt16 nBorder ); + + // StartDocPos corresponds to VisArea.TopLeft(). + void Draw( OutputDevice& rOutDev, const tools::Rectangle& rOutRect ); + void Draw( OutputDevice& rOutDev, const tools::Rectangle& rOutRect, const Point& rStartDocPos ); + void Draw( OutputDevice& rOutDev, const tools::Rectangle& rOutRect, const Point& rStartDocPos, bool bClip ); + void Draw( OutputDevice& rOutDev, const Point& rStartPos, Degree10 nOrientation = 0_deg10 ); + + ErrCode Read( SvStream& rInput, const OUString& rBaseURL, EETextFormat, SvKeyValueIterator* pHTTPHeaderAttrs = nullptr ); + void Write( SvStream& rOutput, EETextFormat ); + + void SetStatusEventHdl( const Link& rLink ); + Link const & GetStatusEventHdl() const; + + void SetNotifyHdl( const Link& rLink ); + Link const & GetNotifyHdl() const; + + void SetRtfImportHdl( const Link& rLink ); + const Link& GetRtfImportHdl() const; + + void SetHtmlImportHdl( const Link& rLink ); + const Link& GetHtmlImportHdl() const; + + // Do not evaluate font formatting => For Outliner + bool IsFlatMode() const; + void SetFlatMode( bool bFlat ); + + void SetControlWord( EEControlBits nWord ); + EEControlBits GetControlWord() const; + + void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ); + void QuickMarkInvalid( const ESelection& rSel ); + void QuickFormatDoc( bool bFull = false ); + void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ); + void QuickInsertLineBreak( const ESelection& rSel ); + void QuickInsertText(const OUString& rText, const ESelection& rSel); + void QuickDelete( const ESelection& rSel ); + void QuickMarkToBeRepainted( sal_Int32 nPara ); + + void SetGlobalCharStretching( sal_uInt16 nX, sal_uInt16 nY ); + void GetGlobalCharStretching( sal_uInt16& rX, sal_uInt16& rY ) const; + + void SetEditTextObjectPool( SfxItemPool* pPool ); + SfxItemPool* GetEditTextObjectPool() const; + + void SetStyleSheetPool( SfxStyleSheetPool* pSPool ); + SfxStyleSheetPool* GetStyleSheetPool(); + + void SetStyleSheet(const EditSelection& aSel, SfxStyleSheet* pStyle); + void SetStyleSheet( sal_Int32 nPara, SfxStyleSheet* pStyle ); + const SfxStyleSheet* GetStyleSheet( sal_Int32 nPara ) const; + SfxStyleSheet* GetStyleSheet( sal_Int32 nPara ); + + void SetWordDelimiters( const OUString& rDelimiters ); + const OUString& GetWordDelimiters() const; + + void EraseVirtualDevice(); + + void SetSpeller( css::uno::Reference< + css::linguistic2::XSpellChecker1 > const &xSpeller ); + css::uno::Reference< + css::linguistic2::XSpellChecker1 > const & + GetSpeller(); + void SetHyphenator( css::uno::Reference< + css::linguistic2::XHyphenator > const & xHyph ); + + void GetAllMisspellRanges( std::vector& rRanges ) const; + void SetAllMisspellRanges( const std::vector& rRanges ); + + static void SetForbiddenCharsTable(const std::shared_ptr& xForbiddenChars); + + void SetDefaultLanguage( LanguageType eLang ); + LanguageType GetDefaultLanguage() const; + + bool HasOnlineSpellErrors() const; + void CompleteOnlineSpelling(); + + bool ShouldCreateBigTextObject() const; + + // For fast Pre-Test without view: + EESpellState HasSpellErrors(); + void ClearSpellErrors(); + bool HasText( const SvxSearchItem& rSearchItem ); + + //spell and return a sentence + bool SpellSentence(EditView const & rEditView, svx::SpellPortions& rToFill ); + // put spell position to start of current sentence + void PutSpellingToSentenceStart( EditView const & rEditView ); + //applies a changed sentence + void ApplyChangedSentence(EditView const & rEditView, const svx::SpellPortions& rNewPortions, bool bRecheck ); + + // for text conversion (see also HasSpellErrors) + bool HasConvertibleTextPortion( LanguageType nLang ); + virtual bool ConvertNextDocument(); + + bool UpdateFields(); + bool UpdateFieldsOnly(); + void RemoveFields( const std::function& isFieldData = [] (const SvxFieldData* ){return true;} ); + + sal_uInt16 GetFieldCount( sal_Int32 nPara ) const; + EFieldInfo GetFieldInfo( sal_Int32 nPara, sal_uInt16 nField ) const; + + bool IsRightToLeft( sal_Int32 nPara ) const; + + css::uno::Reference< css::datatransfer::XTransferable > + CreateTransferable( const ESelection& rSelection ) const; + + // MT: Can't create new virtual functions like for ParagraphInserted/Deleted, must be compatible in SRC638, change later... + void SetBeginMovingParagraphsHdl( const Link& rLink ); + void SetEndMovingParagraphsHdl( const Link& rLink ); + void SetBeginPasteOrDropHdl( const Link& rLink ); + void SetEndPasteOrDropHdl( const Link& rLink ); + + virtual void PaintingFirstLine(sal_Int32 nPara, const Point& rStartPos, const Point& rOrigin, Degree10 nOrientation, OutputDevice& rOutDev); + virtual void ParagraphInserted( sal_Int32 nNewParagraph ); + virtual void ParagraphDeleted( sal_Int32 nDeletedParagraph ); + virtual void ParagraphConnected( sal_Int32 nLeftParagraph, sal_Int32 nRightParagraph ); + virtual void ParaAttribsChanged( sal_Int32 nParagraph ); + virtual void StyleSheetChanged( SfxStyleSheet* pStyle ); + void ParagraphHeightChanged( sal_Int32 nPara ); + + virtual void DrawingText( const Point& rStartPos, const OUString& rText, + sal_Int32 nTextStart, sal_Int32 nTextLen, + o3tl::span pDXArray, const SvxFont& rFont, + sal_Int32 nPara, sal_uInt8 nRightToLeft, + const EEngineData::WrongSpellVector* pWrongSpellVector, + const SvxFieldData* pFieldData, + bool bEndOfLine, + bool bEndOfParagraph, + const css::lang::Locale* pLocale, + const Color& rOverlineColor, + const Color& rTextLineColor); + + virtual void DrawingTab( const Point& rStartPos, tools::Long nWidth, const OUString& rChar, + const SvxFont& rFont, sal_Int32 nPara, sal_uInt8 nRightToLeft, + bool bEndOfLine, + bool bEndOfParagraph, + const Color& rOverlineColor, + const Color& rTextLineColor); + virtual OUString GetUndoComment( sal_uInt16 nUndoId ) const; + virtual bool SpellNextDocument(); + /** @return true, when click was consumed. false otherwise. */ + virtual bool FieldClicked( const SvxFieldItem& rField ); + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rTxtColor, std::optional& rFldColor ); + + // override this if access to bullet information needs to be provided + virtual const SvxNumberFormat * GetNumberFormat( sal_Int32 nPara ) const; + + virtual tools::Rectangle GetBulletArea( sal_Int32 nPara ); + + static rtl::Reference CreatePool(); + static SfxItemPool& GetGlobalItemPool(); + static bool DoesKeyChangeText( const KeyEvent& rKeyEvent ); + static bool DoesKeyMoveCursor( const KeyEvent& rKeyEvent ); + static bool IsSimpleCharInput( const KeyEvent& rKeyEvent ); + static void SetFontInfoInItemSet( SfxItemSet& rItemSet, const vcl::Font& rFont ); + static void SetFontInfoInItemSet( SfxItemSet& rItemSet, const SvxFont& rFont ); + static vcl::Font CreateFontFromItemSet( const SfxItemSet& rItemSet, SvtScriptType nScriptType ); + static SvxFont CreateSvxFontFromItemSet( const SfxItemSet& rItemSet ); + static bool IsPrintable( sal_Unicode c ) { return ( ( c >= 32 ) && ( c != 127 ) ); } + static bool HasValidData( const css::uno::Reference< css::datatransfer::XTransferable >& rTransferable ); + /** sets a link that is called at the beginning of a drag operation at an edit view */ + void SetBeginDropHdl( const Link& rLink ); + Link const & GetBeginDropHdl() const; + + /** sets a link that is called at the end of a drag operation at an edit view */ + void SetEndDropHdl( const Link& rLink ); + Link const & GetEndDropHdl() const; + + /// specifies if auto-correction should capitalize the first word or not (default is on) + void SetFirstWordCapitalization( bool bCapitalize ); + + /** specifies if auto-correction should replace a leading single quotation + mark (apostrophe) or not (default is on) */ + void SetReplaceLeadingSingleQuotationMark( bool bReplace ); + + EditDoc& GetEditDoc(); + const EditDoc& GetEditDoc() const; + void dumpAsXmlEditDoc(xmlTextWriterPtr pWriter) const; + + ParaPortionList& GetParaPortions(); + const ParaPortionList& GetParaPortions() const; + + bool IsFormatted() const; + bool IsHtmlImportHandlerSet() const; + bool IsRtfImportHandlerSet() const; + bool IsImportRTFStyleSheetsSet() const; + + void CallRtfImportHandler(RtfImportInfo& rInfo); + void CallHtmlImportHandler(HtmlImportInfo& rInfo); + + void ParaAttribsToCharAttribs(ContentNode* pNode); + + EditPaM CreateEditPaM(const EPaM& rEPaM); + EditPaM ConnectParagraphs( + ContentNode* pLeft, ContentNode* pRight, bool bBackward); + + EditPaM InsertField(const EditSelection& rEditSelection, const SvxFieldItem& rFld); + EditPaM InsertText(const EditSelection& aCurEditSelection, const OUString& rStr); + EditSelection InsertText(const EditTextObject& rTextObject, const EditSelection& rSel); + EditPaM InsertParaBreak(const EditSelection& rEditSelection); + EditPaM InsertLineBreak(const EditSelection& rEditSelection); + + EditPaM CursorLeft( + const EditPaM& rPaM, sal_uInt16 nCharacterIteratorMode = css::i18n::CharacterIteratorMode::SKIPCELL); + EditPaM CursorRight( + const EditPaM& rPaM, sal_uInt16 nCharacterIteratorMode = css::i18n::CharacterIteratorMode::SKIPCELL); + + void SeekCursor(ContentNode* pNode, sal_Int32 nPos, SvxFont& rFont); + + EditPaM DeleteSelection(const EditSelection& rSel); + + ESelection CreateESelection(const EditSelection& rSel) const; + EditSelection CreateSelection(const ESelection& rSel); + + const SfxItemSet& GetBaseParaAttribs(sal_Int32 nPara) const; + void SetParaAttribsOnly(sal_Int32 nPara, const SfxItemSet& rSet); + void SetAttribs(const EditSelection& rSel, const SfxItemSet& rSet, SetAttribsMode nSpecial = SetAttribsMode::NONE); + + OUString GetSelected(const EditSelection& rSel) const; + EditPaM DeleteSelected(const EditSelection& rSel); + + SvtScriptType GetScriptType(const EditSelection& rSel) const; + + void RemoveParaPortion(sal_Int32 nNode); + + void SetCallParaInsertedOrDeleted(bool b); + bool IsCallParaInsertedOrDeleted() const; + + void AppendDeletedNodeInfo(DeletedNodeInfo* pInfo); + void UpdateSelections(); + + void InsertContent(ContentNode* pNode, sal_Int32 nPos); + EditPaM SplitContent(sal_Int32 nNode, sal_Int32 nSepPos); + EditPaM ConnectContents(sal_Int32 nLeftNode, bool bBackward); + + void InsertFeature(const EditSelection& rEditSelection, const SfxPoolItem& rItem); + + EditSelection MoveParagraphs(const Range& rParagraphs, sal_Int32 nNewPos); + + void RemoveCharAttribs(sal_Int32 nPara, sal_uInt16 nWhich = 0, bool bRemoveFeatures = false); + void RemoveCharAttribs(const EditSelection& rSel, bool bRemoveParaAttribs, sal_uInt16 nWhich); + void RemoveCharAttribs(const EditSelection& rSel, EERemoveParaAttribsMode eMode, sal_uInt16 nWhich); + + ViewsType& GetEditViews(); + const ViewsType& GetEditViews() const; + + void SetUndoMode(bool b); + void FormatAndLayout(EditView* pCurView, bool bCalledFromUndo = false); + + void Undo(EditView* pView); + void Redo(EditView* pView); + + sal_Int32 GetOverflowingParaNum() const; + sal_Int32 GetOverflowingLineNum() const; + void ClearOverflowingParaNum(); + bool IsPageOverflow(); + + // tdf#132288 By default inserting an attribute beside another that is of + // the same type expands the original instead of inserting another. But the + // spell check dialog doesn't want that behaviour + void DisableAttributeExpanding(); + + // Optimization, if set, formatting will be done only for text lines that fit + // in given paper size and exceeding lines will be ignored. + void EnableSkipOutsideFormat(bool set); + + void SetLOKSpecialPaperSize(const Size& rSize); + const Size& GetLOKSpecialPaperSize() const; + +#ifdef DBG_UTIL + static void DumpData(const EditEngine* pEE, bool bInfoBox); +#endif +}; + +#endif // INCLUDED_EDITENG_EDITENG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editengdllapi.h b/include/editeng/editengdllapi.h new file mode 100644 index 000000000..5d77e453e --- /dev/null +++ b/include/editeng/editengdllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_EDITENGDLLAPI_H +#define INCLUDED_EDITENG_EDITENGDLLAPI_H + +#include + +#if defined(EDITENG_DLLIMPLEMENTATION) +#define EDITENG_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define EDITENG_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define EDITENG_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editerr.hxx b/include/editeng/editerr.hxx new file mode 100644 index 000000000..e88b7b0f1 --- /dev/null +++ b/include/editeng/editerr.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_EDITERR_HXX +#define INCLUDED_EDITENG_EDITERR_HXX + +#include + +#define ERRCODE_SVX_LINGU_LANGUAGENOTEXISTS ErrCode(ErrCodeArea::Svx, 2) +#define ERRCODE_SVX_GRAPHIC_WRONG_FILEFORMAT ErrCode(ErrCodeArea::Svx, ErrCodeClass::Read, 8) + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editids.hrc b/include/editeng/editids.hrc new file mode 100644 index 000000000..a418a3f88 --- /dev/null +++ b/include/editeng/editids.hrc @@ -0,0 +1,162 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_EDITIDS_HRC +#define INCLUDED_EDITENG_EDITIDS_HRC + +#include + +class SfxGrabBagItem; +class SfxUInt16Item; +class SvxBrushItem; +class SvxFontItem; +class SvxKerningItem; +class SvxLanguageItem; +class SvxLineSpacingItem; +class SvxPageModelItem; +class SvxPostureItem; +class SvxTabStopItem; +class SvxUnderlineItem; +class SvxWeightItem; + +/* + These SID_SVX_START entries came from include/svx/svxids.hrc, avoid + accidentally colliding entries with include/svx/svxids.hrc and + include/sfx2/sfxsids.hrc. Only add new SID_SVX_START entries to + include/svx/svxids.hrc +*/ +#define SID_ATTR_BRUSH TypedWhichId( SID_SVX_START + 1 ) +#define SID_ATTR_TABSTOP TypedWhichId( SID_SVX_START + 2 ) +#define SID_ATTR_TABSTOP_DEFAULTS TypedWhichId( SID_SVX_START + 3 ) +#define SID_ATTR_TABSTOP_POS TypedWhichId( SID_SVX_START + 4 ) +#define SID_ATTR_TABSTOP_OFFSET TypedWhichId( SID_SVX_START + 5 ) +#define SID_ATTR_CHAR ( SID_SVX_START + 6 ) +#define SID_ATTR_CHAR_FONT TypedWhichId( SID_SVX_START + 7 ) +#define SID_ATTR_CHAR_POSTURE TypedWhichId( SID_SVX_START + 8 ) +#define SID_ATTR_CHAR_WEIGHT TypedWhichId( SID_SVX_START + 9 ) +#define SID_ATTR_CHAR_SHADOWED ( SID_SVX_START + 10 ) +#define SID_ATTR_CHAR_WORDLINEMODE ( SID_SVX_START + 11 ) +#define SID_ATTR_CHAR_CONTOUR ( SID_SVX_START + 12 ) +#define SID_ATTR_CHAR_STRIKEOUT ( SID_SVX_START + 13 ) +#define SID_ATTR_CHAR_UNDERLINE TypedWhichId( SID_SVX_START + 14 ) +#define SID_ATTR_CHAR_FONTHEIGHT ( SID_SVX_START + 15 ) + // free +#define SID_ATTR_CHAR_COLOR ( SID_SVX_START + 17 ) +#define SID_ATTR_CHAR_KERNING TypedWhichId( SID_SVX_START + 18 ) +#define SID_ATTR_CHAR_CASEMAP ( SID_SVX_START + 19 ) +#define SID_ATTR_CHAR_LANGUAGE ( SID_SVX_START + 20 ) +#define SID_ATTR_CHAR_ESCAPEMENT ( SID_SVX_START + 21 ) +#define SID_ATTR_CHAR_FONTLIST ( SID_SVX_START + 22 ) +#define SID_ATTR_BORDER_OUTER ( SID_SVX_START + 24 ) +#define SID_ATTR_BORDER_SHADOW ( SID_SVX_START + 25 ) +#define SID_ATTR_PARA_ADJUST ( SID_SVX_START + 27 ) +#define SID_ATTR_PARA_ADJUST_LEFT ( SID_SVX_START + 28 ) +#define SID_ATTR_PARA_ADJUST_RIGHT ( SID_SVX_START + 29 ) +#define SID_ATTR_PARA_ADJUST_CENTER ( SID_SVX_START + 30 ) +#define SID_ATTR_PARA_ADJUST_BLOCK ( SID_SVX_START + 31 ) +#define SID_ATTR_PARA_LINESPACE TypedWhichId( SID_SVX_START + 33 ) +#define SID_ATTR_PARA_LINESPACE_10 ( SID_SVX_START + 34 ) +#define SID_ATTR_PARA_LINESPACE_15 ( SID_SVX_START + 35 ) +#define SID_ATTR_PARA_LINESPACE_115 ( SID_SVX_START + 26 ) +#define SID_ATTR_PARA_LINESPACE_20 ( SID_SVX_START + 36 ) +#define SID_ATTR_PARA_PAGEBREAK ( SID_SVX_START + 37 ) +#define SID_ATTR_PARA_HYPHENZONE ( SID_SVX_START + 38 ) +#define SID_ATTR_PARA_SPLIT ( SID_SVX_START + 39 ) +#define SID_ATTR_PARA_ORPHANS ( SID_SVX_START + 40 ) +#define SID_ATTR_PARA_WIDOWS ( SID_SVX_START + 41 ) +#define SID_ATTR_PARA_ULSPACE ( SID_SVX_START + 42 ) +#define SID_ATTR_PARA_LRSPACE ( SID_SVX_START + 43 ) +#define SID_ATTR_PARA_LEFTSPACE ( SID_SVX_START + 44 ) +#define SID_ATTR_PARA_RIGHTSPACE ( SID_SVX_START + 45 ) +#define SID_ATTR_PARA_FIRSTLINESPACE ( SID_SVX_START + 46 ) +#define SID_ATTR_PARA_BELOWSPACE ( SID_SVX_START + 47 ) +#define SID_ATTR_LRSPACE ( SID_SVX_START + 48 ) +#define SID_ATTR_ULSPACE ( SID_SVX_START + 49 ) +#define SID_ATTR_PARA_ABOVESPACE ( SID_SVX_START + 64 ) +#define SID_ATTR_PARA_MODEL TypedWhichId( SID_SVX_START + 65 ) +#define SID_ATTR_PARA_KEEP ( SID_SVX_START + 66 ) +#define SID_ATTR_CHAR_AUTOKERN ( SID_SVX_START + 67 ) +#define SID_HANGING_INDENT ( SID_SVX_START + 68 ) +#define SID_ATTR_PARA_BULLET ( SID_SVX_START + 250 ) +#define SID_ATTR_PARA_OUTLLEVEL ( SID_SVX_START + 300 ) +#define SID_FIELD ( SID_SVX_START + 363 ) // related to EE_FEATURE_FIELD +#define SID_ATTR_PARA_REGISTER ( SID_SVX_START + 413 ) +#define SID_ATTR_PARA_PAGENUM ( SID_SVX_START + 457 ) +#define SID_ATTR_PARA_NUMRULE ( SID_SVX_START + 587 ) +#define SID_ATTR_BRUSH_CHAR ( SID_SVX_START + 591 ) +#define SID_ATTR_NUMBERING_RULE TypedWhichId( SID_SVX_START + 855 ) +#define SID_ATTR_CHAR_CHARSETCOLOR ( SID_SVX_START + 877 ) +#define SID_ATTR_CHAR_CJK_FONT ( SID_SVX_START + 887 ) +#define SID_ATTR_CHAR_CJK_FONTHEIGHT ( SID_SVX_START + 888 ) +#define SID_ATTR_CHAR_CJK_LANGUAGE TypedWhichId( SID_SVX_START + 889 ) +#define SID_ATTR_CHAR_CJK_POSTURE ( SID_SVX_START + 890 ) +#define SID_ATTR_CHAR_CJK_WEIGHT ( SID_SVX_START + 891 ) +#define SID_ATTR_CHAR_CTL_FONT ( SID_SVX_START + 892 ) +#define SID_ATTR_CHAR_CTL_FONTHEIGHT ( SID_SVX_START + 893 ) +#define SID_ATTR_CHAR_CTL_LANGUAGE TypedWhichId( SID_SVX_START + 894 ) +#define SID_ATTR_CHAR_CTL_POSTURE ( SID_SVX_START + 895 ) +#define SID_ATTR_CHAR_CTL_WEIGHT ( SID_SVX_START + 896 ) +#define SID_ATTR_CHAR_TWO_LINES ( SID_SVX_START + 897 ) +#define SID_ATTR_CHAR_CJK_RUBY ( SID_SVX_START + 898 ) +#define SID_ATTR_CHAR_EMPHASISMARK ( SID_SVX_START + 899 ) +#define SID_ATTR_PARA_SCRIPTSPACE ( SID_SVX_START + 901 ) +#define SID_ATTR_PARA_HANGPUNCTUATION ( SID_SVX_START + 902 ) +#define SID_ATTR_PARA_FORBIDDEN_RULES ( SID_SVX_START + 903 ) +#define SID_ATTR_CHAR_VERTICAL ( SID_SVX_START + 905 ) +#define SID_ATTR_CHAR_ROTATED ( SID_SVX_START + 910 ) +#define SID_ATTR_CHAR_SCALEWIDTH ( SID_SVX_START + 911 ) +#define SID_ATTR_CHAR_WIDTH_FIT_TO_LINE ( SID_SVX_START + 919 ) +#define SID_ATTR_CHAR_RELIEF ( SID_SVX_START + 920 ) +#define SID_PARA_VERTALIGN ( SID_SVX_START + 925 ) +#define SID_ATTR_FRAMEDIRECTION ( SID_SVX_START + 944 ) +#define SID_ATTR_PARA_SNAPTOGRID ( SID_SVX_START + 945 ) +#define SID_ATTR_PARA_LRSPACE_VERTICAL ( SID_SVX_START + 947 ) +#define SID_ATTR_PARA_LEFT_TO_RIGHT ( SID_SVX_START + 950 ) +#define SID_ATTR_PARA_RIGHT_TO_LEFT ( SID_SVX_START + 951 ) +#define SID_ATTR_CHAR_HIDDEN ( SID_SVX_START + 989 ) +#define SID_ATTR_CHAR_LATIN_FONT ( SID_SVX_START + 994 ) +#define SID_ATTR_CHAR_LATIN_FONTHEIGHT ( SID_SVX_START + 995 ) +#define SID_ATTR_CHAR_LATIN_LANGUAGE ( SID_SVX_START + 996 ) +#define SID_ATTR_CHAR_LATIN_POSTURE ( SID_SVX_START + 997 ) +#define SID_ATTR_CHAR_LATIN_WEIGHT ( SID_SVX_START + 998 ) +#define SID_ATTR_CHAR_GRABBAG TypedWhichId( SID_SVX_START + 1142 ) +#define SID_ATTR_CHAR_BACK_COLOR ( SID_SVX_START + 1153 ) + +// these ID didn't exist prior to the svx split, add new ids here +#define SID_ATTR_CHAR_OVERLINE ( SID_EDIT_START + 68 ) +#define SID_ATTR_ALIGN_HOR_JUSTIFY_METHOD ( SID_EDIT_START + 69 ) +#define SID_ATTR_ALIGN_VER_JUSTIFY_METHOD ( SID_EDIT_START + 70 ) +#define SID_ATTR_ALIGN_HOR_JUSTIFY ( SID_EDIT_START + 71 ) +#define SID_ATTR_ALIGN_VER_JUSTIFY TypedWhichId( SID_EDIT_START + 72 ) +#define SID_ATTR_PARA_OUTLINE_LEVEL TypedWhichId( SID_EDIT_START + 73 ) +#define SID_ATTR_CHAR_PREVIEW_FONT TypedWhichId( SID_EDIT_START + 74 ) +#define SID_ATTR_CHAR_ENDPREVIEW_FONT TypedWhichId( SID_EDIT_START + 75 ) +#define SID_ATTR_CHAR_BOX ( SID_EDIT_START + 76 ) +#define SID_ATTR_CHAR_SHADOW ( SID_EDIT_START + 77 ) +#define SID_ATTR_PARA_GRABBAG TypedWhichId( SID_EDIT_START + 78 ) + + +#if 95 > (SID_EDIT_END-SID_EDIT_START) +#error Resource-Overflow in #line, #file +#endif + +#endif + +// ******************************************************************* EOF + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editobj.hxx b/include/editeng/editobj.hxx new file mode 100644 index 000000000..5badaf8e8 --- /dev/null +++ b/include/editeng/editobj.hxx @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_EDITOBJ_HXX +#define INCLUDED_EDITENG_EDITOBJ_HXX + +#include +#include +#include +#include + +#include + +#include +#include + +class SfxItemPool; +class SfxItemSet; +class SvxFieldItem; +class SvxFieldData; +enum class OutlinerMode; +struct EECharAttrib; +typedef struct _xmlTextWriter* xmlTextWriterPtr; + +namespace editeng { + +class FieldUpdater; +struct Section; + +} + +namespace svl { + +class SharedString; +class SharedStringPool; + +} + +enum class TextRotation { NONE, TOPTOBOTTOM, BOTTOMTOTOP }; + +class EDITENG_DLLPUBLIC EditTextObject +{ +public: + virtual ~EditTextObject(); + + /** + * Set paragraph strings to the shared string pool. + * + * @param rPool shared string pool. + */ + virtual void NormalizeString( svl::SharedStringPool& rPool ) = 0; + + virtual std::vector GetSharedStrings() const = 0; + + virtual const SfxItemPool* GetPool() const = 0; + virtual OutlinerMode GetUserType() const = 0; // For OutlinerMode, it can however not save in compatible format + virtual void SetUserType( OutlinerMode n ) = 0; + + virtual bool IsEffectivelyVertical() const = 0; + virtual bool GetVertical() const = 0; + virtual bool IsTopToBottom() const = 0; + virtual void SetVertical( bool bVertical ) = 0; + virtual void SetRotation( TextRotation nRotation ) = 0; + virtual TextRotation GetRotation() const = 0; + + virtual SvtScriptType GetScriptType() const = 0; + + virtual std::unique_ptr Clone() const = 0; + + virtual sal_Int32 GetParagraphCount() const = 0; + + virtual OUString GetText(sal_Int32 nPara) const = 0; + + virtual void ClearPortionInfo() = 0; + + virtual bool HasOnlineSpellErrors() const = 0; + + virtual void GetCharAttribs( sal_Int32 nPara, std::vector& rLst ) const = 0; + + virtual bool RemoveCharAttribs( sal_uInt16 nWhich ) = 0; + + /** + * Get all text sections in this content. Sections are non-overlapping + * segments of text split either by paragraph boundaries or format + * boundaries. Each section object contains all applied formats and/or a + * field item. + */ + virtual void GetAllSections( std::vector& rAttrs ) const = 0; + + virtual bool IsFieldObject() const = 0; + virtual const SvxFieldItem* GetField() const = 0; + virtual const SvxFieldData* GetFieldData(sal_Int32 nPara, size_t nPos, sal_Int32 nType) const = 0; + virtual bool HasField( sal_Int32 nType = css::text::textfield::Type::UNSPECIFIED ) const = 0; + + virtual const SfxItemSet& GetParaAttribs(sal_Int32 nPara) const = 0; + + virtual void GetStyleSheet(sal_Int32 nPara, OUString& rName, SfxStyleFamily& eFamily) const = 0; + virtual void SetStyleSheet(sal_Int32 nPara, const OUString& rName, const SfxStyleFamily& eFamily) = 0; + virtual bool ChangeStyleSheets( + std::u16string_view rOldName, SfxStyleFamily eOldFamily, const OUString& rNewName, SfxStyleFamily eNewFamily) = 0; + virtual void ChangeStyleSheetName(SfxStyleFamily eFamily, std::u16string_view rOldName, const OUString& rNewName) = 0; + + virtual editeng::FieldUpdater GetFieldUpdater() = 0; + + virtual bool operator==( const EditTextObject& rCompare ) const = 0; + + /** Compare, ignoring SfxItemPool pointer. + */ + bool Equals( const EditTextObject& rCompare ) const; + + // #i102062# + virtual bool isWrongListEqual(const EditTextObject& rCompare) const = 0; + +#if DEBUG_EDIT_ENGINE + virtual void Dump() const = 0; +#endif + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const = 0; +}; + +#endif // INCLUDED_EDITENG_EDITOBJ_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editrids.hrc b/include/editeng/editrids.hrc new file mode 100644 index 000000000..31ac07a1d --- /dev/null +++ b/include/editeng/editrids.hrc @@ -0,0 +1,318 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_INCLUDE_EDITENG_EDITRIDS_HRC +#define INCLUDED_INCLUDE_EDITENG_EDITRIDS_HRC + +#define NC_(Context, String) TranslateId(Context, reinterpret_cast(u8##String)) + +// enum SvxBreak ------------------------------------------------------------ +#define RID_SVXITEMS_BREAK_NONE NC_("RID_SVXITEMS_BREAK_NONE", "No break") +#define RID_SVXITEMS_BREAK_COLUMN_BEFORE NC_("RID_SVXITEMS_BREAK_COLUMN_BEFORE", "Break before new column") +#define RID_SVXITEMS_BREAK_COLUMN_AFTER NC_("RID_SVXITEMS_BREAK_COLUMN_AFTER", "Break after new column") +#define RID_SVXITEMS_BREAK_COLUMN_BOTH NC_("RID_SVXITEMS_BREAK_COLUMN_BOTH", "Break before and after new column") +#define RID_SVXITEMS_BREAK_PAGE_BEFORE NC_("RID_SVXITEMS_BREAK_PAGE_BEFORE", "Break before new page") +#define RID_SVXITEMS_BREAK_PAGE_AFTER NC_("RID_SVXITEMS_BREAK_PAGE_AFTER", "Break after new page") +#define RID_SVXITEMS_BREAK_PAGE_BOTH NC_("RID_SVXITEMS_BREAK_PAGE_BOTH", "Break before and after new page") + +// enum SvxShadowLocation --------------------------------------------------- +#define RID_SVXITEMS_SHADOW_NONE NC_("RID_SVXITEMS_SHADOW_NONE", "No Shadow") +#define RID_SVXITEMS_SHADOW_TOPLEFT NC_("RID_SVXITEMS_SHADOW_TOPLEFT", "Shadow top left") +#define RID_SVXITEMS_SHADOW_TOPRIGHT NC_("RID_SVXITEMS_SHADOW_TOPRIGHT", "Shadow top right") +#define RID_SVXITEMS_SHADOW_BOTTOMLEFT NC_("RID_SVXITEMS_SHADOW_BOTTOMLEFT", "Shadow bottom left") +#define RID_SVXITEMS_SHADOW_BOTTOMRIGHT NC_("RID_SVXITEMS_SHADOW_BOTTOMRIGHT", "Shadow bottom right") + +// enum ColorName ----------------------------------------------------------- +#define RID_SVXITEMS_COLOR_BLACK NC_("RID_SVXITEMS_COLOR_BLACK", "Black") +#define RID_SVXITEMS_COLOR_BLUE NC_("RID_SVXITEMS_COLOR_BLUE", "Blue") +#define RID_SVXITEMS_COLOR_GREEN NC_("RID_SVXITEMS_COLOR_GREEN", "Green") +#define RID_SVXITEMS_COLOR_CYAN NC_("RID_SVXITEMS_COLOR_CYAN", "Cyan") +#define RID_SVXITEMS_COLOR_RED NC_("RID_SVXITEMS_COLOR_RED", "Red") +#define RID_SVXITEMS_COLOR_MAGENTA NC_("RID_SVXITEMS_COLOR_MAGENTA", "Magenta") +#define RID_SVXITEMS_COLOR_BROWN NC_("RID_SVXITEMS_COLOR_BROWN", "Brown") +#define RID_SVXITEMS_COLOR_GRAY NC_("RID_SVXITEMS_COLOR_GRAY", "Gray") +#define RID_SVXITEMS_COLOR_LIGHTGRAY NC_("RID_SVXITEMS_COLOR_LIGHTGRAY", "Light Gray") +#define RID_SVXITEMS_COLOR_LIGHTBLUE NC_("RID_SVXITEMS_COLOR_LIGHTBLUE", "Light Blue") +#define RID_SVXITEMS_COLOR_LIGHTGREEN NC_("RID_SVXITEMS_COLOR_LIGHTGREEN", "Light Green") +#define RID_SVXITEMS_COLOR_LIGHTCYAN NC_("RID_SVXITEMS_COLOR_LIGHTCYAN", "Light Cyan") +#define RID_SVXITEMS_COLOR_LIGHTRED NC_("RID_SVXITEMS_COLOR_LIGHTRED", "Light Red") +#define RID_SVXITEMS_COLOR_LIGHTMAGENTA NC_("RID_SVXITEMS_COLOR_LIGHTMAGENTA", "Light Magenta") +#define RID_SVXITEMS_COLOR_YELLOW NC_("RID_SVXITEMS_COLOR_YELLOW", "Yellow") +#define RID_SVXITEMS_COLOR_WHITE NC_("RID_SVXITEMS_COLOR_WHITE", "White") + +// enum FontItalic ------------------------------------------------------- +#define RID_SVXITEMS_ITALIC_NONE NC_("RID_SVXITEMS_ITALIC_NONE", "Not Italic") +#define RID_SVXITEMS_ITALIC_OBLIQUE NC_("RID_SVXITEMS_ITALIC_OBLIQUE", "Oblique italic") +#define RID_SVXITEMS_ITALIC_NORMAL NC_("RID_SVXITEMS_ITALIC_NORMAL", "Italic") + +// enum FontWeight ------------------------------------------------------- +#define RID_SVXITEMS_WEIGHT_DONTKNOW NC_("RID_SVXITEMS_WEIGHT_DONTKNOW", "?") +#define RID_SVXITEMS_WEIGHT_THIN NC_("RID_SVXITEMS_WEIGHT_THIN", "thin") +#define RID_SVXITEMS_WEIGHT_ULTRALIGHT NC_("RID_SVXITEMS_WEIGHT_ULTRALIGHT", "ultra thin") +#define RID_SVXITEMS_WEIGHT_LIGHT NC_("RID_SVXITEMS_WEIGHT_LIGHT", "light") +#define RID_SVXITEMS_WEIGHT_SEMILIGHT NC_("RID_SVXITEMS_WEIGHT_SEMILIGHT", "semi light") +#define RID_SVXITEMS_WEIGHT_NORMAL NC_("RID_SVXITEMS_WEIGHT_NORMAL", "normal") +#define RID_SVXITEMS_WEIGHT_MEDIUM NC_("RID_SVXITEMS_WEIGHT_MEDIUM", "medium") +#define RID_SVXITEMS_WEIGHT_SEMIBOLD NC_("RID_SVXITEMS_WEIGHT_SEMIBOLD", "semi bold") +#define RID_SVXITEMS_WEIGHT_BOLD NC_("RID_SVXITEMS_WEIGHT_BOLD", "bold") +#define RID_SVXITEMS_WEIGHT_ULTRABOLD NC_("RID_SVXITEMS_WEIGHT_ULTRABOLD", "ultra bold") +#define RID_SVXITEMS_WEIGHT_BLACK NC_("RID_SVXITEMS_WEIGHT_BLACK", "black") + +// enum FontUnderline - used for underline ------------------------------ +#define RID_SVXITEMS_UL_NONE NC_("RID_SVXITEMS_UL_NONE", "No underline") +#define RID_SVXITEMS_UL_SINGLE NC_("RID_SVXITEMS_UL_SINGLE", "Single underline") +#define RID_SVXITEMS_UL_DOUBLE NC_("RID_SVXITEMS_UL_DOUBLE", "Double underline") +#define RID_SVXITEMS_UL_DOTTED NC_("RID_SVXITEMS_UL_DOTTED", "Dotted underline") +#define RID_SVXITEMS_UL_DONTKNOW NC_("RID_SVXITEMS_UL_DONTKNOW", "Underline") +#define RID_SVXITEMS_UL_DASH NC_("RID_SVXITEMS_UL_DASH", "Underline (dashes)") +#define RID_SVXITEMS_UL_LONGDASH NC_("RID_SVXITEMS_UL_LONGDASH", "Underline (long dashes)") +#define RID_SVXITEMS_UL_DASHDOT NC_("RID_SVXITEMS_UL_DASHDOT", "Underline (dot dash)") +#define RID_SVXITEMS_UL_DASHDOTDOT NC_("RID_SVXITEMS_UL_DASHDOTDOT", "Underline (dot dot dash)") +#define RID_SVXITEMS_UL_SMALLWAVE NC_("RID_SVXITEMS_UL_SMALLWAVE", "Underline (small wave)") +#define RID_SVXITEMS_UL_WAVE NC_("RID_SVXITEMS_UL_WAVE", "Underline (Wave)") +#define RID_SVXITEMS_UL_DOUBLEWAVE NC_("RID_SVXITEMS_UL_DOUBLEWAVE", "Underline (Double wave)") +#define RID_SVXITEMS_UL_BOLD NC_("RID_SVXITEMS_UL_BOLD", "Underlined (Bold)") +#define RID_SVXITEMS_UL_BOLDDOTTED NC_("RID_SVXITEMS_UL_BOLDDOTTED", "Dotted underline (Bold)") +#define RID_SVXITEMS_UL_BOLDDASH NC_("RID_SVXITEMS_UL_BOLDDASH", "Underline (Dash bold)") +#define RID_SVXITEMS_UL_BOLDLONGDASH NC_("RID_SVXITEMS_UL_BOLDLONGDASH", "Underline (long dash, bold)") +#define RID_SVXITEMS_UL_BOLDDASHDOT NC_("RID_SVXITEMS_UL_BOLDDASHDOT", "Underline (dot dash, bold)") +#define RID_SVXITEMS_UL_BOLDDASHDOTDOT NC_("RID_SVXITEMS_UL_BOLDDASHDOTDOT", "Underline (dot dot dash, bold)") +#define RID_SVXITEMS_UL_BOLDWAVE NC_("RID_SVXITEMS_UL_BOLDWAVE", "Underline (wave, bold)") + +// enum FontUnderline - used for overline ------------------------------- +#define RID_SVXITEMS_OL_NONE NC_("RID_SVXITEMS_OL_NONE", "No overline") +#define RID_SVXITEMS_OL_SINGLE NC_("RID_SVXITEMS_OL_SINGLE", "Single overline") +#define RID_SVXITEMS_OL_DOUBLE NC_("RID_SVXITEMS_OL_DOUBLE", "Double overline") +#define RID_SVXITEMS_OL_DOTTED NC_("RID_SVXITEMS_OL_DOTTED", "Dotted overline") +#define RID_SVXITEMS_OL_DONTKNOW NC_("RID_SVXITEMS_OL_DONTKNOW", "Overline") +#define RID_SVXITEMS_OL_DASH NC_("RID_SVXITEMS_OL_DASH", "Overline (dashes)") +#define RID_SVXITEMS_OL_LONGDASH NC_("RID_SVXITEMS_OL_LONGDASH", "Overline (long dashes)") +#define RID_SVXITEMS_OL_DASHDOT NC_("RID_SVXITEMS_OL_DASHDOT", "Overline (dot dash)") +#define RID_SVXITEMS_OL_DASHDOTDOT NC_("RID_SVXITEMS_OL_DASHDOTDOT", "Overline (dot dot dash)") +#define RID_SVXITEMS_OL_SMALLWAVE NC_("RID_SVXITEMS_OL_SMALLWAVE", "Overline (small wave)") +#define RID_SVXITEMS_OL_WAVE NC_("RID_SVXITEMS_OL_WAVE", "Overline (Wave)") +#define RID_SVXITEMS_OL_DOUBLEWAVE NC_("RID_SVXITEMS_OL_DOUBLEWAVE", "Overline (Double wave)") +#define RID_SVXITEMS_OL_BOLD NC_("RID_SVXITEMS_OL_BOLD", "Overlined (Bold)") +#define RID_SVXITEMS_OL_BOLDDOTTED NC_("RID_SVXITEMS_OL_BOLDDOTTED", "Dotted overline (Bold)") +#define RID_SVXITEMS_OL_BOLDDASH NC_("RID_SVXITEMS_OL_BOLDDASH", "Overline (Dash bold)") +#define RID_SVXITEMS_OL_BOLDLONGDASH NC_("RID_SVXITEMS_OL_BOLDLONGDASH", "Overline (long dash, bold)") +#define RID_SVXITEMS_OL_BOLDDASHDOT NC_("RID_SVXITEMS_OL_BOLDDASHDOT", "Overline (dot dash, bold)") +#define RID_SVXITEMS_OL_BOLDDASHDOTDOT NC_("RID_SVXITEMS_OL_BOLDDASHDOTDOT", "Overline (dot dot dash, bold)") +#define RID_SVXITEMS_OL_BOLDWAVE NC_("RID_SVXITEMS_OL_BOLDWAVE", "Overline (wave, bold)") + +// enum FontStrikeout ---------------------------------------------------- +#define RID_SVXITEMS_STRIKEOUT_NONE NC_("RID_SVXITEMS_STRIKEOUT_NONE", "No strikethrough") +#define RID_SVXITEMS_STRIKEOUT_SINGLE NC_("RID_SVXITEMS_STRIKEOUT_SINGLE", "Single strikethrough") +#define RID_SVXITEMS_STRIKEOUT_DOUBLE NC_("RID_SVXITEMS_STRIKEOUT_DOUBLE", "Double strikethrough") +#define RID_SVXITEMS_STRIKEOUT_DONTKNOW NC_("RID_SVXITEMS_STRIKEOUT_DONTKNOW", "Strikethrough") +#define RID_SVXITEMS_STRIKEOUT_BOLD NC_("RID_SVXITEMS_STRIKEOUT_BOLD", "Bold strikethrough") +#define RID_SVXITEMS_STRIKEOUT_SLASH NC_("RID_SVXITEMS_STRIKEOUT_SLASH", "Strike through with slash") +#define RID_SVXITEMS_STRIKEOUT_X NC_("RID_SVXITEMS_STRIKEOUT_X", "Strike through with Xes") + +// enum CASEMAP ---------------------------------------------------------- +#define RID_SVXITEMS_CASEMAP_NONE NC_("RID_SVXITEMS_CASEMAP_NONE", "None") +#define RID_SVXITEMS_CASEMAP_UPPERCASE NC_("RID_SVXITEMS_CASEMAP_VERSALIEN", "Caps") +#define RID_SVXITEMS_CASEMAP_LOWERCASE NC_("RID_SVXITEMS_CASEMAP_GEMEINE", "Lowercase") +#define RID_SVXITEMS_CASEMAP_TITLE NC_("RID_SVXITEMS_CASEMAP_TITEL", "Title") +#define RID_SVXITEMS_CASEMAP_SMALLCAPS NC_("RID_SVXITEMS_CASEMAP_KAPITAELCHEN", "Small caps") + +// enum ESCAPEMENT ------------------------------------------------------- +#define RID_SVXITEMS_ESCAPEMENT_OFF NC_("RID_SVXITEMS_ESCAPEMENT_OFF", "Normal position") +#define RID_SVXITEMS_ESCAPEMENT_SUPER NC_("RID_SVXITEMS_ESCAPEMENT_SUPER", "Superscript ") +#define RID_SVXITEMS_ESCAPEMENT_SUB NC_("RID_SVXITEMS_ESCAPEMENT_SUB", "Subscript ") +#define RID_SVXITEMS_ESCAPEMENT_AUTO NC_("RID_SVXITEMS_ESCAPEMENT_AUTO", "automatic") + +// enum SvxAdjust ----------------------------------------------------------- +#define RID_SVXITEMS_ADJUST_LEFT NC_("RID_SVXITEMS_ADJUST_LEFT", "Align left") +#define RID_SVXITEMS_ADJUST_RIGHT NC_("RID_SVXITEMS_ADJUST_RIGHT", "Align right") +#define RID_SVXITEMS_ADJUST_BLOCK NC_("RID_SVXITEMS_ADJUST_BLOCK", "Justify") +#define RID_SVXITEMS_ADJUST_CENTER NC_("RID_SVXITEMS_ADJUST_CENTER", "Centered") +#define RID_SVXITEMS_ADJUST_BLOCKLINE NC_("RID_SVXITEMS_ADJUST_BLOCKLINE", "Justify") +#define RID_SOLID NC_("RID_SOLID", "Single, solid") +#define RID_DOTTED NC_("RID_DOTTED", "Single, dotted") +#define RID_DASHED NC_("RID_DASHED", "Single, dashed") +#define RID_DOUBLE NC_("RID_DOUBLE", "Double") +#define RID_THINTHICK_SMALLGAP NC_("RID_THINTHICK_SMALLGAP", "Double, inside: fine, outside: thick, spacing: small") +#define RID_THINTHICK_MEDIUMGAP NC_("RID_THINTHICK_MEDIUMGAP", "Double, inside: fine, outside: thick, spacing: medium") +#define RID_THINTHICK_LARGEGAP NC_("RID_THINTHICK_LARGEGAP", "Double, inside: fine, outside: thick, spacing: large") +#define RID_THICKTHIN_SMALLGAP NC_("RID_THICKTHIN_SMALLGAP", "Double, inside: thick, outside: fine, spacing: small") +#define RID_THICKTHIN_MEDIUMGAP NC_("RID_THICKTHIN_MEDIUMGAP", "Double, inside: thick, outside: fine, spacing: medium") +#define RID_THICKTHIN_LARGEGAP NC_("RID_THICKTHIN_LARGEGAP", "Double, inside: thick, outside: fine, spacing: large") +#define RID_EMBOSSED NC_("RID_EMBOSSED", "3D embossed") +#define RID_ENGRAVED NC_("RID_ENGRAVED", "3D engraved") +#define RID_INSET NC_("RID_INSET", "Inset") +#define RID_OUTSET NC_("RID_OUTSET", "Outset") +#define RID_FINE_DASHED NC_("RID_FINE_DASHED", "Single, fine dashed") +#define RID_DOUBLE_THIN NC_("RID_DOUBLE_THIN", "Double, fixed thin lines") +#define RID_DASH_DOT NC_("RID_DASH_DOT", "Single, dash-dot") +#define RID_DASH_DOT_DOT NC_("RID_DASH_DOT_DOT", "Single, dash-dot-dot") +#define RID_SVXITEMS_METRIC_MM NC_("RID_SVXITEMS_METRIC_MM", "mm") +#define RID_SVXITEMS_METRIC_CM NC_("RID_SVXITEMS_METRIC_CM", "cm") +#define RID_SVXITEMS_METRIC_INCH NC_("RID_SVXITEMS_METRIC_INCH", "inch") +#define RID_SVXITEMS_METRIC_POINT NC_("RID_SVXITEMS_METRIC_POINT", "pt") +#define RID_SVXITEMS_METRIC_TWIP NC_("RID_SVXITEMS_METRIC_TWIP", "twip") +#define RID_SVXITEMS_METRIC_PIXEL NC_("RID_SVXITEMS_METRIC_PIXEL", "pixel") + +// GetValueText of BoolItems +#define RID_SVXITEMS_SHADOWED_TRUE NC_("RID_SVXITEMS_SHADOWED_TRUE", "Shadowed") +#define RID_SVXITEMS_SHADOWED_FALSE NC_("RID_SVXITEMS_SHADOWED_FALSE", "Not Shadowed") +#define RID_SVXITEMS_BLINK_TRUE NC_("RID_SVXITEMS_BLINK_TRUE", "Blinking") +#define RID_SVXITEMS_BLINK_FALSE NC_("RID_SVXITEMS_BLINK_FALSE", "Not Blinking") +#define RID_SVXITEMS_AUTOKERN_TRUE NC_("RID_SVXITEMS_AUTOKERN_TRUE", "Pair Kerning") +#define RID_SVXITEMS_AUTOKERN_FALSE NC_("RID_SVXITEMS_AUTOKERN_FALSE", "No pair kerning") +#define RID_SVXITEMS_WORDLINE_TRUE NC_("RID_SVXITEMS_WORDLINE_TRUE", "Individual words") +#define RID_SVXITEMS_WORDLINE_FALSE NC_("RID_SVXITEMS_WORDLINE_FALSE", "Not Words Only") +#define RID_SVXITEMS_CONTOUR_TRUE NC_("RID_SVXITEMS_CONTOUR_TRUE", "Outline") +#define RID_SVXITEMS_CONTOUR_FALSE NC_("RID_SVXITEMS_CONTOUR_FALSE", "No Outline") +#define RID_SVXITEMS_PRINT_TRUE NC_("RID_SVXITEMS_PRINT_TRUE", "Print") +#define RID_SVXITEMS_PRINT_FALSE NC_("RID_SVXITEMS_PRINT_FALSE", "Don't print") +#define RID_SVXITEMS_OPAQUE_TRUE NC_("RID_SVXITEMS_OPAQUE_TRUE", "Opaque") +#define RID_SVXITEMS_OPAQUE_FALSE NC_("RID_SVXITEMS_OPAQUE_FALSE", "Not Opaque") +#define RID_SVXITEMS_FMTKEEP_TRUE NC_("RID_SVXITEMS_FMTKEEP_TRUE", "Keep with next paragraph") +#define RID_SVXITEMS_FMTKEEP_FALSE NC_("RID_SVXITEMS_FMTKEEP_FALSE", "Don't Keep Paragraphs Together") +#define RID_SVXITEMS_FMTSPLIT_TRUE NC_("RID_SVXITEMS_FMTSPLIT_TRUE", "Split paragraph") +#define RID_SVXITEMS_FMTSPLIT_FALSE NC_("RID_SVXITEMS_FMTSPLIT_FALSE", "Don't split paragraph") +#define RID_SVXITEMS_PROT_CONTENT_TRUE NC_("RID_SVXITEMS_PROT_CONTENT_TRUE", "Contents protected") +#define RID_SVXITEMS_PROT_CONTENT_FALSE NC_("RID_SVXITEMS_PROT_CONTENT_FALSE", "Contents not protected") +#define RID_SVXITEMS_PROT_SIZE_TRUE NC_("RID_SVXITEMS_PROT_SIZE_TRUE", "Size protected") +#define RID_SVXITEMS_PROT_SIZE_FALSE NC_("RID_SVXITEMS_PROT_SIZE_FALSE", "Size not protected") +#define RID_SVXITEMS_PROT_POS_TRUE NC_("RID_SVXITEMS_PROT_POS_TRUE", "Position protected") +#define RID_SVXITEMS_PROT_POS_FALSE NC_("RID_SVXITEMS_PROT_POS_FALSE", "Position not protected") +#define RID_SVXITEMS_TRANSPARENT_TRUE NC_("RID_SVXITEMS_TRANSPARENT_TRUE", "Transparent") +#define RID_SVXITEMS_TRANSPARENT_FALSE NC_("RID_SVXITEMS_TRANSPARENT_FALSE", "Not Transparent") +#define RID_SVXITEMS_HYPHEN_TRUE NC_("RID_SVXITEMS_HYPHEN_TRUE", "Hyphenation") +#define RID_SVXITEMS_HYPHEN_FALSE NC_("RID_SVXITEMS_HYPHEN_FALSE", "No hyphenation") +#define RID_SVXITEMS_PAGE_END_TRUE NC_("RID_SVXITEMS_PAGE_END_TRUE", "Page End") +#define RID_SVXITEMS_PAGE_END_FALSE NC_("RID_SVXITEMS_PAGE_END_FALSE", "No Page End") +#define RID_SVXITEMS_SIZE_WIDTH NC_("RID_SVXITEMS_SIZE_WIDTH", "Width: ") +#define RID_SVXITEMS_SIZE_HEIGHT NC_("RID_SVXITEMS_SIZE_HEIGHT", "Height: ") +#define RID_SVXITEMS_LRSPACE_LEFT NC_("RID_SVXITEMS_LRSPACE_LEFT", "Indent left ") +#define RID_SVXITEMS_LRSPACE_FLINE NC_("RID_SVXITEMS_LRSPACE_FLINE", "First Line ") +#define RID_SVXITEMS_LRSPACE_RIGHT NC_("RID_SVXITEMS_LRSPACE_RIGHT", "Indent right ") +#define RID_SVXITEMS_SHADOW_COMPLETE NC_("RID_SVXITEMS_SHADOW_COMPLETE", "Shadow: ") +#define RID_SVXITEMS_BORDER_COMPLETE NC_("RID_SVXITEMS_BORDER_COMPLETE", "Borders ") +#define RID_SVXITEMS_BORDER_NONE NC_("RID_SVXITEMS_BORDER_NONE", "No border") +#define RID_SVXITEMS_BORDER_TOP NC_("RID_SVXITEMS_BORDER_TOP", "top ") +#define RID_SVXITEMS_BORDER_BOTTOM NC_("RID_SVXITEMS_BORDER_BOTTOM", "bottom ") +#define RID_SVXITEMS_BORDER_LEFT NC_("RID_SVXITEMS_BORDER_LEFT", "left ") +#define RID_SVXITEMS_BORDER_RIGHT NC_("RID_SVXITEMS_BORDER_RIGHT", "right ") +#define RID_SVXITEMS_BORDER_DISTANCE NC_("RID_SVXITEMS_BORDER_DISTANCE", "Spacing ") +#define RID_SVXITEMS_ULSPACE_UPPER NC_("RID_SVXITEMS_ULSPACE_UPPER", "From top ") +#define RID_SVXITEMS_ULSPACE_LOWER NC_("RID_SVXITEMS_ULSPACE_LOWER", "From bottom ") +#define RID_SVXITEMS_LINESPACING_SINGLE NC_("RID_SVXITEMS_LINESPACING_SINGLE", "Single") +#define RID_SVXITEMS_LINESPACING_115 NC_("RID_SVXITEMS_LINESPACING_115", "1.15 Lines") +#define RID_SVXITEMS_LINESPACING_15 NC_("RID_SVXITEMS_LINESPACING_15", "1.5 Lines") +#define RID_SVXITEMS_LINESPACING_DOUBLE NC_("RID_SVXITEMS_LINESPACING_DOUBLE", "Double") +#define RID_SVXITEMS_LINESPACING_PROPORTIONAL NC_("RID_SVXITEMS_LINESPACING_PROPORTIONAL", "Proportional") +#define RID_SVXITEMS_LINESPACING_MIN NC_("RID_SVXITEMS_LINESPACING_MIN", "At least") +#define RID_SVXITEMS_LINESPACING_LEADING NC_("RID_SVXITEMS_LINESPACING_LEADING", "Leading") +#define RID_SVXITEMS_LINESPACING_FIXED NC_("RID_SVXITEMS_LINESPACING_FIXED", "Fixed") +// To translators: %1 == will be replaced by the number of lines +#define RID_SVXITEMS_LINES NC_("RID_SVXITEMS_LINES", "%1 Lines") +#define RID_SVXITEMS_WIDOWS_COMPLETE NC_("RID_SVXITEMS_WIDOWS_COMPLETE", "Widow control") +#define RID_SVXITEMS_ORPHANS_COMPLETE NC_("RID_SVXITEMS_ORPHANS_COMPLETE", "Orphan control") +#define RID_SVXITEMS_HYPHEN_MINLEAD NC_("RID_SVXITEMS_HYPHEN_MINLEAD", "%1 characters at end of line") +#define RID_SVXITEMS_HYPHEN_MINTRAIL NC_("RID_SVXITEMS_HYPHEN_MINTRAIL", "%1 characters at beginning of line") +#define RID_SVXITEMS_HYPHEN_MAX NC_("RID_SVXITEMS_HYPHEN_MAX", "%1 hyphens") +#define RID_SVXITEMS_HYPHEN_NO_CAPS_TRUE NC_("RID_SVXITEMS_HYPHEN_NO_CAPS_TRUE", "Not hyphenated CAPS") +#define RID_SVXITEMS_HYPHEN_LAST_WORD_TRUE NC_("RID_SVXITEMS_HYPHEN_NO_CAPS_FALSE", "Not hyphenated last word") +#define RID_SVXITEMS_HYPHEN_MINWORDLEN NC_("RID_SVXITEMS_HYPHEN_MINWORDLEN", "%1 characters in words") +#define RID_SVXITEMS_HYPHEN_ZONE NC_("RID_SVXITEMS_HYPHEN_ZONE", "Hyphenation zone ") +#define RID_SVXITEMS_PAGEMODEL_COMPLETE NC_("RID_SVXITEMS_PAGEMODEL_COMPLETE", "Page Style: ") +#define RID_SVXITEMS_KERNING_COMPLETE NC_("RID_SVXITEMS_KERNING_COMPLETE", "Kerning ") +#define RID_SVXITEMS_KERNING_EXPANDED NC_("RID_SVXITEMS_KERNING_EXPANDED", "locked ") +#define RID_SVXITEMS_KERNING_CONDENSED NC_("RID_SVXITEMS_KERNING_CONDENSED", "Condensed ") +#define RID_SVXITEMS_GRAPHIC NC_("RID_SVXITEMS_GRAPHIC", "Graphic") +#define RID_SVXITEMS_EMPHASIS_NONE_STYLE NC_("RID_SVXITEMS_EMPHASIS_NONE_STYLE", "none") +#define RID_SVXITEMS_EMPHASIS_DOT_STYLE NC_("RID_SVXITEMS_EMPHASIS_DOT_STYLE", "Dots ") +#define RID_SVXITEMS_EMPHASIS_CIRCLE_STYLE NC_("RID_SVXITEMS_EMPHASIS_CIRCLE_STYLE", "Circle ") +// ??? disc == filled ring +#define RID_SVXITEMS_EMPHASIS_DISC_STYLE NC_("RID_SVXITEMS_EMPHASIS_DISC_STYLE", "Filled circle ") +#define RID_SVXITEMS_EMPHASIS_ACCENT_STYLE NC_("RID_SVXITEMS_EMPHASIS_ACCENT_STYLE", "Accent ") +#define RID_SVXITEMS_EMPHASIS_ABOVE_POS NC_("RID_SVXITEMS_EMPHASIS_ABOVE_POS", "Above") +#define RID_SVXITEMS_EMPHASIS_BELOW_POS NC_("RID_SVXITEMS_EMPHASIS_BELOW_POS", "Below") +#define RID_SVXITEMS_TWOLINES_OFF NC_("RID_SVXITEMS_TWOLINES_OFF", "Double-lined off") +#define RID_SVXITEMS_TWOLINES NC_("RID_SVXITEMS_TWOLINES", "Double-lined") +#define RID_SVXITEMS_SCRPTSPC_OFF NC_("RID_SVXITEMS_SCRPTSPC_OFF", "No automatic character spacing") +#define RID_SVXITEMS_SCRPTSPC_ON NC_("RID_SVXITEMS_SCRPTSPC_ON", "No automatic character spacing") +#define RID_SVXITEMS_HNGPNCT_OFF NC_("RID_SVXITEMS_HNGPNCT_OFF", "No hanging punctuation at line end") +#define RID_SVXITEMS_HNGPNCT_ON NC_("RID_SVXITEMS_HNGPNCT_ON", "Hanging punctuation at line end") +#define RID_SVXITEMS_FORBIDDEN_RULE_OFF NC_("RID_SVXITEMS_FORBIDDEN_RULE_OFF", "Apply list of forbidden characters to beginning and end of lines") +#define RID_SVXITEMS_FORBIDDEN_RULE_ON NC_("RID_SVXITEMS_FORBIDDEN_RULE_ON", "Don't apply list of forbidden characters to beginning and end of lines") +#define RID_SVXITEMS_CHARROTATE_OFF NC_("RID_SVXITEMS_CHARROTATE_OFF", "No rotated characters") +#define RID_SVXITEMS_CHARROTATE NC_("RID_SVXITEMS_CHARROTATE", "Character rotated by $(ARG1)°") +#define RID_SVXITEMS_CHARROTATE_FITLINE NC_("RID_SVXITEMS_CHARROTATE_FITLINE", "Fit to line") +#define RID_SVXITEMS_TEXTROTATE_OFF NC_("RID_SVXITEMS_TEXTROTATE_OFF", "Text is not rotated") +#define RID_SVXITEMS_TEXTROTATE NC_("RID_SVXITEMS_TEXTROTATE", "Text is rotated by $(ARG1)°") +#define RID_SVXITEMS_CHARSCALE NC_("RID_SVXITEMS_CHARSCALE", "Characters scaled $(ARG1)%") +#define RID_SVXITEMS_CHARSCALE_OFF NC_("RID_SVXITEMS_CHARSCALE_OFF", "No scaled characters") +#define RID_SVXITEMS_RELIEF_NONE NC_("RID_SVXITEMS_RELIEF_NONE", "No relief") +#define RID_SVXITEMS_RELIEF_EMBOSSED NC_("RID_SVXITEMS_RELIEF_EMBOSSED", "Relief") +#define RID_SVXITEMS_RELIEF_ENGRAVED NC_("RID_SVXITEMS_RELIEF_ENGRAVED", "Engraved") +#define RID_SVXITEMS_PARAVERTALIGN_AUTO NC_("RID_SVXITEMS_PARAVERTALIGN_AUTO", "Automatic text alignment") +#define RID_SVXITEMS_PARAVERTALIGN_BASELINE NC_("RID_SVXITEMS_PARAVERTALIGN_BASELINE", "Text aligned to base line") +#define RID_SVXITEMS_PARAVERTALIGN_TOP NC_("RID_SVXITEMS_PARAVERTALIGN_TOP", "Text aligned top") +#define RID_SVXITEMS_PARAVERTALIGN_CENTER NC_("RID_SVXITEMS_PARAVERTALIGN_CENTER", "Text aligned middle") +#define RID_SVXITEMS_PARAVERTALIGN_BOTTOM NC_("RID_SVXITEMS_PARAVERTALIGN_BOTTOM", "Text aligned bottom") +#define RID_SVXITEMS_FRMDIR_HORI_LEFT_TOP NC_("RID_SVXITEMS_FRMDIR_HORI_LEFT_TOP", "Text direction left-to-right (horizontal)") +#define RID_SVXITEMS_FRMDIR_HORI_RIGHT_TOP NC_("RID_SVXITEMS_FRMDIR_HORI_RIGHT_TOP", "Text direction right-to-left (horizontal)") +#define RID_SVXITEMS_FRMDIR_VERT_TOP_RIGHT NC_("RID_SVXITEMS_FRMDIR_VERT_TOP_RIGHT", "Text direction right-to-left (vertical)") +#define RID_SVXITEMS_FRMDIR_VERT_TOP_LEFT NC_("RID_SVXITEMS_FRMDIR_VERT_TOP_LEFT", "Text direction left-to-right (vertical)") +#define RID_SVXITEMS_FRMDIR_ENVIRONMENT NC_("RID_SVXITEMS_FRMDIR_ENVIRONMENT", "Use superordinate object text direction setting") +#define RID_SVXITEMS_FRMDIR_VERT_BOT_LEFT NC_("RID_SVXITEMS_FRMDIR_VERT_BOT_LEFT", "Text direction left-to-right (vertical from bottom)") +#define RID_SVXITEMS_PARASNAPTOGRID_ON NC_("RID_SVXITEMS_PARASNAPTOGRID_ON", "Paragraph snaps to text grid (if active)") +#define RID_SVXITEMS_PARASNAPTOGRID_OFF NC_("RID_SVXITEMS_PARASNAPTOGRID_OFF", "Paragraph does not snap to text grid") +#define RID_SVXITEMS_CHARHIDDEN_FALSE NC_("RID_SVXITEMS_CHARHIDDEN_FALSE", "Not hidden") +#define RID_SVXITEMS_CHARHIDDEN_TRUE NC_("RID_SVXITEMS_CHARHIDDEN_TRUE", "Hidden") + +#define RID_SVXSTR_PAPERBIN NC_("RID_SVXSTR_PAPERBIN", "Paper tray") +#define RID_SVXSTR_PAPERBIN_SETTINGS NC_("RID_SVXSTR_PAPERBIN_SETTINGS", "[From printer settings]") + +#define RID_EDITUNDO_DEL NC_("RID_EDITUNDO_DEL", "Delete") +#define RID_EDITUNDO_MOVE NC_("RID_EDITUNDO_MOVE", "Move") +#define RID_EDITUNDO_INSERT NC_("RID_EDITUNDO_INSERT", "Insert") +#define RID_EDITUNDO_REPLACE NC_("RID_EDITUNDO_REPLACE", "Replace") +#define RID_EDITUNDO_SETATTRIBS NC_("RID_EDITUNDO_SETATTRIBS", "Apply attributes") +#define RID_EDITUNDO_RESETATTRIBS NC_("RID_EDITUNDO_RESETATTRIBS", "Reset attributes") +#define RID_EDITUNDO_INDENT NC_("RID_EDITUNDO_INDENT", "Indent") +#define RID_EDITUNDO_SETSTYLE NC_("RID_EDITUNDO_SETSTYLE", "Apply Styles") +#define RID_EDITUNDO_TRANSLITERATE NC_("RID_EDITUNDO_TRANSLITERATE", "Change Case") +#define RID_STR_WORD NC_("RID_STR_WORD", "Word is %x") +#define RID_STR_PARAGRAPH NC_("RID_STR_PARAGRAPH", "Paragraph is %x") +#define RID_SVXSTR_AUTOMATIC NC_("RID_SVXSTR_AUTOMATIC", "Automatic") + +#define RID_SVXSTR_A11Y_IMAGEBULLET_DESCRIPTION NC_("RID_SVXSTR_A11Y_IMAGEBULLET_DESCRIPTION", "Image bullet in paragraph") +#define RID_SVXSTR_A11Y_IMAGEBULLET_NAME NC_("RID_SVXSTR_A11Y_IMAGEBULLET_NAME", "Image bullet") +#define RID_SVXSTR_A11Y_PARAGRAPH_DESCRIPTION NC_("RID_SVXSTR_A11Y_PARAGRAPH_DESCRIPTION", "Paragraph: $(ARG) ") + +#define RID_SVXSTR_QUERY_CONTINUE NC_("RID_SVXSTR_QUERY_CONTINUE", "Continue checking at beginning of document?") +#define RID_SVXSTR_QUERY_BW_CONTINUE NC_("RID_SVXSTR_QUERY_BW_CONTINUE", "Continue checking at end of document?") +#define RID_SVXSTR_DIC_ERR_UNKNOWN NC_("RID_SVXSTR_DIC_ERR_UNKNOWN", "Word cannot be added to dictionary\ndue to unknown reason.") +#define RID_SVXSTR_DIC_ERR_FULL NC_("RID_SVXSTR_DIC_ERR_FULL", "The dictionary is already full.") +#define RID_SVXSTR_DIC_ERR_READONLY NC_("RID_SVXSTR_DIC_ERR_READONLY", "The dictionary is read-only.") + +#define RID_OUTLUNDO_DEPTH NC_("RID_OUTLUNDO_DEPTH", "Indent") +#define RID_OUTLUNDO_EXPAND NC_("RID_OUTLUNDO_EXPAND", "Show subpoints") +#define RID_OUTLUNDO_COLLAPSE NC_("RID_OUTLUNDO_COLLAPSE", "Collapse") +#define RID_OUTLUNDO_ATTR NC_("RID_OUTLUNDO_ATTR", "Apply attributes") +#define RID_OUTLUNDO_INSERT NC_("RID_OUTLUNDO_INSERT", "Insert") + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editstat.hxx b/include/editeng/editstat.hxx new file mode 100644 index 000000000..eec50ea67 --- /dev/null +++ b/include/editeng/editstat.hxx @@ -0,0 +1,144 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_EDITSTAT_HXX +#define INCLUDED_EDITENG_EDITSTAT_HXX + +#include +#include +#include + +enum class EEControlBits +{ + NONE = 0x00000000, + USECHARATTRIBS = 0x00000001, // Use of hard character attributes + DOIDLEFORMAT = 0x00000008, // Formatting idle + PASTESPECIAL = 0x00000010, // Allow PasteSpecial + AUTOINDENTING = 0x00000020, // Automatic indenting + UNDOATTRIBS = 0x00000040, // Undo for Attributes... + ONECHARPERLINE = 0x00000080, // One character per line + NOCOLORS = 0x00000100, // Engine: No Color + OUTLINER = 0x00000200, // Special treatment Outliner/Outline mode + OUTLINER2 = 0x00000400, // Special treatment Outliner/Page + ALLOWBIGOBJS = 0x00000800, // Portion info in text object + ONLINESPELLING = 0x00001000, // During the edit Spelling + STRETCHING = 0x00002000, // Stretch mode + MARKNONURLFIELDS = 0x00004000, // Mark fields other than URL with color + MARKURLFIELDS = 0x00008000, // Mark URL fields with color + MARKFIELDS = (MARKNONURLFIELDS | MARKURLFIELDS), + RTFSTYLESHEETS = 0x00020000, // Use Stylesheets when imported + AUTOCORRECT = 0x00080000, // AutoCorrect + AUTOCOMPLETE = 0x00100000, // AutoComplete + AUTOPAGESIZEX = 0x00200000, // Adjust paper width to Text + AUTOPAGESIZEY = 0x00400000, // Adjust paper height to Text + AUTOPAGESIZE = (AUTOPAGESIZEX | AUTOPAGESIZEY), + FORMAT100 = 0x01000000, // Always format to 100% + ULSPACESUMMATION = 0x02000000, // MS Compat: sum SA and SB, not maximum value +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +enum class EVControlBits +{ + AUTOSCROLL = 0x0001, // Auto scrolling horizontally + ENABLEPASTE = 0x0004, // Enable Paste + SINGLELINEPASTE = 0x0008, // View: Paste in input line ... + OVERWRITE = 0x0010, // Overwrite mode + INVONEMORE = 0x0020, // Invalidate one pixel more + AUTOSIZEX = 0x0040, // Automatically adapt to text width + AUTOSIZEY = 0x0080, // Automatically adapt to Text width + AUTOSIZE = (AUTOSIZEX|AUTOSIZEY) +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +enum class EditStatusFlags +{ + NONE = 0x0000, + HSCROLL = 0x0001, + VSCROLL = 0x0002, + CURSOROUT = 0x0004, + TEXTWIDTHCHANGED = 0x0010, + TextHeightChanged = 0x0020, + WRONGWORDCHANGED = 0x0040 +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +inline void SetFlags( EVControlBits& rBits, EVControlBits nMask, bool bOn ) +{ + if ( bOn ) + rBits |= nMask; + else + rBits &= ~nMask; +} + +class EditStatus +{ +protected: + EditStatusFlags nStatusBits; + EEControlBits nControlBits; + +public: + EditStatus() { nStatusBits = EditStatusFlags::NONE; nControlBits = EEControlBits::NONE; } + + void Clear() { nStatusBits = EditStatusFlags::NONE; } + + EditStatusFlags GetStatusWord() const { return nStatusBits; } + EditStatusFlags& GetStatusWord() { return nStatusBits; } + + EEControlBits& GetControlWord() { return nControlBits; } +}; + +enum class SpellCallbackCommand +{ + IGNOREWORD = 0x0001, + STARTSPELLDLG = 0x0002, + ADDTODICTIONARY = 0x0003, + WORDLANGUAGE = 0x0004, + PARALANGUAGE = 0x0005, + AUTOCORRECT_OPTIONS = 0x0006, +}; + +struct SpellCallbackInfo +{ + SpellCallbackCommand nCommand; + OUString aWord; + + SpellCallbackInfo( SpellCallbackCommand nCMD, OUString _aWord ) + : aWord(std::move( _aWord )) + { + nCommand = nCMD; + } + + SpellCallbackInfo( SpellCallbackCommand nCMD ) + { + nCommand = nCMD; + } +}; + +#endif // INCLUDED_EDITENG_EDITSTAT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editund2.hxx b/include/editeng/editund2.hxx new file mode 100644 index 000000000..3f6975a3a --- /dev/null +++ b/include/editeng/editund2.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_EDITUND2_HXX +#define INCLUDED_EDITENG_EDITUND2_HXX + +#include +#include + +class EditEngine; + +class EDITENG_DLLPUBLIC EditUndoManager : public SfxUndoManager +{ + using SfxUndoManager::Undo; + using SfxUndoManager::Redo; + friend class ImpEditEngine; + + EditEngine* mpEditEngine; + void SetEditEngine(EditEngine* pNew); + +public: + EditUndoManager(sal_uInt16 nMaxUndoActionCount = 20); + + virtual bool Undo() override; + virtual bool Redo() override; +}; + +// EditUndo + +class EDITENG_DLLPUBLIC EditUndo : public SfxUndoAction +{ +private: + sal_uInt16 nId; + ViewShellId mnViewShellId; + EditEngine* mpEditEngine; + +public: + EditUndo(sal_uInt16 nI, EditEngine* pEE); + virtual ~EditUndo() override; + + EditEngine* GetEditEngine() { return mpEditEngine; } + + virtual void Undo() override = 0; + virtual void Redo() override = 0; + + virtual bool CanRepeat(SfxRepeatTarget&) const override; + virtual OUString GetComment() const override; + /// See SfxUndoAction::GetViewShellId(). + ViewShellId GetViewShellId() const override; + sal_uInt16 GetId() const; +}; + +#endif // INCLUDED_EDITENG_EDITUND2_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/editview.hxx b/include/editeng/editview.hxx new file mode 100644 index 000000000..4f312b578 --- /dev/null +++ b/include/editeng/editview.hxx @@ -0,0 +1,382 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// MyEDITVIEW, due to exported EditView +#ifndef INCLUDED_EDITENG_EDITVIEW_HXX +#define INCLUDED_EDITENG_EDITVIEW_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +class EditTextObject; +class EditEngine; +class ImpEditEngine; +class ImpEditView; +class OutlinerViewShell; +class SvxSearchItem; +class SvxFieldItem; +namespace vcl { class Window; } +namespace weld { class Widget; } +class KeyEvent; +class MouseEvent; +class CommandEvent; +class SvStream; +class SvKeyValueIterator; +class SfxStyleSheet; +class SfxItemSet; +namespace vcl { class Cursor; } +namespace vcl { class Font; } +class FontList; +class InputContext; +class OutputDevice; +enum class TransliterationFlags; +enum class PointerStyle; + +namespace com { +namespace sun { +namespace star { +namespace datatransfer { + class XTransferable; + namespace clipboard { + class XClipboard; + } + namespace dnd { + class XDropTarget; + } +} +namespace linguistic2 { + class XSpellChecker1; + class XLanguageGuessing; +} +}}} + +template class Link; + +enum class ScrollRangeCheck +{ + NoNegative = 1, // No negative VisArea when scrolling + PaperWidthTextSize = 2, // VisArea must be within paper width, Text Size +}; + +// Helper class that allows to set a callback at the EditView. When +// set, Invalidates and repaints are suppressed at the EditView, but +// EditViewInvalidate() will be triggered to allow the consumer to +// react itself as needed. +// Also Selection visualization is suppressed and EditViewSelectionChange +// is triggered when Selection changes and needs reaction. +class EDITENG_DLLPUBLIC EditViewCallbacks +{ +public: + virtual ~EditViewCallbacks(); + + // call this when text visualization changed in any way. It + // will also update selection, so no need to call this self + // additionally (but will also do no harm) + virtual void EditViewInvalidate(const tools::Rectangle& rRect) = 0; + + // call this when only selection is changed. Text change will + // then *not* be checked and not be reacted on. Still, when + // only the selection is changed, this is useful and faster + virtual void EditViewSelectionChange() = 0; + + // return the OutputDevice that the EditView will draw to + virtual OutputDevice& EditViewOutputDevice() const = 0; + + virtual weld::Widget* EditViewPopupParent() const + { + return nullptr; + } + + // return the Mouse Position + virtual Point EditViewPointerPosPixel() const = 0; + + // Triggered to update InputEngine context information + virtual void EditViewInputContext(const InputContext& rInputContext) = 0; + + // Triggered to update InputEngine cursor position + virtual void EditViewCursorRect(const tools::Rectangle& rRect, int nExtTextInputWidth) = 0; + + // Triggered if scroll bar state should change + virtual void EditViewScrollStateChange() + { + } + + // Access to clipboard + virtual css::uno::Reference GetClipboard() const = 0; + + // implemented if drag and drop support is wanted + virtual css::uno::Reference GetDropTarget() + { + return nullptr; + } +}; + +class EDITENG_DLLPUBLIC EditView final +{ + friend class EditEngine; + friend class ImpEditEngine; + friend class EditSelFunctionSet; + +public: + typedef std::vector> OutWindowSet; + +public: // Needed for Undo + ImpEditView* GetImpEditView() const { return pImpEditView.get(); } + ImpEditEngine* GetImpEditEngine() const; + +private: + std::unique_ptr + pImpEditView; + OUString aDicNameSingle; + + EditView( const EditView& ) = delete; + EditView& operator=( const EditView& ) = delete; + +public: + EditView( EditEngine* pEng, vcl::Window* pWindow ); + ~EditView(); + + // set EditViewCallbacks for external handling of Repaints/Visualization + void setEditViewCallbacks(EditViewCallbacks* pEditViewCallbacks); + EditViewCallbacks* getEditViewCallbacks() const; + + void SetEditEngine( EditEngine* pEditEngine ); + EditEngine* GetEditEngine() const; + + void SetWindow( vcl::Window* pWin ); + vcl::Window* GetWindow() const; + OutputDevice& GetOutputDevice() const; + + LanguageType GetInputLanguage() const; + + bool HasOtherViewWindow( vcl::Window* pWin ); + bool AddOtherViewWindow( vcl::Window* pWin ); + bool RemoveOtherViewWindow( vcl::Window* pWin ); + + void Paint( const tools::Rectangle& rRect, OutputDevice* pTargetDevice = nullptr ); + tools::Rectangle GetInvalidateRect() const; + void InvalidateWindow(const tools::Rectangle& rClipRect); + void InvalidateOtherViewWindows( const tools::Rectangle& rInvRect ); + void Invalidate(); + ::Pair Scroll( tools::Long nHorzScroll, tools::Long nVertScroll, ScrollRangeCheck nRangeCheck = ScrollRangeCheck::NoNegative ); + + void SetBroadcastLOKViewCursor(bool bSet); + tools::Rectangle GetEditCursor() const; + void ShowCursor( bool bGotoCursor = true, bool bForceVisCursor = true, bool bActivate = false ); + void HideCursor( bool bDeactivate = false ); + + void SetSelectionMode( EESelectionMode eMode ); + + void SetReadOnly( bool bReadOnly ); + bool IsReadOnly() const; + + bool HasSelection() const; + ESelection GetSelection() const; + void SetSelection( const ESelection& rNewSel ); + bool IsSelectionAtPoint(const Point& rPointPixel); + void SelectCurrentWord( sal_Int16 nWordType = css::i18n::WordType::ANYWORD_IGNOREWHITESPACES ); + /// Returns the rectangles of the current selection in TWIPs. + void GetSelectionRectangles(std::vector& rLogicRects) const; + + bool IsInsertMode() const; + void SetInsertMode( bool bInsert ); + + OUString GetSelected() const; + void DeleteSelected(); + + SvtScriptType GetSelectedScriptType() const; + + // VisArea position of the Output window. + // A size change also affects the VisArea + void SetOutputArea( const tools::Rectangle& rRect ); + const tools::Rectangle& GetOutputArea() const; + + // Document position. + // A size change also affects the VisArea + void SetVisArea( const tools::Rectangle& rRect ); + tools::Rectangle GetVisArea() const; + + PointerStyle GetPointer() const; + + vcl::Cursor* GetCursor() const; + + void InsertText( const OUString& rNew, bool bSelect = false , bool bLOKShowSelect = true); + void InsertParaBreak(); + + bool PostKeyEvent( const KeyEvent& rKeyEvent, vcl::Window const * pFrameWin = nullptr ); + + bool MouseButtonUp( const MouseEvent& rMouseEvent ); + bool MouseButtonDown( const MouseEvent& rMouseEvent ); + void ReleaseMouse(); + bool MouseMove( const MouseEvent& rMouseEvent ); + bool Command(const CommandEvent& rCEvt); + + void Cut(); + void Copy(); + void Paste(); + void PasteSpecial(); + + void Undo(); + void Redo(); + + // especially for Oliver Specht + Point GetWindowPosTopLeft( sal_Int32 nParagraph ); + void MoveParagraphs( Range aParagraphs, sal_Int32 nNewPos ); + void MoveParagraphs( tools::Long nDiff ); + + const SfxItemSet& GetEmptyItemSet() const; + SfxItemSet GetAttribs(); + void SetAttribs( const SfxItemSet& rSet ); + void RemoveAttribs( bool bRemoveParaAttribs = false, sal_uInt16 nWhich = 0 ); + void RemoveAttribs( EERemoveParaAttribsMode eMode, sal_uInt16 nWhich ); + void RemoveCharAttribs( sal_Int32 nPara, sal_uInt16 nWhich ); + void RemoveAttribsKeepLanguages( bool bRemoveParaAttribs ); + + ErrCode Read( SvStream& rInput, EETextFormat eFormat, SvKeyValueIterator* pHTTPHeaderAttrs ); + + void SetBackgroundColor( const Color& rColor ); + Color const & GetBackgroundColor() const; + + /// Informs this edit view about which view shell contains it. + void RegisterViewShell(OutlinerViewShell* pViewShell); + /// Informs this edit view about which other shell listens to it. + void RegisterOtherShell(OutlinerViewShell* pOtherShell); + + void SetControlWord( EVControlBits nWord ); + EVControlBits GetControlWord() const; + + std::unique_ptr CreateTextObject(); + void InsertText( const EditTextObject& rTextObject ); + void InsertText( css::uno::Reference< css::datatransfer::XTransferable > const & xDataObj, const OUString& rBaseURL, bool bUseSpecial ); + + css::uno::Reference GetClipboard() const; + css::uno::Reference GetTransferable() const; + + // An EditView, so that when TRUE the update will be free from flickering: + // @return the previous bUpdateLayout state + bool SetEditEngineUpdateLayout( bool bUpdate ); + void ForceLayoutCalculation(); + + const SfxStyleSheet* GetStyleSheet() const; + SfxStyleSheet* GetStyleSheet(); + + void SetAnchorMode( EEAnchorMode eMode ); + EEAnchorMode GetAnchorMode() const; + + void CompleteAutoCorrect( vcl::Window const * pFrameWin = nullptr ); + + EESpellState StartSpeller(weld::Widget* pDialogParent, bool bMultipleDoc = false); + EESpellState StartThesaurus(weld::Widget* pDialogParent); + sal_Int32 StartSearchAndReplace( const SvxSearchItem& rSearchItem ); + + // for text conversion + void StartTextConversion(weld::Widget* pDialogParent, LanguageType nSrcLang, LanguageType nDestLang, const vcl::Font *pDestFont, sal_Int32 nOptions, bool bIsInteractive, bool bMultipleDoc); + + void TransliterateText( TransliterationFlags nTransliterationMode ); + + bool IsCursorAtWrongSpelledWord(); + bool IsWrongSpelledWordAtPos( const Point& rPosPixel, bool bMarkIfWrong = false ); + bool ExecuteSpellPopup(const Point& rPosPixel, const Link& rCallBack); + OUString SpellIgnoreWord(); + + void InsertField( const SvxFieldItem& rFld ); + const SvxFieldItem* GetFieldUnderMousePointer() const; + const SvxFieldItem* GetFieldUnderMousePointer( sal_Int32& nPara, sal_Int32& nPos ) const; + const SvxFieldItem* GetField( const Point& rPos, sal_Int32* pnPara = nullptr, sal_Int32* pnPos = nullptr ) const; + + const SvxFieldItem* GetFieldAtSelection() const; + /// Select and return the field at the current cursor position + const SvxFieldData* GetFieldAtCursor() const; + void SelectFieldAtCursor(); + + void SetInvalidateMore( sal_uInt16 nPixel ); + sal_uInt16 GetInvalidateMore() const; + + // grows or shrinks the font height for the current selection + void ChangeFontSize( bool bGrow, const FontList* pList ); + + static bool ChangeFontSize( bool bGrow, SfxItemSet& rSet, const FontList* pFontList ); + + OUString GetSurroundingText() const; + Selection GetSurroundingTextSelection() const; + bool DeleteSurroundingText(const Selection& rRange); + + /** Tries to determine the language of 'rText', returning a matching known + locale if possible, or a fallback, or LANGUAGE_NONE if nothing found or + matched. + + @param bIsParaText + If TRUE, rText is a paragraph and the language is obtained by + passing the text to xLangGuess. + IF FALSE, a language match is tried for, in order, + 1. the default document language (non-CTL, non-CJK, aka LATIN) + 2. the UI language (Tools->Options->LanguageSettings->Languages User Interface) + 3. the locale (Tools->Options->LanguageSettings->Languages Locale) + 4. en-US + If nothing matched, LANGUAGE_NONE is returned. + */ + static LanguageType CheckLanguage( + const OUString &rText, + const css::uno::Reference< css::linguistic2::XSpellChecker1 >& xSpell, + const css::uno::Reference< css::linguistic2::XLanguageGuessing >& xLangGuess, + bool bIsParaText ); + /// Allows adjusting the point or mark of the selection to a document coordinate. + void SetCursorLogicPosition(const Point& rPosition, bool bPoint, bool bClearMark); + /// Trigger selection drawing callback in pOtherShell based on our shell's selection state. + void DrawSelectionXOR(OutlinerViewShell* pOtherShell); + + /** + * This is meant for Calc(LOK), but there may be other use-cases. + * In Calc, all logical positions are computed by + * doing independent pixel-alignment for each cell's size. The *LOKSpecial* methods + * can be used to set/get the output-area and visible-area in real logical + * units. This enables EditView to send cursor/selection messages in + * real logical units like it is done for Writer. + */ + void InitLOKSpecialPositioning(MapUnit eUnit, const tools::Rectangle& rOutputArea, + const Point& rVisDocStartPos); + void SetLOKSpecialOutputArea(const tools::Rectangle& rOutputArea); + const tools::Rectangle & GetLOKSpecialOutputArea() const; + void SetLOKSpecialVisArea(const tools::Rectangle& rVisArea); + tools::Rectangle GetLOKSpecialVisArea() const; + bool HasLOKSpecialPositioning() const; + + void SuppressLOKMessages(bool bSet); + bool IsSuppressLOKMessages() const; + + /// To inform editeng that negated x document coordinates are in use. + void SetNegativeX(bool bSet); + bool IsNegativeX() const; +}; + +#endif // INCLUDED_EDITENG_EDITVIEW_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/edtdlg.hxx b/include/editeng/edtdlg.hxx new file mode 100644 index 000000000..68783dc2d --- /dev/null +++ b/include/editeng/edtdlg.hxx @@ -0,0 +1,105 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_EDTDLG_HXX +#define INCLUDED_EDITENG_EDTDLG_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::linguistic2 +{ + class XThesaurus; + class XHyphenator; +} + +template class Link; + +class SvxSpellWrapper; +class LinkParamNone; + +namespace weld { class Button; } +namespace weld { class Toggleable; } + +class AbstractThesaurusDialog : public VclAbstractDialog +{ +protected: + virtual ~AbstractThesaurusDialog() override = default; +public: + virtual OUString GetWord() = 0; +}; + +class AbstractHyphenWordDialog : public VclAbstractDialog +{ +protected: + virtual ~AbstractHyphenWordDialog() override = default; +}; + +class AbstractHangulHanjaConversionDialog : public VclAbstractTerminatedDialog +{ +protected: + virtual ~AbstractHangulHanjaConversionDialog() override = default; +public: + virtual void EnableRubySupport( bool _bVal ) = 0; + virtual void SetByCharacter( bool _bByCharacter ) = 0; + virtual void SetConversionDirectionState( bool _bTryBothDirections, editeng::HangulHanjaConversion::ConversionDirection _ePrimaryConversionDirection ) = 0; + virtual void SetConversionFormat( editeng::HangulHanjaConversion::ConversionFormat _eType ) = 0; + virtual void SetOptionsChangedHdl( const Link& _rHdl ) = 0; + virtual void SetIgnoreHdl( const Link& _rHdl ) = 0; + virtual void SetIgnoreAllHdl( const Link& _rHdl ) = 0; + virtual void SetChangeHdl( const Link& _rHdl ) = 0; + virtual void SetChangeAllHdl( const Link& _rHdl ) = 0; + virtual void SetClickByCharacterHdl( const Link& _rHdl ) = 0; + virtual void SetConversionFormatChangedHdl( const Link& _rHdl ) = 0; + virtual void SetFindHdl( const Link& _rHdl ) = 0; + virtual bool GetUseBothDirections() const= 0; + virtual editeng::HangulHanjaConversion::ConversionDirection + GetDirection( editeng::HangulHanjaConversion::ConversionDirection _eDefaultDirection ) const = 0; + virtual void SetCurrentString( + const OUString& _rNewString, + const css::uno::Sequence< OUString >& _rSuggestions, + bool _bOriginatesFromDocument = true )=0; + virtual OUString GetCurrentString( ) const =0; + virtual editeng::HangulHanjaConversion::ConversionFormat + GetConversionFormat( ) const =0; + virtual void FocusSuggestion( )= 0; + virtual OUString GetCurrentSuggestion( ) const =0; +}; + +class EDITENG_DLLPUBLIC EditAbstractDialogFactory : virtual public VclAbstractDialogFactory +{ +public: + virtual ~EditAbstractDialogFactory() override; // needed for export of vtable + static EditAbstractDialogFactory* Create(); + virtual VclPtr CreateThesaurusDialog(weld::Widget*, + css::uno::Reference xThesaurus, + const OUString &rWord, LanguageType nLanguage) = 0; + + virtual VclPtr CreateHyphenWordDialog(weld::Widget*, + const OUString &rWord, LanguageType nLang, + css::uno::Reference< css::linguistic2::XHyphenator > &xHyphen, + SvxSpellWrapper* pWrapper) = 0; + virtual VclPtr CreateHangulHanjaConversionDialog(weld::Widget* pParent) = 0; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/eedata.hxx b/include/editeng/eedata.hxx new file mode 100644 index 000000000..ad0ab7b13 --- /dev/null +++ b/include/editeng/eedata.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_EEDATA_HXX +#define INCLUDED_EDITENG_EEDATA_HXX + + +// extended data definitions for EditEngine portion stripping (StripPortions() +// support). These may be mapped to some primitive definitions from Drawinglayer +// later. +#include + +#include + +namespace EEngineData +{ + // spell checking wrong vector containing the redlining data + class WrongSpellClass + { + public: + sal_Int32 nStart; + sal_Int32 nEnd; + + WrongSpellClass(sal_Int32 nS, sal_Int32 nE) : nStart(nS), nEnd(nE) {} + }; + + typedef std::vector< WrongSpellClass > WrongSpellVector; + +} // end of namespace EditEngine + +#endif // INCLUDED_EDITENG_EEDATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/eeitem.hxx b/include/editeng/eeitem.hxx new file mode 100644 index 000000000..f86224486 --- /dev/null +++ b/include/editeng/eeitem.hxx @@ -0,0 +1,148 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_EEITEM_HXX +#define INCLUDED_EDITENG_EEITEM_HXX + +#include +#include + +class SfxBoolItem; +class SfxGrabBagItem; +class SfxInt16Item; +class SvxAdjustItem; +class SvxAutoKernItem; +class SvxCaseMapItem; +class SvxCharReliefItem; +class SvxCharScaleWidthItem; +class SvxColorItem; +class SvxContourItem; +class SvxCrossedOutItem; +class SvxEmphasisMarkItem; +class SvxEscapementItem; +class SvxFieldItem; +class SvxFontHeightItem; +class SvxFontItem; +class SvxForbiddenRuleItem; +class SvxFrameDirectionItem; +class SvxHangingPunctuationItem; +class SvxKerningItem; +class SvxLanguageItem; +class SvxLineSpacingItem; +class SvxLRSpaceItem; +class SvxOverlineItem; +class SvxPostureItem; +class SvXMLAttrContainerItem; +class SvxScriptSpaceItem; +class SvxShadowedItem; +class SvxTabStopItem; +class SvxULSpaceItem; +class SvxUnderlineItem; +class SvxWeightItem; +class SvxWordLineModeItem; +class SvxBulletItem; +class SvxNumBulletItem; +class SvxJustifyMethodItem; +class SvxVerJustifyItem; +class SfxVoidItem; + +/* + * NOTE: Changes in this file will probably require + * consistent changes in eerdll.cxx and editdoc.cxx + * as well. +*/ + +constexpr sal_uInt16 EE_ITEMS_START(OWN_ATTR_VALUE_END + 1); + +// Paragraph attributes: +constexpr sal_uInt16 EE_PARA_START (EE_ITEMS_START + 0); +constexpr TypedWhichId EE_PARA_WRITINGDIR (EE_PARA_START+0); +constexpr TypedWhichId EE_PARA_XMLATTRIBS (EE_PARA_START+1); +constexpr TypedWhichId EE_PARA_HANGINGPUNCTUATION (EE_PARA_START+2); +constexpr TypedWhichId EE_PARA_FORBIDDENRULES (EE_PARA_START+3); +constexpr TypedWhichId EE_PARA_ASIANCJKSPACING (EE_PARA_START+4); +constexpr TypedWhichId EE_PARA_NUMBULLET (EE_PARA_START+5); +constexpr TypedWhichId EE_PARA_HYPHENATE (EE_PARA_START+6); +constexpr TypedWhichId EE_PARA_HYPHENATE_NO_CAPS (EE_PARA_START+7); +constexpr TypedWhichId EE_PARA_HYPHENATE_NO_LAST_WORD (EE_PARA_START+8); +constexpr TypedWhichId EE_PARA_BULLETSTATE (EE_PARA_START+9); +constexpr TypedWhichId EE_PARA_OUTLLRSPACE (EE_PARA_START+10); +constexpr TypedWhichId EE_PARA_OUTLLEVEL (EE_PARA_START+11); +constexpr TypedWhichId EE_PARA_BULLET (EE_PARA_START+12); +constexpr TypedWhichId EE_PARA_LRSPACE (EE_PARA_START+13); +constexpr TypedWhichId EE_PARA_ULSPACE (EE_PARA_START+14); +constexpr TypedWhichId EE_PARA_SBL (EE_PARA_START+15); +constexpr TypedWhichId EE_PARA_JUST (EE_PARA_START+16); +constexpr TypedWhichId EE_PARA_TABS (EE_PARA_START+17); +constexpr TypedWhichId EE_PARA_JUST_METHOD (EE_PARA_START+18); +constexpr TypedWhichId EE_PARA_VER_JUST (EE_PARA_START+19); +constexpr sal_uInt16 EE_PARA_END (EE_PARA_START + 19); + +// Character attributes: +constexpr sal_uInt16 EE_CHAR_START (EE_PARA_END + 1); +constexpr TypedWhichId EE_CHAR_COLOR (EE_CHAR_START+0); +constexpr TypedWhichId EE_CHAR_FONTINFO (EE_CHAR_START+1); +constexpr TypedWhichId EE_CHAR_FONTHEIGHT (EE_CHAR_START+2); +constexpr TypedWhichId EE_CHAR_FONTWIDTH (EE_CHAR_START+3); +constexpr TypedWhichId EE_CHAR_WEIGHT (EE_CHAR_START+4); +constexpr TypedWhichId EE_CHAR_UNDERLINE (EE_CHAR_START+5); +constexpr TypedWhichId EE_CHAR_STRIKEOUT (EE_CHAR_START+6); +constexpr TypedWhichId EE_CHAR_ITALIC (EE_CHAR_START+7); +constexpr TypedWhichId EE_CHAR_OUTLINE (EE_CHAR_START+8); +constexpr TypedWhichId EE_CHAR_SHADOW (EE_CHAR_START+9); +constexpr TypedWhichId EE_CHAR_ESCAPEMENT (EE_CHAR_START+10); +constexpr TypedWhichId EE_CHAR_PAIRKERNING (EE_CHAR_START+11); +constexpr TypedWhichId EE_CHAR_KERNING (EE_CHAR_START+12); +constexpr TypedWhichId EE_CHAR_WLM (EE_CHAR_START+13); +constexpr TypedWhichId EE_CHAR_LANGUAGE (EE_CHAR_START+14); +constexpr TypedWhichId EE_CHAR_LANGUAGE_CJK (EE_CHAR_START+15); +constexpr TypedWhichId EE_CHAR_LANGUAGE_CTL (EE_CHAR_START+16); +constexpr TypedWhichId EE_CHAR_FONTINFO_CJK (EE_CHAR_START+17); +constexpr TypedWhichId EE_CHAR_FONTINFO_CTL (EE_CHAR_START+18); +constexpr TypedWhichId EE_CHAR_FONTHEIGHT_CJK (EE_CHAR_START+19); +constexpr TypedWhichId EE_CHAR_FONTHEIGHT_CTL (EE_CHAR_START+20); +constexpr TypedWhichId EE_CHAR_WEIGHT_CJK (EE_CHAR_START+21); +constexpr TypedWhichId EE_CHAR_WEIGHT_CTL (EE_CHAR_START+22); +constexpr TypedWhichId EE_CHAR_ITALIC_CJK (EE_CHAR_START+23); +constexpr TypedWhichId EE_CHAR_ITALIC_CTL (EE_CHAR_START+24); +constexpr TypedWhichId EE_CHAR_EMPHASISMARK (EE_CHAR_START+25); +constexpr TypedWhichId EE_CHAR_RELIEF (EE_CHAR_START+26); +constexpr TypedWhichId EE_CHAR_RUBI_DUMMY (EE_CHAR_START+27); +constexpr TypedWhichId EE_CHAR_XMLATTRIBS (EE_CHAR_START+28); +constexpr TypedWhichId EE_CHAR_OVERLINE (EE_CHAR_START+29); +constexpr TypedWhichId EE_CHAR_CASEMAP (EE_CHAR_START+30); +constexpr TypedWhichId EE_CHAR_GRABBAG (EE_CHAR_START+31); +constexpr TypedWhichId EE_CHAR_BKGCOLOR (EE_CHAR_START+32); + +constexpr sal_uInt16 EE_CHAR_END (EE_CHAR_START + 32); + +constexpr sal_uInt16 EE_FEATURE_START (EE_CHAR_END + 1); +constexpr sal_uInt16 EE_FEATURE_TAB (EE_FEATURE_START + 0); +constexpr sal_uInt16 EE_FEATURE_LINEBR (EE_FEATURE_TAB + 1); +constexpr sal_uInt16 EE_FEATURE_NOTCONV (EE_FEATURE_LINEBR + 1); +constexpr TypedWhichId EE_FEATURE_FIELD (EE_FEATURE_NOTCONV + 1); +constexpr sal_uInt16 EE_FEATURE_END (EE_FEATURE_FIELD + 0); + +constexpr sal_uInt16 EE_ITEMS_END (EE_FEATURE_END); + +constexpr sal_uInt16 EDITITEMCOUNT (EE_ITEMS_END - EE_ITEMS_START + 1); + +#endif // _ INCLUDED_EDITENG_EEITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/eerdll.hxx b/include/editeng/eerdll.hxx new file mode 100644 index 000000000..b77d6a0d4 --- /dev/null +++ b/include/editeng/eerdll.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_EERDLL_HXX +#define INCLUDED_EDITENG_EERDLL_HXX + +#include +#include +#include +#include + +class GlobalEditData; +namespace editeng +{ +class SharedVclResources; +} + +OUString EDITENG_DLLPUBLIC EditResId(TranslateId aId); + +class EditDLL +{ + std::unique_ptr pGlobalData; + std::weak_ptr pSharedVcl; + +public: + EditDLL(); + ~EditDLL(); + + GlobalEditData* GetGlobalData() const { return pGlobalData.get(); } + std::shared_ptr GetSharedVclResources(); + static EditDLL& Get(); +}; + +#endif // INCLUDED_EDITENG_EERDLL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/emphasismarkitem.hxx b/include/editeng/emphasismarkitem.hxx new file mode 100644 index 000000000..f54c85735 --- /dev/null +++ b/include/editeng/emphasismarkitem.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_EMPHASISMARKITEM_HXX +#define INCLUDED_EDITENG_EMPHASISMARKITEM_HXX + +#include +#include +#include + +// class SvxEmphasisMarkItem ---------------------------------------------- + +/* [Description] + + This item describes the Font emphasis. +*/ + +class EDITENG_DLLPUBLIC SvxEmphasisMarkItem final : public SfxUInt16Item +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxEmphasisMarkItem( const FontEmphasisMark eVal /*= FontEmphasisMark::NONE*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + SfxEnumItem + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual SvxEmphasisMarkItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + // enum cast + FontEmphasisMark GetEmphasisMark() const + { return static_cast(GetValue()); } +}; + +#endif // INCLUDED_EDITENG_EMPHASISMARKITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/escapementitem.hxx b/include/editeng/escapementitem.hxx new file mode 100644 index 000000000..ea8f99e35 --- /dev/null +++ b/include/editeng/escapementitem.hxx @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_ESCAPEMENTITEM_HXX +#define INCLUDED_EDITENG_ESCAPEMENTITEM_HXX + +#include +#include +#include + +// class SvxEscapementItem ----------------------------------------------- + +#define DFLT_ESC_SUPER 33 // 42% (100 - DFLT_ESC_PROP) of ascent (~80% of font height) = 33% of total font height +#define DFLT_ESC_SUB -8 // 42% of descent (~20% of font height) = -8%. previously -33% (pre-2020), previously 8/100 (pre-2000?) +#define DFLT_ESC_PROP 58 +#define MAX_ESC_POS 13999 +#define DFLT_ESC_AUTO_SUPER (MAX_ESC_POS+1) +#define DFLT_ESC_AUTO_SUB -DFLT_ESC_AUTO_SUPER + +/* [Description] + + This item describes the writing position. +*/ + +class EDITENG_DLLPUBLIC SvxEscapementItem final : public SfxEnumItemInterface +{ + short nEsc; + sal_uInt8 nProp; +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxEscapementItem( const sal_uInt16 nId ); + SvxEscapementItem( const SvxEscapement eEscape, + const sal_uInt16 nId ); + SvxEscapementItem( const short nEsc, const sal_uInt8 nProp, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual SvxEscapementItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + void SetEscapement( const SvxEscapement eNew ) + { + if( SvxEscapement::Off == eNew ) + { + nEsc = 0; + nProp = 100; + } + else + { + nProp = DFLT_ESC_PROP; + if( SvxEscapement::Superscript == eNew ) + nEsc = DFLT_ESC_SUPER; + else + nEsc = DFLT_ESC_SUB; + } + } + SvxEscapement GetEscapement() const { return static_cast< SvxEscapement >( GetEnumValue() ); } + + short &GetEsc() { return nEsc; } + short GetEsc() const { return nEsc; } + + sal_uInt8 &GetProportionalHeight() { return nProp; } + sal_uInt8 GetProportionalHeight() const { return nProp; } + + virtual sal_uInt16 GetValueCount() const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetEnumValue() const override; + virtual void SetEnumValue( sal_uInt16 nNewVal ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/fhgtitem.hxx b/include/editeng/fhgtitem.hxx new file mode 100644 index 000000000..efaad86bd --- /dev/null +++ b/include/editeng/fhgtitem.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FHGTITEM_HXX +#define INCLUDED_EDITENG_FHGTITEM_HXX + +#include +#include +#include + +// class SvxFontHeightItem ----------------------------------------------- + +// Warning: twips values + +/* [Description] + + This item describes the font height +*/ + +constexpr sal_uInt16 FONTHEIGHT_16_VERSION = 0x0001; +constexpr sal_uInt16 FONTHEIGHT_UNIT_VERSION = 0x0002; + +class EDITENG_DLLPUBLIC SvxFontHeightItem final : public SfxPoolItem +{ + sal_uInt32 nHeight; + sal_uInt16 nProp; // default 100% + MapUnit ePropUnit; // Percent, Twip, ... + +private: + friend void Create_legacy_direct_set(SvxFontHeightItem& rItem, sal_uInt32 nH, sal_uInt16 nP, MapUnit eP); + void legacy_direct_set(sal_uInt32 nH, sal_uInt16 nP, MapUnit eP) { nHeight = nH; nProp = nP; ePropUnit = eP; } + +public: + static SfxPoolItem* CreateDefault(); + + SvxFontHeightItem( const sal_uInt32 nSz /*= 240*/, const sal_uInt16 nPropHeight /*= 100*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxFontHeightItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + void SetHeight( sal_uInt32 nNewHeight, const sal_uInt16 nNewProp = 100, + MapUnit eUnit = MapUnit::MapRelative ); + + void SetHeight( sal_uInt32 nNewHeight, sal_uInt16 nNewProp, + MapUnit eUnit, MapUnit eCoreUnit ); + + sal_uInt32 GetHeight() const { return nHeight; } + + void SetProp( sal_uInt16 nNewProp, MapUnit eUnit ) + { + DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" ); + nProp = nNewProp; + ePropUnit = eUnit; + } + + sal_uInt16 GetProp() const { return nProp; } + + MapUnit GetPropUnit() const { return ePropUnit; } // Percent, Twip, ... + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/fieldupdater.hxx b/include/editeng/fieldupdater.hxx new file mode 100644 index 000000000..e15754ffd --- /dev/null +++ b/include/editeng/fieldupdater.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_EDITENG_FIELDUPDATER_HXX +#define INCLUDED_EDITENG_FIELDUPDATER_HXX + +#include +#include + +class EditTextObject; + +namespace editeng +{ +class FieldUpdaterImpl; + +/** + * Wrapper for EditTextObject to handle updating of fields without exposing + * the internals of EditTextObject structure. + */ +class EDITENG_DLLPUBLIC FieldUpdater +{ + std::unique_ptr mpImpl; + +public: + FieldUpdater(EditTextObject& rObj); + FieldUpdater(const FieldUpdater& r); + ~FieldUpdater(); + + /** + * Set a new table ID to all table fields. + * + * @param nTab new table ID + */ + void updateTableFields(int nTab); +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/flditem.hxx b/include/editeng/flditem.hxx new file mode 100644 index 000000000..7dec33e9e --- /dev/null +++ b/include/editeng/flditem.hxx @@ -0,0 +1,438 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FLDITEM_HXX +#define INCLUDED_EDITENG_FLDITEM_HXX + +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::text { + class XTextContent; +} + +class SvNumberFormatter; +class MetaAction; + +// class SvxFieldItem --------------------------------------------------- + + +class EDITENG_DLLPUBLIC SvxFieldData +{ +public: + + static SvxFieldData* Create(const css::uno::Reference& xContent); + + static constexpr auto CLASS_ID = css::text::textfield::Type::UNSPECIFIED; + virtual sal_Int32 GetClassId() const { return CLASS_ID; } + + SvxFieldData(); + virtual ~SvxFieldData(); + + SvxFieldData(SvxFieldData const &) = default; + SvxFieldData(SvxFieldData &&) = default; + SvxFieldData & operator =(SvxFieldData const &) = default; + SvxFieldData & operator =(SvxFieldData &&) = default; + + virtual std::unique_ptr Clone() const; + virtual bool operator==( const SvxFieldData& ) const; + + virtual MetaAction* createBeginComment() const; + static MetaAction* createEndComment(); +}; + +/** + * This item stores a field (SvxFieldData). The field is controlled by or + * belongs to the item. The field itself is determined by a derivation from + * SvxFieldData (RTTI) + */ +class EDITENG_DLLPUBLIC SvxFieldItem final : public SfxPoolItem +{ + std::unique_ptr mpField; +public: + SvxFieldItem( std::unique_ptr pField, const sal_uInt16 nId ); + SvxFieldItem( const SvxFieldData& rField, const sal_uInt16 nId ); + SvxFieldItem( const SvxFieldItem& rItem ); + virtual ~SvxFieldItem() override; + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SvxFieldItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + const SvxFieldData* GetField() const { return mpField.get(); } +}; + + +// The following are the derivatives of SvxFieldData ... + + +enum class SvxDateType { Fix, Var }; +enum class SvxDateFormat { + AppDefault = 0, // Set as in App + System, // Set as in System + StdSmall, + StdBig, + A, // 13.02.96 + B, // 13.02.1996 + C, // 13.Feb 1996 + D, // 13.February 1996 + E, // Tue, 13.February 1996 + F // Tuesday, 13.February 1996 +}; + +class EDITENG_DLLPUBLIC SvxDateField final : public SvxFieldData +{ + sal_Int32 nFixDate; + SvxDateType eType; + SvxDateFormat eFormat; + +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::DATE; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + + SvxDateField(); + explicit SvxDateField( const Date& rDate, + SvxDateType eType, + SvxDateFormat eFormat = SvxDateFormat::StdSmall ); + + sal_Int32 GetFixDate() const { return nFixDate; } + void SetFixDate( const Date& rDate ) { nFixDate = rDate.GetDate(); } + + SvxDateType GetType() const { return eType; } + void SetType( SvxDateType eTp ) { eType = eTp; } + + SvxDateFormat GetFormat() const { return eFormat; } + void SetFormat( SvxDateFormat eFmt ) { eFormat = eFmt; } + + // If eLanguage==LANGUAGE_DONTKNOW the language/country + // used in number formatter initialization is taken. + OUString GetFormatted( SvNumberFormatter& rFormatter, LanguageType eLanguage ) const; + static OUString GetFormatted( Date const & rDate, SvxDateFormat eFormat, SvNumberFormatter& rFormatter, LanguageType eLanguage ); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; + + virtual MetaAction* createBeginComment() const override; +}; + + +enum class SvxURLFormat { + AppDefault = 0, // Set as in App + Url, // Represent URL + Repr // Constitute representation +}; + +class EDITENG_DLLPUBLIC SvxURLField final : public SvxFieldData +{ +private: + SvxURLFormat eFormat; + OUString aURL; // URL-Address + OUString aRepresentation; // What is shown + OUString aTargetFrame; // In what Frame + +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::URL; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + + SvxURLField(); + SvxURLField( OUString aURL, OUString aRepres, SvxURLFormat eFmt = SvxURLFormat::Url ); + + const OUString& GetURL() const { return aURL; } + void SetURL( const OUString& rURL ) { aURL = rURL; } + + const OUString& GetRepresentation() const { return aRepresentation; } + void SetRepresentation( const OUString& rRep ) { aRepresentation= rRep; } + + const OUString& GetTargetFrame() const { return aTargetFrame; } + void SetTargetFrame( const OUString& rFrm ) { aTargetFrame = rFrm; } + + SvxURLFormat GetFormat() const { return eFormat; } + void SetFormat( SvxURLFormat eFmt ) { eFormat = eFmt; } + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; + + virtual MetaAction* createBeginComment() const override; +}; + +class EDITENG_DLLPUBLIC SvxPageField final: public SvxFieldData +{ +public: + virtual sal_Int32 GetClassId() const override { return css::text::textfield::Type::PAGE; } + SvxPageField(); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; + + virtual MetaAction* createBeginComment() const override; +}; + +class EDITENG_DLLPUBLIC SvxPageTitleField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::PAGE_NAME; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxPageTitleField(); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; + + virtual MetaAction* createBeginComment() const override; +}; + +class EDITENG_DLLPUBLIC SvxPagesField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::PAGES; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxPagesField(); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + +class EDITENG_DLLPUBLIC SvxTimeField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::TIME; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxTimeField(); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; + + virtual MetaAction* createBeginComment() const override; +}; + +class EDITENG_DLLPUBLIC SvxFileField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::DOCINFO_TITLE; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxFileField(); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + +class EDITENG_DLLPUBLIC SvxTableField final: public SvxFieldData +{ + int mnTab; +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::TABLE; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxTableField(); + explicit SvxTableField(int nTab); + + void SetTab(int nTab); + int GetTab() const { return mnTab;} + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + + +enum class SvxTimeType { + Fix, + Var +}; +enum class SvxTimeFormat { + AppDefault = 0, // Set as in App + System, // Set as in System + Standard, + HH24_MM, // 13:49 + HH24_MM_SS, // 13:49:38 + HH24_MM_SS_00, // 13:49:38.78 + HH12_MM, // 01:49 + HH12_MM_SS, // 01:49:38 + HH12_MM_SS_00, // 01:49:38.78 + HH12_MM_AMPM, // 01:49 PM + HH12_MM_SS_AMPM, // 01:49:38 PM + HH12_MM_SS_00_AMPM // 01:49:38.78 PM +}; + +class EDITENG_DLLPUBLIC SvxExtTimeField final : public SvxFieldData +{ +private: + sal_Int64 m_nFixTime; + SvxTimeType eType; + SvxTimeFormat eFormat; + +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::EXTENDED_TIME; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxExtTimeField(); + explicit SvxExtTimeField( const tools::Time& rTime, + SvxTimeType eType, + SvxTimeFormat eFormat = SvxTimeFormat::Standard ); + + sal_Int64 GetFixTime() const { return m_nFixTime; } + void SetFixTime( const tools::Time& rTime ) { m_nFixTime = rTime.GetTime(); } + + SvxTimeType GetType() const { return eType; } + void SetType( SvxTimeType eTp ) { eType = eTp; } + + SvxTimeFormat GetFormat() const { return eFormat; } + void SetFormat( SvxTimeFormat eFmt ) { eFormat = eFmt; } + + // If eLanguage==LANGUAGE_DONTKNOW the language/country + // used in number formatter initialization is taken. + OUString GetFormatted( SvNumberFormatter& rFormatter, LanguageType eLanguage ) const; + static OUString GetFormatted( tools::Time const & rTime, SvxTimeFormat eFormat, SvNumberFormatter& rFormatter, LanguageType eLanguage ); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; + + virtual MetaAction* createBeginComment() const override; +}; + + +enum class SvxFileType { + Fix, + Var +}; +enum class SvxFileFormat { + NameAndExt = 0, // File name with Extension + PathFull, // full path + PathOnly, // only path + NameOnly // only file name +}; + + +class EDITENG_DLLPUBLIC SvxExtFileField final : public SvxFieldData +{ +private: + OUString aFile; + SvxFileType eType; + SvxFileFormat eFormat; + +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::EXTENDED_FILE; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxExtFileField(); + explicit SvxExtFileField( const OUString& rString, + SvxFileType eType = SvxFileType::Var, + SvxFileFormat eFormat = SvxFileFormat::PathFull ); + + const OUString& GetFile() const { return aFile; } + void SetFile( const OUString& rString ) { aFile = rString; } + + SvxFileType GetType() const { return eType; } + void SetType( SvxFileType eTp ) { eType = eTp; } + + SvxFileFormat GetFormat() const { return eFormat; } + void SetFormat( SvxFileFormat eFmt ) { eFormat = eFmt; } + + OUString GetFormatted() const; + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + + +enum class SvxAuthorType { + Fix, Var +}; +enum class SvxAuthorFormat { + FullName, // full name + LastName, // Only Last name + FirstName, // Only first name + ShortName // Initials +}; + +class EDITENG_DLLPUBLIC SvxAuthorField final : public SvxFieldData +{ +private: + OUString aName; + OUString aFirstName; + OUString aShortName; + SvxAuthorType eType; + SvxAuthorFormat eFormat; + +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::AUTHOR; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxAuthorField( + const OUString& rFirstName, + const OUString& rLastName, + const OUString& rShortName, + SvxAuthorType eType = SvxAuthorType::Var, + SvxAuthorFormat eFormat = SvxAuthorFormat::FullName ); + + SvxAuthorType GetType() const { return eType; } + void SetType( SvxAuthorType eTp ) { eType = eTp; } + + SvxAuthorFormat GetFormat() const { return eFormat; } + void SetFormat( SvxAuthorFormat eFmt ) { eFormat = eFmt; } + + OUString GetFormatted() const; + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + +/** this field is used as a placeholder for a header&footer in impress. The actual + value is stored at the page */ +class EDITENG_DLLPUBLIC SvxHeaderField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::PRESENTATION_HEADER; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxHeaderField(); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + +/** this field is used as a placeholder for a header&footer in impress. The actual + value is stored at the page */ +class EDITENG_DLLPUBLIC SvxFooterField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::PRESENTATION_FOOTER; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxFooterField(); + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + +/** this field is used as a placeholder for a header&footer in impress. The actual + value is stored at the page */ +class EDITENG_DLLPUBLIC SvxDateTimeField final: public SvxFieldData +{ +public: + static constexpr auto CLASS_ID = css::text::textfield::Type::PRESENTATION_DATE_TIME; + virtual sal_Int32 GetClassId() const override { return CLASS_ID; } + SvxDateTimeField(); + + static OUString GetFormatted( Date const & rDate, tools::Time const & rTime, + SvxDateFormat eDateFormat, SvxTimeFormat eTimeFormat, + SvNumberFormatter& rFormatter, LanguageType eLanguage ); + + virtual std::unique_ptr Clone() const override; + virtual bool operator==( const SvxFieldData& ) const override; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/flstitem.hxx b/include/editeng/flstitem.hxx new file mode 100644 index 000000000..71756464e --- /dev/null +++ b/include/editeng/flstitem.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FLSTITEM_HXX +#define INCLUDED_EDITENG_FLSTITEM_HXX + +#include +#include +#include +#include + +// class SvxFontListItem ------------------------------------------------- + +class FontList; + +/* + [Description] + + This item serves as a transport medium for a font list. The font list is + not copied and not deleted! +*/ + +class EDITENG_DLLPUBLIC SvxFontListItem final : public SfxPoolItem +{ +private: + const FontList* pFontList; + css::uno::Sequence< OUString > aFontNameSeq; + +public: + SvxFontListItem( const FontList* pFontLst, + const sal_uInt16 nId ); + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SvxFontListItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + const FontList* GetFontList() const { return pFontList; } +}; + + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/fontitem.hxx b/include/editeng/fontitem.hxx new file mode 100644 index 000000000..deabf3101 --- /dev/null +++ b/include/editeng/fontitem.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FONTITEM_HXX +#define INCLUDED_EDITENG_FONTITEM_HXX + +#include +#include +#include +#include + +/** This item describes a Font. +*/ +class EDITENG_DLLPUBLIC SvxFontItem final : public SfxPoolItem +{ + OUString aFamilyName; + OUString aStyleName; + FontFamily eFamily; + FontPitch ePitch; + rtl_TextEncoding eTextEncoding; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxFontItem(const sal_uInt16 nId); + SvxFontItem(const FontFamily eFam, OUString aFamilyName, + OUString aStyleName, + const FontPitch eFontPitch /*= PITCH_DONTKNOW*/, + const rtl_TextEncoding eFontTextEncoding /*= RTL_TEXTENCODING_DONTKNOW*/, + const sal_uInt16 nId); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==(const SfxPoolItem& rItem) const override; + bool operator<(const SfxPoolItem& rCmp) const override; + virtual SvxFontItem* Clone(SfxItemPool *pPool = nullptr) const override; + virtual bool QueryValue(css::uno::Any& rVal, sal_uInt8 nMemberId = 0) const override; + virtual bool PutValue(const css::uno::Any& rVal, sal_uInt8 nMemberId) override; + + virtual bool GetPresentation(SfxItemPresentation ePres, + MapUnit eCoreMetric, MapUnit ePresMetric, + OUString &rText, const IntlWrapper&) const override; + + // Access methods: + void SetFamilyName(const OUString& rFamilyName) + { + aFamilyName = rFamilyName; + } + const OUString &GetFamilyName() const + { + return aFamilyName; + } + + void SetStyleName(const OUString &rStyleName) + { + aStyleName = rStyleName; + } + const OUString &GetStyleName() const + { + return aStyleName; + } + + void SetFamily(FontFamily _eFamily) + { + eFamily = _eFamily; + } + FontFamily GetFamily() const + { + return eFamily; + } + + void SetPitch(FontPitch _ePitch) + { + ePitch = _ePitch; + } + FontPitch GetPitch() const + { + return ePitch; + } + + void SetCharSet(rtl_TextEncoding _eEncoding) + { + eTextEncoding = _eEncoding; + } + rtl_TextEncoding GetCharSet() const + { + return eTextEncoding; + } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +EDITENG_DLLPUBLIC void GetDefaultFonts(SvxFontItem& rLatin, + SvxFontItem& rAsian, + SvxFontItem& rComplex); + +#endif // INCLUDED_EDITENG_FONTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/forbiddencharacterstable.hxx b/include/editeng/forbiddencharacterstable.hxx new file mode 100644 index 000000000..f91aade4a --- /dev/null +++ b/include/editeng/forbiddencharacterstable.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_FORBIDDENCHARACTERSTABLE_HXX +#define INCLUDED_EDITENG_FORBIDDENCHARACTERSTABLE_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno { class XComponentContext; } + +class EDITENG_DLLPUBLIC SvxForbiddenCharactersTable +{ +public: + typedef std::map Map; +private: + Map maMap; + css::uno::Reference< css::uno::XComponentContext > m_xContext; + SvxForbiddenCharactersTable(css::uno::Reference< css::uno::XComponentContext > xContext); + +public: + static std::shared_ptr makeForbiddenCharactersTable(const css::uno::Reference& rxContext); + + Map& GetMap() { return maMap; } + const css::i18n::ForbiddenCharacters* GetForbiddenCharacters( LanguageType nLanguage, bool bGetDefault ); + void SetForbiddenCharacters( LanguageType nLanguage , const css::i18n::ForbiddenCharacters& ); + void ClearForbiddenCharacters( LanguageType nLanguage ); +}; + +#endif // INCLUDED_EDITENG_FORBIDDENCHARACTERSTABLE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/forbiddenruleitem.hxx b/include/editeng/forbiddenruleitem.hxx new file mode 100644 index 000000000..93e46b433 --- /dev/null +++ b/include/editeng/forbiddenruleitem.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FORBIDDENRULEITEM_HXX +#define INCLUDED_EDITENG_FORBIDDENRULEITEM_HXX + +#include +#include + +// class SvxForbiddenRuleItem ----------------------------------------- + +/* [Description] + + This item describe how to handle the last character of a line. +*/ + +class EDITENG_DLLPUBLIC SvxForbiddenRuleItem final : public SfxBoolItem +{ +public: + SvxForbiddenRuleItem( bool bOn /*= false*/, + const sal_uInt16 nId ); + + virtual SvxForbiddenRuleItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/formatbreakitem.hxx b/include/editeng/formatbreakitem.hxx new file mode 100644 index 000000000..71f331769 --- /dev/null +++ b/include/editeng/formatbreakitem.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FORMATBREAKITEM_HXX +#define INCLUDED_EDITENG_FORMATBREAKITEM_HXX + +#include +#include +#include + + +// class SvxFormatBreakItem ------------------------------------------------- + +/* [Description] + + This item describes a wrap-attribute + Automatic?, Page or column break, before or after? +*/ +constexpr sal_uInt16 FMTBREAK_NOAUTO = 0x0001; + +class EDITENG_DLLPUBLIC SvxFormatBreakItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + inline SvxFormatBreakItem( const SvxBreak eBrk /*= SvxBreak::NONE*/, + const sal_uInt16 nWhich ); + SvxFormatBreakItem(SvxFormatBreakItem const &) = default; // SfxPoolItem copy function dichotomy + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + + virtual SvxFormatBreakItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual sal_uInt16 GetValueCount() const override; + + SvxBreak GetBreak() const { return GetValue(); } +}; + + +inline SvxFormatBreakItem::SvxFormatBreakItem( const SvxBreak eBreak, + const sal_uInt16 _nWhich ) : + SfxEnumItem( _nWhich, eBreak ) +{} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/frmdir.hxx b/include/editeng/frmdir.hxx new file mode 100644 index 000000000..ef5275d26 --- /dev/null +++ b/include/editeng/frmdir.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_FRMDIR_HXX +#define INCLUDED_EDITENG_FRMDIR_HXX + +#include +#include + +/** + * Defines possible text directions in frames. + * A scoped enum over the constants in css::text:WritingMode2. + */ +enum class SvxFrameDirection +{ + /** used as an error return value in SW */ + Unknown = -1, + + /** Horizontal, from left to right, from top to bottom + (typical for western languages). */ + Horizontal_LR_TB = css::text::WritingMode2::LR_TB, + + /** Horizontal, from right to left, from top to bottom + (typical for arabic/hebrew languages). */ + Horizontal_RL_TB = css::text::WritingMode2::RL_TB, + + /** Vertical, from top to bottom, from right to left + (typical for asian languages). */ + Vertical_RL_TB = css::text::WritingMode2::TB_RL, + + /** Vertical, from top to bottom, from left to right + (typical for mongol language). */ + Vertical_LR_TB = css::text::WritingMode2::TB_LR, + + /** Use the value from the environment, can only be used in frames. */ + Environment = css::text::WritingMode2::CONTEXT, + + /** Vertical, from bottom to top, from left to right. */ + Vertical_LR_BT = css::text::WritingMode2::BT_LR, +}; + +TranslateId getFrmDirResId(size_t nIndex); + +#endif // INCLUDED_EDITENG_FRMDIR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/frmdiritem.hxx b/include/editeng/frmdiritem.hxx new file mode 100644 index 000000000..2a439aa50 --- /dev/null +++ b/include/editeng/frmdiritem.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_FRMDIRITEM_HXX +#define INCLUDED_EDITENG_FRMDIRITEM_HXX + +#include +#include +#include + +/* This item defines a frame direction, which place the content inside + a frame. It exist different kind of directions which are used to the + layout text for Western, CJK and CTL languages. +*/ + +class EDITENG_DLLPUBLIC SvxFrameDirectionItem final : public SfxEnumItem +{ +public: + SvxFrameDirectionItem( SvxFrameDirection nValue, sal_uInt16 nWhich ); + virtual ~SvxFrameDirectionItem() override; + + SvxFrameDirectionItem(SvxFrameDirectionItem const &) = default; + SvxFrameDirectionItem(SvxFrameDirectionItem &&) = default; + SvxFrameDirectionItem & operator =(SvxFrameDirectionItem const &) = delete; + SvxFrameDirectionItem & operator =(SvxFrameDirectionItem &&) = delete; + + virtual SvxFrameDirectionItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual sal_uInt16 GetValueCount() const override + { + return sal_uInt16(SvxFrameDirection::Vertical_LR_BT) + 1; + } + + // SfxPoolItem copy function dichotomy + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif // INCLUDED_EDITENG_FRMDIRITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/hangulhanja.hxx b/include/editeng/hangulhanja.hxx new file mode 100644 index 000000000..f2a5dcf99 --- /dev/null +++ b/include/editeng/hangulhanja.hxx @@ -0,0 +1,288 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_HANGULHANJA_HXX +#define INCLUDED_EDITENG_HANGULHANJA_HXX + +#include +#include +#include + +namespace com::sun::star::lang { struct Locale; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { template class Sequence; } +namespace vcl { class Font; } +namespace weld { class Widget; } + + +namespace editeng +{ + + + class HangulHanjaConversion_Impl; + + + //= HangulHanjaConversion + + /** encapsulates Hangul-Hanja conversion functionality + +

    terminology: +

    • A text portion is some (potentially large) piece of text + which is to be analyzed for convertible sub-strings.
    • +
    • A text unit is a sub string in a text portion, which is + to be converted as a whole.
    • +
    + For instance, you could have two independent selections within your document, which are then + two text portions. A text unit would be single Hangul/Hanja words within a portion, or even + single Hangul syllabification when "replace by character" is enabled. +

    + */ + class EDITENG_DLLPUBLIC HangulHanjaConversion + { + friend class HangulHanjaConversion_Impl; + + public: + enum ReplacementAction + { + eExchange, // simply exchange one text with another + eReplacementBracketed, // keep the original, and put the replacement in brackets after it + eOriginalBracketed, // replace the original text, but put it in brackets after the replacement + eReplacementAbove, // keep the original, and put the replacement text as ruby text above it + eOriginalAbove, // replace the original text, but put it as ruby text above it + eReplacementBelow, // keep the original, and put the replacement text as ruby text below it + eOriginalBelow // replace the original text, but put it as ruby text below it + }; + + enum ConversionType // does not specify direction... + { + eConvHangulHanja, // Korean Hangul/Hanja conversion + eConvSimplifiedTraditional // Chinese simplified / Chinese traditional conversion + }; + + // Note: conversion direction for eConvSimplifiedTraditional is + // specified by source language. + // This one is for Hangul/Hanja where source and target language + // are the same. + enum ConversionDirection + { + eHangulToHanja, + eHanjaToHangul + }; + + enum ConversionFormat + { + eSimpleConversion, // used for simplified / traditional Chinese as well + eHangulBracketed, + eHanjaBracketed, + eRubyHanjaAbove, + eRubyHanjaBelow, + eRubyHangulAbove, + eRubyHangulBelow + }; + + private: + ::std::unique_ptr< HangulHanjaConversion_Impl > m_pImpl; + + // used to set initial values of m_pImpl object from saved ones + static bool m_bUseSavedValues; // defines if the following two values should be used for initialization + static bool m_bTryBothDirectionsSave; + static ConversionDirection m_ePrimaryConversionDirectionSave; + + HangulHanjaConversion (const HangulHanjaConversion &) = delete; + HangulHanjaConversion & operator= (const HangulHanjaConversion &) = delete; + + public: + HangulHanjaConversion( + weld::Widget* pUIParent, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::lang::Locale& _rSourceLocale, + const css::lang::Locale& _rTargetLocale, + const vcl::Font* _pTargetFont, + sal_Int32 nOptions, + bool _bIsInteractive + ); + + virtual ~HangulHanjaConversion() COVERITY_NOEXCEPT_FALSE; + + // converts the whole document + void ConvertDocument(); + + weld::Widget* GetUIParent() const; // the parent window for any UI we raise + LanguageType GetSourceLanguage() const; + LanguageType GetTargetLanguage() const; + const vcl::Font* GetTargetFont() const; + sal_Int32 GetConversionOptions() const; + bool IsInteractive() const; + + // chinese text conversion + static inline bool IsSimplified( LanguageType nLang ); + static inline bool IsTraditional( LanguageType nLang ); + static inline bool IsChinese( LanguageType nLang ); + + // used to specify that the conversion direction states from the + // last incarnation should be used as + // initial conversion direction for the next incarnation. + // (A hack used to transport a state information from + // one incarnation to the next. Used in Writers text conversion...) + static void SetUseSavedConversionDirectionState( bool bVal ); + static bool IsUseSavedConversionDirectionState(); + + protected: + /** retrieves the next text portion which is to be analyzed + +

    pseudo-abstract, needs to be overridden

    + + @param _rNextPortion + upon return, this must contain the next text portion + @param _rLangOfPortion + upon return, this must contain the language for the found text portion. + (necessary for Chinese translation since there are 5 language variants + too look for even if the 'source' language usually is only 'simplified' + or 'traditional'.) + */ + virtual void GetNextPortion( + OUString& /* [out] */ _rNextPortion, + LanguageType& /* [out] */ _rLangOfPortion, + bool /* [in] */ _bAllowImplicitChangesForNotConvertibleText ) = 0; + + /** announces a new "current unit" + +

    This will be called whenever it is necessary to interactively ask the user for + a conversion. In such a case, a range within the current portion (see GetNextPortion) + is presented to the user for choosing a substitution. Additionally, this method is called, + so that derived classes can e.g. highlight this text range in a document view.

    + +

    Note that the indexes are relative to the most recent replace action. See + ReplaceUnit for details.

    + + @param _nUnitStart + the start index of the unit + + @param _nUnitEnd + the start index (exclusively!) of the unit. + + @param _bAllowImplicitChangesForNotConvertibleText + allows implicit changes other than the text itself for the + text parts not being convertible. + Used for chinese translation to attribute all not convertible + text (e.g. western text, empty paragraphs, spaces, ...) to + the target language and target font of the conversion. + This is to ensure that after the conversion any new text entered + anywhere in the document will have the target language (of course + CJK Language only) and target font (CJK font only) set. + + @see GetNextPortion + */ + virtual void HandleNewUnit( const sal_Int32 _nUnitStart, const sal_Int32 _nUnitEnd ) = 0; + + /** replaces a text unit within a text portion with a new text + +

    pseudo-abstract, needs to be overridden

    + +

    Note an important thing about the indices: They are always relative to the previous + call of ReplaceUnit. This means when you get a call to ReplaceUnit, and replace some text + in your document, then you have to remember the document position immediately behind + the changed text. In a next call to ReplaceUnit, an index of 0 will denote exactly + this position behind the previous replacement
    + The reason is that this class here does not know anything about your document structure, + so after a replacement took place, it's impossible to address anything in the range from the + beginning of the portion up to the replaced text.
    + In the very first call to ReplaceUnit, an index of 0 denotes the very first position of + the current portion.

    + +

    If the language of the text to be replaced is different from + the target language (as given by 'GetTargetLanguage') for example + when converting simplified Chinese from/to traditional Chinese + the language attribute of the new text has to be changed as well, + **and** the font is to be set to the default (document) font for + that language.

    + + @param _nUnitStart + the start index of the range to replace + + @param _nUnitEnd + the end index (exclusively!) of the range to replace. E.g., an index + pair (4,5) indicates a range of length 1. + + @param _rOrigText + the original text to be replaced (as returned by GetNextPortion). + Since in Chinese conversion the original text is needed as well + in order to only do the minimal necessary text changes and to keep + as much attributes as possible this is supplied here as well. + + @param _rReplaceWith + The replacement text + + @param _rOffsets + An sequence matching the indices (characters) of _rReplaceWith + to the indices of the characters in the original text they are + replacing. + This is necessary since some portions of the text may get + converted in portions of different length than the original. + The sequence will be empty if all conversions in the text are + of equal length. That is if always the character at index i in + _rOffsets is replacing the character at index i in the original + text for all valid index values of i. + + @param _eAction + replacement action to take + + @param pNewUnitLanguage + if the replacement unit is required to have a new language that + is specified here. If the language is to be left unchanged this + is the 0 pointer. + */ + virtual void ReplaceUnit( + const sal_Int32 _nUnitStart, const sal_Int32 _nUnitEnd, + const OUString& _rOrigText, + const OUString& _rReplaceWith, + const css::uno::Sequence< sal_Int32 > &_rOffsets, + ReplacementAction _eAction, + LanguageType *pNewUnitLanguage + ) = 0; + + /** specifies if rubies are supported by the document implementing + this class. + + @return + if rubies are supported. + */ + virtual bool HasRubySupport() const = 0; + }; + + bool HangulHanjaConversion::IsSimplified( LanguageType nLang ) + { + return MsLangId::isSimplifiedChinese(nLang); + } + + bool HangulHanjaConversion::IsTraditional( LanguageType nLang ) + { + return MsLangId::isTraditionalChinese(nLang); + } + + bool HangulHanjaConversion::IsChinese( LanguageType nLang ) + { + return MsLangId::isChinese(nLang); + } + +} + + +#endif // INCLUDED_EDITENG_HANGULHANJA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/hngpnctitem.hxx b/include/editeng/hngpnctitem.hxx new file mode 100644 index 000000000..c59d4db0c --- /dev/null +++ b/include/editeng/hngpnctitem.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_HNGPNCTITEM_HXX +#define INCLUDED_EDITENG_HNGPNCTITEM_HXX + +#include +#include + +// class SvxHangingPunctuationItem ----------------------------------------- + +/* [Description] + + This item describe how to handle the last character of a line. +*/ + +class EDITENG_DLLPUBLIC SvxHangingPunctuationItem final : public SfxBoolItem +{ +public: + SvxHangingPunctuationItem( bool bOn /*= false*/, const sal_uInt16 nId ); + + virtual SvxHangingPunctuationItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/hyphenzoneitem.hxx b/include/editeng/hyphenzoneitem.hxx new file mode 100644 index 000000000..7104d2d7d --- /dev/null +++ b/include/editeng/hyphenzoneitem.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_HYPHENZONEITEM_HXX +#define INCLUDED_EDITENG_HYPHENZONEITEM_HXX + +#include +#include + +// class SvxHyphenZoneItem ----------------------------------------------- + +/* [Description] + + This item describes a hyphenation attribute (automatic?, number of + characters at the end of the line and start). +*/ + +class EDITENG_DLLPUBLIC SvxHyphenZoneItem final : public SfxPoolItem +{ + bool bHyphen : 1; + bool bPageEnd : 1; + bool bNoCapsHyphenation : 1; + bool bNoLastWordHyphenation : 1; + sal_uInt8 nMinLead; + sal_uInt8 nMinTrail; + sal_uInt8 nMaxHyphens; // max. consecutive lines with hyphenation + sal_uInt8 nMinWordLength; // hyphenate only words with at least nMinWordLength characters + sal_uInt16 nTextHyphenZone; // don't force hyphenation at line end, allow this extra white space + +public: + static SfxPoolItem* CreateDefault(); + + SvxHyphenZoneItem( const bool bHyph /*= false*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxHyphenZoneItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + void SetHyphen( const bool bNew ) { bHyphen = bNew; } + bool IsHyphen() const { return bHyphen; } + + void SetPageEnd( const bool bNew ) { bPageEnd = bNew; } + bool IsPageEnd() const { return bPageEnd; } + + void SetNoCapsHyphenation( const bool bNew ) { bNoCapsHyphenation = bNew; } + bool IsNoCapsHyphenation() const { return bNoCapsHyphenation; } + void SetNoLastWordHyphenation( const bool bNew ) { bNoLastWordHyphenation = bNew; } + bool IsNoLastWordHyphenation() const { return bNoLastWordHyphenation; } + + sal_uInt8 &GetMinLead() { return nMinLead; } + sal_uInt8 GetMinLead() const { return nMinLead; } + + sal_uInt8 &GetMinTrail() { return nMinTrail; } + sal_uInt8 GetMinTrail() const { return nMinTrail; } + + sal_uInt8 &GetMaxHyphens() { return nMaxHyphens; } + sal_uInt8 GetMaxHyphens() const { return nMaxHyphens; } + + sal_uInt8 &GetMinWordLength() { return nMinWordLength; } + sal_uInt8 GetMinWordLength() const { return nMinWordLength; } + + sal_uInt16 &GetTextHyphenZone() { return nTextHyphenZone; } + sal_uInt16 GetTextHyphenZone() const { return nTextHyphenZone; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/itemtype.hxx b/include/editeng/itemtype.hxx new file mode 100644 index 000000000..7f70a7073 --- /dev/null +++ b/include/editeng/itemtype.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_ITEMTYPE_HXX +#define INCLUDED_EDITENG_ITEMTYPE_HXX + +// forward --------------------------------------------------------------- +#include +#include +#include +#include +#include + +class Color; +class IntlWrapper; +// static and prototypes ------------------------------------------------- + +inline constexpr OUStringLiteral cpDelim = u", "; + +EDITENG_DLLPUBLIC OUString GetMetricText( tools::Long nVal, MapUnit eSrcUnit, MapUnit eDestUnit, const IntlWrapper * pIntl ); +OUString GetColorString( const Color& rCol ); +EDITENG_DLLPUBLIC TranslateId GetMetricId(MapUnit eUnit); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/justifyitem.hxx b/include/editeng/justifyitem.hxx new file mode 100644 index 000000000..616427f46 --- /dev/null +++ b/include/editeng/justifyitem.hxx @@ -0,0 +1,104 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_JUSTIFYITEM_HXX +#define INCLUDED_EDITENG_JUSTIFYITEM_HXX + +#include +#include +#include +#include + +class EDITENG_DLLPUBLIC SvxHorJustifyItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxHorJustifyItem( const sal_uInt16 nId ); + + SvxHorJustifyItem( + const SvxCellHorJustify eJustify /*= SvxCellHorJustify::Standard*/, + const sal_uInt16 nId ); + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual sal_uInt16 GetValueCount() const override; + static OUString GetValueText( SvxCellHorJustify nVal ); + virtual SvxHorJustifyItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + SvxHorJustifyItem(SvxHorJustifyItem const &) = default; // SfxPoolItem copy function dichotomy +}; + + +class EDITENG_DLLPUBLIC SvxVerJustifyItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxVerJustifyItem( const sal_uInt16 nId ); + + SvxVerJustifyItem( + const SvxCellVerJustify eJustify, + const sal_uInt16 nId ); + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual sal_uInt16 GetValueCount() const override; + static OUString GetValueText( SvxCellVerJustify nVal ); + virtual SvxVerJustifyItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + SvxVerJustifyItem(SvxVerJustifyItem const &) = default; // SfxPoolItem copy function dichotomy +}; + + +class EDITENG_DLLPUBLIC SvxJustifyMethodItem final : public SfxEnumItem +{ +public: + SvxJustifyMethodItem( + const SvxCellJustifyMethod eMethod, + const sal_uInt16 nId ); + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual sal_uInt16 GetValueCount() const override; + static OUString GetValueText( SvxCellJustifyMethod nVal ); + virtual SvxJustifyMethodItem* Clone( SfxItemPool *pPool = nullptr ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/keepitem.hxx b/include/editeng/keepitem.hxx new file mode 100644 index 000000000..c108560ce --- /dev/null +++ b/include/editeng/keepitem.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_KEEPITEM_HXX +#define INCLUDED_EDITENG_KEEPITEM_HXX + +#include +#include + + +// class SvxFormatKeepItem ------------------------------------------------ + +/* [Description] + + This item describes a logical variable "keep paragraphs together?". +*/ + +class EDITENG_DLLPUBLIC SvxFormatKeepItem final : public SfxBoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + inline SvxFormatKeepItem( const bool bKeep /*= false*/, + const sal_uInt16 _nWhich ); + SvxFormatKeepItem(SvxFormatKeepItem const &) = default; // SfxPoolItem copy function dichotomy + + // "pure virtual Methods" from SfxPoolItem + virtual SvxFormatKeepItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +inline SvxFormatKeepItem::SvxFormatKeepItem( const bool bKeep, const sal_uInt16 _nWhich ) : + SfxBoolItem( _nWhich, bKeep ) +{} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/kernitem.hxx b/include/editeng/kernitem.hxx new file mode 100644 index 000000000..23a8c1909 --- /dev/null +++ b/include/editeng/kernitem.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_KERNITEM_HXX +#define INCLUDED_EDITENG_KERNITEM_HXX + +#include +#include + +// class SvxKerningItem -------------------------------------------------- + +// Note: Twips value +// Twips: 0 = no kerning + +/* [Description] + + This item describes the kerning. +*/ + +class EDITENG_DLLPUBLIC SvxKerningItem final : public SfxInt16Item +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxKerningItem( const short nKern /*= 0*/, const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxKerningItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/langitem.hxx b/include/editeng/langitem.hxx new file mode 100644 index 000000000..4d3852141 --- /dev/null +++ b/include/editeng/langitem.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_LANGITEM_HXX +#define INCLUDED_EDITENG_LANGITEM_HXX + +#include +#include +#include + +// class SvxLanguageItem ------------------------------------------------- + +/* [Description] + + This item describes a Language. +*/ + +// MSVC hack: +class SAL_DLLPUBLIC_RTTI SvxLanguageItem_Base: public SfxEnumItem { +protected: + explicit SvxLanguageItem_Base(sal_uInt16 nWhich, LanguageType nValue): + SfxEnumItem(nWhich, nValue) + {} +}; + +class EDITENG_DLLPUBLIC SvxLanguageItem final : public SvxLanguageItem_Base +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxLanguageItem( const LanguageType eLang /*= LANGUAGE_GERMAN*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool GetPresentation(SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper&) const override; + + virtual SvxLanguageItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual sal_uInt16 GetValueCount() const override; + + SvxLanguageItem(SvxLanguageItem const &) = default; // SfxPoolItem copy function dichotomy + + LanguageType GetLanguage() const + { return GetValue(); } + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/legacyitem.hxx b/include/editeng/legacyitem.hxx new file mode 100644 index 000000000..d92bcb59d --- /dev/null +++ b/include/editeng/legacyitem.hxx @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_LEGACYITEM_HXX +#define INCLUDED_EDITENG_LEGACYITEM_HXX + +#include +#include + +////////////////////////////////////////////////////////////////////////////// +// // editeng +// SvxFontItem aFont; +// SvxFontHeightItem aHeight; +// SvxWeightItem aWeight; +// SvxPostureItem aPosture; +// SvxUnderlineItem aUnderline; +// SvxOverlineItem aOverline; +// SvxCrossedOutItem aCrossedOut; +// SvxContourItem aContour; +// SvxShadowedItem aShadowed; +// SvxColorItem aColor; +// SvxBoxItem aBox; +// SvxLineItem aTLBR; +// SvxBrushItem aBackground; +// SvxAdjustItem aAdjust; +// SvxHorJustifyItem aHorJustify; +// SvxVerJustifyItem aVerJustify; +// SvxFrameDirectionItem m_aTextOrientation; +////////////////////////////////////////////////////////////////////////////// + +class SvStream; +class SvxFontItem; +class SvxFontHeightItem; +class SvxWeightItem; +class SvxPostureItem; +class SvxTextLineItem; +class SvxCrossedOutItem; +class SvxShadowedItem; +class SvxColorItem; +class SvxBoxItem; +class SvxLineItem; +class SvxBrushItem; +class SvxAdjustItem; +class SvxHorJustifyItem; +class SvxVerJustifyItem; +class SvxFrameDirectionItem; +class SvxFormatBreakItem; +class SvxFormatKeepItem; +class SvxShadowItem; + +namespace legacy +{ + namespace SvxFont + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxFontItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxFontItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxFontHeight + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxFontHeightItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxFontHeightItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxWeight + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxWeightItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxWeightItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxPosture + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxPostureItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxPostureItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxTextLine // SvxUnderlineItem, SvxOverlineItem -> SvxTextLineItem + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxTextLineItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxTextLineItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxCrossedOut + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxCrossedOutItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxCrossedOutItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + // SvxContourItem -> SfxBoolItem + // SvxShadowedItem -> SfxBoolItem + + namespace SvxColor + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxColorItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxColorItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxBox + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxBoxItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxBoxItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxLine + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxLineItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxLineItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxBrush + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxBrushItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxBrushItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxAdjust + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxAdjustItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxAdjustItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxHorJustify + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxHorJustifyItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxHorJustifyItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxVerJustify + { + sal_uInt16 UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) GetVersion(sal_uInt16 nFileFormatVersion); + void UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) Create(SvxVerJustifyItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvStream& Store(const SvxVerJustifyItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxFrameDirection + { + sal_uInt16 EDITENG_DLLPUBLIC GetVersion(sal_uInt16 nFileFormatVersion); + void EDITENG_DLLPUBLIC Create(SvxFrameDirectionItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + EDITENG_DLLPUBLIC SvStream& Store(const SvxFrameDirectionItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxFormatBreak + { + sal_uInt16 EDITENG_DLLPUBLIC GetVersion(sal_uInt16 nFileFormatVersion); + void EDITENG_DLLPUBLIC Create(SvxFormatBreakItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + EDITENG_DLLPUBLIC SvStream& Store(const SvxFormatBreakItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxFormatKeep + { + sal_uInt16 EDITENG_DLLPUBLIC GetVersion(sal_uInt16 nFileFormatVersion); + void EDITENG_DLLPUBLIC Create(SvxFormatKeepItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + EDITENG_DLLPUBLIC SvStream& Store(const SvxFormatKeepItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + + namespace SvxShadow + { + sal_uInt16 EDITENG_DLLPUBLIC GetVersion(sal_uInt16 nFileFormatVersion); + void EDITENG_DLLPUBLIC Create(SvxShadowItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + EDITENG_DLLPUBLIC SvStream& Store(const SvxShadowItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } +} + +#endif // INCLUDED_EDITENG_LEGACYITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/lineitem.hxx b/include/editeng/lineitem.hxx new file mode 100644 index 000000000..0e481767a --- /dev/null +++ b/include/editeng/lineitem.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_LINEITEM_HXX +#define INCLUDED_EDITENG_LINEITEM_HXX + +#include +#include +#include + + +// class SvxLineItem ----------------------------------------------------- + + +/* +[Description] +This Item transports an editeng::SvxBorderLine. +*/ + +namespace editeng { + class SvxBorderLine; +} + +class EDITENG_DLLPUBLIC SvxLineItem final : public SfxPoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxLineItem( const sal_uInt16 nId ); + SvxLineItem( const SvxLineItem& rCpy ); + virtual ~SvxLineItem() override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxLineItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + const editeng::SvxBorderLine* + GetLine() const { return pLine.get(); } + void SetLine( const editeng::SvxBorderLine *pNew ); + +private: + std::unique_ptr pLine; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/lrspitem.hxx b/include/editeng/lrspitem.hxx new file mode 100644 index 000000000..0510ee47d --- /dev/null +++ b/include/editeng/lrspitem.hxx @@ -0,0 +1,168 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_LRSPITEM_HXX +#define INCLUDED_EDITENG_LRSPITEM_HXX + +#include +#include + + +// class SvxLRSpaceItem -------------------------------------------------- + +/* [Description] + + Left/Right margin and first line indent + + SvxLRSpaceItem offers two interfaces for views from the left margin and + first line indent. The get methods return the member, with the layout also + as expected: the left edge shifts to the negative first line indent to the + left. The SetTxt/Gettxt methods assume that the left side represents the + 0 coordinate for the first line indent: + + UI UI LAYOUT UI/TEXT UI/TEXT (Where?) + SetTextLeft SetTxtFirst GetLeft GetTextLeft GetTxtFirst (What?) + 500 -500 0 500 -500 (How much?) + 500 0 500 500 0 + 500 +500 500 500 +500 + 700 -500 200 700 -500 +*/ + +#define LRSPACE_TXTLEFT_VERSION (sal_uInt16(0x0002)) +#define LRSPACE_NEGATIVE_VERSION (sal_uInt16(0x0004)) + +class EDITENG_DLLPUBLIC SvxLRSpaceItem final : public SfxPoolItem +{ + tools::Long nTxtLeft; // We spend a sal_uInt16 + tools::Long nLeftMargin; // nLeft or the negative first-line indent + tools::Long nRightMargin; // The unproblematic right edge + /// The amount of extra space added to the left margin. + tools::Long m_nGutterMargin; + /// The amount of extra space added to the right margin, on mirrored pages. + tools::Long m_nRightGutterMargin; + + sal_uInt16 nPropFirstLineOffset, nPropLeftMargin, nPropRightMargin; + short nFirstLineOffset; // First-line indent _always_ relative to nTxtLeft + bool bAutoFirst; // Automatic calculation of the first line indent + bool bExplicitZeroMarginValRight; + bool bExplicitZeroMarginValLeft; + + void AdjustLeft(); // nLeftMargin and nTxtLeft are being adjusted. + +public: + + static SfxPoolItem* CreateDefault(); + + explicit SvxLRSpaceItem( const sal_uInt16 nId ); + SvxLRSpaceItem( const tools::Long nLeft, const tools::Long nRight, + const tools::Long nTLeft /*= 0*/, const short nOfset /*= 0*/, + const sal_uInt16 nId ); + SvxLRSpaceItem(SvxLRSpaceItem const &) = default; // SfxPoolItem copy function dichotomy + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxLRSpaceItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + // The "layout interface": + inline void SetLeft ( const tools::Long nL, const sal_uInt16 nProp = 100 ); + inline void SetRight( const tools::Long nR, const sal_uInt16 nProp = 100 ); + + // Query/direct setting of the absolute values + tools::Long GetLeft() const { return nLeftMargin; } + tools::Long GetRight() const { return nRightMargin;} + void SetLeftValue( const tools::Long nL ) { nTxtLeft = nLeftMargin = nL; } + void SetRightValue( const tools::Long nR ) { nRightMargin = nR; } + bool IsAutoFirst() const { return bAutoFirst; } + void SetAutoFirst( const bool bNew ) { bAutoFirst = bNew; } + + bool IsExplicitZeroMarginValRight() const { return bExplicitZeroMarginValRight; } + bool IsExplicitZeroMarginValLeft() const { return bExplicitZeroMarginValLeft; } + void SetExplicitZeroMarginValRight( const bool eR ) { bExplicitZeroMarginValRight = eR; } + void SetExplicitZeroMarginValLeft( const bool eL ) { bExplicitZeroMarginValLeft = eL; } + sal_uInt16 GetPropLeft() const { return nPropLeftMargin; } + sal_uInt16 GetPropRight() const { return nPropRightMargin;} + + // The UI/text interface: + inline void SetTextLeft( const tools::Long nL, const sal_uInt16 nProp = 100 ); + tools::Long GetTextLeft() const { return nTxtLeft; } + + inline void SetTextFirstLineOffset( const short nF, const sal_uInt16 nProp = 100 ); + short GetTextFirstLineOffset() const { return nFirstLineOffset; } + void SetPropTextFirstLineOffset( const sal_uInt16 nProp ) + { nPropFirstLineOffset = nProp; } + sal_uInt16 GetPropTextFirstLineOffset() const + { return nPropFirstLineOffset; } + void SetTextFirstLineOffsetValue( const short nValue ) + { nFirstLineOffset = nValue; } + void SetGutterMargin(const tools::Long nGutterMargin) { m_nGutterMargin = nGutterMargin; } + tools::Long GetGutterMargin() const { return m_nGutterMargin; } + void SetRightGutterMargin(const tools::Long nRightGutterMargin) { m_nRightGutterMargin = nRightGutterMargin; } + tools::Long GetRightGutterMargin() const { return m_nRightGutterMargin; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + virtual boost::property_tree::ptree dumpAsJSON() const override; +}; + +inline void SvxLRSpaceItem::SetLeft( const tools::Long nL, const sal_uInt16 nProp ) +{ + nLeftMargin = (nL * nProp) / 100; + nTxtLeft = nLeftMargin; + nPropLeftMargin = nProp; +} +inline void SvxLRSpaceItem::SetRight( const tools::Long nR, const sal_uInt16 nProp ) +{ + if (0 == nR) + { + SetExplicitZeroMarginValRight(true); + } + nRightMargin = (nR * nProp) / 100; + nPropRightMargin = nProp; +} +inline void SvxLRSpaceItem::SetTextFirstLineOffset( const short nF, + const sal_uInt16 nProp ) +{ + nFirstLineOffset = short((tools::Long(nF) * nProp ) / 100); + nPropFirstLineOffset = nProp; + AdjustLeft(); +} + +inline void SvxLRSpaceItem::SetTextLeft( const tools::Long nL, const sal_uInt16 nProp ) +{ + if (0 == nL) + { + SetExplicitZeroMarginValLeft(true); + } + nTxtLeft = (nL * nProp) / 100; + nPropLeftMargin = nProp; + AdjustLeft(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/lspcitem.hxx b/include/editeng/lspcitem.hxx new file mode 100644 index 000000000..e4c97cfcd --- /dev/null +++ b/include/editeng/lspcitem.hxx @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_LSPCITEM_HXX +#define INCLUDED_EDITENG_LSPCITEM_HXX + +#include +#include +#include +#include + +// class SvxLineSpacingItem ---------------------------------------------- + +/* [Description] + This item describes the distance between the lines. +*/ + +#define LINE_SPACE_DEFAULT_HEIGHT 200 +class EDITENG_DLLPUBLIC SvxLineSpacingItem final : public SfxEnumItemInterface +{ + short nInterLineSpace; + sal_uInt16 nLineHeight; + sal_uInt16 nPropLineSpace; + SvxLineSpaceRule eLineSpaceRule; + SvxInterLineSpaceRule eInterLineSpaceRule; + +public: + static SfxPoolItem* CreateDefault(); + + // The writer relies on a default height of 200! Actually, I would + // initialize all values to 0, but who can ignore the consequences in + // writer? => Rather have a crooked vales as the default, but the + // programmer sees that there's something special happening. + + SvxLineSpacingItem( sal_uInt16 nLineHeight /*= LINE_SPACE_DEFAULT_HEIGHT*/, const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxLineSpacingItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + // Methods to query and edit. InterlineSpace is added to the height. + short GetInterLineSpace() const { return nInterLineSpace; } + void SetInterLineSpace( const short nSpace ) + { + nInterLineSpace = nSpace; + eInterLineSpaceRule = SvxInterLineSpaceRule::Fix; + } + + // Determines the absolute or minimum row height. + sal_uInt16 GetLineHeight() const { return nLineHeight; } + void SetLineHeight( const sal_uInt16 nHeight ) + { + nLineHeight = nHeight; + eLineSpaceRule = SvxLineSpaceRule::Min; + } + + // To increase or decrease the row height. + sal_uInt16 GetPropLineSpace() const { return nPropLineSpace; } + void SetPropLineSpace( const sal_uInt16 nProp ) + { + nPropLineSpace = nProp; + eInterLineSpaceRule = SvxInterLineSpaceRule::Prop; + } + + void SetLineSpaceRule(SvxLineSpaceRule e) { eLineSpaceRule = e; } + SvxLineSpaceRule GetLineSpaceRule() const { return eLineSpaceRule; } + + void SetInterLineSpaceRule(SvxInterLineSpaceRule e) { eInterLineSpaceRule = e; } + SvxInterLineSpaceRule GetInterLineSpaceRule() const { return eInterLineSpaceRule; } + + virtual sal_uInt16 GetValueCount() const override; + virtual sal_uInt16 GetEnumValue() const override; + virtual void SetEnumValue( sal_uInt16 nNewVal ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/macros.hxx b/include/editeng/macros.hxx new file mode 100644 index 000000000..3bc26db60 --- /dev/null +++ b/include/editeng/macros.hxx @@ -0,0 +1,17 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_EDITENG_MACROS_HXX +#define INCLUDED_EDITENG_MACROS_HXX + +#define DEBUG_EDIT_ENGINE 0 + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/measfld.hxx b/include/editeng/measfld.hxx new file mode 100644 index 000000000..10ed89b2f --- /dev/null +++ b/include/editeng/measfld.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_MEASFLD_HXX +#define INCLUDED_EDITENG_MEASFLD_HXX + +#include +#include +#include + +enum class SdrMeasureFieldKind { Value, Unit, Rotate90Blanks }; + +class EDITENG_DLLPUBLIC SdrMeasureField final : public SvxFieldData { + SdrMeasureFieldKind eMeasureFieldKind; +public: + virtual sal_Int32 GetClassId() const override { return css::text::textfield::Type::MEASURE; } + SdrMeasureField(SdrMeasureFieldKind eNewKind): eMeasureFieldKind(eNewKind) {} + virtual ~SdrMeasureField() override; + virtual std::unique_ptr Clone() const override; + virtual bool operator==(const SvxFieldData&) const override; + SdrMeasureFieldKind GetMeasureFieldKind() const { return eMeasureFieldKind; } + + SdrMeasureField(SdrMeasureField const &) = default; + SdrMeasureField(SdrMeasureField &&) = default; + SdrMeasureField & operator =(SdrMeasureField const &) = default; + SdrMeasureField & operator =(SdrMeasureField &&) = default; +}; + + +#endif // INCLUDED_EDITENG_MEASFLD_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/memberids.h b/include/editeng/memberids.h new file mode 100644 index 000000000..9b89ebafa --- /dev/null +++ b/include/editeng/memberids.h @@ -0,0 +1,195 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_MEMBERIDS_H +#define INCLUDED_EDITENG_MEMBERIDS_H + +#define MID_LOCATION 0x3c +#define MID_TRANSPARENT 0x4b +#define MID_BG_COLOR 0x22 +#define MID_FLAGS 0x2e +#define MID_DISTANCE 0x29 +#define MID_FG_COLOR 0x2c +#define MID_OUTER_WIDTH 0x41 +#define MID_INNER_WIDTH 0x35 +#define MID_LINESPACE 0x3b +#define MID_LINE_STYLE 0x90 + +//NameOrIndex +#define MID_NAME 16 + +// SvxPageModelItem +#define MID_AUTO 1 + +// SvxTabStop +#define MID_TABSTOPS 0 +#define MID_STD_TAB 1 + +//SvxHyphenZoneItem +#define MID_IS_HYPHEN 0 +#define MID_HYPHEN_MIN_LEAD 1 +#define MID_HYPHEN_MIN_TRAIL 2 +#define MID_HYPHEN_MAX_HYPHENS 3 +#define MID_HYPHEN_NO_CAPS 4 +#define MID_HYPHEN_NO_LAST_WORD 5 +#define MID_HYPHEN_MIN_WORD_LENGTH 6 +#define MID_HYPHEN_ZONE 7 + +// SvxBoxInfoItem +#define MID_HORIZONTAL 1 +#define MID_VERTICAL 2 +#define MID_VALIDFLAGS 4 + +//AdjustItem +#define MID_PARA_ADJUST 0 +#define MID_LAST_LINE_ADJUST 1 +#define MID_EXPAND_SINGLE 2 + +//SvxFontItem +// Don't use 0 as it used for the whole struct +#define MID_FONT_FAMILY_NAME 1 +#define MID_FONT_STYLE_NAME 2 +#define MID_FONT_FAMILY 3 +#define MID_FONT_CHAR_SET 4 +#define MID_FONT_PITCH 5 + +// SvxCharReliefItem +#define MID_RELIEF 0 + +//SvxCharRotateItem +#define MID_ROTATE 0 +#define MID_FITTOLINE 1 + +//SvxEscapementItem +#define MID_ESC 0 +#define MID_ESC_HEIGHT 1 +#define MID_AUTO_ESC 2 + +//SvxFontHeightItem +#define MID_FONTHEIGHT 1 +#define MID_FONTHEIGHT_PROP 2 +#define MID_FONTHEIGHT_DIFF 3 + +//SvxTextLineItem +#define MID_TEXTLINED 0 +#define MID_TL_STYLE 1 +#define MID_TL_COLOR 2 +#define MID_TL_HASCOLOR 3 + +//SvxCrossedOutItem +#define MID_CROSSED_OUT 0 +#define MID_CROSS_OUT 1 + +//SvxPostureItem +#define MID_ITALIC 0 +#define MID_POSTURE 1 + +//SvxBoolItem +#define MID_BOLD 0 +#define MID_WEIGHT 1 + +//SvxLanguageItem +#define MID_LANG_INT 0 +#define MID_LANG_LOCALE 1 + +//SvxEmphasisMarkItem +#define MID_EMPHASIS 0 + +//SvxTwoLinesItem +#define MID_TWOLINES 0 +#define MID_START_BRACKET 1 +#define MID_END_BRACKET 2 + +//ULSpaceItem +#define MID_UP_MARGIN 3 +#define MID_LO_MARGIN 4 +#define MID_UP_REL_MARGIN 5 +#define MID_LO_REL_MARGIN 6 +#define MID_CTX_MARGIN 7 + +//LRSpaceItem +#define MID_L_MARGIN 4 +#define MID_R_MARGIN 5 +#define MID_L_REL_MARGIN 6 +#define MID_R_REL_MARGIN 7 +#define MID_FIRST_LINE_INDENT 8 +#define MID_FIRST_LINE_REL_INDENT 9 +#define MID_FIRST_AUTO 10 +#define MID_TXT_LMARGIN 11 +#define MID_GUTTER_MARGIN 12 + +//ProtectItem +#define MID_PROTECT_CONTENT 0 +#define MID_PROTECT_SIZE 1 +#define MID_PROTECT_POSITION 2 + +//SvxBoxItem +#define LEFT_BORDER 1 +#define RIGHT_BORDER 2 +#define TOP_BORDER 3 +#define BOTTOM_BORDER 4 +#define BORDER_DISTANCE 5 +#define LEFT_BORDER_DISTANCE 6 +#define RIGHT_BORDER_DISTANCE 7 +#define TOP_BORDER_DISTANCE 8 +#define BOTTOM_BORDER_DISTANCE 9 +#define MID_LEFT_BORDER 10 +#define MID_RIGHT_BORDER 11 +#define MID_TOP_BORDER 12 +#define MID_BOTTOM_BORDER 13 +#define LINE_STYLE 14 +#define LINE_WIDTH 15 + +//BrushItem +#define MID_BACK_COLOR 0 +#define MID_GRAPHIC_POSITION 1 +#define MID_GRAPHIC 2 +#define MID_GRAPHIC_TRANSPARENT 3 +#define MID_GRAPHIC_URL 4 +#define MID_GRAPHIC_FILTER 5 +#define MID_GRAPHIC_REPEAT 6 +#define MID_GRAPHIC_TRANSPARENCY 7 +#define MID_BACK_COLOR_R_G_B 8 +#define MID_BACK_COLOR_TRANSPARENCY 9 +#define MID_SHADING_VALUE 10 + +//SvxFormatBreakItem +#define MID_BREAK_BEFORE 0 +#define MID_BREAK_AFTER 1 + +// SvxHorJustifyItem +#define MID_HORJUST_HORJUST 0 +#define MID_HORJUST_ADJUST 1 + +// SvxShadowItem +#define MID_SHADOW_TRANSPARENCE 1 + +// SvxColorItem +#define MID_COLOR_RGB 0 +#define MID_COLOR_ALPHA 1 +//#define MID_GRAPHIC_TRANSPARENT 3 // used, but already defined above +#define MID_COLOR_THEME_INDEX 4 +#define MID_COLOR_TINT_OR_SHADE 5 +#define MID_COLOR_LUM_MOD 6 +#define MID_COLOR_LUM_OFF 7 + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/misspellrange.hxx b/include/editeng/misspellrange.hxx new file mode 100644 index 000000000..f46c25e22 --- /dev/null +++ b/include/editeng/misspellrange.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_EDITENG_MISSPELLRANGE_HXX +#define INCLUDED_EDITENG_MISSPELLRANGE_HXX + +#include + +#include + +namespace editeng +{ +struct MisspellRange +{ + size_t mnStart; + size_t mnEnd; + + MisspellRange(size_t nStart, size_t nEnd); +}; + +struct MisspellRanges +{ + sal_Int32 mnParagraph; + std::vector maRanges; + + MisspellRanges(sal_Int32 nParagraph, std::vector&& rRanges); +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/nhypitem.hxx b/include/editeng/nhypitem.hxx new file mode 100644 index 000000000..1078a055b --- /dev/null +++ b/include/editeng/nhypitem.hxx @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_NHYPITEM_HXX +#define INCLUDED_EDITENG_NHYPITEM_HXX + +#include +#include + +// class SvxNoHyphenItem ------------------------------------------------- +class EDITENG_DLLPUBLIC SvxNoHyphenItem final : public SfxBoolItem +{ +public: + SvxNoHyphenItem( const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxNoHyphenItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/numdef.hxx b/include/editeng/numdef.hxx new file mode 100644 index 000000000..6039ec555 --- /dev/null +++ b/include/editeng/numdef.hxx @@ -0,0 +1,28 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_NUMDEF_HXX +#define INCLUDED_EDITENG_NUMDEF_HXX + +#define SVX_MAX_NUM 10 // max. possible numbering level +#define SVX_DEF_BULLET (0xF000 + 149) // Character for lists + +#endif // INCLUDED_EDITENG_NUMDEF_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/numitem.hxx b/include/editeng/numitem.hxx new file mode 100644 index 000000000..baa6ad320 --- /dev/null +++ b/include/editeng/numitem.hxx @@ -0,0 +1,359 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_NUMITEM_HXX +#define INCLUDED_EDITENG_NUMITEM_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SvxBrushItem; +class Graphic; +class SvxNodeNum; +namespace com::sun::star::text { class XNumberingFormatter; } + +namespace com::sun::star::lang { struct Locale; } + + +#define SVX_NO_NUM 200 // Marker for no numbering +#define SVX_NO_NUMLEVEL 0x20 +#define SVX_NUM_REL_SIZE_MIN 25 // Lower limit for numbering relative size + + +#define LINK_TOKEN 0x80 //indicate linked bitmaps - for use in dialog only + +typedef struct _xmlTextWriter* xmlTextWriterPtr; + +class EDITENG_DLLPUBLIC SvxNumberType +{ + static sal_Int32 nRefCount; + static css::uno::Reference xFormatter; + + SvxNumType nNumType; + bool bShowSymbol; // Also show Symbol ? + +public: + explicit SvxNumberType(SvxNumType nType = SVX_NUM_ARABIC); + SvxNumberType(const SvxNumberType& rType); + ~SvxNumberType(); + SvxNumberType & operator =(SvxNumberType const &) = default; + + OUString GetNumStr( sal_Int32 nNo ) const; + OUString GetNumStr( sal_Int32 nNo, const css::lang::Locale& rLocale ) const; + + void SetNumberingType(SvxNumType nSet) {nNumType = nSet;} + SvxNumType GetNumberingType() const {return nNumType;} + + void SetShowSymbol(bool bSet) {bShowSymbol = bSet;} + bool IsShowSymbol()const{return bShowSymbol;} + + bool IsTextFormat() const + { + return css::style::NumberingType::NUMBER_NONE != nNumType && + css::style::NumberingType::CHAR_SPECIAL != nNumType && + css::style::NumberingType::BITMAP != nNumType; + } + + void dumpAsXml(xmlTextWriterPtr w) const; +}; + +class EDITENG_DLLPUBLIC SvxNumberFormat : public SvxNumberType +{ +public: + enum SvxNumPositionAndSpaceMode + { + LABEL_WIDTH_AND_POSITION, + LABEL_ALIGNMENT + }; + enum LabelFollowedBy + { + LISTTAB, + SPACE, + NOTHING, + NEWLINE + }; + +private: + OUString sPrefix; + OUString sSuffix; + std::optional sListFormat; // Format string ">%1.%2<" can be used instead of prefix/suffix + // Right now it is optional value to distinguish empty list format + // and not set list format when we need to fallback to prefix/suffix. + + SvxAdjust eNumAdjust; + + sal_uInt8 nInclUpperLevels; // Take over numbers from the previous level. + sal_uInt16 nStart; // Start of counting + + sal_UCS4 cBullet; // Symbol + sal_uInt16 nBulletRelSize; // percentage size of bullets + Color nBulletColor; // Bullet color + + // mode indicating, if the position and spacing of the list label is + // determined by the former attributes (nFirstLineOffset, nAbsLSpace + // and nCharTextDistance) called position and spacing via label + // width and position (LABEL_WIDTH_AND_POSITION) or by the new attributes + // (meLabelFollowedBy, mnListtabPos, mnFirstLineIndent and mnIndentAt) + // called position and spacing via label alignment. + // Note 1: Attribute is relevant for both modes. + // Note 2: The values of the former attributes are treated as 0, if mode + // LABEL_ALIGNMENT is active. + SvxNumPositionAndSpaceMode mePositionAndSpaceMode; + + sal_Int32 nFirstLineOffset; // First line indent + sal_Int32 nAbsLSpace; // Distance Border<->Number + short nCharTextDistance; // Distance Number<->Text + + // specifies what follows the list label before the text of the first line + // of the list item starts + LabelFollowedBy meLabelFollowedBy; + // specifies an additional list tab stop position for meLabelFollowedBy = LISTTAB + tools::Long mnListtabPos; + // specifies the first line indent + tools::Long mnFirstLineIndent; + // specifies the indent before the text, e.g. in L2R-layout the left margin + tools::Long mnIndentAt; + + std::unique_ptr + pGraphicBrush; + sal_Int16 eVertOrient; // vertical alignment of a bitmap + + Size aGraphicSize; // Always! in 1/100 mm + std::optional + pBulletFont; // Pointer to the bullet font + + OUString sCharStyleName; // Character Style + +public: + explicit SvxNumberFormat( SvxNumType nNumberingType ); + SvxNumberFormat(const SvxNumberFormat& rFormat); + SvxNumberFormat( SvStream & rStream ); + + virtual ~SvxNumberFormat(); + + void Store(SvStream &rStream, FontToSubsFontConverter pConverter); + + SvxNumberFormat& operator=( const SvxNumberFormat& ); + bool operator==( const SvxNumberFormat& ) const; + bool operator!=( const SvxNumberFormat& rFmt) const {return !(*this == rFmt);} + + void SetNumAdjust(SvxAdjust eSet) {eNumAdjust = eSet;} + SvxAdjust GetNumAdjust() const {return eNumAdjust;} + void SetPrefix(const OUString& rSet) { sPrefix = rSet;} + const OUString& GetPrefix() const { return sPrefix;} + void SetSuffix(const OUString& rSet) { sSuffix = rSet;} + const OUString& GetSuffix() const { return sSuffix;} + // Based on prefix and suffix initialize them (for backward compatibility) and generate listformat string + void SetListFormat(const OUString& rPrefix, const OUString& rSuffix, int nLevel); + void SetListFormat(std::optional oSet = std::nullopt); + bool HasListFormat() const { return sListFormat.has_value(); } + OUString GetListFormat(bool bIncludePrefixSuffix = true) const; + + void SetCharFormatName(const OUString& rSet){ sCharStyleName = rSet; } + virtual OUString GetCharFormatName()const; + + void SetBulletFont(const vcl::Font* pFont); + const std::optional& GetBulletFont() const { return pBulletFont; } + void SetBulletChar(sal_UCS4 cSet){cBullet = cSet;} + sal_UCS4 GetBulletChar()const {return cBullet;} + void SetBulletRelSize(sal_uInt16 nSet) {nBulletRelSize = std::max(nSet,sal_uInt16(SVX_NUM_REL_SIZE_MIN));} + sal_uInt16 GetBulletRelSize() const { return nBulletRelSize;} + void SetBulletColor(Color nSet){nBulletColor = nSet;} + const Color& GetBulletColor()const {return nBulletColor;} + + void SetIncludeUpperLevels( sal_uInt8 nSet ) { nInclUpperLevels = nSet;} + sal_uInt8 GetIncludeUpperLevels()const { return nInclUpperLevels;} + void SetStart(sal_uInt16 nSet) {nStart = nSet;} + sal_uInt16 GetStart() const {return nStart;} + + virtual void SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = nullptr, const sal_Int16* pOrient = nullptr); + const SvxBrushItem* GetBrush() const {return pGraphicBrush.get();} + void SetGraphic( const OUString& rName ); + sal_Int16 GetVertOrient() const; + void SetGraphicSize(const Size& rSet) {aGraphicSize = rSet;} + const Size& GetGraphicSize() const {return aGraphicSize;} + + SvxNumPositionAndSpaceMode GetPositionAndSpaceMode() const { return mePositionAndSpaceMode;} + void SetPositionAndSpaceMode( SvxNumPositionAndSpaceMode ePositionAndSpaceMode ); + + void SetAbsLSpace(sal_Int32 nSet) {nAbsLSpace = nSet;} + sal_Int32 GetAbsLSpace() const; + void SetFirstLineOffset(sal_Int32 nSet) { nFirstLineOffset = nSet;} + sal_Int32 GetFirstLineOffset() const; + void SetCharTextDistance(short nSet) { nCharTextDistance = nSet; } + short GetCharTextDistance() const; + + void SetLabelFollowedBy( const LabelFollowedBy eLabelFollowedBy ); + LabelFollowedBy GetLabelFollowedBy() const { return meLabelFollowedBy;} + OUString GetLabelFollowedByAsString() const; + void SetListtabPos( const tools::Long nListtabPos ); + tools::Long GetListtabPos() const { return mnListtabPos;} + void SetFirstLineIndent( const tools::Long nFirstLineIndent ); + tools::Long GetFirstLineIndent() const { return mnFirstLineIndent;} + void SetIndentAt( const tools::Long nIndentAt ); + tools::Long GetIndentAt() const { return mnIndentAt;} + + static Size GetGraphicSizeMM100(const Graphic* pGraphic); + static OUString CreateRomanString( sal_Int32 nNo, bool bUpper ); +}; + +//Feature-Flags (only sal_uInt16!) +enum class SvxNumRuleFlags : sal_uInt16 +{ + NONE = 0x0000, + CONTINUOUS = 0x0001, // consecutive numbers possible? + CHAR_STYLE = 0x0004, // Character styles? + BULLET_REL_SIZE = 0x0008, // relative bullet size? + BULLET_COLOR = 0x0010, // Bullet color + NO_NUMBERS = 0x0080, // Numbering are not allowed + ENABLE_LINKED_BMP = 0x0100, // linked bitmaps are available + ENABLE_EMBEDDED_BMP = 0x0200 // embedded bitmaps are available +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +enum class SvxNumRuleType : sal_uInt8 +{ + NUMBERING, + OUTLINE_NUMBERING, + PRESENTATION_NUMBERING +}; + +class EDITENG_DLLPUBLIC SvxNumRule final +{ + std::unique_ptr aFmts[SVX_MAX_NUM]; + sal_uInt16 nLevelCount; // Number of supported levels + SvxNumRuleFlags nFeatureFlags; // What is supported? + SvxNumRuleType eNumberingType; // Type of numbering + bool bContinuousNumbering; // sequential numbering + bool aFmtsSet[SVX_MAX_NUM]; // Flags indicating valid levels + + static sal_Int32 nRefCount; +public: + SvxNumRule( SvxNumRuleFlags nFeatures, + sal_uInt16 nLevels, + bool bCont, + SvxNumRuleType eType = SvxNumRuleType::NUMBERING, + SvxNumberFormat::SvxNumPositionAndSpaceMode + eDefaultNumberFormatPositionAndSpaceMode + = SvxNumberFormat::LABEL_WIDTH_AND_POSITION ); + SvxNumRule(const SvxNumRule& rCopy); + SvxNumRule(SvxNumRule&&) noexcept; + SvxNumRule(SvStream &rStream); + ~SvxNumRule(); + + bool operator==( const SvxNumRule& ) const; + bool operator!=( const SvxNumRule& rRule ) const {return !(*this == rRule);} + + SvxNumRule& operator=( const SvxNumRule& ); + SvxNumRule& operator=( SvxNumRule&& ) noexcept; + + void Store(SvStream &rStream); + void dumpAsXml(xmlTextWriterPtr pWriter) const; + const SvxNumberFormat* Get(sal_uInt16 nLevel)const; + const SvxNumberFormat& GetLevel(sal_uInt16 nLevel)const; + void SetLevel(sal_uInt16 nLevel, const SvxNumberFormat& rFmt, bool bIsValid = true); + void SetLevel(sal_uInt16 nLevel, const SvxNumberFormat* pFmt); + + bool IsContinuousNumbering()const + {return bContinuousNumbering;} + void SetContinuousNumbering(bool bSet) + {bContinuousNumbering = bSet;} + + sal_uInt16 GetLevelCount() const {return nLevelCount;} + bool IsFeatureSupported(SvxNumRuleFlags nFeature) const + { return bool(nFeatureFlags & nFeature); } + SvxNumRuleFlags GetFeatureFlags() const {return nFeatureFlags;} + void SetFeatureFlag( SvxNumRuleFlags nFlag, bool bSet = true ) { if(bSet) nFeatureFlags |= nFlag; else nFeatureFlags &= ~nFlag; } + + OUString MakeNumString( const SvxNodeNum& ) const; + + SvxNumRuleType GetNumRuleType() const { return eNumberingType; } + + void UnLinkGraphics(); +}; + +class EDITENG_DLLPUBLIC SvxNumBulletItem final : public SfxPoolItem +{ + SvxNumRule maNumRule; +public: + explicit SvxNumBulletItem(SvxNumRule const & rRule); + explicit SvxNumBulletItem(SvxNumRule && rRule); + SvxNumBulletItem(SvxNumRule const & rRule, sal_uInt16 nWhich ); + SvxNumBulletItem(SvxNumRule && rRule, sal_uInt16 nWhich ); + SvxNumBulletItem(const SvxNumBulletItem& rCopy); + virtual ~SvxNumBulletItem() override; + + virtual SvxNumBulletItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + + const SvxNumRule& GetNumRule() const { return maNumRule; } + SvxNumRule& GetNumRule() { return maNumRule; } + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +class SvxNodeNum +{ + sal_uInt16 nLevelVal[ SVX_MAX_NUM ] = {}; // Numbers of all levels + sal_uInt8 nMyLevel = 0; // Current Level + +public: + explicit inline SvxNodeNum() = default; + inline SvxNodeNum& operator=( const SvxNodeNum& rCpy ); + + sal_uInt8 GetLevel() const { return nMyLevel; } + void SetLevel( sal_uInt8 nVal ) { nMyLevel = nVal; } + + const sal_uInt16* GetLevelVal() const { return nLevelVal; } + sal_uInt16* GetLevelVal() { return nLevelVal; } +}; + +inline SvxNodeNum& SvxNodeNum::operator=( const SvxNodeNum& rCpy ) +{ + if ( &rCpy != this) + { + nMyLevel = rCpy.nMyLevel; + + memcpy( nLevelVal, rCpy.nLevelVal, sizeof( nLevelVal ) ); + } + return *this; +} + +SvxNumRule SvxConvertNumRule( const SvxNumRule& rRule, sal_uInt16 nLevel, SvxNumRuleType eType ); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/opaqitem.hxx b/include/editeng/opaqitem.hxx new file mode 100644 index 000000000..d38747747 --- /dev/null +++ b/include/editeng/opaqitem.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_OPAQITEM_HXX +#define INCLUDED_EDITENG_OPAQITEM_HXX + +#include +#include + +// class SvxOpaqueItem --------------------------------------------------- + + +/* [Description] + + This item describes a logical variable "Opaque yes or no." +*/ + +class EDITENG_DLLPUBLIC SvxOpaqueItem final : public SfxBoolItem +{ +public: + explicit SvxOpaqueItem( const sal_uInt16 nId , const bool bOpa = true ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxOpaqueItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +inline SvxOpaqueItem::SvxOpaqueItem( const sal_uInt16 nId, const bool bOpa ) + : SfxBoolItem( nId, bOpa ) +{} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/optitems.hxx b/include/editeng/optitems.hxx new file mode 100644 index 000000000..f4cbd2df8 --- /dev/null +++ b/include/editeng/optitems.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_OPTITEMS_HXX +#define INCLUDED_EDITENG_OPTITEMS_HXX + +#include +#include + + +// class SfxHyphenRegionItem --------------------------------------------- + +class EDITENG_DLLPUBLIC SfxHyphenRegionItem final : public SfxPoolItem +{ + sal_uInt8 nMinLead; + sal_uInt8 nMinTrail; + +public: + + SfxHyphenRegionItem( const sal_uInt16 nId ); + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SfxHyphenRegionItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + sal_uInt8 &GetMinLead() { return nMinLead; } + sal_uInt8 GetMinLead() const { return nMinLead; } + + sal_uInt8 &GetMinTrail() { return nMinTrail; } + sal_uInt8 GetMinTrail() const { return nMinTrail; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/orphitem.hxx b/include/editeng/orphitem.hxx new file mode 100644 index 000000000..4181e7c74 --- /dev/null +++ b/include/editeng/orphitem.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_ORPHITEM_HXX +#define INCLUDED_EDITENG_ORPHITEM_HXX + +#include +#include + +// class SvxOrphansItem -------------------------------------------------- + +/* [Description] + + This item describes the number of lines for the orphans system. +*/ + +class EDITENG_DLLPUBLIC SvxOrphansItem final : public SfxByteItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxOrphansItem( const sal_uInt8 nL /*= 0*/, const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxOrphansItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/outliner.hxx b/include/editeng/outliner.hxx new file mode 100644 index 000000000..ab24be0b1 --- /dev/null +++ b/include/editeng/outliner.hxx @@ -0,0 +1,989 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_OUTLINER_HXX +#define INCLUDED_EDITENG_OUTLINER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +class OutlinerEditEng; +class Outliner; +class EditView; +class EditUndo; +class ParagraphList; +class OutlinerParaObject; +class SvStream; +class SvxSearchItem; +class SvxFieldItem; +namespace vcl { class Window; } +namespace weld { class Widget; } +class KeyEvent; +class MouseEvent; +class CommandEvent; +class MapMode; +class SfxStyleSheetPool; +class SfxStyleSheet; +class SfxItemPool; +class SfxItemSet; +class SvxNumberFormat; +class EditEngine; +class SvKeyValueIterator; +class SvxForbiddenCharactersTable; +class OutlinerViewShell; +enum class CharCompressType; +enum class TransliterationFlags; +class SvxFieldData; +enum class PointerStyle; +class SvxNumRule; +enum class TextRotation; + +namespace com::sun::star::linguistic2 { + class XSpellChecker1; + class XHyphenator; +} +namespace svx{ + struct SpellPortion; + typedef std::vector SpellPortions; +} +namespace basegfx { class B2DPolyPolygon; } +namespace com::sun::star::lang { struct Locale; } + + + +// internal use only! +enum class ParaFlag +{ + NONE = 0x0000, + HOLDDEPTH = 0x4000, + SETBULLETTEXT = 0x8000, + ISPAGE = 0x0100, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +// Undo-Action-Ids +#define OLUNDO_DEPTH EDITUNDO_USER +// #define OLUNDO_HEIGHT EDITUNDO_USER+1 +#define OLUNDO_EXPAND EDITUNDO_USER+2 +#define OLUNDO_COLLAPSE EDITUNDO_USER+3 +// #define OLUNDO_REMOVE EDITUNDO_USER+4 +#define OLUNDO_ATTR EDITUNDO_USER+5 +#define OLUNDO_INSERT EDITUNDO_USER+6 +// #define OLUNDO_MOVEPARAGRAPHS EDITUNDO_USER+7 + +class Paragraph : protected ParagraphData +{ +private: + friend class Outliner; + friend class ParagraphList; + friend class OutlinerView; + friend class OutlinerParaObject; + friend class OutlinerEditEng; + friend class OutlinerUndoCheckPara; + friend class OutlinerUndoChangeParaFlags; + + Paragraph& operator=(const Paragraph& rPara ) = delete; + + OUString aBulText; + Size aBulSize; + ParaFlag nFlags; + bool bVisible; + + bool IsVisible() const { return bVisible; } + void SetText( const OUString& rText ) { aBulText = rText; aBulSize.setWidth(-1); } + void Invalidate() { aBulSize.setWidth(-1); } + void SetDepth( sal_Int16 nNewDepth ) { nDepth = nNewDepth; aBulSize.setWidth(-1); } + const OUString& GetText() const { return aBulText; } + + Paragraph( sal_Int16 nDepth ); + Paragraph( const Paragraph& ) = delete; + Paragraph( const ParagraphData& ); + + sal_Int16 GetDepth() const { return nDepth; } + + sal_Int16 GetNumberingStartValue() const { return mnNumberingStartValue; } + void SetNumberingStartValue( sal_Int16 nNumberingStartValue ); + + bool IsParaIsNumberingRestart() const { return mbParaIsNumberingRestart; } + void SetParaIsNumberingRestart( bool bParaIsNumberingRestart ); + + void SetFlag( ParaFlag nFlag ) { nFlags |= nFlag; } + void RemoveFlag( ParaFlag nFlag ) { nFlags &= ~nFlag; } + bool HasFlag( ParaFlag nFlag ) const { return bool(nFlags & nFlag); } +public: + ~Paragraph(); + void dumpAsXml(xmlTextWriterPtr pWriter) const; +}; + +struct ParaRange +{ + sal_Int32 nStartPara; + sal_Int32 nEndPara; + + ParaRange( sal_Int32 nS, sal_Int32 nE ) : nStartPara(nS), nEndPara(nE) {} + + void Adjust(); +}; + +inline void ParaRange::Adjust() +{ + if ( nStartPara > nEndPara ) + { + std::swap(nStartPara, nEndPara); + } +} + +class EDITENG_DLLPUBLIC OutlinerView final +{ + friend class Outliner; + + Outliner* pOwner; + std::unique_ptr pEditView; + + enum class MouseTarget { + Text = 0, + Bullet = 1, + Hypertext = 2, // Outside OutputArea + Outside = 3 // Outside OutputArea + }; + + EDITENG_DLLPRIVATE void ImplExpandOrCollaps( sal_Int32 nStartPara, sal_Int32 nEndPara, bool bExpand ); + + EDITENG_DLLPRIVATE sal_Int32 ImpCheckMousePos( const Point& rPosPixel, MouseTarget& reTarget); + EDITENG_DLLPRIVATE void ImpToggleExpand( Paragraph const * pParentPara ); + EDITENG_DLLPRIVATE ParaRange ImpGetSelectedParagraphs( bool bIncludeHiddenChildren ); + + EDITENG_DLLPRIVATE sal_Int32 ImpInitPaste( sal_Int32& rStart ); + EDITENG_DLLPRIVATE void ImpPasted( sal_Int32 nStart, sal_Int32 nPrevParaCount, sal_Int32 nSize); + EDITENG_DLLPRIVATE sal_Int32 ImpCalcSelectedPages( bool bIncludeFirstSelected ); + + Link aEndCutPasteLink; + +public: + OutlinerView( Outliner* pOut, vcl::Window* pWindow ); + ~OutlinerView(); + + EditView& GetEditView() const { return *pEditView; } + + void Scroll( tools::Long nHorzScroll, tools::Long nVertScroll ); + + void Paint( const tools::Rectangle& rRect, OutputDevice* pTargetDevice = nullptr ); + bool PostKeyEvent( const KeyEvent& rKEvt, vcl::Window const * pFrameWin = nullptr ); + bool MouseButtonDown( const MouseEvent& ); + bool MouseButtonUp( const MouseEvent& ); + void ReleaseMouse(); + bool MouseMove( const MouseEvent& ); + + void ShowCursor( bool bGotoCursor = true, bool bActivate = false ); + void HideCursor( bool bDeactivate = false ); + + Outliner* GetOutliner() const { return pOwner; } + + void SetWindow( vcl::Window* pWindow ); + vcl::Window* GetWindow() const; + + void SetReadOnly( bool bReadOnly ); + bool IsReadOnly() const; + + void SetOutputArea( const tools::Rectangle& rRect ); + tools::Rectangle const & GetOutputArea() const; + + tools::Rectangle GetVisArea() const; + + void CreateSelectionList (std::vector &aSelList) ; + + void Select( Paragraph const * pParagraph, bool bSelect = true); + + OUString GetSelected() const; + void SelectRange( sal_Int32 nFirst, sal_Int32 nCount ); + void SetAttribs( const SfxItemSet& ); + void Indent( short nDiff ); + void AdjustDepth( short nDX ); // Later replace with Indent! + + void AdjustHeight( tools::Long nDY ); + + void Read( SvStream& rInput, EETextFormat eFormat, SvKeyValueIterator* pHTTPHeaderAttrs ); + + void InsertText( const OUString& rNew, bool bSelect = false ); + void InsertText( const OutlinerParaObject& rParaObj ); + void Expand(); + void Collapse(); + void ExpandAll(); + void CollapseAll(); + + void SetBackgroundColor( const Color& rColor ); + Color const & GetBackgroundColor() const; + + /// Informs this edit view about which view shell contains it. + void RegisterViewShell(OutlinerViewShell* pViewShell); + + SfxItemSet GetAttribs(); + + void Cut(); + void Copy(); + void Paste( bool bUseSpecial = false ); + void PasteSpecial(); + + const SfxStyleSheet* GetStyleSheet() const; + SfxStyleSheet* GetStyleSheet(); + + void SetControlWord( EVControlBits nWord ); + EVControlBits GetControlWord() const; + + void SetAnchorMode( EEAnchorMode eMode ); + EEAnchorMode GetAnchorMode() const; + + PointerStyle GetPointer( const Point& rPosPixel ); + bool Command(const CommandEvent& rCEvt); + + void StartSpeller(weld::Widget* pDialogParent); + EESpellState StartThesaurus(weld::Widget* pDialogParent); + sal_Int32 StartSearchAndReplace( const SvxSearchItem& rSearchItem ); + + // for text conversion + void StartTextConversion(weld::Widget* pDialogParent, LanguageType nSrcLang, LanguageType nDestLang, const vcl::Font *pDestFont, sal_Int32 nOptions, bool bIsInteractive, bool bMultipleDoc); + + void TransliterateText( TransliterationFlags nTransliterationMode ); + + ESelection GetSelection() const; + + SvtScriptType GetSelectedScriptType() const; + + void SetVisArea( const tools::Rectangle& rRect ); + void SetSelection( const ESelection& ); + void GetSelectionRectangles(std::vector& rLogicRects) const; + + void RemoveAttribs( bool bRemoveParaAttribs, bool bKeepLanguages = false ); + void RemoveAttribsKeepLanguages( bool bRemoveParaAttribs ); + bool HasSelection() const; + + void InsertField( const SvxFieldItem& rFld ); + const SvxFieldItem* GetFieldUnderMousePointer() const; + const SvxFieldItem* GetFieldAtSelection() const; + /// Return the field at the current cursor position or nullptr if no field found + const SvxFieldData* GetFieldAtCursor() const; + /// Select the field at the current cursor position + void SelectFieldAtCursor(); + + /** enables bullets for the selected paragraphs if the bullets/numbering of the first paragraph is off + or disables bullets/numbering for the selected paragraphs if the bullets/numbering of the first paragraph is on + */ + void ToggleBullets(); + + void ToggleBulletsNumbering( + const bool bToggle, + const bool bHandleBullets, + const SvxNumRule* pNumRule ); + + /** apply bullets/numbering for paragraphs + + @param boolean bHandleBullets + true: handle bullets + false: handle numbering + + @param pNewNumRule + numbering rule which needs to be applied. can be 0. + + @param boolean bAtSelection + true: apply bullets/numbering at selected paragraphs + false: apply bullets/numbering at all paragraphs + */ + void ApplyBulletsNumbering( + const bool bHandleBullets, + const SvxNumRule* pNewNumRule, + const bool bCheckCurrentNumRuleBeforeApplyingNewNumRule, + const bool bAtSelection = false ); + + /** switch off bullets/numbering for paragraphs + + @param boolean bAtSelection + true: switch off bullets/numbering at selected paragraphs + false: switch off bullets/numbering at all paragraphs + */ + void SwitchOffBulletsNumbering( + const bool bAtSelection = false ); + + /** enables numbering for the selected paragraphs that are not enabled and ignore all selected + paragraphs that already have numbering enabled. + */ + void EnsureNumberingIsOn(); + + bool IsCursorAtWrongSpelledWord(); + bool IsWrongSpelledWordAtPos( const Point& rPosPixel ); + void ExecuteSpellPopup(const Point& rPosPixel, const Link& rCallBack); + + void SetInvalidateMore( sal_uInt16 nPixel ); + sal_uInt16 GetInvalidateMore() const; + + OUString GetSurroundingText() const; + Selection GetSurroundingTextSelection() const; + bool DeleteSurroundingText(const Selection& rRange); + + void SetEndCutPasteLinkHdl(const Link &rLink) { aEndCutPasteLink = rLink; } +}; + +/// Interface class to not depend on SfxViewShell in editeng. +class SAL_NO_VTABLE SAL_DLLPUBLIC_RTTI OutlinerViewShell +{ +public: + virtual void libreOfficeKitViewCallback(int nType, const char* pPayload) const = 0; + virtual void libreOfficeKitViewCallbackWithViewId(int nType, const char* pPayload, int nViewId) const = 0; + virtual void libreOfficeKitViewInvalidateTilesCallback(const tools::Rectangle* pRect, int nPart) const = 0; + virtual void libreOfficeKitViewUpdatedCallback(int nType) const = 0; + virtual void libreOfficeKitViewUpdatedCallbackPerViewId(int nType, int nViewId, int nSourceViewId) const = 0; + virtual ViewShellId GetViewShellId() const = 0; + virtual ViewShellDocId GetDocId() const = 0; + /// Wrapper around SfxLokHelper::notifyOtherViews(). + virtual void NotifyOtherViews(int nType, const OString& rKey, const OString& rPayload) = 0; + /// Wrapper around SfxLokHelper::notifyOtherView(). + virtual void NotifyOtherView(OutlinerViewShell* pOtherShell, int nType, const OString& rKey, const OString& rPayload) = 0; + virtual vcl::Window* GetEditWindowForActiveOLEObj() const = 0; + +protected: + ~OutlinerViewShell() noexcept {} +}; + +// some thesaurus functionality to avoid code duplication in different projects... +bool EDITENG_DLLPUBLIC GetStatusValueForThesaurusFromContext( OUString &rStatusVal, LanguageType &rLang, const EditView &rEditView ); +void EDITENG_DLLPUBLIC ReplaceTextWithSynonym( EditView &rEditView, const OUString &rSynonmText ); + +typedef ::std::vector< OutlinerView* > ViewList; + +class EDITENG_DLLPUBLIC DrawPortionInfo +{ +public: + const Point& mrStartPos; + const OUString maText; + sal_Int32 mnTextStart; + sal_Int32 mnTextLen; + sal_Int32 mnPara; + const SvxFont& mrFont; + o3tl::span mpDXArray; + + const EEngineData::WrongSpellVector* mpWrongSpellVector; + const SvxFieldData* mpFieldData; + const css::lang::Locale* mpLocale; + const Color maOverlineColor; + const Color maTextLineColor; + + sal_uInt8 mnBiDiLevel; + + bool mbFilled; + tools::Long mnWidthToFill; + + bool mbEndOfLine : 1; + bool mbEndOfParagraph : 1; + bool mbEndOfBullet : 1; + + bool IsRTL() const { return mnBiDiLevel % 2 == 1; } + + DrawPortionInfo( + const Point& rPos, + OUString aTxt, + sal_Int32 nTxtStart, + sal_Int32 nTxtLen, + const SvxFont& rFnt, + sal_Int32 nPar, + o3tl::span pDXArr, + const EEngineData::WrongSpellVector* pWrongSpellVector, + const SvxFieldData* pFieldData, + const css::lang::Locale* pLocale, + const Color& rOverlineColor, + const Color& rTextLineColor, + sal_uInt8 nBiDiLevel, + bool bFilled, + tools::Long nWidthToFill, + bool bEndOfLine, + bool bEndOfParagraph, + bool bEndOfBullet) + : mrStartPos(rPos), + maText(std::move(aTxt)), + mnTextStart(nTxtStart), + mnTextLen(nTxtLen), + mnPara(nPar), + mrFont(rFnt), + mpDXArray(pDXArr), + mpWrongSpellVector(pWrongSpellVector), + mpFieldData(pFieldData), + mpLocale(pLocale), + maOverlineColor(rOverlineColor), + maTextLineColor(rTextLineColor), + mnBiDiLevel(nBiDiLevel), + mbFilled( bFilled ), + mnWidthToFill( nWidthToFill ), + mbEndOfLine(bEndOfLine), + mbEndOfParagraph(bEndOfParagraph), + mbEndOfBullet(bEndOfBullet) + {} +}; + +class EDITENG_DLLPUBLIC DrawBulletInfo +{ +public: + const GraphicObject maBulletGraphicObject; + Point maBulletPosition; + Size maBulletSize; + + DrawBulletInfo( + const GraphicObject& rBulletGraphicObject, + const Point& rBulletPosition, + const Size& rBulletSize) + : maBulletGraphicObject(rBulletGraphicObject), + maBulletPosition(rBulletPosition), + maBulletSize(rBulletSize) + {} +}; + +struct EDITENG_DLLPUBLIC PaintFirstLineInfo +{ + sal_Int32 mnPara; + const Point& mrStartPos; + VclPtr mpOutDev; + + PaintFirstLineInfo( sal_Int32 nPara, const Point& rStartPos, OutputDevice* pOutDev ) + : mnPara( nPara ), mrStartPos( rStartPos ), mpOutDev( pOutDev ) + {} +}; + +class SdrPage; + +class EditFieldInfo +{ +private: + Outliner* pOutliner; + const SvxFieldItem& rFldItem; + + std::optional mxTxtColor; + std::optional mxFldColor; + + OUString aRepresentation; + + sal_Int32 nPara; + sal_Int32 nPos; + + EditFieldInfo( const EditFieldInfo& ) = delete; + + SdrPage* mpSdrPage; + +public: + EditFieldInfo( Outliner* pOutl, const SvxFieldItem& rFItem, sal_Int32 nPa, sal_Int32 nPo ) + : rFldItem( rFItem ) + { + pOutliner = pOutl; + nPara = nPa; nPos = nPo; + mpSdrPage = nullptr; + } + + Outliner* GetOutliner() const { return pOutliner; } + + const SvxFieldItem& GetField() const { return rFldItem; } + + std::optional const & GetTextColor() const { return mxTxtColor; } + void SetTextColor( std::optional xCol ) { mxTxtColor = xCol; } + + std::optional const & GetFieldColor() const { return mxFldColor; } + void SetFieldColor( std::optional xCol ) { mxFldColor = xCol; } + + sal_Int32 GetPara() const { return nPara; } + sal_Int32 GetPos() const { return nPos; } + + const OUString& GetRepresentation() const { return aRepresentation; } + OUString& GetRepresentation() { return aRepresentation; } + void SetRepresentation( const OUString& rStr ){ aRepresentation = rStr; } + + void SetSdrPage( SdrPage* pPage ) { mpSdrPage = pPage; } + SdrPage* GetSdrPage() const { return mpSdrPage; } +}; + + struct EBulletInfo +{ + SvxFont aFont; + tools::Rectangle aBounds; + OUString aText; + sal_Int32 nParagraph; + sal_uInt16 nType; // see SvxNumberType + bool bVisible; + + EBulletInfo() : nParagraph( EE_PARA_NOT_FOUND ), nType( 0 ), bVisible( false ) {} +}; + +enum class OutlinerMode { + DontKnow = 0x0000, + TextObject = 0x0001, + TitleObject = 0x0002, + OutlineObject = 0x0003, + OutlineView = 0x0004 +}; + +class EDITENG_DLLPUBLIC Outliner : public SfxBroadcaster +{ +public: + struct ParagraphHdlParam { Outliner* pOutliner; Paragraph* pPara; }; + struct DepthChangeHdlParam { Outliner* pOutliner; Paragraph* pPara; ParaFlag nPrevFlags; }; +private: + friend class OutlinerView; + friend class OutlinerEditEng; + friend class OutlinerParaObject; + friend class OLUndoExpand; + friend class OutlinerUndoChangeDepth; + friend class OutlinerUndoCheckPara; + friend class OutlinerUndoChangeParaFlags; + + friend class TextChainingUtils; + + std::unique_ptr pEditEngine; + + std::unique_ptr pParaList; + ViewList aViewList; + + sal_Int32 mnFirstSelPage; + Link aDrawPortionHdl; + Link aDrawBulletHdl; + Link aParaInsertedHdl; + Link aParaRemovingHdl; + Link aDepthChangedHdl; + Link aBeginMovingHdl; + Link aEndMovingHdl; + Link aIndentingPagesHdl; + Link aRemovingPagesHdl; + Link aCalcFieldValueHdl; + Link maPaintFirstLineHdl; + Link maBeginPasteOrDropHdl; + Link maEndPasteOrDropHdl; + + sal_Int32 nDepthChangedHdlPrevDepth; + sal_Int16 nMaxDepth; + static constexpr sal_Int16 gnMinDepth = -1; + + OutlinerMode nOutlinerMode; + + bool bFirstParaIsEmpty; + sal_uInt8 nBlockInsCallback; + bool bStrippingPortions; + bool bPasting; + + DECL_DLLPRIVATE_LINK( ParaVisibleStateChangedHdl, Paragraph&, void ); + DECL_DLLPRIVATE_LINK( BeginMovingParagraphsHdl, MoveParagraphsInfo&, void ); + DECL_DLLPRIVATE_LINK( EndMovingParagraphsHdl, MoveParagraphsInfo&, void ); + DECL_DLLPRIVATE_LINK( BeginPasteOrDropHdl, PasteOrDropInfos&, void ); + DECL_DLLPRIVATE_LINK( EndPasteOrDropHdl, PasteOrDropInfos&, void ); + DECL_DLLPRIVATE_LINK( EditEngineNotifyHdl, EENotify&, void ); + void ImplCheckParagraphs( sal_Int32 nStart, sal_Int32 nEnd ); + bool ImplHasNumberFormat( sal_Int32 nPara ) const; + Size ImplGetBulletSize( sal_Int32 nPara ); + sal_uInt16 ImplGetNumbering( sal_Int32 nPara, const SvxNumberFormat* pParaFmt ); + void ImplCalcBulletText( sal_Int32 nPara, bool bRecalcLevel, bool bRecalcChildren ); + OUString ImplGetBulletText( sal_Int32 nPara ); + void ImplCheckNumBulletItem( sal_Int32 nPara ); + void ImplInitDepth( sal_Int32 nPara, sal_Int16 nDepth, bool bCreateUndo ); + void ImplSetLevelDependentStyleSheet( sal_Int32 nPara ); + + void ImplBlockInsertionCallbacks( bool b ); + + void ImpFilterIndents( sal_Int32 nFirstPara, sal_Int32 nLastPara ); + bool ImpConvertEdtToOut( sal_Int32 nPara ); + + void ImpTextPasted( sal_Int32 nStartPara, sal_Int32 nCount ); + vcl::Font ImpCalcBulletFont( sal_Int32 nPara ) const; + tools::Rectangle ImpCalcBulletArea( sal_Int32 nPara, bool bAdjust, bool bReturnPaperPos ); + bool ImpCanIndentSelectedPages( OutlinerView* pCurView ); + bool ImpCanDeleteSelectedPages( OutlinerView* pCurView ); + bool ImpCanDeleteSelectedPages( OutlinerView* pCurView, sal_Int32 nFirstPage, sal_Int32 nPages ); + + void ImplCheckDepth( sal_Int16& rnDepth ) const; + +protected: + void ParagraphInserted( sal_Int32 nParagraph ); + void ParagraphDeleted( sal_Int32 nParagraph ); + void ParaAttribsChanged( sal_Int32 nParagraph ); + + void StyleSheetChanged( SfxStyleSheet const * pStyle ); + + void InvalidateBullet(sal_Int32 nPara); + void PaintBullet(sal_Int32 nPara, const Point& rStartPos, + const Point& rOrigin, Degree10 nOrientation, + OutputDevice& rOutDev); + + // used by OutlinerEditEng. Allows Outliner objects to provide + // bullet access to the EditEngine. + const SvxNumberFormat* GetNumberFormat( sal_Int32 nPara ) const; + +public: + + Outliner( SfxItemPool* pPool, OutlinerMode nMode ); + virtual ~Outliner() override; + + void dumpAsXml(xmlTextWriterPtr pWriter) const; + + void Init( OutlinerMode nMode ); + + void SetVertical( bool bVertical); + void SetRotation(TextRotation nRotation); + bool IsVertical() const; + bool IsTopToBottom() const; + + void SetTextColumns(sal_Int16 nColumns, sal_Int32 nSpacing); + + void SetFixedCellHeight( bool bUseFixedCellHeight ); + + void SetDefaultHorizontalTextDirection( EEHorizontalTextDirection eHTextDir ); + EEHorizontalTextDirection GetDefaultHorizontalTextDirection() const; + + LanguageType GetLanguage( sal_Int32 nPara, sal_Int32 nPos ) const; + + void SetAsianCompressionMode( CharCompressType nCompressionMode ); + + void SetKernAsianPunctuation( bool bEnabled ); + + void SetAddExtLeading( bool b ); + + size_t InsertView( OutlinerView* pView, size_t nIndex = size_t(-1) ); + void RemoveView( OutlinerView const * pView ); + void RemoveView( size_t nIndex ); + OutlinerView* GetView( size_t nIndex ) const; + size_t GetViewCount() const; + + Paragraph* Insert( const OUString& rText, sal_Int32 nAbsPos = EE_PARA_APPEND, sal_Int16 nDepth = 0 ); + void SetText( const OutlinerParaObject& ); + void AddText( const OutlinerParaObject&, bool bAppend = false ); + void SetText( const OUString& rText, Paragraph* pParagraph ); + OUString GetText( Paragraph const * pPara, sal_Int32 nParaCount=1 ) const; + + void SetToEmptyText(); + + std::optional CreateParaObject( sal_Int32 nStartPara = 0, sal_Int32 nParaCount = EE_PARA_ALL ) const; + + const SfxItemSet& GetEmptyItemSet() const; + + void SetRefMapMode( const MapMode& ); + MapMode const & GetRefMapMode() const; + + void SetBackgroundColor( const Color& rColor ); + Color const & GetBackgroundColor() const; + + void SetMaxDepth( sal_Int16 nDepth ); + sal_Int16 GetMaxDepth() const { return nMaxDepth; } + + /// @return previous value of bUpdateLayout state + bool SetUpdateLayout( bool bUpdate ); + bool IsUpdateLayout() const; + + void Clear(); + + void RemoveAttribs( const ESelection& rSelection, bool bRemoveParaAttribs, sal_uInt16 nWhich ); + + sal_Int32 GetParagraphCount() const; + Paragraph* GetParagraph( sal_Int32 nAbsPos ) const; + + bool HasChildren( Paragraph const * pParagraph ) const; + sal_Int32 GetChildCount( Paragraph const * pParent ) const; + bool IsExpanded( Paragraph const * pPara ) const; + Paragraph* GetParent( Paragraph const * pParagraph ) const; + sal_Int32 GetAbsPos( Paragraph const * pPara ) const; + + sal_Int16 GetDepth( sal_Int32 nPara ) const; + void SetDepth( Paragraph* pParagraph, sal_Int16 nNewDepth ); + + void EnableUndo( bool bEnable ); + bool IsUndoEnabled() const; + void UndoActionStart( sal_uInt16 nId ); + void UndoActionEnd(); + void InsertUndo( std::unique_ptr pUndo ); + bool IsInUndo() const; + + void ClearModifyFlag(); + bool IsModified() const; + + void ParagraphInsertedHdl(Paragraph*); + void SetParaInsertedHdl(const Link& rLink){aParaInsertedHdl=rLink;} + const Link& GetParaInsertedHdl() const { return aParaInsertedHdl; } + + void SetParaRemovingHdl(const Link& rLink){aParaRemovingHdl=rLink;} + const Link& GetParaRemovingHdl() const { return aParaRemovingHdl; } + + std::optional GetNonOverflowingText() const; + std::optional GetOverflowingText() const; + void ClearOverflowingParaNum(); + bool IsPageOverflow(); + + OutlinerParaObject GetEmptyParaObject() const; + + + void DepthChangedHdl(Paragraph*, ParaFlag nPrevFlags); + void SetDepthChangedHdl(const Link& rLink){aDepthChangedHdl=rLink;} + const Link& GetDepthChangedHdl() const { return aDepthChangedHdl; } + sal_Int16 GetPrevDepth() const { return static_cast(nDepthChangedHdlPrevDepth); } + + bool RemovingPagesHdl( OutlinerView* ); + void SetRemovingPagesHdl(const Link& rLink){aRemovingPagesHdl=rLink;} + bool IndentingPagesHdl( OutlinerView* ); + void SetIndentingPagesHdl(const Link& rLink){aIndentingPagesHdl=rLink;} + // valid only in the two upper handlers + sal_Int32 GetSelPageCount() const { return nDepthChangedHdlPrevDepth; } + + void SetCalcFieldValueHdl(const Link& rLink ) { aCalcFieldValueHdl= rLink; } + const Link& GetCalcFieldValueHdl() const { return aCalcFieldValueHdl; } + + void SetDrawPortionHdl(const Link& rLink){aDrawPortionHdl=rLink;} + + void SetDrawBulletHdl(const Link& rLink){aDrawBulletHdl=rLink;} + + void SetPaintFirstLineHdl(const Link& rLink) { maPaintFirstLineHdl = rLink; } + + void SetModifyHdl( const Link& rLink ); + Link const & GetModifyHdl() const; + + void SetNotifyHdl( const Link& rLink ); + + void SetStatusEventHdl( const Link& rLink ); + Link const & GetStatusEventHdl() const; + + void Draw( OutputDevice& rOutDev, const tools::Rectangle& rOutRect ); + void Draw( OutputDevice& rOutDev, const Point& rStartPos ); + + const Size& GetPaperSize() const; + void SetPaperSize( const Size& rSize ); + + void SetPolygon( const basegfx::B2DPolyPolygon& rPolyPolygon ); + void SetPolygon( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::B2DPolyPolygon* pLinePolyPolygon); + void ClearPolygon(); + + const Size& GetMinAutoPaperSize() const; + void SetMinAutoPaperSize( const Size& rSz ); + + const Size& GetMaxAutoPaperSize() const; + void SetMaxAutoPaperSize( const Size& rSz ); + + void SetMinColumnWrapHeight(tools::Long nVal); + + void SetDefTab( sal_uInt16 nTab ); + + bool IsFlatMode() const; + void SetFlatMode( bool bFlat ); + + void EnableAutoColor( bool b ); + + void ForceAutoColor( bool b ); + bool IsForceAutoColor() const; + + EBulletInfo GetBulletInfo( sal_Int32 nPara ); + + void SetWordDelimiters( const OUString& rDelimiters ); + OUString const & GetWordDelimiters() const; + OUString GetWord( sal_Int32 nPara, sal_Int32 nIndex ); + + void StripPortions(); + + void DrawingText( const Point& rStartPos, const OUString& rText, + sal_Int32 nTextStart, sal_Int32 nTextLen, + o3tl::span pDXArray, const SvxFont& rFont, + sal_Int32 nPara, sal_uInt8 nRightToLeft, + const EEngineData::WrongSpellVector* pWrongSpellVector, + const SvxFieldData* pFieldData, + bool bEndOfLine, + bool bEndOfParagraph, + bool bEndOfBullet, + const css::lang::Locale* pLocale, + const Color& rOverlineColor, + const Color& rTextLineColor); + + void DrawingTab( const Point& rStartPos, tools::Long nWidth, const OUString& rChar, + const SvxFont& rFont, sal_Int32 nPara, sal_uInt8 nRightToLeft, + bool bEndOfLine, + bool bEndOfParagraph, + const Color& rOverlineColor, + const Color& rTextLineColor); + + Size CalcTextSize(); + Size CalcTextSizeNTP(); + + void SetStyleSheetPool( SfxStyleSheetPool* pSPool ); + SfxStyleSheetPool* GetStyleSheetPool(); + + bool IsInSelectionMode() const; + + void SetStyleSheet( sal_Int32 nPara, SfxStyleSheet* pStyle ); + SfxStyleSheet* GetStyleSheet( sal_Int32 nPara ); + + void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& ); + SfxItemSet const & GetParaAttribs( sal_Int32 nPara ) const; + + void Remove( Paragraph const * pPara, sal_Int32 nParaCount ); + bool Expand( Paragraph const * ); + bool Collapse( Paragraph const * ); + + void SetParaFlag( Paragraph* pPara, ParaFlag nFlag ); + static bool HasParaFlag( const Paragraph* pPara, ParaFlag nFlag ); + + + void SetControlWord( EEControlBits nWord ); + EEControlBits GetControlWord() const; + + const Link& GetBeginMovingHdl() const { return aBeginMovingHdl; } + void SetBeginMovingHdl(const Link& rLink) {aBeginMovingHdl=rLink;} + const Link& GetEndMovingHdl() const {return aEndMovingHdl;} + void SetEndMovingHdl( const Link& rLink){aEndMovingHdl=rLink;} + + sal_uInt32 GetLineCount( sal_Int32 nParagraph ) const; + sal_Int32 GetLineLen( sal_Int32 nParagraph, sal_Int32 nLine ) const; + sal_uInt32 GetLineHeight( sal_Int32 nParagraph ); + + ErrCode Read( SvStream& rInput, const OUString& rBaseURL, EETextFormat, SvKeyValueIterator* pHTTPHeaderAttrs = nullptr ); + + SfxUndoManager& GetUndoManager(); + SfxUndoManager* SetUndoManager(SfxUndoManager* pNew); + + void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ); + void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ); + void QuickInsertLineBreak( const ESelection& rSel ); + + // Only for EditEngine mode + void QuickInsertText( const OUString& rText, const ESelection& rSel ); + void QuickDelete( const ESelection& rSel ); + /// Set attributes from rSet an all characters of nPara. + void SetCharAttribs(sal_Int32 nPara, const SfxItemSet& rSet); + void RemoveCharAttribs( sal_Int32 nPara, sal_uInt16 nWhich = 0 ); + void QuickFormatDoc(); + + bool UpdateFields(); + void RemoveFields( const std::function& isFieldData = [] (const SvxFieldData* ){return true;} ); + + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rTxtColor, std::optional& rFldColor ); + + void SetSpeller( css::uno::Reference< css::linguistic2::XSpellChecker1 > const &xSpeller ); + css::uno::Reference< css::linguistic2::XSpellChecker1 > const & + GetSpeller(); + void SetHyphenator( css::uno::Reference< css::linguistic2::XHyphenator > const & xHyph ); + + static void SetForbiddenCharsTable(const std::shared_ptr& xForbiddenChars); + + // Deprecated + void SetDefaultLanguage( LanguageType eLang ); + + void CompleteOnlineSpelling(); + + EESpellState HasSpellErrors(); + bool HasText( const SvxSearchItem& rSearchItem ); + virtual bool SpellNextDocument(); + + // for text conversion + bool HasConvertibleTextPortion( LanguageType nLang ); + virtual bool ConvertNextDocument(); + + void SetEditTextObjectPool( SfxItemPool* pPool ); + SfxItemPool* GetEditTextObjectPool() const; + + void SetRefDevice( OutputDevice* pRefDev ); + OutputDevice* GetRefDevice() const; + + sal_uInt32 GetTextHeight() const; + tools::Rectangle GetParaBounds( sal_Int32 nParagraph ) const; + Point GetDocPos( const Point& rPaperPos ) const; + bool IsTextPos( const Point& rPaperPos, sal_uInt16 nBorder ); + bool IsTextPos( const Point& rPaperPos, sal_uInt16 nBorder, bool* pbBulletPos ); + + void SetGlobalCharStretching( sal_uInt16 nX = 100, sal_uInt16 nY = 100 ); + void GetGlobalCharStretching( sal_uInt16& rX, sal_uInt16& rY ) const; + void EraseVirtualDevice(); + + bool ShouldCreateBigTextObject() const; + + const EditEngine& GetEditEngine() const; + + // this is needed for StarOffice Api + void SetLevelDependentStyleSheet( sal_Int32 nPara ); + + OutlinerMode GetOutlinerMode() const { return nOutlinerMode; } + + // spell and return a sentence + bool SpellSentence(EditView const & rEditView, svx::SpellPortions& rToFill ); + // put spell position to start of current sentence + void PutSpellingToSentenceStart( EditView const & rEditView ); + // applies a changed sentence + void ApplyChangedSentence(EditView const & rEditView, const svx::SpellPortions& rNewPortions, bool bRecheck ); + + /** sets a link that is called at the beginning of a drag operation at an edit view */ + void SetBeginDropHdl( const Link& rLink ); + + /** sets a link that is called at the end of a drag operation at an edit view */ + void SetEndDropHdl( const Link& rLink ); + + /** sets a link that is called before a drop or paste operation. */ + void SetBeginPasteOrDropHdl( const Link& rLink ); + + /** sets a link that is called after a drop or paste operation. */ + void SetEndPasteOrDropHdl( const Link& rLink ); + + sal_Int16 GetNumberingStartValue( sal_Int32 nPara ) const; + void SetNumberingStartValue( sal_Int32 nPara, sal_Int16 nNumberingStartValue ); + + bool IsParaIsNumberingRestart( sal_Int32 nPara ) const; + void SetParaIsNumberingRestart( sal_Int32 nPara, bool bParaIsNumberingRestart ); + + /** determine the bullets/numbering status of the given paragraphs + + @param nParaStart + index of paragraph at which the check starts + + @param nParaEnd + index of paragraph at which the check ends + + @returns + 0 : all paragraphs have bullets + 1 : all paragraphs have numbering + 2 : otherwise + */ + sal_Int32 GetBulletsNumberingStatus( + const sal_Int32 nParaStart, + const sal_Int32 nParaEnd ) const; + + // convenient method to determine the bullets/numbering status for all paragraphs + sal_Int32 GetBulletsNumberingStatus() const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/outlobj.hxx b/include/editeng/outlobj.hxx new file mode 100644 index 000000000..1703cf09c --- /dev/null +++ b/include/editeng/outlobj.hxx @@ -0,0 +1,204 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +class EditTextObject; +enum class OutlinerMode; +enum class TextRotation; + +/** + * This is the guts of OutlinerParaObject, refcounted and shared among + * multiple instances of OutlinerParaObject. + */ +struct EDITENG_DLLPUBLIC OutlinerParaObjData +{ + // data members + std::unique_ptr mpEditTextObject; + ParagraphDataVector maParagraphDataVector; + bool mbIsEditDoc; + + // constructor + OutlinerParaObjData( std::unique_ptr pEditTextObject, ParagraphDataVector&& rParagraphDataVector, bool bIsEditDoc ); + + OutlinerParaObjData( const OutlinerParaObjData& r ); + + OutlinerParaObjData( OutlinerParaObjData&& r ) = default; + + // assignment operator + OutlinerParaObjData& operator=(const OutlinerParaObjData& rCandidate) = delete; + + // destructor + ~OutlinerParaObjData(); + + bool operator==(const OutlinerParaObjData& rCandidate) const; + + // #i102062# + bool isWrongListEqual(const OutlinerParaObjData& rCompare) const; +}; + +class EDITENG_DLLPUBLIC OutlinerParaObject +{ +friend class std::optional; + ::o3tl::cow_wrapper< OutlinerParaObjData > mpImpl; + + OutlinerParaObject(std::nullopt_t) noexcept + : mpImpl(std::nullopt) {} + OutlinerParaObject( const OutlinerParaObject& other, std::nullopt_t ) noexcept + : mpImpl(other.mpImpl, std::nullopt) {} + +public: + // constructors/destructor + OutlinerParaObject(std::unique_ptr, ParagraphDataVector&&, bool bIsEditDoc); + OutlinerParaObject( std::unique_ptr ); + OutlinerParaObject( const OutlinerParaObject&); + OutlinerParaObject(OutlinerParaObject&&) noexcept; + ~OutlinerParaObject(); + + // assignment operator + OutlinerParaObject& operator=(const OutlinerParaObject& rCandidate); + OutlinerParaObject& operator=(OutlinerParaObject&&) noexcept; + + // compare operator + bool operator==(const OutlinerParaObject& rCandidate) const; + bool operator!=(const OutlinerParaObject& rCandidate) const { return !operator==(rCandidate); } + + // #i102062# + bool isWrongListEqual(const OutlinerParaObject& rCompare) const; + + // outliner mode access + OutlinerMode GetOutlinerMode() const; + void SetOutlinerMode(OutlinerMode nNew); + + // vertical access + bool IsEffectivelyVertical() const; + bool GetVertical() const; + bool IsTopToBottom() const; + void SetVertical(bool bNew); + void SetRotation(TextRotation nRotation); + TextRotation GetRotation() const; + + // data read access + sal_Int32 Count() const; + sal_Int16 GetDepth(sal_Int32 nPara) const; + const EditTextObject& GetTextObject() const; + const ParagraphData& GetParagraphData(sal_Int32 nIndex) const; + + // portion info support + void ClearPortionInfo(); + + // StyleSheet support + bool ChangeStyleSheets(std::u16string_view rOldName, SfxStyleFamily eOldFamily, + const OUString& rNewName, SfxStyleFamily eNewFamily); + void ChangeStyleSheetName(SfxStyleFamily eFamily, std::u16string_view rOldName, + const OUString& rNewName); + void SetStyleSheets(sal_uInt16 nLevel, const OUString& rNewName, + const SfxStyleFamily& rNewFamily); + + void dumpAsXml(xmlTextWriterPtr pWriter) const; +}; + +namespace std +{ + /** Specialise std::optional template for the case where we are wrapping a o3tl::cow_wrapper + type, and we can make the pointer inside the cow_wrapper act as an empty value, + and save ourselves some storage */ + template<> + class optional + { + public: + optional() noexcept : maParaObject(std::nullopt) {} + optional(std::nullopt_t) noexcept : maParaObject(std::nullopt) {} + optional(const optional& other) : + maParaObject(other.maParaObject, std::nullopt) {} + optional(optional&& other) noexcept : + maParaObject(std::move(other.maParaObject)) {} + optional(OutlinerParaObject&& para) noexcept : + maParaObject(std::move(para)) {} + optional(const OutlinerParaObject& para) noexcept : + maParaObject(para) {} + template< class... Args > + explicit optional( std::in_place_t, Args&&... args ) : + maParaObject(std::forward(args)...) {} + + optional& operator=(optional const & other) + { + maParaObject = other.maParaObject; + return *this; + } + optional& operator=(optional&& other) noexcept + { + maParaObject = std::move(other.maParaObject); + return *this; + } + template< class... Args > + void emplace(Args&&... args ) + { + maParaObject = OutlinerParaObject(std::forward(args)...); + } + + bool has_value() const noexcept { return !maParaObject.mpImpl.empty(); } + explicit operator bool() const noexcept { return !maParaObject.mpImpl.empty(); } + void reset() { maParaObject.mpImpl.set_empty(); } + + OutlinerParaObject& value() + { + throwIfEmpty(); + return maParaObject; + } + OutlinerParaObject& operator*() + { + throwIfEmpty(); + return maParaObject; + } + const OutlinerParaObject& operator*() const + { + throwIfEmpty(); + return maParaObject; + } + OutlinerParaObject* operator->() + { + throwIfEmpty(); + return &maParaObject; + } + const OutlinerParaObject* operator->() const + { + throwIfEmpty(); + return &maParaObject; + } + private: + void throwIfEmpty() const + { + if (maParaObject.mpImpl.empty()) + throw std::logic_error("empty std::optional"); + } + OutlinerParaObject maParaObject; + }; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/overflowingtxt.hxx b/include/editeng/overflowingtxt.hxx new file mode 100644 index 000000000..5b95f2d12 --- /dev/null +++ b/include/editeng/overflowingtxt.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_OVERFLOWINGTXT_HXX +#define INCLUDED_EDITENG_OVERFLOWINGTXT_HXX + +#include +#include + +#include +#include + +namespace com::sun::star { + namespace datatransfer { class XTransferable; } +} + +class OutlinerParaObject; +class Outliner; + + +/* + * A collection of static methods for attaching text. + * Strongly coupled with some of the classes in this file. + */ +class TextChainingUtils +{ +public: + static css::uno::Reference< css::datatransfer::XTransferable> CreateTransferableFromText(Outliner const *); + + static std::optional JuxtaposeParaObject( + css::uno::Reference< css::datatransfer::XTransferable > const & xOverflowingContent, + Outliner *, + OutlinerParaObject const *); + static std::optional DeeplyMergeParaObject( + css::uno::Reference< css::datatransfer::XTransferable > const & xOverflowingContent, + Outliner *, + OutlinerParaObject const *); +}; + +/* + * The classes OverflowingText and NonOverflowingText handle the + * actual preparation of the OutlinerParaObjects to be used in destination + * and source box respectively. +*/ + +class OverflowingText +{ +public: + OverflowingText(css::uno::Reference< css::datatransfer::XTransferable > xOverflowingContent); + + std::optional JuxtaposeParaObject(Outliner *, OutlinerParaObject const *); + std::optional DeeplyMergeParaObject(Outliner *, OutlinerParaObject const *); + +private: + css::uno::Reference< css::datatransfer::XTransferable > mxOverflowingContent; +}; + +class NonOverflowingText +{ +public: + NonOverflowingText(const ESelection &aSel, bool bLastParaInterrupted); + + std::optional RemoveOverflowingText(Outliner *) const; + ESelection GetOverflowPointSel() const; + bool IsLastParaInterrupted() const; + +private: + ESelection maContentSel; + bool mbLastParaInterrupted; +}; + + +/* + * classes OFlowChainedText and UFlowChainedText: + * contain and handle the state of a broken up text _after_ a flow event + * (respectively after Overflow and Underflow). + * + */ +class EDITENG_DLLPUBLIC OFlowChainedText +{ +public: + OFlowChainedText(Outliner const *, bool ); + ~OFlowChainedText(); + + std::optional InsertOverflowingText(Outliner *, OutlinerParaObject const *); + std::optional RemoveOverflowingText(Outliner *); + + ESelection GetOverflowPointSel() const; + + bool IsLastParaInterrupted() const; + +private: + std::optional mpNonOverflowingTxt; + std::optional mpOverflowingTxt; + + bool mbIsDeepMerge; +}; + +// UFlowChainedText is a simpler class than OFlowChainedText: it almost only joins para-objects +class EDITENG_DLLPUBLIC UFlowChainedText +{ +public: + UFlowChainedText(Outliner const *, bool); + std::optional CreateMergedUnderflowParaObject(Outliner *, OutlinerParaObject const *); + +private: + css::uno::Reference< css::datatransfer::XTransferable > mxUnderflowingTxt; + + bool mbIsDeepMerge; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/paperinf.hxx b/include/editeng/paperinf.hxx new file mode 100644 index 000000000..2ccc8fbf9 --- /dev/null +++ b/include/editeng/paperinf.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PAPERINF_HXX +#define INCLUDED_EDITENG_PAPERINF_HXX + +// INCLUDE --------------------------------------------------------------- + +#include +#include +#include +#include +#include + +// forward --------------------------------------------------------------- + +class Printer; + +// class SvxPaperInfo ----------------------------------------------------- + +class EDITENG_DLLPUBLIC SvxPaperInfo +{ +public: + static Size GetDefaultPaperSize( MapUnit eUnit = MapUnit::MapTwip ); + static Size GetPaperSize( Paper ePaper, MapUnit eUnit = MapUnit::MapTwip ); + static Size GetPaperSize( const Printer* pPrinter ); + static Paper GetSvxPaper( const Size &rSize, MapUnit eUnit ); + static tools::Long GetSloppyPaperDimension( tools::Long nSize ); + static OUString GetName( Paper ePaper ); +}; + +// INLINE ----------------------------------------------------------------- + +inline Size &Swap(Size &rSize) +{ + const tools::Long lVal = rSize.Width(); + rSize.setWidth( rSize.Height() ); + rSize.setHeight( lVal ); + return rSize; +} + +inline Size &LandscapeSwap(Size &rSize) +{ + if ( rSize.Height() > rSize.Width() ) + Swap( rSize ); + return rSize; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/paragraphdata.hxx b/include/editeng/paragraphdata.hxx new file mode 100644 index 000000000..f0e859d6f --- /dev/null +++ b/include/editeng/paragraphdata.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_PARAGRAPHDATA_HXX +#define INCLUDED_EDITENG_PARAGRAPHDATA_HXX + +#include +#include + +class ParagraphData +{ + friend class Paragraph; + friend class OutlinerParaObject; + +protected: + sal_Int16 nDepth; + sal_Int16 mnNumberingStartValue; + bool mbParaIsNumberingRestart; + +public: + ParagraphData(); + + bool operator==(const ParagraphData& rCandidate) const; + + sal_Int16 getDepth() const { return nDepth; } +}; + +typedef ::std::vector< ParagraphData > ParagraphDataVector; + +#endif // INCLUDED_EDITENG_PARAGRAPHDATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/paravertalignitem.hxx b/include/editeng/paravertalignitem.hxx new file mode 100644 index 000000000..335b15f37 --- /dev/null +++ b/include/editeng/paravertalignitem.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PARAVERTALIGNITEM_HXX +#define INCLUDED_EDITENG_PARAVERTALIGNITEM_HXX + +#include +#include + +// class SvxParaVertAlignItem ---------------------------------------------- + +/* [Description] + + This item defines the character alignment in the lines of a paragraph. + Currently the alignment can be none (i.e. baseline), top, center or bottom. + +*/ + +class EDITENG_DLLPUBLIC SvxParaVertAlignItem final : public SfxUInt16Item +{ +public: + enum class Align { Automatic, Baseline, Top, Center, Bottom }; + static SfxPoolItem* CreateDefault(); + + SvxParaVertAlignItem( Align nValue /*= 0*/, + const sal_uInt16 nId ); + + virtual SvxParaVertAlignItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + Align GetValue() const { return static_cast(SfxUInt16Item::GetValue()); } + void SetValue(Align n) { SfxUInt16Item::SetValue(static_cast(n)); } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/pbinitem.hxx b/include/editeng/pbinitem.hxx new file mode 100644 index 000000000..d6bf7229b --- /dev/null +++ b/include/editeng/pbinitem.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PBINITEM_HXX +#define INCLUDED_EDITENG_PBINITEM_HXX + +#include +#include + +// define ---------------------------------------------------------------- + +#define PAPERBIN_PRINTER_SETTINGS (sal_uInt8(0xFF)) + +// class SvxPaperBinItem ------------------------------------------------- + +/* [Description] + + This item describes selecting a paper tray of the printer. +*/ + +class EDITENG_DLLPUBLIC SvxPaperBinItem final : public SfxByteItem +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit inline SvxPaperBinItem( const sal_uInt16 nId , + const sal_uInt8 nTray = PAPERBIN_PRINTER_SETTINGS ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxPaperBinItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +inline SvxPaperBinItem::SvxPaperBinItem( const sal_uInt16 nId, const sal_uInt8 nT ) + : SfxByteItem( nId, nT ) +{} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/pgrditem.hxx b/include/editeng/pgrditem.hxx new file mode 100644 index 000000000..ef8c24e66 --- /dev/null +++ b/include/editeng/pgrditem.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PGRDITEM_HXX +#define INCLUDED_EDITENG_PGRDITEM_HXX + +#include +#include + +// class SvxParaGridItem ------------------------------------------------- + + +/* [Description] + + Paragraph snap to grid +*/ + +class EDITENG_DLLPUBLIC SvxParaGridItem final : public SfxBoolItem +{ +public: + SvxParaGridItem( const bool bSnapToGrid /*= true*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxParaGridItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/pmdlitem.hxx b/include/editeng/pmdlitem.hxx new file mode 100644 index 000000000..f4bfa53c4 --- /dev/null +++ b/include/editeng/pmdlitem.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PMDLITEM_HXX +#define INCLUDED_EDITENG_PMDLITEM_HXX + +#include +#include + +// class SvxPageModelItem ------------------------------------------------ + +/* [Description] + + This item contains a name of a page template. +*/ + +class EDITENG_DLLPUBLIC SvxPageModelItem final : public SfxStringItem +{ +private: + bool bAuto; + +public: + static SfxPoolItem* CreateDefault(); + + explicit inline SvxPageModelItem( sal_uInt16 nWh ); + inline SvxPageModelItem( const OUString& rModel, bool bA /*= false*/, + sal_uInt16 nWh ); + + virtual SvxPageModelItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + virtual bool operator==( const SfxPoolItem& ) const override; +}; + +inline SvxPageModelItem::SvxPageModelItem( sal_uInt16 nWh ) + : bAuto( false ) +{ + SetWhich( nWh ); +} + +inline SvxPageModelItem::SvxPageModelItem( const OUString& rModel, bool bA, + sal_uInt16 nWh ) : + SfxStringItem( nWh, rModel ), + bAuto( bA ) +{} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/postitem.hxx b/include/editeng/postitem.hxx new file mode 100644 index 000000000..93ed44b6b --- /dev/null +++ b/include/editeng/postitem.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_POSTITEM_HXX +#define INCLUDED_EDITENG_POSTITEM_HXX + +#include +#include +#include + +// class SvxPostureItem -------------------------------------------------- + +/* [Description] + + This item describes the font setting (Italic) +*/ + +class EDITENG_DLLPUBLIC SvxPostureItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxPostureItem( const FontItalic ePost /*= ITALIC_NONE*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + SwEnumItem + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxPostureItem* Clone( SfxItemPool *pPool = nullptr ) const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetValueCount() const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool HasBoolValue() const override; + virtual bool GetBoolValue() const override; + virtual void SetBoolValue( bool bVal ) override; + + // enum cast + FontItalic GetPosture() const + { return GetValue(); } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif // INCLUDED_EDITENG_POSTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/prntitem.hxx b/include/editeng/prntitem.hxx new file mode 100644 index 000000000..8f0e6a8fc --- /dev/null +++ b/include/editeng/prntitem.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PRNTITEM_HXX +#define INCLUDED_EDITENG_PRNTITEM_HXX + +#include +#include + + +// class SvxPrintItem ---------------------------------------------------- + + +/* [Description] + + This item describes a logical variable "Print yes or no". +*/ + + +class EDITENG_DLLPUBLIC SvxPrintItem final : public SfxBoolItem +{ +public: + explicit SvxPrintItem( const sal_uInt16 nId , const bool bPrt = true ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxPrintItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +inline SvxPrintItem::SvxPrintItem( const sal_uInt16 nId, const bool bPrt ) + : SfxBoolItem( nId, bPrt ) +{} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/protitem.hxx b/include/editeng/protitem.hxx new file mode 100644 index 000000000..4f3f1c4ac --- /dev/null +++ b/include/editeng/protitem.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_PROTITEM_HXX +#define INCLUDED_EDITENG_PROTITEM_HXX + +#include +#include + +// class SvxProtectItem -------------------------------------------------- + + +/* [Description] + + This item describes, if content, size or position should be protected. +*/ + +class EDITENG_DLLPUBLIC SvxProtectItem final : public SfxPoolItem +{ + bool bCntnt :1; // Content protected + bool bSize :1; // Size protected + bool bPos :1; // Position protected + +public: + static SfxPoolItem* CreateDefault(); + + explicit inline SvxProtectItem( const sal_uInt16 nId ); + SvxProtectItem(SvxProtectItem const &) = default; // SfxPoolItem copy function dichotomy + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + + virtual SvxProtectItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + bool IsContentProtected() const { return bCntnt; } + bool IsSizeProtected() const { return bSize; } + bool IsPosProtected() const { return bPos; } + void SetContentProtect( bool bNew ) { bCntnt = bNew; } + void SetSizeProtect ( bool bNew ) { bSize = bNew; } + void SetPosProtect ( bool bNew ) { bPos = bNew; } + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +inline SvxProtectItem::SvxProtectItem( const sal_uInt16 nId ) + : SfxPoolItem( nId ) +{ + bCntnt = bSize = bPos = false; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/rsiditem.hxx b/include/editeng/rsiditem.hxx new file mode 100644 index 000000000..78ab9b8bf --- /dev/null +++ b/include/editeng/rsiditem.hxx @@ -0,0 +1,37 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_EDITENG_RSIDITEM_HXX +#define INCLUDED_EDITENG_RSIDITEM_HXX + +#include +#include + + +// SvxRsidItem + + +class EDITENG_DLLPUBLIC SvxRsidItem final : public SfxUInt32Item +{ +public: + SvxRsidItem( sal_uInt32 nRsid, sal_uInt16 nId ) : SfxUInt32Item( nId, nRsid ) {} + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxRsidItem* Clone( SfxItemPool* pPool = nullptr ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif // INCLUDED_EDITENG_RSIDITEM_HXX diff --git a/include/editeng/scriptspaceitem.hxx b/include/editeng/scriptspaceitem.hxx new file mode 100644 index 000000000..9a4cac3de --- /dev/null +++ b/include/editeng/scriptspaceitem.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SCRIPTSPACEITEM_HXX +#define INCLUDED_EDITENG_SCRIPTSPACEITEM_HXX + +#include +#include + +// class SvxScriptSpaceItem ---------------------------------------------- + +/* [Description] + + This item describe the script type of the selected text and is only + used for the user interface. +*/ + +class EDITENG_DLLPUBLIC SvxScriptSpaceItem final : public SfxBoolItem +{ +public: + SvxScriptSpaceItem( bool bOn /*= false*/, + const sal_uInt16 nId ); + + virtual SvxScriptSpaceItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/scripttypeitem.hxx b/include/editeng/scripttypeitem.hxx new file mode 100644 index 000000000..bfe84f5f6 --- /dev/null +++ b/include/editeng/scripttypeitem.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SCRIPTTYPEITEM_HXX +#define INCLUDED_EDITENG_SCRIPTTYPEITEM_HXX + +#include +#include +#include + +class EDITENG_DLLPUBLIC SvxScriptSetItem final : public SfxSetItem +{ +public: + SvxScriptSetItem( sal_uInt16 nSlotId, SfxItemPool& rPool ); + + virtual SvxScriptSetItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + static const SfxPoolItem* GetItemOfScriptSet( const SfxItemSet& rSet, + sal_uInt16 nWhich ); + + static const SfxPoolItem* GetItemOfScript( sal_uInt16 nSlotId, const SfxItemSet& rSet, SvtScriptType nScript ); + + const SfxPoolItem* GetItemOfScript( SvtScriptType nScript ) const; + + void PutItemForScriptType( SvtScriptType nScriptType, const SfxPoolItem& rItem ); + + static void GetWhichIds( sal_uInt16 nSlotId, const SfxItemSet& rSet, sal_uInt16& rLatin, sal_uInt16& rAsian, sal_uInt16& rComplex); + + void GetWhichIds( sal_uInt16& rLatin, sal_uInt16& rAsian, sal_uInt16& rComplex) const; + + static void GetSlotIds( sal_uInt16 nSlotId, sal_uInt16& rLatin, sal_uInt16& rAsian, + sal_uInt16& rComplex ); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/section.hxx b/include/editeng/section.hxx new file mode 100644 index 000000000..d14189c24 --- /dev/null +++ b/include/editeng/section.hxx @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_EDITENG_SECTION_HXX +#define INCLUDED_EDITENG_SECTION_HXX + +#include + +#include + +class SfxPoolItem; + +namespace editeng +{ +struct Section +{ + sal_Int32 mnParagraph; + sal_Int32 mnStart; + sal_Int32 mnEnd; + + std::vector maAttributes; + + Section(sal_Int32 nPara, sal_Int32 nStart, sal_Int32 nEnd); +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/shaditem.hxx b/include/editeng/shaditem.hxx new file mode 100644 index 000000000..bed848215 --- /dev/null +++ b/include/editeng/shaditem.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SHADITEM_HXX +#define INCLUDED_EDITENG_SHADITEM_HXX + +#include +#include +#include + +#include +#include + + +// class SvxShadowItem --------------------------------------------------- + +/* [Description] + + This item describes the shadow attribute (color, width and position). +*/ +enum class SvxShadowItemSide { TOP, BOTTOM, LEFT, RIGHT }; + +class EDITENG_DLLPUBLIC SvxShadowItem final : public SfxEnumItemInterface +{ + Color aShadowColor; + sal_uInt16 nWidth; + SvxShadowLocation eLocation; +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxShadowItem( const sal_uInt16 nId , + const Color *pColor = nullptr, const sal_uInt16 nWidth = 100 /*5pt*/, + const SvxShadowLocation eLoc = SvxShadowLocation::NONE ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxShadowItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + const Color& GetColor() const { return aShadowColor;} + void SetColor( const Color &rNew ) { aShadowColor = rNew; } + + sal_uInt16 GetWidth() const { return nWidth; } + SvxShadowLocation GetLocation() const { return eLocation; } + + void SetWidth( sal_uInt16 nNew ) { nWidth = nNew; } + void SetLocation( SvxShadowLocation eNew ) { eLocation = eNew; } + + // Calculate width of the shadow on the page. + sal_uInt16 CalcShadowSpace( SvxShadowItemSide nShadow ) const; + + virtual sal_uInt16 GetValueCount() const override; + virtual sal_uInt16 GetEnumValue() const override; + virtual void SetEnumValue( sal_uInt16 nNewVal ) override; + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif // INCLUDED_EDITENG_SHADITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/shdditem.hxx b/include/editeng/shdditem.hxx new file mode 100644 index 000000000..dbe30a672 --- /dev/null +++ b/include/editeng/shdditem.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SHDDITEM_HXX +#define INCLUDED_EDITENG_SHDDITEM_HXX + +#include +#include + +// class SvxShadowedItem ------------------------------------------------- + +/* [Description] + + This item describes, whether and how it is shaded. +*/ + +class EDITENG_DLLPUBLIC SvxShadowedItem final : public SfxBoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxShadowedItem( const bool bShadowed /*= false*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxShadowedItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + SvxShadowedItem(SvxShadowedItem const &) = default; // SfxPoolItem copy function dichotomy +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/sizeitem.hxx b/include/editeng/sizeitem.hxx new file mode 100644 index 000000000..2247c76d9 --- /dev/null +++ b/include/editeng/sizeitem.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SIZEITEM_HXX +#define INCLUDED_EDITENG_SIZEITEM_HXX + +#include +#include +#include + +// class SvxSizeItem ----------------------------------------------------- + +/* [Description] + + This item describes a two-dimensional size. +*/ + +class EDITENG_DLLPUBLIC SvxSizeItem : public SfxPoolItem +{ + + Size m_aSize; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxSizeItem( const sal_uInt16 nId ); + SvxSizeItem( const sal_uInt16 nId, const Size& rSize); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxSizeItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + const Size& GetSize() const { return m_aSize; } + void SetSize(const Size& rSize) { m_aSize = rSize; } + + tools::Long GetWidth() const { return m_aSize.getWidth(); } + tools::Long GetHeight() const { return m_aSize.getHeight(); } + void SetWidth(tools::Long n) { m_aSize.setWidth(n); } + void SetHeight(tools::Long n) { m_aSize.setHeight(n); } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/spltitem.hxx b/include/editeng/spltitem.hxx new file mode 100644 index 000000000..553e3263f --- /dev/null +++ b/include/editeng/spltitem.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SPLTITEM_HXX +#define INCLUDED_EDITENG_SPLTITEM_HXX + +#include +#include + +// class SvxFormatSplitItem ------------------------------------------------- + +/* [Description] + + This item describes a logical variable "split paragraph yes or no". +*/ + +class EDITENG_DLLPUBLIC SvxFormatSplitItem final : public SfxBoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + virtual ~SvxFormatSplitItem() override; + + inline SvxFormatSplitItem( const bool bSplit /*= true*/, + const sal_uInt16 nWh ); + + SvxFormatSplitItem(SvxFormatSplitItem const &) = default; + SvxFormatSplitItem(SvxFormatSplitItem &&) = default; + SvxFormatSplitItem & operator =(SvxFormatSplitItem const &) = delete; // due to SfxBoolItem + SvxFormatSplitItem & operator =(SvxFormatSplitItem &&) = delete; // due to SfxBoolItem + + // "pure virtual Methods" from SfxPoolItem + virtual SvxFormatSplitItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +inline SvxFormatSplitItem::SvxFormatSplitItem( const bool bSplit, const sal_uInt16 nWh ) : + SfxBoolItem( nWh, bSplit ) +{} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/splwrap.hxx b/include/editeng/splwrap.hxx new file mode 100644 index 000000000..79d55d179 --- /dev/null +++ b/include/editeng/splwrap.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SPLWRAP_HXX +#define INCLUDED_EDITENG_SPLWRAP_HXX + +#include +#include +#include +#include +#include +#include + +// forward --------------------------------------------------------------- + +namespace com::sun::star::linguistic2 { + class XDictionary; + class XSpellChecker1; + class XHyphenator; +} + +// misc functions --------------------------------------------------------------- + +void EDITENG_DLLPUBLIC SvxPrepareAutoCorrect( OUString &rOldText, const OUString &rNewText ); + +/*-------------------------------------------------------------------- + Description: The SpellWrapper + --------------------------------------------------------------------*/ + +class EDITENG_DLLPUBLIC SvxSpellWrapper { +private: + friend class SvxSpellCheckDialog; + friend class SvxHyphenWordDialog; + friend struct SvxHyphenWordDialog_Impl; + + weld::Widget* pWin; + std::unique_ptr xWait; + css::uno::Reference< + css::uno::XInterface > xLast; // result of last spelling/hyphenation attempt + css::uno::Reference< + css::linguistic2::XHyphenator > xHyph; + bool bOtherCntnt : 1; // set => Check special sections initially + bool bReverse : 1; // Reverse spell check + bool bStartDone : 1; // Beginning already corrected + bool bEndDone : 1; // End part already corrected + bool bStartChk : 1; // Examine the beginning + bool bRevAllowed : 1; // Reverse spell check prohibited + bool bAllRight : 1; // Record wrong words in the dedicated + // dictionary and do not start the dialog. + + EDITENG_DLLPRIVATE bool SpellNext(); // select next area + bool FindSpellError(); // Check for errors (over areas) + + SvxSpellWrapper(SvxSpellWrapper const &) = delete; + void operator =(SvxSpellWrapper const &) = delete; + +public: + SvxSpellWrapper( weld::Widget* pWn, + const bool bStart, const bool bIsAllRight ); + SvxSpellWrapper( weld::Widget* pWn, + css::uno::Reference< css::linguistic2::XHyphenator > const &xHyphenator, + const bool bStart, const bool bOther ); + + virtual ~SvxSpellWrapper(); + + static sal_Int16 CheckSpellLang( + css::uno::Reference< css::linguistic2::XSpellChecker1 > const & xSpell, + LanguageType nLang ); + static sal_Int16 CheckHyphLang( + css::uno::Reference< css::linguistic2::XHyphenator >const & xHyph, + LanguageType nLang ); + + static void ShowLanguageErrors(); + + void SpellDocument(); // Perform Spell Checking + bool IsStartDone() const { return bStartDone; } + bool IsEndDone() const { return bEndDone; } + bool IsAllRight() const { return bAllRight; } + +protected: + const css::uno::Reference< css::uno::XInterface >& + GetLast() const { return xLast; } + void SetLast(const css::uno::Reference< css::uno::XInterface > &xNewLast) + { xLast = xNewLast; } + virtual bool SpellMore(); // examine further documents? + virtual void SpellStart( SvxSpellArea eSpell ); // Preparing the area + virtual void SpellContinue(); // Check Areas + // Result available through GetLast + virtual void ReplaceAll( const OUString &rNewText ); //Replace word from the replace list + static css::uno::Reference< css::linguistic2::XDictionary > + GetAllRightDic(); + virtual void SpellEnd(); // Finish area + virtual void InsertHyphen( const sal_Int32 nPos ); // Insert hyphen +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/svxacorr.hxx b/include/editeng/svxacorr.hxx new file mode 100644 index 000000000..7483e83c1 --- /dev/null +++ b/include/editeng/svxacorr.hxx @@ -0,0 +1,447 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_SVXACORR_HXX +#define INCLUDED_EDITENG_SVXACORR_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +class CharClass; +class SfxPoolItem; +class SotStorage; +class SvxAutoCorrect; +class SfxObjectShell; +namespace vcl { class Window; } +namespace com::sun::star::embed { class XStorage; } +namespace tools { template class SvRef; } + +struct CompareSvStringsISortDtor +{ + bool operator()( std::u16string_view lhs, std::u16string_view rhs ) const + { + return o3tl::compareToIgnoreAsciiCase( lhs, rhs ) < 0; + } +}; + +class SvStringsISortDtor + : public o3tl::sorted_vector +{ +}; + +// Auto correct flags +enum class ACFlags : sal_uInt32 { + NONE = 0x00000000, + CapitalStartSentence = 0x00000001, // Capital letters at the beginning of a sentence + CapitalStartWord = 0x00000002, // not two Capital letters at the beginning of a word + AddNonBrkSpace = 0x00000004, // Add non breaking space before :,?!% + ChgOrdinalNumber = 0x00000008, // Ordinal-Number 1st, 2nd,.. + ChgToEnEmDash = 0x00000010, // - -> Endash/Emdash + ChgWeightUnderl = 0x00000020, // * -> Bold, _ -> Underscore + SetINetAttr = 0x00000040, // Set INetAttribut + Autocorrect = 0x00000080, // Call AutoCorrect + ChgQuotes = 0x00000100, // replace double quotes + SaveWordCplSttLst = 0x00000200, // Save Auto correction of Capital letter at beginning of sentence. + SaveWordWordStartLst = 0x00000400, // Save Auto correction of TWo INitial CApitals or sMALL iNITIAL. + IgnoreDoubleSpace = 0x00000800, // Ignore 2 Spaces + ChgSglQuotes = 0x00001000, // Replace simple quotes + CorrectCapsLock = 0x00002000, // Correct accidental use of cAPS LOCK key + TransliterateRTL = 0x00004000, // Transliterate RTL text + ChgAngleQuotes = 0x00008000, // >>, << -> angle quotes in some languages + + ChgWordLstLoad = 0x20000000, // Replacement list loaded + CplSttLstLoad = 0x40000000, // Exception list for Capital letters Start loaded + WordStartLstLoad = 0x80000000, // Exception list for Word Start loaded +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +enum class ACQuotes +{ + NONE, + NonBreakingSpace, + CapitalizeIAm, + DoubleAngleQuote, + UseApostrophe, +}; + +// TODO: handle code points > U+FFFF and check users of this class + +// only a mapping class +class EDITENG_DLLPUBLIC SvxAutoCorrDoc +{ +public: + virtual ~SvxAutoCorrDoc(); + + virtual bool Delete( sal_Int32 nStt, sal_Int32 nEnd ) = 0; + virtual bool Insert( sal_Int32 nPos, const OUString& rTxt ) = 0; + virtual bool Replace( sal_Int32 nPos, const OUString& rTxt ) = 0; + virtual bool ReplaceRange( sal_Int32 nPos, sal_Int32 nLen, const OUString& rTxt ) = 0; + + virtual void SetAttr( sal_Int32 nStt, sal_Int32 nEnd, sal_uInt16 nSlotId, + SfxPoolItem& ) = 0; + + virtual bool SetINetAttr( sal_Int32 nStt, sal_Int32 nEnd, const OUString& rURL ) = 0; + + // Return the text of a previous paragraph. + // If no paragraph exits or just an empty one, then return an empty string. + // The flag indicates: + // TRUE: before the normal insertion position (TRUE) + // FALSE: in which the corrected word was inserted. + // (Does not to have to be the same paragraph !!!!) + virtual OUString const* GetPrevPara(bool bAtNormalPos) = 0; + + virtual bool ChgAutoCorrWord( sal_Int32& rSttPos, sal_Int32 nEndPos, + SvxAutoCorrect& rACorrect, + OUString* pPara ) = 0; + virtual bool TransliterateRTLWord( sal_Int32& rSttPos, sal_Int32 nEndPos, + bool bApply = false ) = 0; + + // Is called after the change of the signs by the functions + // - FnCapitalStartWord + // - FnCapitalStartSentence + // As an option, the words can then be inserted into the exception lists. + virtual void SaveCpltSttWord( ACFlags nFlag, sal_Int32 nPos, + const OUString& rExceptWord, + sal_Unicode cChar ); + + // which language at the position? + virtual LanguageType GetLanguage( sal_Int32 nPos ) const; +}; + + +class EDITENG_DLLPUBLIC SvxAutocorrWord +{ + OUString sShort, sLong; + bool bIsTxtOnly; // Is pure ASCII - Text +public: + SvxAutocorrWord( OUString aS, OUString aL, bool bFlag = true ) + : sShort(std::move( aS )), sLong(std::move( aL )), bIsTxtOnly( bFlag ) + {} + + const OUString& GetShort() const { return sShort; } + const OUString& GetLong() const { return sLong; } + bool IsTextOnly() const { return bIsTxtOnly; } +}; + +class EDITENG_DLLPUBLIC SvxAutocorrWordList +{ + struct Impl; + std::unique_ptr mpImpl; + + SvxAutocorrWordList( const SvxAutocorrWordList& ) = delete; + const SvxAutocorrWordList& operator= ( const SvxAutocorrWordList& ) = delete; + + const SvxAutocorrWord* WordMatches(const SvxAutocorrWord *pFnd, + const OUString &rTxt, + sal_Int32 &rStt, + sal_Int32 nEndPos) const; +public: + SvxAutocorrWordList(); + // free any objects still in the set + ~SvxAutocorrWordList(); + void DeleteAndDestroyAll(); + const SvxAutocorrWord* Insert(SvxAutocorrWord aWord) const; + std::optional FindAndRemove(const SvxAutocorrWord *pWord); + void LoadEntry(const OUString& sWrong, const OUString& sRight, bool bOnlyTxt); + bool empty() const; + + struct CompareSvxAutocorrWordList; + typedef std::vector AutocorrWordSetType; + const AutocorrWordSetType & getSortedContent() const; + + const SvxAutocorrWord* SearchWordsInList(const OUString& rTxt, sal_Int32& rStt, sal_Int32 nEndPos) const; +}; + +class EDITENG_DLLPUBLIC SvxAutoCorrectLanguageLists +{ + OUString sShareAutoCorrFile, sUserAutoCorrFile; + // If the AutoCorr file is newer + Date aModifiedDate; + tools::Time aModifiedTime, aLastCheckTime; + + std::unique_ptr pCplStt_ExcptLst; + std::unique_ptr pWordStart_ExcptLst; + std::unique_ptr pAutocorr_List; + SvxAutoCorrect& rAutoCorrect; + + ACFlags nFlags; + + bool IsFileChanged_Imp(); + void LoadXMLExceptList_Imp( std::unique_ptr& rpLst, + const OUString& sStrmName, + tools::SvRef& rStg); + static void SaveExceptList_Imp( const SvStringsISortDtor& rLst, + const OUString& sStrmName, + tools::SvRef const & rStg, + bool bConvert = false); + + bool MakeBlocklist_Imp( SotStorage& rStg ); + void RemoveStream_Imp( const OUString& rName ); + void MakeUserStorage_Impl(); + +public: + SvxAutoCorrectLanguageLists( SvxAutoCorrect& rParent, + OUString aShareAutoCorrectFile, + OUString aUserAutoCorrectFile); + ~SvxAutoCorrectLanguageLists(); + + // Load, Set, Get - the replacement list + SvxAutocorrWordList* LoadAutocorrWordList(); + const SvxAutocorrWordList* GetAutocorrWordList(); + + // Load, Set, Get - the exception list for Capital letter at the + // beginning of a sentence + SvStringsISortDtor* LoadCplSttExceptList(); + void SaveCplSttExceptList(); + SvStringsISortDtor* GetCplSttExceptList(); + bool AddToCplSttExceptList(const OUString& rNew); + + // Load, Set, Get the exception list for TWo INitial CApitals or sMALL iNITIAL + SvStringsISortDtor* LoadWordStartExceptList(); + void SaveWordStartExceptList(); + SvStringsISortDtor* GetWordStartExceptList(); + bool AddToWordStartExceptList(const OUString& rNew); + + // Save word substitutions: + // Store these directly in the storage. The word list is updated + // accordingly! + // - pure Text + bool PutText( const OUString& rShort, const OUString& rLong ); + // - Text with attribution (only the SWG - SWG format!) + void PutText( const OUString& rShort, SfxObjectShell& ); + // - Make combined changes in one pass + bool MakeCombinedChanges( std::vector& aNewEntries, std::vector& aDeleteEntries ); +}; + +class EDITENG_DLLPUBLIC SvxAutoCorrect +{ + friend class SvxAutoCorrectLanguageLists; + + OUString sShareAutoCorrFile, sUserAutoCorrFile; + + SvxSwAutoFormatFlags aSwFlags; // StarWriter AutoFormat Flags + + // all languages in a table + std::map> m_aLangTable; + std::map aLastFileTable; + std::unique_ptr pCharClass; + + LanguageType eCharClassLang; + + ACFlags nFlags; + sal_Unicode cStartDQuote, cEndDQuote, cStartSQuote, cEndSQuote; + + + // private methods + SvxAutoCorrectLanguageLists& GetLanguageList_( LanguageType eLang ); + + void GetCharClass_( LanguageType eLang ); + +protected: + // - Text with attribution (only the SWG - SWG format!) + // rShort is the stream name - encrypted! + virtual bool PutText( const css::uno::Reference < css::embed::XStorage >& rStg, + const OUString& rFileName, const OUString& rShort, SfxObjectShell&, OUString& ); + + // required language in the table add if possible only when the file exists + bool CreateLanguageFile(const LanguageTag& rLanguageTag, bool bNewFile = true); + // - Return the replacement text (only for SWG format, all others can be + // taken from the word list!) + // rShort is the stream name - encrypted! +public: + + sal_Unicode GetQuote( sal_Unicode cInsChar, bool bSttQuote, + LanguageType eLang ) const; + virtual bool GetLongText( const OUString& rShort, OUString& rLong ); + + virtual void refreshBlockList( const css::uno::Reference < css::embed::XStorage >& rStg); + + SvxAutoCorrect( OUString aShareAutocorrFile, + OUString aUserAutocorrFile ); + SvxAutoCorrect( const SvxAutoCorrect& ); + virtual ~SvxAutoCorrect(); + + /** Execute an AutoCorrect. + Returns what has been executed, according to the above auto correct flags. + @param io_bNbspRunNext + Remembers if a NO-BREAK SPACE was added (eg. in "fr" language) + (set to ) at the last character input that may have to + be removed again depending on what character is following. + */ + // FIXME: this has the horrible flaw that the rTxt must be a reference + // to the actual SwTxtNode/EditNode string because it inserts the character + // in rDoc and expects that to side-effect rTxt + void DoAutoCorrect( SvxAutoCorrDoc& rDoc, const OUString& rTxt, + sal_Int32 nPos, sal_Unicode cInsChar, bool bInsert, bool& io_bNbspRunNext, + vcl::Window const * pFrameWin = nullptr ); + + // Return for the autotext expansion the previous word, + // AutoCorrect - corresponding algorithm + OUString GetPrevAutoCorrWord(SvxAutoCorrDoc const& rDoc, const OUString& rTxt, sal_Int32 nPos); + + // Returns vector candidates for AutoText name match, starting with the longest string between + // 3 and 9 characters long, that is a chunk of text starting with a whitespace or with a word's + // first character, and ending at the current cursor position or empty string if no such string + // exists + static std::vector GetChunkForAutoText(std::u16string_view rTxt, sal_Int32 nPos); + + // Search for the words in the replacement table. + // rText - check in this text the words of the list + // rStt - the detected starting position + // nEnd - to check position - as of this item forward + // rLang - Input: in which language is searched + // Output: in which "language list" was it found + const SvxAutocorrWord* SearchWordsInList( const OUString& rTxt, + sal_Int32& rStt, sal_Int32 nEndPos, + SvxAutoCorrDoc& rDoc, + LanguageTag& rLang ); + + // Query/Set the Character for the Quote substitution + sal_Unicode GetStartSingleQuote() const { return cStartSQuote; } + sal_Unicode GetEndSingleQuote() const { return cEndSQuote; } + sal_Unicode GetStartDoubleQuote() const { return cStartDQuote; } + sal_Unicode GetEndDoubleQuote() const { return cEndDQuote; } + + void SetStartSingleQuote( const sal_Unicode cStart ) { cStartSQuote = cStart; } + void SetEndSingleQuote( const sal_Unicode cEnd ) { cEndSQuote = cEnd; } + void SetStartDoubleQuote( const sal_Unicode cStart ) { cStartDQuote = cStart; } + void SetEndDoubleQuote( const sal_Unicode cEnd ) { cEndDQuote = cEnd; } + + OUString GetQuote( SvxAutoCorrDoc const & rDoc, sal_Int32 nInsPos, + sal_Unicode cInsChar, bool bSttQuote ); + void InsertQuote( SvxAutoCorrDoc& rDoc, sal_Int32 nInsPos, + sal_Unicode cInsChar, bool bSttQuote, bool bIns, + LanguageType eLang, ACQuotes eType ) const; + + // Query/Set the name of the AutoCorrect file + // the default is "autocorr.dat" + OUString GetAutoCorrFileName( const LanguageTag& rLanguageTag /* = LANGUAGE_SYSTEM */ , + bool bNewFile = false, + bool bTstUserExist = false, + bool bUnlocalized = false ) const; + + // Query/Set the current settings of AutoCorrect + ACFlags GetFlags() const { return nFlags; } + SvxSwAutoFormatFlags& GetSwFlags() { return aSwFlags;} + const SvxSwAutoFormatFlags& GetSwFlags() const { return aSwFlags; } + bool IsAutoCorrFlag( ACFlags nFlag ) const + { return bool(nFlags & nFlag); } + void SetAutoCorrFlag( ACFlags nFlag, bool bOn = true ); + + // Load, Set, Get - the replacement list + SvxAutocorrWordList* LoadAutocorrWordList( LanguageType eLang ) + { return GetLanguageList_( eLang ).LoadAutocorrWordList(); } + + // Save word substitutions: + // Save these directly in the storage. The word list is updated + // accordingly! + // - pure Text + bool PutText( const OUString& rShort, const OUString& rLong, LanguageType eLang ); + // - Text with attribution (only in the SWG - SWG format!) + void PutText( const OUString& rShort, SfxObjectShell& rShell, LanguageType eLang ) + { GetLanguageList_( eLang ).PutText(rShort, rShell ); } + + void MakeCombinedChanges( std::vector& aNewEntries, + std::vector& aDeleteEntries, + LanguageType eLang ); + + // Load, Set, Get - the exception list for capital letters at the + // beginning of a sentence + void SaveCplSttExceptList( LanguageType eLang ); + SvStringsISortDtor* LoadCplSttExceptList(LanguageType eLang) + { return GetLanguageList_( eLang ).LoadCplSttExceptList(); } + const SvStringsISortDtor* GetCplSttExceptList( LanguageType eLang ) + { return GetLanguageList_( eLang ).GetCplSttExceptList(); } + + // Adds a single word. The list will be immediately written to the file! + bool AddCplSttException( const OUString& rNew, LanguageType eLang ); + + // Load, Set, Get the exception list for TWo INitial CApitals or sMALL iNITIAL + void SaveWordStartExceptList( LanguageType eLang ); + SvStringsISortDtor* LoadWordStartExceptList( LanguageType eLang ) + { return GetLanguageList_( eLang ).LoadWordStartExceptList(); } + const SvStringsISortDtor* GetWordStartExceptList( LanguageType eLang ) + { return GetLanguageList_( eLang ).GetWordStartExceptList(); } + // Adds a single word. The list will be immediately written to the file! + bool AddWordStartException( const OUString& rNew, LanguageType eLang); + + // Search through the Languages for the entry + bool FindInWordStartExceptList( LanguageType eLang, const OUString& sWord ); + bool FindInCplSttExceptList( LanguageType eLang, const OUString& sWord, + bool bAbbreviation = false); + + // Methods for the auto-correction + void FnCapitalStartWord( SvxAutoCorrDoc&, const OUString&, + sal_Int32 nSttPos, sal_Int32 nEndPos, + LanguageType eLang ); + bool FnChgOrdinalNumber( SvxAutoCorrDoc&, const OUString&, + sal_Int32 nSttPos, sal_Int32 nEndPos, + LanguageType eLang ); + bool FnChgToEnEmDash( SvxAutoCorrDoc&, std::u16string_view, + sal_Int32 nSttPos, sal_Int32 nEndPos, + LanguageType eLang ); + bool FnAddNonBrkSpace( SvxAutoCorrDoc&, const OUString&, + sal_Int32 nEndPos, + LanguageType eLang, bool& io_bNbspRunNext ); + bool FnSetINetAttr( SvxAutoCorrDoc&, const OUString&, + sal_Int32 nSttPos, sal_Int32 nEndPos, + LanguageType eLang ); + bool FnChgWeightUnderl( SvxAutoCorrDoc&, const OUString&, + sal_Int32 nEndPos ); + void FnCapitalStartSentence( SvxAutoCorrDoc&, const OUString&, bool bNormalPos, + sal_Int32 nSttPos, sal_Int32 nEndPos, + LanguageType eLang); + bool FnCorrectCapsLock( SvxAutoCorrDoc&, const OUString&, + sal_Int32 nSttPos, sal_Int32 nEndPos, + LanguageType eLang ); + + static ACFlags GetDefaultFlags(); + +// returns sal_True for characters where the function +// 'SvxAutoCorrect::AutoCorrect' should be called. +// (used to avoid occasional 'collisions' with (Thai) input-sequence-checking) + static bool IsAutoCorrectChar( sal_Unicode cChar ); + + static bool NeedsHardspaceAutocorr( sal_Unicode cChar ); + + CharClass& GetCharClass( LanguageType eLang ) + { + if( !pCharClass || eLang != eCharClassLang ) + GetCharClass_( eLang ); + return *pCharClass; + } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/svxenum.hxx b/include/editeng/svxenum.hxx new file mode 100644 index 000000000..6c0216560 --- /dev/null +++ b/include/editeng/svxenum.hxx @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SVXENUM_HXX +#define INCLUDED_EDITENG_SVXENUM_HXX + +#include + +enum class SvxCaseMap +{ + NotMapped, + Uppercase, + Lowercase, + Capitalize, + SmallCaps, + End +}; + +enum class SvxEscapement +{ + Off, + Superscript, + Subscript, + End +}; + +enum class SvxShadowLocation +{ + NONE, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + End +}; + +enum class SvxTabAdjust +{ + Left, + Right, + Decimal, + Center, + Default, + End +}; + +enum class SvxLineSpaceRule +{ + Auto, + Fix, + Min +}; + +enum class SvxInterLineSpaceRule +{ + Off, + Prop, + Fix +}; + +enum class SvxAdjust +{ + Left, + Right, + Block, + Center, + BlockLine, + End, + LAST = End +}; + +enum class SvxBreak +{ + NONE, + ColumnBefore, + ColumnAfter, + ColumnBoth, + PageBefore, + PageAfter, + PageBoth, + End +}; + +enum class SvxCellHorJustify +{ + Standard, + Left, + Center, + Right, + Block, + Repeat +}; + +enum class SvxCellJustifyMethod +{ + Auto, + Distribute +}; + +enum class SvxCellVerJustify +{ + Standard, + Top, + Center, + Bottom, + Block +}; + +enum class SvxCellOrientation +{ + Standard, + TopBottom, + BottomUp, + Stacked +}; + +enum class SvxSpellArea +{ + Body = 0, + BodyEnd, + BodyStart, + Other +}; + +/** + * these must match the values in css::style::NumberingType + */ +enum SvxNumType : sal_Int16 +{ + SVX_NUM_CHARS_UPPER_LETTER = css::style::NumberingType::CHARS_UPPER_LETTER, // Counts from a-z, aa - az, ba - bz, ... + SVX_NUM_CHARS_LOWER_LETTER = css::style::NumberingType::CHARS_LOWER_LETTER, + SVX_NUM_ROMAN_UPPER = css::style::NumberingType::ROMAN_UPPER, + SVX_NUM_ROMAN_LOWER = css::style::NumberingType::ROMAN_LOWER, + SVX_NUM_ARABIC = css::style::NumberingType::ARABIC, + SVX_NUM_NUMBER_NONE = css::style::NumberingType::NUMBER_NONE, + SVX_NUM_CHAR_SPECIAL = css::style::NumberingType::CHAR_SPECIAL, // Bullet + SVX_NUM_PAGEDESC = css::style::NumberingType::PAGE_DESCRIPTOR, // Numbering from the page template + SVX_NUM_BITMAP = css::style::NumberingType::BITMAP, + SVX_NUM_CHARS_UPPER_LETTER_N = css::style::NumberingType::CHARS_UPPER_LETTER_N, // Counts from a-z, aa-zz, aaa-zzz + SVX_NUM_CHARS_LOWER_LETTER_N = css::style::NumberingType::CHARS_LOWER_LETTER_N, + SVX_NUM_TRANSLITERATION = css::style::NumberingType::TRANSLITERATION, + SVX_NUM_NATIVE_NUMBERING = css::style::NumberingType::NATIVE_NUMBERING, + SVX_NUM_FULL_WIDTH_ARABIC = css::style::NumberingType::FULLWIDTH_ARABIC, + SVX_NUM_CIRCLE_NUMBER = css::style::NumberingType::CIRCLE_NUMBER, + SVX_NUM_NUMBER_LOWER_ZH = css::style::NumberingType::NUMBER_LOWER_ZH, + SVX_NUM_NUMBER_UPPER_ZH = css::style::NumberingType::NUMBER_UPPER_ZH, + SVX_NUM_NUMBER_UPPER_ZH_TW = css::style::NumberingType::NUMBER_UPPER_ZH_TW, + SVX_NUM_TIAN_GAN_ZH = css::style::NumberingType::TIAN_GAN_ZH, + SVX_NUM_DI_ZI_ZH = css::style::NumberingType::DI_ZI_ZH, + SVX_NUM_NUMBER_TRADITIONAL_JA = css::style::NumberingType::NUMBER_TRADITIONAL_JA, + SVX_NUM_AIU_FULLWIDTH_JA = css::style::NumberingType::AIU_FULLWIDTH_JA, + SVX_NUM_AIU_HALFWIDTH_JA = css::style::NumberingType::AIU_HALFWIDTH_JA, + SVX_NUM_IROHA_FULLWIDTH_JA = css::style::NumberingType::IROHA_FULLWIDTH_JA, + SVX_NUM_IROHA_HALFWIDTH_JA = css::style::NumberingType::IROHA_HALFWIDTH_JA, + SVX_NUM_NUMBER_UPPER_KO = css::style::NumberingType::NUMBER_UPPER_KO, + SVX_NUM_NUMBER_HANGUL_KO = css::style::NumberingType::NUMBER_HANGUL_KO, + SVX_NUM_HANGUL_JAMO_KO = css::style::NumberingType::HANGUL_JAMO_KO, + SVX_NUM_HANGUL_SYLLABLE_KO = css::style::NumberingType::HANGUL_SYLLABLE_KO, + SVX_NUM_HANGUL_CIRCLED_JAMO_KO = css::style::NumberingType::HANGUL_CIRCLED_JAMO_KO, + SVX_NUM_HANGUL_CIRCLED_SYLLABLE_KO = css::style::NumberingType::HANGUL_CIRCLED_SYLLABLE_KO, + SVX_NUM_CHARS_ARABIC = css::style::NumberingType::CHARS_ARABIC, + SVX_NUM_CHARS_THAI = css::style::NumberingType::CHARS_THAI, + SVX_NUM_CHARS_HEBREW = css::style::NumberingType::CHARS_HEBREW, + SVX_NUM_CHARS_NEPALI = css::style::NumberingType::CHARS_NEPALI, + SVX_NUM_CHARS_KHMER = css::style::NumberingType::CHARS_KHMER, + SVX_NUM_CHARS_LAO = css::style::NumberingType::CHARS_LAO, + SVX_NUM_CHARS_TIBETAN = css::style::NumberingType::CHARS_TIBETAN, + SVX_NUM_CHARS_CYRILLIC_UPPER_LETTER_BG = css::style::NumberingType::CHARS_CYRILLIC_UPPER_LETTER_BG, + SVX_NUM_CHARS_CYRILLIC_LOWER_LETTER_BG = css::style::NumberingType::CHARS_CYRILLIC_LOWER_LETTER_BG, + SVX_NUM_CHARS_CYRILLIC_UPPER_LETTER_N_BG = css::style::NumberingType::CHARS_CYRILLIC_UPPER_LETTER_N_BG, + SVX_NUM_CHARS_CYRILLIC_LOWER_LETTER_N_BG = css::style::NumberingType::CHARS_CYRILLIC_LOWER_LETTER_N_BG, + SVX_NUM_CHARS_CYRILLIC_UPPER_LETTER_RU = css::style::NumberingType::CHARS_CYRILLIC_UPPER_LETTER_RU, + SVX_NUM_CHARS_CYRILLIC_LOWER_LETTER_RU = css::style::NumberingType::CHARS_CYRILLIC_LOWER_LETTER_RU, + SVX_NUM_CHARS_CYRILLIC_UPPER_LETTER_N_RU = css::style::NumberingType::CHARS_CYRILLIC_UPPER_LETTER_N_RU, + SVX_NUM_CHARS_CYRILLIC_LOWER_LETTER_N_RU = css::style::NumberingType::CHARS_CYRILLIC_LOWER_LETTER_N_RU, + SVX_NUM_CHARS_PERSIAN = css::style::NumberingType::CHARS_PERSIAN, + SVX_NUM_CHARS_MYANMAR = css::style::NumberingType::CHARS_MYANMAR, + SVX_NUM_CHARS_CYRILLIC_UPPER_LETTER_SR = css::style::NumberingType::CHARS_CYRILLIC_UPPER_LETTER_SR, + SVX_NUM_CHARS_CYRILLIC_LOWER_LETTER_SR = css::style::NumberingType::CHARS_CYRILLIC_LOWER_LETTER_SR, + SVX_NUM_CHARS_CYRILLIC_UPPER_LETTER_N_SR = css::style::NumberingType::CHARS_CYRILLIC_UPPER_LETTER_N_SR, + SVX_NUM_CHARS_CYRILLIC_LOWER_LETTER_N_SR = css::style::NumberingType::CHARS_CYRILLIC_LOWER_LETTER_N_SR, + SVX_NUM_CHARS_GREEK_UPPER_LETTER = css::style::NumberingType::CHARS_GREEK_UPPER_LETTER, + SVX_NUM_CHARS_GREEK_LOWER_LETTER = css::style::NumberingType::CHARS_GREEK_LOWER_LETTER, + SVX_NUM_CHARS_ARABIC_ABJAD = css::style::NumberingType::CHARS_ARABIC_ABJAD, + SVX_NUM_CHARS_PERSIAN_WORD = css::style::NumberingType::CHARS_PERSIAN_WORD, + SVX_NUM_NUMBER_HEBREW = css::style::NumberingType::NUMBER_HEBREW, + SVX_NUM_NUMBER_ARABIC_INDIC = css::style::NumberingType::NUMBER_ARABIC_INDIC, + SVX_NUM_NUMBER_EAST_ARABIC_INDIC = css::style::NumberingType::NUMBER_EAST_ARABIC_INDIC, + SVX_NUM_NUMBER_INDIC_DEVANAGARI = css::style::NumberingType::NUMBER_INDIC_DEVANAGARI, + SVX_NUM_TEXT_NUMBER = css::style::NumberingType::TEXT_NUMBER, + SVX_NUM_TEXT_CARDINAL = css::style::NumberingType::TEXT_CARDINAL, + SVX_NUM_TEXT_ORDINAL = css::style::NumberingType::TEXT_ORDINAL, + SVX_NUM_SYMBOL_CHICAGO = css::style::NumberingType::SYMBOL_CHICAGO, + SVX_NUM_ARABIC_ZERO = css::style::NumberingType::ARABIC_ZERO, + SVX_NUM_ARABIC_ZERO3 = css::style::NumberingType::ARABIC_ZERO3, + SVX_NUM_ARABIC_ZERO4 = css::style::NumberingType::ARABIC_ZERO4, + SVX_NUM_ARABIC_ZERO5 = css::style::NumberingType::ARABIC_ZERO5, + SVX_NUM_SZEKELY_ROVAS = css::style::NumberingType::SZEKELY_ROVAS +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/svxfont.hxx b/include/editeng/svxfont.hxx new file mode 100644 index 000000000..e0f92c572 --- /dev/null +++ b/include/editeng/svxfont.hxx @@ -0,0 +1,119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_SVXFONT_HXX +#define INCLUDED_EDITENG_SVXFONT_HXX + +#include +#include +#include +#include +#include +#include + +// Percentage of height of lower case small capital letters compared to upper case letters +// See i#1526# for full explanation +#define SMALL_CAPS_PERCENTAGE 80 + +class SvxDoCapitals; +class OutputDevice; +class Printer; +class Point; +namespace tools { class Rectangle; } +class Size; +class EDITENG_DLLPUBLIC SvxFont : public vcl::Font +{ + SvxCaseMap eCaseMap; // Text Markup + short nEsc; // Degree of Superscript/Subscript + sal_uInt8 nPropr; // Degree of reduction of the font height + short nKern; // Kerning in Pt + +public: + SvxFont(); + SvxFont( const vcl::Font &rFont ); + SvxFont( const SvxFont &rFont ); + + // Methods for Superscript/Subscript + short GetEscapement() const { return nEsc; } + void SetEscapement( const short nNewEsc ) { nEsc = nNewEsc; } + // set specific values instead of automatic, and ensure valid value. Depends on nPropr being set already. + void SetNonAutoEscapement(short nNewEsc, const OutputDevice* pOutDev = nullptr); + + sal_uInt8 GetPropr() const { return nPropr; } + void SetPropr( const sal_uInt8 nNewPropr ) { nPropr = nNewPropr; } + void SetProprRel( const sal_uInt8 nNewPropr ) + { SetPropr( static_cast( static_cast(nNewPropr) * static_cast(nPropr) / 100 ) ); } + + // Kerning + short GetFixKerning() const { return nKern; } + void SetFixKerning( const short nNewKern ) { nKern = nNewKern; } + + SvxCaseMap GetCaseMap() const { return eCaseMap; } + void SetCaseMap( const SvxCaseMap eNew ) { eCaseMap = eNew; } + + // Is-Methods: + bool IsCaseMap() const { return SvxCaseMap::NotMapped != eCaseMap; } + bool IsCapital() const { return SvxCaseMap::SmallCaps == eCaseMap; } + bool IsKern() const { return 0 != nKern; } + bool IsEsc() const { return 0 != nEsc; } + + // Consider Upper case, Lower case letters etc. + OUString CalcCaseMap(const OUString &rTxt) const; + + // Handle upper case letters + void DoOnCapitals(SvxDoCapitals &rDo) const; + + void SetPhysFont(OutputDevice& rOut) const; + vcl::Font ChgPhysFont(OutputDevice& rOut) const; + + Size GetCapitalSize( const OutputDevice *pOut, const OUString &rTxt, + const sal_Int32 nIdx, const sal_Int32 nLen) const; + void DrawCapital( OutputDevice *pOut, const Point &rPos, const OUString &rTxt, + const sal_Int32 nIdx, const sal_Int32 nLen ) const; + + Size GetPhysTxtSize( const OutputDevice *pOut, const OUString &rTxt, + const sal_Int32 nIdx, const sal_Int32 nLen ) const; + + Size GetPhysTxtSize( const OutputDevice *pOut ); + + Size GetTextSize(const OutputDevice& rOut, const OUString &rTxt, + const sal_Int32 nIdx = 0, const sal_Int32 nLen = SAL_MAX_INT32) const; + + void QuickDrawText( OutputDevice *pOut, const Point &rPos, const OUString &rTxt, + const sal_Int32 nIdx = 0, const sal_Int32 nLen = SAL_MAX_INT32, + o3tl::span pDXArray = {} ) const; + + Size QuickGetTextSize( const OutputDevice *pOut, const OUString &rTxt, + const sal_Int32 nIdx, const sal_Int32 nLen, + std::vector* pDXArray = nullptr ) const; + + void DrawPrev( OutputDevice* pOut, Printer* pPrinter, + const Point &rPos, const OUString &rTxt, + const sal_Int32 nIdx = 0, const sal_Int32 nLen = SAL_MAX_INT32 ) const; + + static tools::Polygon DrawArrow( OutputDevice &rOut, const tools::Rectangle& rRect, + const Size& rSize, const Color& rCol, bool bLeftOrTop, + bool bVertical ); + + SvxFont& operator=( const SvxFont& rFont ); + SvxFont& operator=( const Font& rFont ); +}; + +#endif // INCLUDED_EDITENG_SVXFONT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/svxrtf.hxx b/include/editeng/svxrtf.hxx new file mode 100644 index 000000000..e5ed1949b --- /dev/null +++ b/include/editeng/svxrtf.hxx @@ -0,0 +1,295 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_SVXRTF_HXX +#define INCLUDED_EDITENG_SVXRTF_HXX + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +struct SvxRTFStyleType; +class SvxRTFItemStackType; +class SvxRTFItemStackList : public std::vector> {}; + +// Mapper-Classes for the various requirements on Document positions +// Swg - NodePosition is a SwIndex, which is used internally +// EditEngine - ULONG to list of paragraphs + +class EditEngine; +class ContentNode; +class EditNodeIdx +{ +public: + EditNodeIdx(EditEngine* pEE, ContentNode* pNd); + sal_Int32 GetIdx() const; + ContentNode* GetNode() { return mpNode; } +private: + EditEngine* mpEditEngine; + ContentNode* mpNode; +}; + +class EditSelection; +class EditPosition +{ +private: + EditEngine* mpEditEngine; + EditSelection* mpCurSel; + +public: + EditPosition(EditEngine* pIEE, EditSelection* pSel); + + sal_Int32 GetNodeIdx() const; + sal_Int32 GetCntIdx() const; + + // clone NodeIndex + EditNodeIdx MakeNodeIdx() const; +}; + +typedef std::map SvxRTFFontTbl; + +// own helper classes for the RTF Parser +struct SvxRTFStyleType +{ + SfxItemSet aAttrSet; // the attributes of Style (+ derivated!) + OUString sName; + sal_uInt16 nBasedOn; + sal_uInt8 nOutlineNo; + + SvxRTFStyleType(SfxItemPool& rPool, const WhichRangesContainer& pWhichRange); +}; + +typedef std::map SvxRTFStyleTbl; + +class EDITENG_DLLPUBLIC SvxRTFParser : public SvRTFParser +{ + std::vector maColorTable; + SvxRTFFontTbl m_FontTable; + SvxRTFStyleTbl m_StyleTable; + std::deque< std::unique_ptr > aAttrStack; + SvxRTFItemStackList m_AttrSetList; + + std::map aPlainMap; + std::map aPardMap; + WhichRangesContainer aWhichMap; + + std::optional mxInsertPosition; + SfxItemPool* pAttrPool; + std::optional mxDefaultColor; + std::optional pDfltFont; + std::unique_ptr pRTFDefaults; + + int nDfltFont; + + bool bNewDoc : 1; // sal_False - Reading in an existing + bool bNewGroup : 1; // sal_True - there was an opening parenthesis + bool bIsSetDfltTab : 1; // sal_True - DefTab was loaded + bool bChkStyleAttr : 1; // sal_True - StyleSheets are evaluated + bool bCalcValue : 1; // sal_True - Twip values adapt to App + bool bIsLeftToRightDef : 1; // sal_True - in LeftToRight char run def. + // sal_False - in RightToLeft char run def. + bool bIsInReadStyleTab : 1; // sal_True - in ReadStyleTable + + SvxRTFParser(SvxRTFParser const&) = delete; + void operator=(SvxRTFParser const&) = delete; + + void ClearColorTbl(); + void ClearAttrStack(); + + SvxRTFItemStackType* GetAttrSet_(); // Create new ItemStackType:s + void ClearStyleAttr_( SvxRTFItemStackType& rStkType ); + + // Sets all the attributes that are different from the current + void SetAttrSet( SvxRTFItemStackType &rSet ); + void SetDefault( int nToken, int nValue ); + + // Execute pard / plain + void RTFPardPlain( bool bPard, SfxItemSet** ppSet ); + + void BuildWhichTable(); + + enum RTF_CharTypeDef + { + NOTDEF_CHARTYPE, + LOW_CHARTYPE, + HIGH_CHARTYPE, + DOUBLEBYTE_CHARTYPE + }; + + // set latin/asian/complex character attributes + void SetScriptAttr( + RTF_CharTypeDef eType, SfxItemSet& rSet, SfxPoolItem& rItem ); + +protected: + virtual void InsertPara() = 0; + + static void DelCharAtEnd( OUStringBuffer& rStr, const sal_Unicode cDel ); + + // is called for each token that is recognized in CallParser + virtual void NextToken( int nToken ) override; + + void ReadStyleTable(); + void ReadColorTable(); + void ReadFontTable(); + void ReadAttr( int nToken, SfxItemSet* pSet ); + void ReadTabAttr( int nToken, SfxItemSet& rSet ); + + inline SfxItemSet& GetAttrSet(); + // no text yet inserted? (SttPos from the top stack entry!) + bool IsAttrSttPos(); + void AttrGroupEnd(); // edit the current, delete from stack + void SetAllAttrOfStk(); // end all Attr. and set it into doc + + + virtual void InsertText() = 0; + virtual void MovePos( bool bForward = true ) = 0; + virtual void SetEndPrevPara( std::optional& rpNodePos, + sal_Int32& rCntPos )=0; + virtual void SetAttrInDoc( SvxRTFItemStackType &rSet ); + // for Tokens, which are not evaluated in ReadAttr + virtual void UnknownAttrToken( int nToken ); + + // if no-one would like to have any twips + virtual void CalcValue(); + + SvxRTFParser( SfxItemPool& rAttrPool, SvStream& rIn ); + virtual ~SvxRTFParser() override; + + void SetNewDoc( bool bFlag ) { bNewDoc = bFlag; } + bool IsChkStyleAttr() const { return bChkStyleAttr; } + void SetChkStyleAttr( bool bFlag ) { bChkStyleAttr = bFlag; } + bool IsCalcValue() const { return bCalcValue; } + void SetCalcValue( bool bFlag ) { bCalcValue = bFlag; } + + // Query/Set the current insert position + void SetInsPos( const EditPosition& rNew ); + SvxRTFStyleTbl& GetStyleTbl() { return m_StyleTable; } + +public: + + virtual SvParserState CallParser() override; + + inline const Color& GetColor( size_t nId ) const; + const vcl::Font& GetFont( sal_uInt16 nId ); // Changes the default Font + + virtual bool IsEndPara( EditNodeIdx* pNd, sal_Int32 nCnt ) const = 0; + + // to set a different attribute pool. May only be done prior to CallParser! + // The maps are not generated anew! + void SetAttrPool( SfxItemPool* pNewPool ) { pAttrPool = pNewPool; } + // to set different WhichIds for a different pool. + void SetPardMap(sal_uInt16 wid, sal_uInt16 widTrue) { aPardMap[wid] = widTrue; } + // to be able to assign them from the outside as for example table cells + void ReadBorderAttr( int nToken, SfxItemSet& rSet, bool bTableDef=false ); + void ReadBackgroundAttr( int nToken, SfxItemSet& rSet, bool bTableDef=false ); + + // for asynchronous read from the SvStream + virtual void Continue( int nToken ) override; + + // get RTF default ItemSets. Must be used by pard/plain tokens or in + // reset of Style-Items + const SfxItemSet& GetRTFDefaults(); +}; + +// The stack for the attributes: +// this class may only be used by SvxRTFParser! +class SvxRTFItemStackType +{ + friend class SvxRTFParser; + + SfxItemSet aAttrSet; + std::optional mxStartNodeIdx; + std::optional mxEndNodeIdx; + sal_Int32 nSttCnt, nEndCnt; + SvxRTFItemStackList maChildList; + sal_uInt16 nStyleNo; + + SvxRTFItemStackType(SvxRTFItemStackType const&) = delete; + void operator=(SvxRTFItemStackType const&) = delete; + + SvxRTFItemStackType( SfxItemPool&, const WhichRangesContainer& pWhichRange, + const EditPosition& ); + + static std::unique_ptr createSvxRTFItemStackType( + SfxItemPool&, const WhichRangesContainer& pWhichRange, const EditPosition&); + + void Add(std::unique_ptr); + void Compress( const SvxRTFParser& ); + void DropChildList(); + +public: + SvxRTFItemStackType(const SvxRTFItemStackType&, const EditPosition&, + bool bCopyAttr); + ~SvxRTFItemStackType(); + //cmc, I'm very suspicious about SetStartPos, it doesn't change + //its children's starting position, and the implementation looks + //bad, consider this deprecated. + void SetStartPos( const EditPosition& rPos ); + + const EditNodeIdx& GetSttNode() const { return *mxStartNodeIdx; } + const EditNodeIdx& GetEndNode() const { return *mxEndNodeIdx; } + + sal_Int32 GetSttCnt() const { return nSttCnt; } + sal_Int32 GetEndCnt() const { return nEndCnt; } + + SfxItemSet& GetAttrSet() { return aAttrSet; } + const SfxItemSet& GetAttrSet() const { return aAttrSet; } + + sal_uInt16 StyleNo() const { return nStyleNo; } + + void SetRTFDefaults( const SfxItemSet& rDefaults ); +}; + + +// ----------- Inline Implementations -------------- + +inline const Color& SvxRTFParser::GetColor( size_t nId ) const +{ + if( nId < maColorTable.size() ) + return maColorTable[ nId ]; + return *mxDefaultColor; +} + +inline SfxItemSet& SvxRTFParser::GetAttrSet() +{ + SvxRTFItemStackType* pTmp; + if( bNewGroup || aAttrStack.empty() ) + pTmp = GetAttrSet_(); + else + { + pTmp = aAttrStack.back().get(); + if ( pTmp == nullptr ) + pTmp = GetAttrSet_(); + } + return pTmp->aAttrSet; +} + + +#endif // INCLUDED_EDITENG_SVXRTF_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/swafopt.hxx b/include/editeng/swafopt.hxx new file mode 100644 index 000000000..180ba6d1b --- /dev/null +++ b/include/editeng/swafopt.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_SWAFOPT_HXX +#define INCLUDED_EDITENG_SWAFOPT_HXX + +#include + +#include +#include +#include +#include +#include +#include + +class SmartTagMgr; + +namespace editeng { + +class EDITENG_DLLPUBLIC IAutoCompleteString +{ +private: + OUString m_String; +public: + explicit IAutoCompleteString(OUString aString) : m_String(std::move(aString)) {} + virtual ~IAutoCompleteString() {} + OUString const& GetAutoCompleteString() const { return m_String; } +}; + +struct CompareAutoCompleteString +{ + bool operator()(IAutoCompleteString *const& lhs, + IAutoCompleteString *const& rhs) const + { + return lhs->GetAutoCompleteString().compareToIgnoreAsciiCase( + rhs->GetAutoCompleteString()) < 0; + } +}; + +class SortedAutoCompleteStrings + : public o3tl::sorted_vector +{ + bool owning_; + + SortedAutoCompleteStrings& operator =(SortedAutoCompleteStrings const &) = delete; + + // For createNonOwningCopy only: + SortedAutoCompleteStrings(SortedAutoCompleteStrings const & other): + sorted_vector(other), owning_(false) {} + +public: + SortedAutoCompleteStrings(): owning_(true) {} + + ~SortedAutoCompleteStrings() { if (owning_) DeleteAndDestroyAll(); } + + SortedAutoCompleteStrings createNonOwningCopy() const { return *this; } +}; + +} // namespace editeng + +// Class of options for AutoFormat +struct EDITENG_DLLPUBLIC SvxSwAutoFormatFlags +{ + vcl::Font aBulletFont; + vcl::Font aByInputBulletFont; + /// only valid inside the Dialog!!! + const editeng::SortedAutoCompleteStrings * m_pAutoCompleteList; + SmartTagMgr* pSmartTagMgr; + + sal_UCS4 cBullet; + sal_UCS4 cByInputBullet; + + sal_uInt16 nAutoCmpltWordLen, nAutoCmpltListLen; + sal_uInt16 nAutoCmpltExpandKey; + + sal_uInt8 nRightMargin; + + bool bAutoCorrect : 1; + bool bCapitalStartSentence : 1; + bool bCapitalStartWord : 1; + + bool bChgUserColl : 1; + bool bChgEnumNum : 1; + + bool bAFormatByInput : 1; + bool bDelEmptyNode : 1; + bool bSetNumRule : 1; + + bool bChgOrdinalNumber : 1; + bool bChgToEnEmDash : 1; + bool bAddNonBrkSpace : 1; + bool bTransliterateRTL : 1; + bool bChgAngleQuotes : 1; + bool bChgWeightUnderl : 1; + bool bSetINetAttr : 1; + + bool bSetBorder : 1; + bool bCreateTable : 1; + bool bReplaceStyles : 1; + + bool bWithRedlining : 1; + + bool bRightMargin : 1; + + bool bAutoCompleteWords : 1; + bool bAutoCmpltCollectWords : 1; + bool bAutoCmpltEndless : 1; +// -- under NT here starts a new long + bool bAutoCmpltAppendBlank : 1; + bool bAutoCmpltShowAsTip : 1; + + bool bAFormatDelSpacesAtSttEnd : 1; + bool bAFormatDelSpacesBetweenLines : 1; + bool bAFormatByInpDelSpacesAtSttEnd : 1; + bool bAFormatByInpDelSpacesBetweenLines : 1; + + bool bAutoCmpltKeepList : 1; + + SvxSwAutoFormatFlags(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/tstpitem.hxx b/include/editeng/tstpitem.hxx new file mode 100644 index 000000000..b5aab04bc --- /dev/null +++ b/include/editeng/tstpitem.hxx @@ -0,0 +1,149 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_TSTPITEM_HXX +#define INCLUDED_EDITENG_TSTPITEM_HXX + +#include +#include +#include +#include + +// class SvxTabStop ------------------------------------------------------ + +#define SVX_TAB_DEFCOUNT 10 +#define SVX_TAB_DEFDIST 1134 // 2cm in twips +#define SVX_TAB_NOTFOUND USHRT_MAX +#define cDfltDecimalChar u'\0' // Get from IntlWrapper +#define cDfltFillChar u' ' + +class EDITENG_DLLPUBLIC SvxTabStop +{ +private: + sal_Int32 nTabPos; + SvxTabAdjust eAdjustment; + mutable sal_Unicode + m_cDecimal; + sal_Unicode cFill; + + void fillDecimal() const; + +public: + SvxTabStop(); + explicit SvxTabStop( const sal_Int32 nPos, + const SvxTabAdjust eAdjst = SvxTabAdjust::Left, + const sal_Unicode cDec = cDfltDecimalChar, + const sal_Unicode cFil = cDfltFillChar ); + + sal_Int32& GetTabPos() { return nTabPos; } + sal_Int32 GetTabPos() const { return nTabPos; } + + SvxTabAdjust& GetAdjustment() { return eAdjustment; } + SvxTabAdjust GetAdjustment() const { return eAdjustment; } + + sal_Unicode& GetDecimal() { fillDecimal(); return m_cDecimal; } + sal_Unicode GetDecimal() const { fillDecimal(); return m_cDecimal; } + + sal_Unicode& GetFill() { return cFill; } + sal_Unicode GetFill() const { return cFill; } + + bool operator==( const SvxTabStop& rTS ) const + { + return ( nTabPos == rTS.nTabPos && + eAdjustment == rTS.eAdjustment && + m_cDecimal == rTS.m_cDecimal && + cFill == rTS.cFill ); + } + bool operator!=( const SvxTabStop& rTS ) const + { + return !operator==(rTS); + } + // For the SortedArray: + bool operator <( const SvxTabStop& rTS ) const + { return nTabPos < rTS.nTabPos; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const; +}; + +// class SvxTabStopItem -------------------------------------------------- + +typedef o3tl::sorted_vector SvxTabStopArr; + +/* [Description] + + This item describes a list of TabStops. +*/ + +class EDITENG_DLLPUBLIC SvxTabStopItem final : public SfxPoolItem +{ + SvxTabStopArr maTabStops; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxTabStopItem( sal_uInt16 nWhich ); + SvxTabStopItem( const sal_uInt16 nTabs, + const sal_uInt16 nDist, + const SvxTabAdjust eAdjst /*= SvxTabAdjust::Default*/, + sal_uInt16 nWhich ); + + // Returns index of the tab or TAB_NOTFOUND + sal_uInt16 GetPos( const SvxTabStop& rTab ) const; + + // Returns index of the tab at nPos, or TAB_NOTFOUND + sal_uInt16 GetPos( const sal_Int32 nPos ) const; + + // unprivatized: + sal_uInt16 Count() const { return maTabStops.size(); } + bool Insert( const SvxTabStop& rTab ); + void Insert( const SvxTabStopItem* pTabs ); + void Remove( const sal_uInt16 nPos, const sal_uInt16 nLen = 1 ) + { maTabStops.erase( maTabStops.begin() + nPos, maTabStops.begin() + nPos + nLen ); } + + // Assignment operator, equality operator (caution: expensive!) + + // this is already included in SfxPoolItem declaration + //int operator!=( const SvxTabStopItem& rTSI ) const + // { return !( operator==( rTSI ) ); } + + const SvxTabStop& operator[]( const sal_uInt16 nPos ) const + { return maTabStops[nPos]; } + + const SvxTabStop& At( const sal_uInt16 nPos ) const + { + return maTabStops[nPos]; + } + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxTabStopItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/twolinesitem.hxx b/include/editeng/twolinesitem.hxx new file mode 100644 index 000000000..d39a3ac60 --- /dev/null +++ b/include/editeng/twolinesitem.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_TWOLINESITEM_HXX +#define INCLUDED_EDITENG_TWOLINESITEM_HXX + +#include +#include +#include + +class EDITENG_DLLPUBLIC SvxTwoLinesItem final : public SfxPoolItem +{ + sal_Unicode cStartBracket, cEndBracket; + bool bOn; +public: + SvxTwoLinesItem( bool bOn /*= true*/, + sal_Unicode nStartBracket /*= 0*/, + sal_Unicode nEndBracket /*= 0*/, + sal_uInt16 nId ); + virtual ~SvxTwoLinesItem() override; + + SvxTwoLinesItem(SvxTwoLinesItem const &) = default; + SvxTwoLinesItem(SvxTwoLinesItem &&) = default; + SvxTwoLinesItem & operator =(SvxTwoLinesItem const &) = delete; // due to SfxPoolItem + SvxTwoLinesItem & operator =(SvxTwoLinesItem &&) = delete; // due to SfxPoolItem + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SvxTwoLinesItem* Clone( SfxItemPool* pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& rIntl ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + bool GetValue() const { return bOn; } + + sal_Unicode GetStartBracket() const { return cStartBracket; } + + sal_Unicode GetEndBracket() const { return cEndBracket; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/txtrange.hxx b/include/editeng/txtrange.hxx new file mode 100644 index 000000000..c6661f687 --- /dev/null +++ b/include/editeng/txtrange.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_TXTRANGE_HXX +#define INCLUDED_EDITENG_TXTRANGE_HXX + +#include +#include +#include +#include +#include + +namespace basegfx { + class B2DPolyPolygon; +} + +class EDITENG_DLLPUBLIC TextRanger +{ + //! The RangeCache class is used to cache the result of a single range calculation. + struct RangeCacheItem + { + Range range; //!< Range for which we calculated results. + std::deque results; //!< Calculated results for the range. + RangeCacheItem(const Range& rng) : range(rng) {}; + }; + std::deque mRangeCache; //!< Cached range calculations. + tools::PolyPolygon maPolyPolygon; // Surface polygon + std::optional mpLinePolyPolygon; // Line polygon + mutable std::optional mxBound; // Comprehensive rectangle + sal_uInt16 nCacheSize; // Cache-Size + sal_uInt16 nRight; // Distance Contour-Text + sal_uInt16 nLeft; // Distance Text-Contour + sal_uInt16 nUpper; // Distance Contour-Text + sal_uInt16 nLower; // Distance Text-Contour + sal_uInt32 nPointCount; // Number of polygon points + bool bSimple : 1; // Just outside edge + bool bInner : 1; // TRUE: Object inline (EditEngine); + // FALSE: Object flow (StarWriter); + bool bVertical :1;// for vertical writing mode + + TextRanger( const TextRanger& ) = delete; + const tools::Rectangle& GetBoundRect_() const; +public: + TextRanger( const basegfx::B2DPolyPolygon& rPolyPolygon, + const basegfx::B2DPolyPolygon* pLinePolyPolygon, + sal_uInt16 nCacheSize, sal_uInt16 nLeft, sal_uInt16 nRight, + bool bSimple, bool bInner, bool bVert = false ); + ~TextRanger(); + std::deque* GetTextRanges( const Range& rRange ); + sal_uInt16 GetRight() const { return nRight; } + sal_uInt16 GetLeft() const { return nLeft; } + sal_uInt16 GetUpper() const { return nUpper; } + sal_uInt16 GetLower() const { return nLower; } + sal_uInt32 GetPointCount() const { return nPointCount; } + bool IsSimple() const { return bSimple; } + bool IsInner() const { return bInner; } + bool IsVertical() const { return bVertical; } + const tools::Rectangle& GetBoundRect() const + { return mxBound ? const_cast< const tools::Rectangle& >(*mxBound) : GetBoundRect_(); } + void SetUpper( sal_uInt16 nNew ){ nUpper = nNew; } + void SetLower( sal_uInt16 nNew ){ nLower = nNew; } + void SetVertical( bool bNew ); +}; + +#endif // _TXTRANGE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/udlnitem.hxx b/include/editeng/udlnitem.hxx new file mode 100644 index 000000000..e190348bb --- /dev/null +++ b/include/editeng/udlnitem.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_UDLNITEM_HXX +#define INCLUDED_EDITENG_UDLNITEM_HXX + +#include +#include +#include +#include + +// class SvxTextLineItem ------------------------------------------------ + +/* Value container for underline and overline font effects */ + +class EDITENG_DLLPUBLIC SvxTextLineItem : public SfxEnumItem +{ + Color mColor; +public: + SvxTextLineItem( const FontLineStyle eSt, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxTextLineItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual OUString GetValueTextByPos( sal_uInt16 nPos ) const; + virtual sal_uInt16 GetValueCount() const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + using SfxEnumItem::SetValue; + virtual bool HasBoolValue() const override; + virtual bool GetBoolValue() const override; + virtual void SetBoolValue( bool bVal ) override; + + virtual bool operator==( const SfxPoolItem& ) const override; + + // enum cast + FontLineStyle GetLineStyle() const + { return GetValue(); } + void SetLineStyle( FontLineStyle eNew ) + { SetValue(eNew); } + + const Color& GetColor() const { return mColor; } + void SetColor( const Color& rCol ) { mColor = rCol; } +}; + +// class SvxUnderlineItem ------------------------------------------------ + +/* Value container for underline font effects */ + +class EDITENG_DLLPUBLIC SvxUnderlineItem final : public SvxTextLineItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxUnderlineItem( const FontLineStyle eSt, + const sal_uInt16 nId ); + + virtual SvxUnderlineItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual OUString GetValueTextByPos( sal_uInt16 nPos ) const override; +}; + +// class SvxOverlineItem ------------------------------------------------ + +/* Value container for overline font effects */ + +class EDITENG_DLLPUBLIC SvxOverlineItem final : public SvxTextLineItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxOverlineItem( const FontLineStyle eSt, + const sal_uInt16 nId ); + + virtual SvxOverlineItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual OUString GetValueTextByPos( sal_uInt16 nPos ) const override; +}; + +#endif // INCLUDED_EDITENG_UDLNITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/ulspitem.hxx b/include/editeng/ulspitem.hxx new file mode 100644 index 000000000..b0131ab99 --- /dev/null +++ b/include/editeng/ulspitem.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_ULSPITEM_HXX +#define INCLUDED_EDITENG_ULSPITEM_HXX + +#include +#include + + +// class SvxULSpaceItem -------------------------------------------------- + +/* [Description] + + This item describes the Upper- and Lower space of a page or paragraph. +*/ + +#define ULSPACE_16_VERSION (sal_uInt16(0x0001)) + +class EDITENG_DLLPUBLIC SvxULSpaceItem final : public SfxPoolItem +{ + sal_uInt16 nUpper; // Upper space + sal_uInt16 nLower; // Lower space + bool bContext; // Contextual spacing? + sal_uInt16 nPropUpper, nPropLower; // relative or absolute (=100%) +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxULSpaceItem( const sal_uInt16 nId ); + SvxULSpaceItem( const sal_uInt16 nUp, const sal_uInt16 nLow, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxULSpaceItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual void ScaleMetrics( tools::Long nMult, tools::Long nDiv ) override; + virtual bool HasMetrics() const override; + + inline void SetUpper( const sal_uInt16 nU, const sal_uInt16 nProp = 100 ); + inline void SetLower( const sal_uInt16 nL, const sal_uInt16 nProp = 100 ); + + void SetUpperValue( const sal_uInt16 nU ) { nUpper = nU; } + void SetLowerValue( const sal_uInt16 nL ) { nLower = nL; } + void SetContextValue( const bool bC ) { bContext = bC; } + void SetPropUpper( const sal_uInt16 nU ) { nPropUpper = nU; } + void SetPropLower( const sal_uInt16 nL ) { nPropLower = nL; } + + sal_uInt16 GetUpper() const { return nUpper; } + sal_uInt16 GetLower() const { return nLower; } + bool GetContext() const { return bContext; } + sal_uInt16 GetPropUpper() const { return nPropUpper; } + sal_uInt16 GetPropLower() const { return nPropLower; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + virtual boost::property_tree::ptree dumpAsJSON() const override; +}; + +inline void SvxULSpaceItem::SetUpper( const sal_uInt16 nU, const sal_uInt16 nProp ) +{ + nUpper = sal_uInt16((sal_uInt32(nU) * nProp ) / 100); nPropUpper = nProp; +} +inline void SvxULSpaceItem::SetLower( const sal_uInt16 nL, const sal_uInt16 nProp ) +{ + nLower = sal_uInt16((sal_uInt32(nL) * nProp ) / 100); nPropLower = nProp; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoedhlp.hxx b/include/editeng/unoedhlp.hxx new file mode 100644 index 000000000..5b70de35c --- /dev/null +++ b/include/editeng/unoedhlp.hxx @@ -0,0 +1,156 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOEDHLP_HXX +#define INCLUDED_EDITENG_UNOEDHLP_HXX + +#include +#include +#include +#include +#include + +struct EENotify; +class EditEngine; + +/** Extends TextHint by two additional parameters which are necessary + for the SfxHintId::EditSourceParasMoved hint. TextHint's value in this + case denotes the destination position, the two parameters the + start and the end of the moved paragraph range. + */ +class SAL_DLLPUBLIC_RTTI SvxEditSourceHint : public TextHint +{ +private: + sal_Int32 mnStart; + sal_Int32 mnEnd; + +public: + SvxEditSourceHint( SfxHintId nId ); + SvxEditSourceHint( SfxHintId nId, sal_Int32 nValue, sal_Int32 nStart, sal_Int32 nEnd ); + + using TextHint::GetValue; + sal_Int32 GetStartValue() const { return mnStart;} + sal_Int32 GetEndValue() const { return mnEnd;} +}; +class SvxEditSourceHintEndPara final : public SvxEditSourceHint +{ +public: + SvxEditSourceHintEndPara() : SvxEditSourceHint(SfxHintId::EditSourceSelectionChanged) {} +}; +/** Helper class for common functionality in edit sources + */ +class EDITENG_DLLPUBLIC SvxEditSourceHelper +{ +public: + + /** Translates EditEngine notifications into broadcastable hints + + @param aNotify + Notification object sent by the EditEngine. + + @return the translated hint + */ + static ::std::unique_ptr EENotification2Hint( EENotify const * aNotify ); + + /** Calculate attribute run for EditEngines + + Please note that the range returned is half-open: [nStartIndex,nEndIndex) + + @param nStartIndex + Herein, the start index of the range of similar attributes is returned + + @param nEndIndex + Herein, the end index (exclusive) of the range of similar attributes is returned + + @param rEE + The EditEngine to query for attributes + + @param nPara + The paragraph the following index value is to be interpreted in + + @param nIndex + The character index from which the range of similar attributed characters is requested + */ + static void GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, const EditEngine& rEE, sal_Int32 nPara, sal_Int32 nIndex, bool bInCell = false); + + /** Convert point from edit engine to user coordinate space + + As the edit engine internally keeps vertical text unrotated, + all internal edit engine methods return their stuff unrotated, + too. This method rotates and shifts given point appropriately, + if vertical writing is on. + + @param rPoint + Point to transform + + @param rEESize + Paper size of the edit engine + + @param bIsVertical + Whether output text is vertical or not + + @return the possibly transformed point + */ + static Point EEToUserSpace( const Point& rPoint, const Size& rEESize, bool bIsVertical ); + + /** Convert point from user to edit engine coordinate space + + As the edit engine internally keeps vertical text unrotated, + all internal edit engine methods return their stuff unrotated, + too. This method rotates and shifts given point appropriately, + if vertical writing is on. + + @param rPoint + Point to transform + + @param rEESize + Paper size of the edit engine + + @param bIsVertical + Whether output text is vertical or not + + @return the possibly transformed point + */ + static Point UserSpaceToEE( const Point& rPoint, const Size& rEESize, bool bIsVertical ); + + /** Convert rect from edit engine to user coordinate space + + As the edit engine internally keeps vertical text unrotated, + all internal edit engine methods return their stuff unrotated, + too. This method rotates and shifts given rect appropriately, + if vertical writing is on. + + @param rRect + Rectangle to transform + + @param rEESize + Paper size of the edit engine + + @param bIsVertical + Whether output text is vertical or not + + @return the possibly transformed rect + */ + static tools::Rectangle EEToUserSpace( const tools::Rectangle& rRect, const Size& rEESize, bool bIsVertical ); + +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoedprx.hxx b/include/editeng/unoedprx.hxx new file mode 100644 index 000000000..f1db61fe9 --- /dev/null +++ b/include/editeng/unoedprx.hxx @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOEDPRX_HXX +#define INCLUDED_EDITENG_UNOEDPRX_HXX + +#include +#include +#include +#include + +#include +#include + +class SvxAccessibleTextAdapter final : public SvxTextForwarder +{ +public: + SvxAccessibleTextAdapter(); + virtual ~SvxAccessibleTextAdapter() override; + + virtual sal_Int32 GetParagraphCount() const override; + virtual sal_Int32 GetTextLen( sal_Int32 nParagraph ) const override; + virtual OUString GetText( const ESelection& rSel ) const override; + virtual SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ) const override; + virtual SfxItemSet GetParaAttribs( sal_Int32 nPara ) const override; + virtual void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& rSet ) override; + virtual void RemoveAttribs( const ESelection& rSelection ) override; + virtual void GetPortions( sal_Int32 nPara, std::vector& rList ) const override; + + sal_Int32 CalcEditEngineIndex( sal_Int32 nPara, sal_Int32 nLogicalIndex ); + + virtual SfxItemState GetItemState( const ESelection& rSel, sal_uInt16 nWhich ) const override; + virtual SfxItemState GetItemState( sal_Int32 nPara, sal_uInt16 nWhich ) const override; + + virtual void QuickInsertText( const OUString& rText, const ESelection& rSel ) override; + virtual void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) override; + virtual void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) override; + virtual void QuickInsertLineBreak( const ESelection& rSel ) override; + + virtual SfxItemPool* GetPool() const override; + + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rpTxtColor, std::optional& rpFldColor ) override; + virtual void FieldClicked( const SvxFieldItem& rField ) override; + + virtual bool IsValid() const override; + + virtual LanguageType GetLanguage( sal_Int32, sal_Int32 ) const override; + virtual sal_Int32 GetFieldCount( sal_Int32 nPara ) const override; + virtual EFieldInfo GetFieldInfo( sal_Int32 nPara, sal_uInt16 nField ) const override; + virtual EBulletInfo GetBulletInfo( sal_Int32 nPara ) const override; + virtual tools::Rectangle GetCharBounds( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual tools::Rectangle GetParaBounds( sal_Int32 nPara ) const override; + virtual MapMode GetMapMode() const override; + virtual OutputDevice* GetRefDevice() const override; + virtual bool GetIndexAtPoint( const Point&, sal_Int32& nPara, sal_Int32& nIndex ) const override; + virtual bool GetWordIndices( sal_Int32 nPara, sal_Int32 nIndex, sal_Int32& nStart, sal_Int32& nEnd ) const override; + virtual bool GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, sal_Int32 nPara, sal_Int32 nIndex, bool bInCell = false ) const override; + virtual sal_Int32 GetLineCount( sal_Int32 nPara ) const override; + virtual sal_Int32 GetLineLen( sal_Int32 nPara, sal_Int32 nLine ) const override; + virtual void GetLineBoundaries( /*out*/sal_Int32 &rStart, /*out*/sal_Int32 &rEnd, sal_Int32 nParagraph, sal_Int32 nLine ) const override; + virtual sal_Int32 GetLineNumberAtIndex( sal_Int32 nPara, sal_Int32 nIndex ) const override; + + virtual bool Delete( const ESelection& ) override; + virtual bool InsertText( const OUString&, const ESelection& ) override; + virtual bool QuickFormatDoc( bool bFull = false ) override; + virtual sal_Int16 GetDepth( sal_Int32 nPara ) const override; + virtual bool SetDepth( sal_Int32 nPara, sal_Int16 nNewDepth ) override; + + virtual const SfxItemSet* GetEmptyItemSetPtr() override; + + // implementation functions for XParagraphAppend and XTextPortionAppend + // (not needed for accessibility, only for new import API) + virtual void AppendParagraph() override; + virtual sal_Int32 AppendTextPortion( sal_Int32 nPara, const OUString &rText, const SfxItemSet &rSet ) override; + + //XTextCopy + virtual void CopyText(const SvxTextForwarder& rSource) override; + + void SetForwarder( SvxTextForwarder& ); + bool HaveImageBullet( sal_Int32 nPara ) const; + bool HaveTextBullet( sal_Int32 nPara ) const; + + /** Query whether all text in given selection is editable + + @return sal_True if every character in the given selection can + be changed, and sal_False if e.g. a field or a bullet is + contained therein. + */ + bool IsEditable( const ESelection& rSelection ) const; + +private: + SvxTextForwarder* mpTextForwarder; +}; + +class SvxAccessibleTextEditViewAdapter final : public SvxEditViewForwarder +{ +public: + + SvxAccessibleTextEditViewAdapter(); + virtual ~SvxAccessibleTextEditViewAdapter() override; + + // SvxViewForwarder interface + virtual bool IsValid() const override; + virtual Point LogicToPixel( const Point& rPoint, const MapMode& rMapMode ) const override; + virtual Point PixelToLogic( const Point& rPoint, const MapMode& rMapMode ) const override; + + // SvxEditViewForwarder interface + virtual bool GetSelection( ESelection& rSelection ) const override; + virtual bool SetSelection( const ESelection& rSelection ) override; + virtual bool Copy() override; + virtual bool Cut() override; + virtual bool Paste() override; + + void SetForwarder( SvxEditViewForwarder&, SvxAccessibleTextAdapter& ); + +private: + SvxEditViewForwarder* mpViewForwarder; + SvxAccessibleTextAdapter* mpTextForwarder; +}; + +class UNLESS_MERGELIBS(EDITENG_DLLPUBLIC) SvxEditSourceAdapter final : public SvxEditSource +{ +public: + SvxEditSourceAdapter(); + virtual ~SvxEditSourceAdapter() override; + + virtual std::unique_ptr Clone() const override; + virtual SvxTextForwarder* GetTextForwarder() override; + SvxAccessibleTextAdapter* GetTextForwarderAdapter(); // covariant return types don't work on MSVC + virtual SvxViewForwarder* GetViewForwarder() override; + virtual SvxEditViewForwarder* GetEditViewForwarder( bool bCreate = false ) override; + SvxAccessibleTextEditViewAdapter* GetEditViewForwarderAdapter( bool bCreate ); // covariant return types don't work on MSVC + virtual void UpdateData() override; + virtual SfxBroadcaster& GetBroadcaster() const override; + + void SetEditSource( ::std::unique_ptr< SvxEditSource > && pAdaptee ); + + bool IsValid() const { return mbEditSourceValid;} + +private: + SvxEditSourceAdapter( const SvxEditSourceAdapter& ) = delete; + SvxEditSourceAdapter& operator= ( const SvxEditSourceAdapter& ) = delete; + + ::std::unique_ptr< SvxEditSource > mpAdaptee; + + SvxAccessibleTextAdapter maTextAdapter; + SvxAccessibleTextEditViewAdapter maEditViewAdapter; + + mutable SfxBroadcaster maDummyBroadcaster; + + bool mbEditSourceValid; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoedsrc.hxx b/include/editeng/unoedsrc.hxx new file mode 100644 index 000000000..44d8944bc --- /dev/null +++ b/include/editeng/unoedsrc.hxx @@ -0,0 +1,533 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOEDSRC_HXX +#define INCLUDED_EDITENG_UNOEDSRC_HXX + +#include +#include +#include +#include +#include +#include +#include + +#include + +struct ESelection; +struct EFieldInfo; +struct EBulletInfo; +class Color; +class OutputDevice; +class SfxItemSet; +class SvxTextForwarder; +class SvxViewForwarder; +class SvxEditViewForwarder; +class SvxFieldItem; +class SfxBroadcaster; +class SvxUnoTextRangeBase; + +typedef std::vector< SvxUnoTextRangeBase* > SvxUnoTextRangeBaseVec; + +/** Wrapper class for unified EditEngine/Outliner access + + This class wraps a textual object, which might or might not + contain an EditEngine/Outliner. Is used e.g. for filling an + EditEngine with the content of a cell, note page or page template. +*/ +class EDITENG_DLLPUBLIC SvxEditSource +{ +public: + SvxEditSource() = default; + SvxEditSource(SvxEditSource const &) = default; + SvxEditSource(SvxEditSource &&) = default; + SvxEditSource & operator =(SvxEditSource const &) = default; + SvxEditSource & operator =(SvxEditSource &&) = default; + + virtual ~SvxEditSource(); + + /// Returns a new reference to the same object. This is a shallow copy + virtual std::unique_ptr Clone() const = 0; + + /** Query the text forwarder + + @return the text forwarder, or NULL if the underlying object is dead + */ + virtual SvxTextForwarder* GetTextForwarder() = 0; + + /** Query the view forwarder + + @return the view forwarder, or NULL if the underlying object + is dead, or if no view is available + + @derive default implementation provided, overriding is optional + */ + virtual SvxViewForwarder* GetViewForwarder(); + + /** Query the edit view forwarder + + @param bCreate + Determines whether an EditView should be created, if there is + none active. If set to sal_True, and the underlying object is + not in EditMode, the text forwarder changes and the object is + set to EditMode. + + @return the edit view forwarder, or NULL if the underlying + object is dead, or if no view is available (if bCreate is + sal_False, NULL is also returned if the object is not in + EditMode) + + @derive default implementation provided, overriding is optional + + @attention If this method is called with bCreate equal to + sal_True, all previously returned text forwarder can become + invalid + */ + virtual SvxEditViewForwarder* GetEditViewForwarder( bool bCreate = false ); + + /// Write back data to model + virtual void UpdateData() = 0; + + /** Returns broadcaster the underlying edit engine's events are sent from + + @derive default implementation provided, overriding is optional + */ + virtual SfxBroadcaster& GetBroadcaster() const; + + /** adds the given SvxUnoTextRangeBase to the text object + capsulated by this SvxEditSource. This allows the text + object to inform all created text ranges about changes + and also allows to re use already created instances. + All SvxUnoTextRangeBase must remove itself with + removeRange() before they are deleted. */ + virtual void addRange( SvxUnoTextRangeBase* pNewRange ); + + /** removes the given SvxUnoTextRangeBase from the text + object capsulated by this SvxEditSource. This text range + will not be informed any longer of changes on the underlying + text and will also not re used anymore. */ + virtual void removeRange( SvxUnoTextRangeBase* pOldRange ); + + /** returns a const list of all text ranges that are registered + for the underlying text object. */ + virtual const SvxUnoTextRangeBaseVec& getRanges() const; +}; + + +/** Contains an EditEngine or an Outliner and unifies access to them. + + The EditEngine-UNO objects use this class only. To reflect changes + not only in the EditEngine, but also in the model data, call + SvxEditSource::UpdateData(). This copies back the data to the model's + EditTextObject/OutlinerParaObject. + */ +class EDITENG_DLLPUBLIC SvxTextForwarder +{ +public: + virtual ~SvxTextForwarder() COVERITY_NOEXCEPT_FALSE; + + virtual sal_Int32 GetParagraphCount() const = 0; + virtual sal_Int32 GetTextLen( sal_Int32 nParagraph ) const = 0; + virtual OUString GetText( const ESelection& rSel ) const = 0; + virtual SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ) const = 0; + virtual SfxItemSet GetParaAttribs( sal_Int32 nPara ) const = 0; + virtual void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& rSet ) = 0; + virtual void RemoveAttribs( const ESelection& rSelection ) = 0; + virtual void GetPortions( sal_Int32 nPara, std::vector& rList ) const = 0; + + virtual SfxItemState GetItemState( const ESelection& rSel, sal_uInt16 nWhich ) const = 0; + virtual SfxItemState GetItemState( sal_Int32 nPara, sal_uInt16 nWhich ) const = 0; + + virtual void QuickInsertText( const OUString& rText, const ESelection& rSel ) = 0; + virtual void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) = 0; + virtual void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) = 0; + virtual void QuickInsertLineBreak( const ESelection& rSel ) = 0; + + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rpTxtColor, std::optional& rpFldColor ) = 0; + virtual void FieldClicked( const SvxFieldItem& rField ) = 0; + + virtual SfxItemPool* GetPool() const = 0; + + virtual const SfxItemSet* GetEmptyItemSetPtr() = 0; + + // implementation functions for XParagraphAppend and XTextPortionAppend + virtual void AppendParagraph() = 0; + virtual sal_Int32 AppendTextPortion( sal_Int32 nPara, const OUString &rText, const SfxItemSet &rSet ) = 0; + + // XTextCopy + virtual void CopyText(const SvxTextForwarder& rSource) = 0; + + /** Query state of forwarder + + @return false, if no longer valid + */ + virtual bool IsValid() const = 0; + + /** Query language of character at given position on the underlying edit engine + + @param nPara[0 .. n-1] + Index of paragraph to query language in + + @param nIndex[0 .. m-1] + Index of character to query language of + */ + virtual LanguageType GetLanguage( sal_Int32 nPara, sal_Int32 nIndex ) const = 0; + + /** Query number of fields in the underlying edit engine + + @param nPara[0 .. n-1] + Index of paragraph to query field number in + */ + virtual sal_Int32 GetFieldCount( sal_Int32 nPara ) const = 0; + + /** Query information for given field number in the underlying edit engine + + @param nPara[0 .. n-1] + Index of paragraph to query field info in + + @param nField[0 .. m-1] + Index of field to query information of + */ + virtual EFieldInfo GetFieldInfo( sal_Int32 nPara, sal_uInt16 nField ) const = 0; + + /** Query information regarding bullets for given paragraph on the underlying edit engine + + @param nPara[0 .. n-1] + Index of paragraph to query bullet info on + */ + virtual EBulletInfo GetBulletInfo( sal_Int32 nPara ) const = 0; + + /** Query the bounding rectangle of the given character + + @param nPara[0 .. n] + Index of paragraph to query the bounds in.

    The virtual + character after the last character of the represented text, + i.e. the one at position n is a special case. Because it does + not represent an existing character its bounding box is + defined in relation to preceding characters. It should be + roughly equivalent to the bounding box of some character when + inserted at the end of the text. Its height typically being + the maximal height of all the characters in the text or the + height of the preceding character, its width being at least + one pixel so that the bounding box is not degenerate.
    + + @param nIndex[0 .. m-1] + Index of character to query the bounds of + + @return rectangle in logical coordinates, relative to upper + left corner of text. The coordinates returned here are to be + interpreted in the map mode given by GetMapMode(). + */ + virtual tools::Rectangle GetCharBounds( sal_Int32 nPara, sal_Int32 nIndex ) const = 0; + + /** Query the bounding rectangle of the given paragraph + + @param nPara[0 .. n-1] + Index of paragraph to query the bounds of + + @return rectangle in logical coordinates, relative to upper + left corner of text. The coordinates returned here are to be + interpreted in the map mode given by GetMapMode(). + */ + virtual tools::Rectangle GetParaBounds( sal_Int32 nPara ) const = 0; + + /** Query the map mode of the underlying EditEngine/Outliner + + @return the map mode used on the EditEngine/Outliner. The + values returned by GetParaBounds() and GetCharBounds() are to + be interpreted in this map mode, the point given to + GetIndexAtPoint() is interpreted in this map mode. + */ + virtual MapMode GetMapMode() const = 0; + + /** Query the reference output device of the underlying EditEngine/Outliner + + @return the OutputDevice used from the EditEngine/Outliner to + format the text. It should be used when performing e.g. font + calculations, since this is usually a printer with fonts and + resolution different from the screen. + */ + virtual OutputDevice* GetRefDevice() const = 0; + + /** Query paragraph and character index of the character at the + given point. Returns sal_True on success, sal_False otherwise + + @param rPoint + Point to query text position of. Is interpreted in logical + coordinates, relative to the upper left corner of the text, and + in the map mode given by GetMapMode() + + @param rPara[0 .. n-1] + Index of paragraph the point is within + + @param rIndex[0 .. m-1] + Index of character the point is over + + @return true, if the point is over any text and both rPara and rIndex are valid + + */ + virtual bool GetIndexAtPoint( const Point& rPoint, sal_Int32& rPara, sal_Int32& rIndex ) const = 0; + + /** Get the start and the end index of the word at the given index + + An index value on a word leads from the first character of + that word up to and including the last space before the next + word. The index values returned do not contain any leading or + trailing white-space. If the input indices are invalid, + sal_False is returned. + + @param nPara[0 .. n-1] + Index of paragraph to start the search in + + @param nIndex[0 .. m-1] + Index of character to query the search on + + @param rStart + Start index (in the same paragraph) + + @param rEnd + End index (in the same paragraph), this point to the last + character still contained in the query + + @return true, if the result is non-empty + */ + virtual bool GetWordIndices( sal_Int32 nPara, sal_Int32 nIndex, sal_Int32& rStart, sal_Int32& rEnd ) const = 0; + + /** Query range of similar attributes + + Please note that the range returned is half-open: [nStartIndex,nEndIndex) + + @param nStartIndex + Herein, the start index of the range of similar attributes is returned + + @param nEndIndex + Herein, the end index (exclusive) of the range of similar attributes is returned + + @param nIndex + The character index from which the range of similar attributed characters is requested + + @return true, if the range has been successfully determined + */ + virtual bool GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, sal_Int32 nPara, sal_Int32 nIndex, bool bInCell = false ) const = 0; + + /** Query number of lines in the formatted paragraph + + @param nPara[0 .. n-1] + Index of paragraph to query number of lines in + + @return number of lines in given paragraph + + */ + virtual sal_Int32 GetLineCount( sal_Int32 nPara ) const = 0; + + /** Query line length + + @param nPara[0 .. n-1] + Index of paragraph to query line length in + + @param nLine[0 .. m-1] + Index of line in paragraph to query line length of + + */ + virtual sal_Int32 GetLineLen( sal_Int32 nPara, sal_Int32 nLine ) const = 0; + + /** Query bounds of line in paragraph + + @param rStart [output param; 0 .. text_len] + The index in the paragraph text that belongs to the chara at the start of the line + + @param rEnd [output param; 0 .. text_len] + The index in the paragraph text that follows the last chara in the line + + @param nParagraph[0 .. n-1] + Index of paragraph to query line length in + + @param nLine[0 .. m-1] + Index of line in paragraph to query line length of + + */ + virtual void GetLineBoundaries( /*out*/sal_Int32 &rStart, /*out*/sal_Int32 &rEnd, sal_Int32 nParagraph, sal_Int32 nLine ) const = 0; + + /** Query the line number for an index in the paragraphs text + + @param nPara[0 .. n-1] + Index of paragraph to query line length in + + @param nIndex[0 .. m-1] + Index of the char in the paragraph text + + @returns [0 .. k-1] + The line number of the char in the paragraph + */ + virtual sal_Int32 GetLineNumberAtIndex( sal_Int32 nPara, sal_Int32 nIndex ) const = 0; + + /** Delete given text range and reformat text + + @param rSelection + The text range to be deleted + + @return true if text has been successfully deleted + */ + virtual bool Delete( const ESelection& rSelection ) = 0; + + /** Insert/Replace given text in given range and reformat text + + @param rText + Text to insert/replace + + @param rSel + Selection where text should be replaced. The empty selection inserts + + @return true if text has been successfully inserted + */ + virtual bool InsertText( const OUString& rText, const ESelection& rSel ) = 0; + + /** Updates the formatting + + @see EditEngine::QuickFormatDoc() for details + + @return true if text have been successfully reformatted + */ + virtual bool QuickFormatDoc( bool bFull = false ) = 0; + + /** Get the outline depth of given paragraph + + @param nPara + Index of the paragraph to query the depth of + + @return the outline level of the given paragraph. The range is + [0,n), where n is the maximal outline level. + */ + virtual sal_Int16 GetDepth( sal_Int32 nPara ) const = 0; + + /** Set the outline depth of given paragraph + + @param nPara + Index of the paragraph to set the depth of + + @param nNewDepth + The depth to set on the given paragraph. The range is + [0,n), where n is the maximal outline level. + + @return true, if depth could be successfully set. Reasons for + failure are e.g. the text does not support outline level + (EditEngine), or the depth range is exceeded. + */ + virtual bool SetDepth( sal_Int32 nPara, sal_Int16 nNewDepth ) = 0; + + virtual sal_Int32 GetNumberingStartValue( sal_Int32 nPara ); + virtual void SetNumberingStartValue( sal_Int32 nPara, sal_Int32 nNumberingStartValue ); + + virtual bool IsParaIsNumberingRestart( sal_Int32 nPara ); + virtual void SetParaIsNumberingRestart( sal_Int32 nPara, bool bParaIsNumberingRestart ); +}; + +/** Encapsulates the document view for the purpose of unified + EditEngine/Outliner access. + + This one has to be different from the SvxEditViewForwarder, since + the latter is only valid in edit mode. + */ +class EDITENG_DLLPUBLIC SvxViewForwarder +{ +public: + virtual ~SvxViewForwarder(); + + /** Query state of forwarder + + @return sal_False, if no longer valid + */ + virtual bool IsValid() const = 0; + + /** Convert from logical, EditEngine-relative coordinates to screen coordinates + + @param rPoint + Point in logical, EditEngine-relative coordinates. + + @param rMapMode + The map mode to interpret the coordinates in. + + @return the point in screen coordinates + */ + virtual Point LogicToPixel( const Point& rPoint, const MapMode& rMapMode ) const = 0; + + /** Convert from screen to logical, EditEngine-relative coordinates + + @param rPoint + Point in screen coordinates + + @param rMapMode + The map mode to interpret the coordinates in. + + @return the point in logical coordinates. + */ + virtual Point PixelToLogic( const Point& rPoint, const MapMode& rMapMode ) const = 0; + +}; + + +/** Encapsulates EditView and OutlinerView for the purpose of unified + EditEngine/Outliner access + */ +class SvxEditViewForwarder : public SvxViewForwarder +{ +public: + + /** Query current selection. + + @param rSelection + Contains the current selection after method call + + @return false, if there is no view or no selection (the empty selection _is_ a selection) + + */ + virtual bool GetSelection( ESelection& rSelection ) const = 0; + + /** Set selection in view. + + @param rSelection + The selection to set + + @return false, if there is no view or selection is invalid + */ + virtual bool SetSelection( const ESelection& rSelection ) = 0; + + /** Copy current selection to clipboard. + + @return false if no selection or no view (the empty selection _is_ a selection) + */ + virtual bool Copy() = 0; + + /** Cut current selection to clipboard. + + @return false if no selection or no view (the empty selection _is_ a selection) + */ + virtual bool Cut() = 0; + + /** Paste clipboard into current selection. + + @return false if no view or no selection (the empty selection _is_ a selection) + */ + virtual bool Paste() = 0; + +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unofdesc.hxx b/include/editeng/unofdesc.hxx new file mode 100644 index 000000000..fbc94b09c --- /dev/null +++ b/include/editeng/unofdesc.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOFDESC_HXX +#define INCLUDED_EDITENG_UNOFDESC_HXX + +#include +#include + +namespace com::sun::star::awt +{ +struct FontDescriptor; +} +namespace vcl +{ +class Font; +} + +class EDITENG_DLLPUBLIC SvxUnoFontDescriptor +{ +public: + static void ConvertToFont(const css::awt::FontDescriptor& rDesc, vcl::Font& rFont); + static void ConvertFromFont(const vcl::Font& rFont, css::awt::FontDescriptor& rDesc); + + static void FillItemSet(const css::awt::FontDescriptor& rDesc, SfxItemSet& rSet); + static void FillFromItemSet(const SfxItemSet& rSet, css::awt::FontDescriptor& rDesc); + + static void setPropertyToDefault(SfxItemSet& rSet); + static css::uno::Any getPropertyDefault(SfxItemPool* pPool); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unofield.hxx b/include/editeng/unofield.hxx new file mode 100644 index 000000000..740a25a5b --- /dev/null +++ b/include/editeng/unofield.hxx @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOFIELD_HXX +#define INCLUDED_EDITENG_UNOFIELD_HXX + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySetInfo; } + +class SvxUnoFieldData_Impl; +class SfxItemPropertySet; +class SvxFieldData; + +/// @throws css::uno::Exception +/// @throws css::uno::RuntimeException +css::uno::Reference< css::uno::XInterface > EDITENG_DLLPUBLIC SvxUnoTextCreateTextField( + std::u16string_view ServiceSpecifier ); + +class EDITENG_DLLPUBLIC SvxUnoTextField final : public cppu::BaseMutex, + public ::cppu::OComponentHelper, + public css::text::XTextField, + public css::beans::XPropertySet, + public css::lang::XServiceInfo, + public css::lang::XUnoTunnel +{ + css::uno::Reference< css::text::XTextRange > mxAnchor; + const SfxItemPropertySet* mpPropSet; + sal_Int32 mnServiceId; + std::unique_ptr mpImpl; + css::uno::Sequence< css::uno::Type > maTypeSequence; + +public: + SvxUnoTextField( sal_Int32 nServiceId ) noexcept; + SvxUnoTextField( css::uno::Reference< css::text::XTextRange > xAnchor, const OUString& rPresentation, const SvxFieldData* pFieldData ) noexcept; + virtual ~SvxUnoTextField() noexcept override; + + // Internal + std::unique_ptr CreateFieldData() const noexcept; + + static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId() noexcept; + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + + // css::uno::XInterface + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ) override; + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + // css::lang::XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; + + // XTextField + virtual OUString SAL_CALL getPresentation( sal_Bool bShowCommand ) override; + + // XTextContent + virtual void SAL_CALL attach( const css::uno::Reference< css::text::XTextRange >& xTextRange ) override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getAnchor( ) override; + + // css::lang::XComponent + virtual void SAL_CALL dispose() override; + virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) override; + virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override; + + // XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; + virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; + virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; + virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; + virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + + // OComponentHelper + virtual void SAL_CALL disposing() override; + + // XServiceInfo + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual OUString SAL_CALL getImplementationName() override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unofored.hxx b/include/editeng/unofored.hxx new file mode 100644 index 000000000..989b5c365 --- /dev/null +++ b/include/editeng/unofored.hxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOFORED_HXX +#define INCLUDED_EDITENG_UNOFORED_HXX + +#include +#include +#include + +// SvxEditEngineForwarder - SvxTextForwarder for EditEngine + +class EDITENG_DLLPUBLIC SvxEditEngineForwarder final : public SvxTextForwarder +{ +private: + EditEngine& rEditEngine; + +public: + SvxEditEngineForwarder( EditEngine& rEngine ); + virtual ~SvxEditEngineForwarder() override; + + virtual sal_Int32 GetParagraphCount() const override; + virtual sal_Int32 GetTextLen( sal_Int32 nParagraph ) const override; + virtual OUString GetText( const ESelection& rSel ) const override; + virtual SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ) const override; + virtual SfxItemSet GetParaAttribs( sal_Int32 nPara ) const override; + virtual void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& rSet ) override; + virtual void RemoveAttribs( const ESelection& rSelection ) override; + virtual void GetPortions( sal_Int32 nPara, std::vector& rList ) const override; + + virtual SfxItemState GetItemState( const ESelection& rSel, sal_uInt16 nWhich ) const override; + virtual SfxItemState GetItemState( sal_Int32 nPara, sal_uInt16 nWhich ) const override; + + virtual void QuickInsertText( const OUString& rText, const ESelection& rSel ) override; + virtual void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) override; + virtual void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) override; + virtual void QuickInsertLineBreak( const ESelection& rSel ) override; + + virtual SfxItemPool* GetPool() const override; + + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rpTxtColor, std::optional& rpFldColor ) override; + virtual void FieldClicked( const SvxFieldItem& rField ) override; + virtual bool IsValid() const override; + + virtual LanguageType GetLanguage( sal_Int32, sal_Int32 ) const override; + virtual sal_Int32 GetFieldCount( sal_Int32 nPara ) const override; + virtual EFieldInfo GetFieldInfo( sal_Int32 nPara, sal_uInt16 nField ) const override; + virtual EBulletInfo GetBulletInfo( sal_Int32 nPara ) const override; + virtual tools::Rectangle GetCharBounds( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual tools::Rectangle GetParaBounds( sal_Int32 nPara ) const override; + virtual MapMode GetMapMode() const override; + virtual OutputDevice* GetRefDevice() const override; + virtual bool GetIndexAtPoint( const Point&, sal_Int32& nPara, sal_Int32& nIndex ) const override; + virtual bool GetWordIndices( sal_Int32 nPara, sal_Int32 nIndex, sal_Int32& nStart, sal_Int32& nEnd ) const override; + virtual bool GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, sal_Int32 nPara, sal_Int32 nIndex, bool bInCell = false ) const override; + virtual sal_Int32 GetLineCount( sal_Int32 nPara ) const override; + virtual sal_Int32 GetLineLen( sal_Int32 nPara, sal_Int32 nLine ) const override; + virtual void GetLineBoundaries( /*out*/sal_Int32 &rStart, /*out*/sal_Int32 &rEnd, sal_Int32 nParagraph, sal_Int32 nLine ) const override; + virtual sal_Int32 GetLineNumberAtIndex( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual bool Delete( const ESelection& ) override; + virtual bool InsertText( const OUString&, const ESelection& ) override; + virtual bool QuickFormatDoc( bool bFull = false ) override; + virtual sal_Int16 GetDepth( sal_Int32 nPara ) const override; + virtual bool SetDepth( sal_Int32 nPara, sal_Int16 nNewDepth ) override; + + virtual const SfxItemSet* GetEmptyItemSetPtr() override; + + // implementation functions for XParagraphAppend and XTextPortionAppend + virtual void AppendParagraph() override; + virtual sal_Int32 AppendTextPortion( sal_Int32 nPara, const OUString &rText, const SfxItemSet &rSet ) override; + //XTextCopy + virtual void CopyText(const SvxTextForwarder& rSource) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoforou.hxx b/include/editeng/unoforou.hxx new file mode 100644 index 000000000..a4535d83b --- /dev/null +++ b/include/editeng/unoforou.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOFOROU_HXX +#define INCLUDED_EDITENG_UNOFOROU_HXX + +#include +#include +#include +#include +#include + +class Outliner; + +// SvxOutlinerForwarder - SvxTextForwarder for Outliner + +class EDITENG_DLLPUBLIC SvxOutlinerForwarder final : public SvxTextForwarder +{ +private: + Outliner& rOutliner; + bool bOutlinerText; + + /** this pointer may be null or point to an item set for the attribs of + the selection maAttribsSelection */ + mutable std::optional moAttribsCache; + + /** if we have a cached attribute item set, this is the selection of it */ + mutable ESelection maAttribCacheSelection; + + /** this pointer may be null or point to an item set for the paragraph + mnParaAttribsCache */ + mutable std::optional moParaAttribsCache; + + /** if we have a cached para attribute item set, this is the paragraph of it */ + mutable sal_Int32 mnParaAttribsCache; + +public: + SvxOutlinerForwarder( Outliner& rOutl, bool bOutlText ); + virtual ~SvxOutlinerForwarder() override; + + virtual sal_Int32 GetParagraphCount() const override; + virtual sal_Int32 GetTextLen( sal_Int32 nParagraph ) const override; + virtual OUString GetText( const ESelection& rSel ) const override; + virtual SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ) const override; + virtual SfxItemSet GetParaAttribs( sal_Int32 nPara ) const override; + virtual void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& rSet ) override; + virtual void RemoveAttribs( const ESelection& rSelection ) override; + virtual void GetPortions( sal_Int32 nPara, std::vector& rList ) const override; + + virtual SfxItemState GetItemState( const ESelection& rSel, sal_uInt16 nWhich ) const override; + virtual SfxItemState GetItemState( sal_Int32 nPara, sal_uInt16 nWhich ) const override; + + virtual void QuickInsertText( const OUString& rText, const ESelection& rSel ) override; + virtual void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) override; + virtual void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) override; + virtual void QuickInsertLineBreak( const ESelection& rSel ) override; + + virtual SfxItemPool* GetPool() const override; + + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rpTxtColor, std::optional& rpFldColor ) override; + virtual void FieldClicked( const SvxFieldItem& rField ) override; + + virtual bool IsValid() const override; + + virtual LanguageType GetLanguage( sal_Int32, sal_Int32 ) const override; + virtual sal_Int32 GetFieldCount( sal_Int32 nPara ) const override; + virtual EFieldInfo GetFieldInfo( sal_Int32 nPara, sal_uInt16 nField ) const override; + virtual EBulletInfo GetBulletInfo( sal_Int32 nPara ) const override; + virtual tools::Rectangle GetCharBounds( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual tools::Rectangle GetParaBounds( sal_Int32 nPara ) const override; + virtual MapMode GetMapMode() const override; + virtual OutputDevice* GetRefDevice() const override; + virtual bool GetIndexAtPoint( const Point&, sal_Int32& nPara, sal_Int32& nIndex ) const override; + virtual bool GetWordIndices( sal_Int32 nPara, sal_Int32 nIndex, sal_Int32& nStart, sal_Int32& nEnd ) const override; + virtual bool GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, sal_Int32 nPara, sal_Int32 nIndex, bool bInCell = false ) const override; + virtual sal_Int32 GetLineCount( sal_Int32 nPara ) const override; + virtual sal_Int32 GetLineLen( sal_Int32 nPara, sal_Int32 nLine ) const override; + virtual void GetLineBoundaries( /*out*/sal_Int32& rStart, /*out*/sal_Int32& rEnd, sal_Int32 nPara, sal_Int32 nLine ) const override; + virtual sal_Int32 GetLineNumberAtIndex( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual bool Delete( const ESelection& ) override; + virtual bool InsertText( const OUString&, const ESelection& ) override; + virtual bool QuickFormatDoc( bool bFull = false ) override; + virtual sal_Int16 GetDepth( sal_Int32 nPara ) const override; + virtual bool SetDepth( sal_Int32 nPara, sal_Int16 nNewDepth ) override; + virtual sal_Int32 GetNumberingStartValue( sal_Int32 nPara ) override; + virtual void SetNumberingStartValue( sal_Int32 nPara, sal_Int32 nNumberingStartValue ) override; + + virtual bool IsParaIsNumberingRestart( sal_Int32 nPara ) override; + virtual void SetParaIsNumberingRestart( sal_Int32 nPara, bool bParaIsNumberingRestart ) override; + + /* this method flushes internal caches for this forwarder */ + void flushCache(); + + virtual const SfxItemSet* GetEmptyItemSetPtr() override; + + // implementation functions for XParagraphAppend and XTextPortionAppend + virtual void AppendParagraph() override; + virtual sal_Int32 AppendTextPortion( sal_Int32 nPara, const OUString &rText, const SfxItemSet &rSet ) override; + //XTextCopy + virtual void CopyText(const SvxTextForwarder& rSource) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoipset.hxx b/include/editeng/unoipset.hxx new file mode 100644 index 000000000..5a0ac105c --- /dev/null +++ b/include/editeng/unoipset.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOIPSET_HXX +#define INCLUDED_EDITENG_UNOIPSET_HXX + +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySetInfo; } + +class SfxItemSet; +class SvxItemPropertySetUsrAnys; + +class EDITENG_DLLPUBLIC SvxItemPropertySet +{ + SfxItemPropertyMap m_aPropertyMap; + mutable css::uno::Reference m_xInfo; + SfxItemPool& mrItemPool; + +public: + SvxItemPropertySet( const SfxItemPropertyMapEntry *pMap, SfxItemPool& rPool ); + ~SvxItemPropertySet(); + + SvxItemPropertySet& operator=( SvxItemPropertySet const & ) = delete; // MSVC2015 workaround + SvxItemPropertySet( SvxItemPropertySet const & ) = delete; // MSVC2015 workaround + + // Methods, which work directly with the ItemSet + static css::uno::Any getPropertyValue( const SfxItemPropertyMapEntry* pMap, const SfxItemSet& rSet, bool bSearchInParent, bool bDontConvertNegativeValues ); + static void setPropertyValue( const SfxItemPropertyMapEntry* pMap, const css::uno::Any& rVal, SfxItemSet& rSet, bool bDontConvertNegativeValues ); + + // Methods that use Any instead + css::uno::Any getPropertyValue( const SfxItemPropertyMapEntry* pMap, SvxItemPropertySetUsrAnys& rAnys ) const; + static void setPropertyValue( const SfxItemPropertyMapEntry* pMap, const css::uno::Any& rVal, SvxItemPropertySetUsrAnys& rAnys ); + + css::uno::Reference< css::beans::XPropertySetInfo > const & getPropertySetInfo() const; + const SfxItemPropertyMap& getPropertyMap() const { return m_aPropertyMap;} + const SfxItemPropertyMapEntry* getPropertyMapEntry(std::u16string_view rName) const; +}; + +struct SvxIDPropertyCombine +{ + sal_uInt16 nWID; + sal_uInt8 memberId; + css::uno::Any aAny; +}; + + +class EDITENG_DLLPUBLIC SvxItemPropertySetUsrAnys +{ + ::std::vector< SvxIDPropertyCombine > aCombineList; + +public: + SvxItemPropertySetUsrAnys(); + ~SvxItemPropertySetUsrAnys(); + bool AreThereOwnUsrAnys() const { return ! aCombineList.empty(); } + css::uno::Any* GetUsrAnyForID(SfxItemPropertyMapEntry const & entry) const; + void AddUsrAnyForID(const css::uno::Any& rAny, SfxItemPropertyMapEntry const & entry); + void ClearAllUsrAny(); +}; + +/** converts the given any with a metric to 100th/mm if needed */ +EDITENG_DLLPUBLIC void SvxUnoConvertToMM( const MapUnit eSourceMapUnit, css::uno::Any & rMetric ) noexcept; + +/** converts the given any with a metric from 100th/mm to the given metric if needed */ +EDITENG_DLLPUBLIC void SvxUnoConvertFromMM( const MapUnit eDestinationMapUnit, css::uno::Any & rMetric ) noexcept; + +#endif // INCLUDED_EDITENG_UNOIPSET_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unolingu.hxx b/include/editeng/unolingu.hxx new file mode 100644 index 000000000..2aec6db1a --- /dev/null +++ b/include/editeng/unolingu.hxx @@ -0,0 +1,133 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOLINGU_HXX +#define INCLUDED_EDITENG_UNOLINGU_HXX + +#include +#include +#include +#include + +namespace com::sun::star::linguistic2 { class XDictionary; } +namespace com::sun::star::linguistic2 { class XHyphenator; } +namespace com::sun::star::linguistic2 { class XLinguProperties; } +namespace com::sun::star::linguistic2 { class XLinguServiceManager2; } +namespace com::sun::star::linguistic2 { class XSearchableDictionaryList; } +namespace com::sun::star::linguistic2 { class XSpellChecker1; } +namespace com::sun::star::linguistic2 { class XThesaurus; } + +class LinguMgrExitLstnr; + +namespace weld { class Window; } +namespace linguistic { enum class DictionaryError; } + + +class EDITENG_DLLPUBLIC LinguMgr +{ + friend class LinguMgrExitLstnr; + + static css::uno::Reference< css::linguistic2::XLinguServiceManager2 > xLngSvcMgr; + static css::uno::Reference< css::linguistic2::XSpellChecker1 > xSpell; + static css::uno::Reference< css::linguistic2::XHyphenator > xHyph; + static css::uno::Reference< css::linguistic2::XThesaurus > xThes; + static css::uno::Reference< css::linguistic2::XSearchableDictionaryList > xDicList; + static css::uno::Reference< css::linguistic2::XLinguProperties > xProp; + + static css::uno::Reference< css::linguistic2::XDictionary > xIgnoreAll; + static css::uno::Reference< css::linguistic2::XDictionary > xChangeAll; + + static rtl::Reference pExitLstnr; + static bool bExiting; + + static css::uno::Reference< css::linguistic2::XSpellChecker1 > GetSpell(); + static css::uno::Reference< css::linguistic2::XHyphenator > GetHyph(); + static css::uno::Reference< css::linguistic2::XThesaurus > GetThes(); + static css::uno::Reference< css::linguistic2::XSearchableDictionaryList > GetDicList(); + static css::uno::Reference< css::linguistic2::XLinguProperties > GetProp(); + static css::uno::Reference< css::linguistic2::XDictionary > GetStandard(); + static css::uno::Reference< css::linguistic2::XDictionary > GetIgnoreAll(); + static css::uno::Reference< css::linguistic2::XDictionary > GetChangeAll(); + + LinguMgr(const LinguMgr &) = delete; + LinguMgr & operator = (const LinguMgr &) = delete; + +public: + + static css::uno::Reference< css::linguistic2::XSpellChecker1 > GetSpellChecker(); + static css::uno::Reference< css::linguistic2::XHyphenator > GetHyphenator(); + static css::uno::Reference< css::linguistic2::XThesaurus > GetThesaurus(); + static css::uno::Reference< css::linguistic2::XSearchableDictionaryList > GetDictionaryList(); + static css::uno::Reference< css::linguistic2::XLinguProperties > GetLinguPropertySet(); + + static css::uno::Reference< css::linguistic2::XLinguServiceManager2 > GetLngSvcMgr(); + + static css::uno::Reference< css::linguistic2::XDictionary > GetStandardDic(); + static css::uno::Reference< css::linguistic2::XDictionary > GetIgnoreAllList(); + static css::uno::Reference< css::linguistic2::XDictionary > GetChangeAllList(); +}; + + +namespace com::sun::star::linguistic2 { + class XHyphenatedWord; +} + + +struct SvxAlternativeSpelling +{ + OUString aReplacement; + sal_Int16 nChangedPos, + nChangedLength; + bool bIsAltSpelling; + + inline SvxAlternativeSpelling(); +}; + +inline SvxAlternativeSpelling::SvxAlternativeSpelling() : + nChangedPos(-1), nChangedLength(-1), bIsAltSpelling(false) +{ +} + + +EDITENG_DLLPUBLIC SvxAlternativeSpelling SvxGetAltSpelling( + const css::uno::Reference< css::linguistic2::XHyphenatedWord > & rHyphWord ); + + +class EDITENG_DLLPUBLIC SvxDicListChgClamp +{ +private: + css::uno::Reference< + css::linguistic2::XSearchableDictionaryList > xDicList; + + SvxDicListChgClamp(const SvxDicListChgClamp &) = delete; + SvxDicListChgClamp & operator = (const SvxDicListChgClamp &) = delete; + +public: + SvxDicListChgClamp( css::uno::Reference< + css::linguistic2::XSearchableDictionaryList > xDicList ); + ~SvxDicListChgClamp(); +}; + +EDITENG_DLLPUBLIC short SvxDicError(weld::Window *pParent, linguistic::DictionaryError nError); + + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unonames.hxx b/include/editeng/unonames.hxx new file mode 100644 index 000000000..2e5b44e1a --- /dev/null +++ b/include/editeng/unonames.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_EDITENG_UNONAMES_HXX +#define INCLUDED_EDITENG_UNONAMES_HXX + +#include + +// Common across fields +inline constexpr OUStringLiteral UNO_TC_PROP_ANCHOR = u"Anchor"; +inline constexpr OUStringLiteral UNO_TC_PROP_TEXTFIELD_TYPE = u"TextFieldType"; +inline constexpr OUStringLiteral UNO_TC_PROP_IS_FIXED = u"IsFixed"; +inline constexpr OUStringLiteral UNO_TC_PROP_CURRENT_PRESENTATION = u"CurrentPresentation"; +inline constexpr OUStringLiteral UNO_TC_PROP_NAME = u"Name"; +inline constexpr OUStringLiteral UNO_TC_PROP_IS_FIXED_LANGUAGE = u"IsFixedLanguage"; +inline constexpr OUStringLiteral UNO_TC_PROP_NUMFORMAT = u"NumberFormat"; + +// Date & Time +inline constexpr OUStringLiteral UNO_TC_PROP_IS_DATE = u"IsDate"; +inline constexpr OUStringLiteral UNO_TC_PROP_DATE_TIME = u"DateTime"; + +// URL +inline constexpr OUStringLiteral UNO_TC_PROP_URL_FORMAT = u"Format"; +inline constexpr OUStringLiteral UNO_TC_PROP_URL_REPRESENTATION = u"Representation"; +inline constexpr OUStringLiteral UNO_TC_PROP_URL_TARGET = u"TargetFrame"; +inline constexpr OUStringLiteral UNO_TC_PROP_URL = u"URL"; + +// Table +inline constexpr OUStringLiteral UNO_TC_PROP_TABLE_POSITION = u"TablePosition"; + +// File +inline constexpr OUStringLiteral UNO_TC_PROP_FILE_FORMAT = u"FileFormat"; + +// Author +inline constexpr OUStringLiteral UNO_TC_PROP_AUTHOR_CONTENT = u"Content"; +inline constexpr OUStringLiteral UNO_TC_PROP_AUTHOR_FORMAT = u"AuthorFormat"; +inline constexpr OUStringLiteral UNO_TC_PROP_AUTHOR_FULLNAME = u"FullName"; + +// Measure +inline constexpr OUStringLiteral UNO_TC_PROP_MEASURE_KIND = u"Kind"; + +inline constexpr OUStringLiteral UNO_TR_PROP_SELECTION = u"Selection"; + +#endif // INCLUDED_EDITENG_UNONAMES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unonrule.hxx b/include/editeng/unonrule.hxx new file mode 100644 index 000000000..d0e89ffdc --- /dev/null +++ b/include/editeng/unonrule.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNONRULE_HXX +#define INCLUDED_EDITENG_UNONRULE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } + +EDITENG_DLLPUBLIC css::uno::Reference< css::container::XIndexReplace > SvxCreateNumRule(const SvxNumRule& rRule); +css::uno::Reference< css::container::XIndexReplace > SvxCreateNumRule(); +/// @throws css::lang::IllegalArgumentException +const SvxNumRule& SvxGetNumRule( css::uno::Reference< css::container::XIndexReplace > const & xRule ); +EDITENG_DLLPUBLIC css::uno::Reference< css::ucb::XAnyCompare > SvxCreateNumRuleCompare() noexcept; + +class SvxUnoNumberingRules final : public ::cppu::WeakAggImplHelper5< css::container::XIndexReplace, css::ucb::XAnyCompare, + css::lang::XUnoTunnel, css::util::XCloneable, css::lang::XServiceInfo > +{ +private: + SvxNumRule maRule; +public: + SvxUnoNumberingRules(SvxNumRule aRule); + virtual ~SvxUnoNumberingRules() noexcept override; + + UNO3_GETIMPLEMENTATION_DECL( SvxUnoNumberingRules ) + + //XIndexReplace + virtual void SAL_CALL replaceByIndex( sal_Int32 Index, const css::uno::Any& Element ) override; + + //XIndexAccess + virtual sal_Int32 SAL_CALL getCount() override ; + virtual css::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) override; + + //XElementAccess + virtual css::uno::Type SAL_CALL getElementType() override; + virtual sal_Bool SAL_CALL hasElements() override; + + // XAnyCompare + virtual sal_Int16 SAL_CALL compare( const css::uno::Any& Any1, const css::uno::Any& Any2 ) override; + + // XCloneable + virtual css::uno::Reference< css::util::XCloneable > SAL_CALL createClone( ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName( ) override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; + + // internal + /// @throws css::uno::RuntimeException + css::uno::Sequence getNumberingRuleByIndex( sal_Int32 nIndex) const; + /// @throws css::uno::RuntimeException + /// @throws css::lang::IllegalArgumentException + void setNumberingRuleByIndex(const css::uno::Sequence& rProperties, sal_Int32 nIndex); + + static sal_Int16 Compare( const css::uno::Any& rAny1, const css::uno::Any& rAny2 ); + + const SvxNumRule& getNumRule() const { return maRule; } +}; + + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoprnms.hxx b/include/editeng/unoprnms.hxx new file mode 100644 index 000000000..8569a3370 --- /dev/null +++ b/include/editeng/unoprnms.hxx @@ -0,0 +1,361 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +inline constexpr OUStringLiteral UNO_NAME_CHAR_COLOR = u"CharColor"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_COLOR_THEME = u"CharColorTheme"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_COLOR_TINT_OR_SHADE = u"CharColorTintOrShade"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_HEIGHT = u"CharHeight"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_POSTURE = u"CharPosture"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_SHADOWED = u"CharShadowed"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_UNDERLINE = u"CharUnderline"; +inline constexpr OUStringLiteral UNO_NAME_CHAR_WEIGHT = u"CharWeight"; + +inline constexpr OUStringLiteral UNO_NAME_FILLSTYLE = u"FillStyle"; +inline constexpr OUStringLiteral UNO_NAME_FILLCOLOR = u"FillColor"; +inline constexpr OUStringLiteral UNO_NAME_FILLCOLOR_THEME = u"FillColorTheme"; +inline constexpr OUStringLiteral UNO_NAME_FILLCOLOR_LUM_MOD = u"FillColorLumMod"; +inline constexpr OUStringLiteral UNO_NAME_FILLCOLOR_LUM_OFF = u"FillColorLumOff"; +inline constexpr OUStringLiteral UNO_NAME_FILLGRADIENT = u"FillGradient"; +inline constexpr OUStringLiteral UNO_NAME_FILLGRADIENTNAME = u"FillGradientName"; +inline constexpr OUStringLiteral UNO_NAME_FILLHATCH = u"FillHatch"; +inline constexpr OUStringLiteral UNO_NAME_FILLHATCHNAME = u"FillHatchName"; +inline constexpr OUStringLiteral UNO_NAME_FILLBITMAP = u"FillBitmap"; +inline constexpr OUStringLiteral UNO_NAME_FILLBITMAPURL = u"FillBitmapURL"; +inline constexpr OUStringLiteral UNO_NAME_FILLBITMAPNAME = u"FillBitmapName"; +inline constexpr OUStringLiteral UNO_NAME_FILLGRADIENTSTEPCOUNT = u"FillGradientStepCount"; +inline constexpr OUStringLiteral UNO_NAME_FILLBACKGROUND = u"FillBackground"; +inline constexpr OUStringLiteral UNO_NAME_FILLUSESLIDEBACKGROUND = u"FillUseSlideBackground"; +inline constexpr OUStringLiteral UNO_NAME_FILLCOLOR_2 = u"FillColor2"; + +inline constexpr OUStringLiteral UNO_NAME_EDGEKIND = u"EdgeKind"; +inline constexpr OUStringLiteral UNO_NAME_EDGELINE1DELTA = u"EdgeLine1Delta"; +inline constexpr OUStringLiteral UNO_NAME_EDGELINE2DELTA = u"EdgeLine2Delta"; +inline constexpr OUStringLiteral UNO_NAME_EDGELINE3DELTA = u"EdgeLine3Delta"; +inline constexpr OUStringLiteral UNO_NAME_EDGENODE1HORZDIST = u"EdgeNode1HorzDist"; +inline constexpr OUStringLiteral UNO_NAME_EDGENODE1VERTDIST = u"EdgeNode1VertDist"; +inline constexpr OUStringLiteral UNO_NAME_EDGENODE2HORZDIST = u"EdgeNode2HorzDist"; +inline constexpr OUStringLiteral UNO_NAME_EDGENODE2VERTDIST = u"EdgeNode2VertDist"; + +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_OFFSET_X = u"FillBitmapOffsetX"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_OFFSET_Y = u"FillBitmapOffsetY"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_POSITION_OFFSET_X = u"FillBitmapPositionOffsetX"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_POSITION_OFFSET_Y = u"FillBitmapPositionOffsetY"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_RECTANGLE_POINT = u"FillBitmapRectanglePoint"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_TILE = u"FillBitmapTile"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_STRETCH = u"FillBitmapStretch"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_LOGICAL_SIZE = u"FillBitmapLogicalSize"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_SIZE_X = u"FillBitmapSizeX"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_SIZE_Y = u"FillBitmapSizeY"; +inline constexpr OUStringLiteral UNO_NAME_FILL_TRANSPARENCE = u"FillTransparence"; +inline constexpr OUStringLiteral UNO_NAME_FILLTRANSPARENCEGRADIENT = u"FillTransparenceGradient"; +inline constexpr OUStringLiteral UNO_NAME_FILLTRANSPARENCEGRADIENTNAME = u"FillTransparenceGradientName"; +inline constexpr OUStringLiteral UNO_NAME_FILLBMP_MODE = u"FillBitmapMode"; + + +inline constexpr OUStringLiteral UNO_NAME_LINESTYLE = u"LineStyle"; +inline constexpr OUStringLiteral UNO_NAME_LINEDASH = u"LineDash"; +inline constexpr OUStringLiteral UNO_NAME_LINEWIDTH = u"LineWidth"; +inline constexpr OUStringLiteral UNO_NAME_LINECOLOR = u"LineColor"; +inline constexpr OUStringLiteral UNO_NAME_LINEJOINT = u"LineJoint"; +inline constexpr OUStringLiteral UNO_NAME_LINESTART = u"LineStart"; +inline constexpr OUStringLiteral UNO_NAME_LINEEND = u"LineEnd"; +inline constexpr OUStringLiteral UNO_NAME_LINESTARTWIDTH = u"LineStartWidth"; +inline constexpr OUStringLiteral UNO_NAME_LINEENDWIDTH = u"LineEndWidth"; +inline constexpr OUStringLiteral UNO_NAME_LINESTARTCENTER = u"LineStartCenter"; +inline constexpr OUStringLiteral UNO_NAME_LINEENDCENTER = u"LineEndCenter"; +inline constexpr OUStringLiteral UNO_NAME_LINETRANSPARENCE = u"LineTransparence"; +inline constexpr OUStringLiteral UNO_NAME_LINECAP = u"LineCap"; + +inline constexpr OUStringLiteral UNO_NAME_SHADOW = u"Shadow"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWCOLOR = u"ShadowColor"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWXDIST = u"ShadowXDistance"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWYDIST = u"ShadowYDistance"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWSIZEX = u"ShadowSizeX"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWSIZEY = u"ShadowSizeY"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWTRANSPARENCE = u"ShadowTransparence"; +inline constexpr OUStringLiteral UNO_NAME_SHADOWBLUR = u"ShadowBlur"; + +inline constexpr OUStringLiteral UNO_NAME_EDGERADIUS = u"CornerRadius"; + +inline constexpr OUStringLiteral UNO_NAME_TEXT_MINFRAMEHEIGHT = u"TextMinimumFrameHeight"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_AUTOGROWHEIGHT = u"TextAutoGrowHeight"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_FITTOSIZE = u"TextFitToSize"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_LEFTDIST = u"TextLeftDistance"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_RIGHTDIST = u"TextRightDistance"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_UPPERDIST = u"TextUpperDistance"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_LOWERDIST = u"TextLowerDistance"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_VERTADJUST = u"TextVerticalAdjust"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_MAXFRAMEHEIGHT = u"TextMaximumFrameHeight"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_MINFRAMEWIDTH = u"TextMinimumFrameWidth"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_MAXFRAMEWIDTH = u"TextMaximumFrameWidth"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_AUTOGROWWIDTH = u"TextAutoGrowWidth"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_HORZADJUST = u"TextHorizontalAdjust"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANIKIND = u"TextAnimationKind"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANIDIRECTION = u"TextAnimationDirection"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANISTARTINSIDE = u"TextAnimationStartInside"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANISTOPINSIDE = u"TextAnimationStopInside"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANICOUNT = u"TextAnimationCount"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANIDELAY = u"TextAnimationDelay"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_ANIAMOUNT = u"TextAnimationAmount"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_CONTOURFRAME = u"TextContourFrame"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_WRITINGMODE = u"TextWritingMode"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_FONTINDEPENDENTLINESPACING = u"FontIndependentLineSpacing"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_WORDWRAP = u"TextWordWrap"; +inline constexpr OUStringLiteral UNO_NAME_TEXT_CHAINNEXTNAME = u"TextChainNextName"; + +inline constexpr OUStringLiteral UNO_NAME_MEASUREKIND = u"MeasureKind"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTHPOS = u"MeasureTextHorizontalPosition"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTVPOS = u"MeasureTextVerticalPosition"; +inline constexpr OUStringLiteral UNO_NAME_MEASURELINEDIST = u"MeasureLineDistance"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREHELPLINEOVERHANG = u"MeasureHelpLineOverhang"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREHELPLINEDIST = u"MeasureHelpLineDistance"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREHELPLINE1LEN = u"MeasureHelpLine1Length"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREHELPLINE2LEN = u"MeasureHelpLine2Length"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREBELOWREFEDGE = u"MeasureBelowReferenceEdge"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTROTA90 = u"MeasureTextRotate90"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTUPSIDEDOWN = u"MeasureTextUpsideDown"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREOVERHANG = u"MeasureOverhang"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREUNIT = u"MeasureUnit"; +inline constexpr OUStringLiteral UNO_NAME_MEASURESHOWUNIT = u"MeasureShowUnit"; +inline constexpr OUStringLiteral UNO_NAME_MEASUREFORMATSTRING = u"MeasureFormatString"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTAUTOANGLE = u"MeasureTextAutoAngle"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTAUTOANGLEVIEW = u"MeasureTextAutoAngleView"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTISFIXEDANGLE = u"MeasureTextIsFixedAngle"; +inline constexpr OUStringLiteral UNO_NAME_MEASURETEXTFIXEDANGLE = u"MeasureTextFixedAngle"; + +inline constexpr OUStringLiteral UNO_NAME_CIRCKIND = u"CircleKind"; +inline constexpr OUStringLiteral UNO_NAME_CIRCSTARTANGLE = u"CircleStartAngle"; +inline constexpr OUStringLiteral UNO_NAME_CIRCENDANGLE = u"CircleEndAngle"; + +inline constexpr OUStringLiteral UNO_NAME_POLYGONKIND = u"PolygonKind"; +inline constexpr OUStringLiteral UNO_NAME_POLYPOLYGON = u"PolyPolygon"; +inline constexpr OUStringLiteral UNO_NAME_POLYPOLYGONBEZIER = u"PolyPolygonBezier"; +inline constexpr OUStringLiteral UNO_NAME_POLYGON = u"Polygon"; + +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_INTEROPGRABBAG = u"InteropGrabBag"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_ZORDER = u"ZOrder"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_MOVEPROTECT = u"MoveProtect"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_SIZEPROTECT = u"SizeProtect"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_PRINTABLE = u"Printable"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_LAYERID = u"LayerID"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_LAYERNAME = u"LayerName"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_NAME = u"Name"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_ROTATEANGLE = u"RotateAngle"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_SHEARANGLE = u"ShearAngle"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_FRAMERECT = u"FrameRect"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_BOUNDRECT = u"BoundRect"; + +// #i68101# +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_TITLE = u"Title"; +inline constexpr OUStringLiteral UNO_NAME_MISC_OBJ_DESCRIPTION = u"Description"; + +inline constexpr OUStringLiteral UNO_NAME_HYPERLINK = u"Hyperlink"; + +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_FILLBITMAP = u"GraphicObjectFillBitmap"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_REPLACEMENT_GRAPHIC = u"ReplacementGraphic"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_GRAFSTREAMURL = u"GraphicStreamURL"; +#define UNO_NAME_GRAPHOBJ_URLPKGPREFIX "vnd.sun.star.Package:" +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_GRAPHIC = u"Graphic"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_GRAPHIC_URL = u"GraphicURL"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_IS_SIGNATURELINE = u"IsSignatureLine"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_ID = u"SignatureLineId"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_SUGGESTED_SIGNER_NAME = u"SignatureLineSuggestedSignerName"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_SUGGESTED_SIGNER_TITLE = u"SignatureLineSuggestedSignerTitle"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_SUGGESTED_SIGNER_EMAIL = u"SignatureLineSuggestedSignerEmail"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_SIGNING_INSTRUCTIONS = u"SignatureLineSigningInstructions"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_SHOW_SIGN_DATE = u"SignatureLineShowSignDate"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_CAN_ADD_COMMENT = u"SignatureLineCanAddComment"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_UNSIGNED_IMAGE = u"SignatureLineUnsignedImage"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_SIGNATURELINE_IS_SIGNED = u"SignatureLineIsSigned"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHOBJ_QRCODE = u"BarCodeProperties"; + +inline constexpr OUStringLiteral UNO_NAME_OLE2_METAFILE = u"MetaFile"; +inline constexpr OUStringLiteral UNO_NAME_OLE2_PERSISTNAME = u"PersistName"; + +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_PERSPECTIVE = u"D3DScenePerspective"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_DISTANCE = u"D3DSceneDistance"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_FOCAL_LENGTH = u"D3DSceneFocalLength"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_TWO_SIDED_LIGHTING = u"D3DSceneTwoSidedLighting"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_1 = u"D3DSceneLightColor1"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_2 = u"D3DSceneLightColor2"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_3 = u"D3DSceneLightColor3"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_4 = u"D3DSceneLightColor4"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_5 = u"D3DSceneLightColor5"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_6 = u"D3DSceneLightColor6"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_7 = u"D3DSceneLightColor7"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTCOLOR_8 = u"D3DSceneLightColor8"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_1 = u"D3DSceneLightOn1"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_2 = u"D3DSceneLightOn2"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_3 = u"D3DSceneLightOn3"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_4 = u"D3DSceneLightOn4"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_5 = u"D3DSceneLightOn5"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_6 = u"D3DSceneLightOn6"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_7 = u"D3DSceneLightOn7"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTON_8 = u"D3DSceneLightOn8"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_1 = u"D3DSceneLightDirection1"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_2 = u"D3DSceneLightDirection2"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_3 = u"D3DSceneLightDirection3"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_4 = u"D3DSceneLightDirection4"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_5 = u"D3DSceneLightDirection5"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_6 = u"D3DSceneLightDirection6"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_7 = u"D3DSceneLightDirection7"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_LIGHTDIRECTION_8 = u"D3DSceneLightDirection8"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_AMBIENTCOLOR = u"D3DSceneAmbientColor"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_SHADOW_SLANT = u"D3DSceneShadowSlant"; +inline constexpr OUStringLiteral UNO_NAME_3D_SCENE_SHADE_MODE = u"D3DSceneShadeMode"; + +inline constexpr OUStringLiteral UNO_NAME_3D_DOUBLE_SIDED = u"D3DDoubleSided"; +inline constexpr OUStringLiteral UNO_NAME_3D_NORMALS_KIND = u"D3DNormalsKind"; +inline constexpr OUStringLiteral UNO_NAME_3D_NORMALS_INVERT = u"D3DNormalsInvert"; +inline constexpr OUStringLiteral UNO_NAME_3D_TEXTURE_PROJ_X = u"D3DTextureProjectionX"; +inline constexpr OUStringLiteral UNO_NAME_3D_TEXTURE_PROJ_Y = u"D3DTextureProjectionY"; +inline constexpr OUStringLiteral UNO_NAME_3D_SHADOW_3D = u"D3DShadow3D"; +inline constexpr OUStringLiteral UNO_NAME_3D_MAT_COLOR = u"D3DMaterialColor"; +inline constexpr OUStringLiteral UNO_NAME_3D_MAT_EMISSION = u"D3DMaterialEmission"; +inline constexpr OUStringLiteral UNO_NAME_3D_MAT_SPECULAR = u"D3DMaterialSpecular"; +inline constexpr OUStringLiteral UNO_NAME_3D_MAT_SPECULAR_INTENSITY = u"D3DMaterialSpecularIntensity"; +inline constexpr OUStringLiteral UNO_NAME_3D_TEXTURE_KIND = u"D3DTextureKind"; +inline constexpr OUStringLiteral UNO_NAME_3D_TEXTURE_MODE = u"D3DTextureMode"; +inline constexpr OUStringLiteral UNO_NAME_3D_TEXTURE_FILTER = u"D3DTextureFilter"; + +// #i28528# +// Added extra Item (Bool) for chart2 to be able to show reduced line geometry +inline constexpr OUStringLiteral UNO_NAME_3D_REDUCED_LINE_GEOMETRY = u"D3DReducedLineGeometry"; + +inline constexpr OUStringLiteral UNO_NAME_3D_HORZ_SEGS = u"D3DHorizontalSegments"; +inline constexpr OUStringLiteral UNO_NAME_3D_VERT_SEGS = u"D3DVerticalSegments"; + +inline constexpr OUStringLiteral UNO_NAME_3D_PERCENT_DIAGONAL = u"D3DPercentDiagonal"; +inline constexpr OUStringLiteral UNO_NAME_3D_BACKSCALE = u"D3DBackscale"; +inline constexpr OUStringLiteral UNO_NAME_3D_LATHE_END_ANGLE = u"D3DEndAngle"; + +inline constexpr OUStringLiteral UNO_NAME_3D_EXTRUDE_DEPTH = u"D3DDepth"; + +inline constexpr OUStringLiteral UNO_NAME_3D_TRANSFORM_MATRIX = u"D3DTransformMatrix"; +inline constexpr OUStringLiteral UNO_NAME_3D_CAMERA_GEOMETRY = u"D3DCameraGeometry"; +inline constexpr OUStringLiteral UNO_NAME_3D_POS = u"D3DPosition"; +inline constexpr OUStringLiteral UNO_NAME_3D_SIZE = u"D3DSize"; +inline constexpr OUStringLiteral UNO_NAME_3D_POS_IS_CENTER = u"D3DPositionIsCenter"; +inline constexpr OUStringLiteral UNO_NAME_3D_POLYPOLYGON3D = u"D3DPolyPolygon3D"; +inline constexpr OUStringLiteral UNO_NAME_3D_NORMALSPOLYGON3D = u"D3DNormalsPolygon3D"; +inline constexpr OUStringLiteral UNO_NAME_3D_TEXTUREPOLYGON3D = u"D3DTexturePolygon3D"; +inline constexpr OUStringLiteral UNO_NAME_3D_LINEONLY = u"D3DLineOnly"; + +// New 3D properties which are possible for lathe and extrude 3d objects +inline constexpr OUStringLiteral UNO_NAME_3D_SMOOTH_NORMALS = u"D3DSmoothNormals"; +inline constexpr OUStringLiteral UNO_NAME_3D_SMOOTH_LIDS = u"D3DSmoothLids"; +inline constexpr OUStringLiteral UNO_NAME_3D_CHARACTER_MODE = u"D3DCharacterMode"; +inline constexpr OUStringLiteral UNO_NAME_3D_CLOSE_FRONT = u"D3DCloseFront"; +inline constexpr OUStringLiteral UNO_NAME_3D_CLOSE_BACK = u"D3DCloseBack"; + +inline constexpr OUStringLiteral UNO_NAME_NUMBERING = u"NumberingIsNumber"; +inline constexpr OUStringLiteral UNO_NAME_NUMBERING_RULES = u"NumberingRules"; +inline constexpr OUStringLiteral UNO_NAME_NUMBERING_LEVEL = u"NumberingLevel"; + +inline constexpr OUStringLiteral UNO_NAME_NRULE_NUMBERINGTYPE = u"NumberingType"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_PREFIX = u"Prefix"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_SUFFIX = u"Suffix"; +#define UNO_NAME_NRULE_BULLETID "BulletId" +inline constexpr OUStringLiteral UNO_NAME_NRULE_BULLET_COLOR = u"BulletColor"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_BULLET_RELSIZE = u"BulletRelSize"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_BULLET_FONT = u"BulletFont"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_START_WITH = u"StartWith"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_LEFT_MARGIN = u"LeftMargin"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_FIRST_LINE_OFFSET = u"FirstLineOffset"; +inline constexpr OUStringLiteral UNO_NAME_NRULE_ADJUST = u"Adjust"; + +inline constexpr OUStringLiteral UNO_NAME_EDIT_FONT_DESCRIPTOR = u"FontDescriptor"; + +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_ADJUST = u"ParaAdjust"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_BMARGIN = u"ParaBottomMargin"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_LASTLINEADJ = u"ParaLastLineAdjust"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_LMARGIN = u"ParaLeftMargin"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_LINESPACING = u"ParaLineSpacing"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_RMARGIN = u"ParaRightMargin"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_TAPSTOPS = u"ParaTabStops"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_TMARGIN = u"ParaTopMargin"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_IS_HYPHEN = u"ParaIsHyphenation"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_IS_HANGING_PUNCTUATION = u"ParaIsHangingPunctuation"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_IS_CHARACTER_DISTANCE = u"ParaIsCharacterDistance"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_IS_FORBIDDEN_RULES = u"ParaIsForbiddenRules"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_PARA_FIRST_LINE_INDENT = u"ParaFirstLineIndent"; + +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_HEIGHT = u"CharHeight"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTNAME = u"CharFontName"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTSTYLENAME = u"CharFontStyleName"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTFAMILY = u"CharFontFamily"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTCHARSET = u"CharFontCharSet"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTPITCH = u"CharFontPitch"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_POSTURE = u"CharPosture"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_WEIGHT = u"CharWeight"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_LOCALE = u"CharLocale"; + +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_HEIGHT_ASIAN = u"CharHeightAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTNAME_ASIAN = u"CharFontNameAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTSTYLENAME_ASIAN = u"CharFontStyleNameAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTFAMILY_ASIAN = u"CharFontFamilyAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTCHARSET_ASIAN = u"CharFontCharSetAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTPITCH_ASIAN = u"CharFontPitchAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_POSTURE_ASIAN = u"CharPostureAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_WEIGHT_ASIAN = u"CharWeightAsian"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_LOCALE_ASIAN = u"CharLocaleAsian"; + +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_HEIGHT_COMPLEX = u"CharHeightComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTNAME_COMPLEX = u"CharFontNameComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTSTYLENAME_COMPLEX = u"CharFontStyleNameComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTFAMILY_COMPLEX = u"CharFontFamilyComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTCHARSET_COMPLEX = u"CharFontCharSetComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_FONTPITCH_COMPLEX = u"CharFontPitchComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_POSTURE_COMPLEX = u"CharPostureComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_WEIGHT_COMPLEX = u"CharWeightComplex"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_LOCALE_COMPLEX = u"CharLocaleComplex"; + +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_COLOR = u"CharColor"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_COLOR_THEME = u"CharColorTheme"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_COLOR_TINT_OR_SHADE = u"CharColorTintOrShade"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_COLOR_LUM_MOD = u"CharColorLumMod"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_COLOR_LUM_OFF = u"CharColorLumOff"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_TRANSPARENCE = u"CharTransparence"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_CROSSEDOUT = u"CharCrossedOut"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_STRIKEOUT = u"CharStrikeout"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_CASEMAP = u"CharCaseMap"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_ESCAPEMENT = u"CharEscapement"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_SHADOWED = u"CharShadowed"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_UNDERLINE = u"CharUnderline"; +inline constexpr OUStringLiteral UNO_NAME_EDIT_CHAR_OVERLINE = u"CharOverline"; + +inline constexpr OUStringLiteral UNO_NAME_BITMAP = u"Bitmap"; + +inline constexpr OUStringLiteral UNO_NAME_LINKDISPLAYNAME = u"LinkDisplayName"; +inline constexpr OUStringLiteral UNO_NAME_LINKDISPLAYBITMAP = u"LinkDisplayBitmap"; + +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_LUMINANCE = u"AdjustLuminance"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_CONTRAST = u"AdjustContrast"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_RED = u"AdjustRed"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_GREEN = u"AdjustGreen"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_BLUE = u"AdjustBlue"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_GAMMA = u"Gamma"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_TRANSPARENCY = u"Transparency"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_COLOR_MODE = u"GraphicColorMode"; +inline constexpr OUStringLiteral UNO_NAME_GRAPHIC_GRAPHICCROP = u"GraphicCrop"; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unotext.hxx b/include/editeng/unotext.hxx new file mode 100644 index 000000000..3c8f95368 --- /dev/null +++ b/include/editeng/unotext.hxx @@ -0,0 +1,677 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOTEXT_HXX +#define INCLUDED_EDITENG_UNOTEXT_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SvxItemPropertySet; +struct SfxItemPropertyMapEntry; + +#define WID_FONTDESC OWN_ATTR_VALUE_START +#define WID_NUMLEVEL OWN_ATTR_VALUE_START+1 +#define WID_PORTIONTYPE OWN_ATTR_VALUE_START+2 +#define WID_NUMBERINGSTARTVALUE OWN_ATTR_VALUE_START+3 +#define WID_PARAISNUMBERINGRESTART OWN_ATTR_VALUE_START+4 + +#define SVX_UNOEDIT_NUMBERING_PROPERTY \ + { UNO_NAME_NUMBERING_RULES, EE_PARA_NUMBULLET, cppu::UnoType::get(), 0, 0 }, \ + { UNO_NAME_NUMBERING, EE_PARA_BULLETSTATE,cppu::UnoType::get(), 0, 0 } + +#define SVX_UNOEDIT_OUTLINER_PROPERTIES \ + SVX_UNOEDIT_NUMBERING_PROPERTY, \ + { UNO_NAME_NUMBERING_LEVEL, WID_NUMLEVEL, ::cppu::UnoType::get(), 0, 0 }, \ + {u"NumberingStartValue", WID_NUMBERINGSTARTVALUE, ::cppu::UnoType::get(), 0, 0 }, \ + {u"ParaIsNumberingRestart", WID_PARAISNUMBERINGRESTART, cppu::UnoType::get(), 0, 0 } + +#define SVX_UNOEDIT_CHAR_PROPERTIES \ + { UNO_NAME_EDIT_CHAR_HEIGHT, EE_CHAR_FONTHEIGHT, cppu::UnoType::get(), 0, MID_FONTHEIGHT|CONVERT_TWIPS }, \ + { u"CharScaleWidth", EE_CHAR_FONTWIDTH, ::cppu::UnoType::get(), 0, 0 }, \ + { UNO_NAME_EDIT_CHAR_FONTNAME, EE_CHAR_FONTINFO, ::cppu::UnoType::get(), 0, MID_FONT_FAMILY_NAME },\ + { UNO_NAME_EDIT_CHAR_FONTSTYLENAME,EE_CHAR_FONTINFO, ::cppu::UnoType::get(), 0, MID_FONT_STYLE_NAME }, \ + { UNO_NAME_EDIT_CHAR_FONTFAMILY, EE_CHAR_FONTINFO, ::cppu::UnoType::get(), 0, MID_FONT_FAMILY }, \ + { UNO_NAME_EDIT_CHAR_FONTCHARSET, EE_CHAR_FONTINFO, ::cppu::UnoType::get(), 0, MID_FONT_CHAR_SET }, \ + { UNO_NAME_EDIT_CHAR_FONTPITCH, EE_CHAR_FONTINFO, ::cppu::UnoType::get(), 0, MID_FONT_PITCH }, \ + { UNO_NAME_EDIT_CHAR_POSTURE, EE_CHAR_ITALIC, ::cppu::UnoType::get(),0, MID_POSTURE }, \ + { UNO_NAME_EDIT_CHAR_WEIGHT, EE_CHAR_WEIGHT, cppu::UnoType::get(), 0, MID_WEIGHT }, \ + { UNO_NAME_EDIT_CHAR_LOCALE, EE_CHAR_LANGUAGE, ::cppu::UnoType::get(),0, MID_LANG_LOCALE }, \ + { UNO_NAME_EDIT_CHAR_COLOR, EE_CHAR_COLOR, ::cppu::UnoType::get(), 0, MID_COLOR_RGB }, \ + { UNO_NAME_EDIT_CHAR_TRANSPARENCE,EE_CHAR_COLOR, ::cppu::UnoType::get(), 0, MID_COLOR_ALPHA }, \ + { UNO_NAME_EDIT_CHAR_COLOR_THEME, EE_CHAR_COLOR, ::cppu::UnoType::get(), 0, MID_COLOR_THEME_INDEX }, \ + { UNO_NAME_EDIT_CHAR_COLOR_TINT_OR_SHADE, EE_CHAR_COLOR, ::cppu::UnoType::get(), 0, MID_COLOR_TINT_OR_SHADE }, \ + { UNO_NAME_EDIT_CHAR_COLOR_LUM_MOD, EE_CHAR_COLOR, ::cppu::UnoType::get(), 0, MID_COLOR_LUM_MOD }, \ + { UNO_NAME_EDIT_CHAR_COLOR_LUM_OFF, EE_CHAR_COLOR, ::cppu::UnoType::get(), 0, MID_COLOR_LUM_OFF }, \ + { u"CharBackColor", EE_CHAR_BKGCOLOR, ::cppu::UnoType::get(), 0, 0 }, \ + { u"CharBackTransparent", EE_CHAR_BKGCOLOR, ::cppu::UnoType::get(), 0, MID_GRAPHIC_TRANSPARENT }, \ + { UNO_NAME_EDIT_CHAR_ESCAPEMENT, EE_CHAR_ESCAPEMENT, ::cppu::UnoType::get(), 0, MID_ESC }, \ + { UNO_NAME_EDIT_CHAR_UNDERLINE, EE_CHAR_UNDERLINE, ::cppu::UnoType::get(), 0, MID_TL_STYLE }, \ + { u"CharUnderlineColor", EE_CHAR_UNDERLINE, ::cppu::UnoType::get(), 0, MID_TL_COLOR }, \ + { u"CharUnderlineHasColor", EE_CHAR_UNDERLINE, cppu::UnoType::get(), 0, MID_TL_HASCOLOR } , \ + { UNO_NAME_EDIT_CHAR_OVERLINE, EE_CHAR_OVERLINE, ::cppu::UnoType::get(), 0, MID_TL_STYLE }, \ + { u"CharOverlineColor", EE_CHAR_OVERLINE, ::cppu::UnoType::get(), 0, MID_TL_COLOR }, \ + { u"CharOverlineHasColor", EE_CHAR_OVERLINE, cppu::UnoType::get(), 0, MID_TL_HASCOLOR } , \ + { UNO_NAME_EDIT_CHAR_CROSSEDOUT, EE_CHAR_STRIKEOUT, cppu::UnoType::get(), 0, MID_CROSSED_OUT }, \ + { UNO_NAME_EDIT_CHAR_STRIKEOUT, EE_CHAR_STRIKEOUT, ::cppu::UnoType::get(), 0, MID_CROSS_OUT}, \ + { UNO_NAME_EDIT_CHAR_CASEMAP, EE_CHAR_CASEMAP, ::cppu::UnoType::get(), 0, 0 }, \ + { UNO_NAME_EDIT_CHAR_SHADOWED, EE_CHAR_SHADOW, cppu::UnoType::get(), 0, 0 }, \ + { u"CharContoured", EE_CHAR_OUTLINE, cppu::UnoType::get(), 0, 0 }, \ + { u"CharEscapementHeight", EE_CHAR_ESCAPEMENT, cppu::UnoType::get(), 0, MID_ESC_HEIGHT },\ + { u"CharAutoKerning", EE_CHAR_PAIRKERNING,cppu::UnoType::get(), 0, 0 } , \ + { u"CharKerning", EE_CHAR_KERNING, ::cppu::UnoType::get() , 0, 0 }, \ + { u"CharWordMode", EE_CHAR_WLM, cppu::UnoType::get(), 0, 0 }, \ + { u"CharEmphasis", EE_CHAR_EMPHASISMARK, ::cppu::UnoType::get(), 0, MID_EMPHASIS},\ + { UNO_NAME_EDIT_CHAR_HEIGHT_ASIAN, EE_CHAR_FONTHEIGHT_CJK, cppu::UnoType::get(), 0, MID_FONTHEIGHT|CONVERT_TWIPS }, \ + { UNO_NAME_EDIT_CHAR_FONTNAME_ASIAN, EE_CHAR_FONTINFO_CJK, ::cppu::UnoType::get(), 0, MID_FONT_FAMILY_NAME },\ + { UNO_NAME_EDIT_CHAR_FONTSTYLENAME_ASIAN, EE_CHAR_FONTINFO_CJK, ::cppu::UnoType::get(), 0, MID_FONT_STYLE_NAME }, \ + { UNO_NAME_EDIT_CHAR_FONTFAMILY_ASIAN, EE_CHAR_FONTINFO_CJK, ::cppu::UnoType::get(), 0, MID_FONT_FAMILY }, \ + { UNO_NAME_EDIT_CHAR_FONTCHARSET_ASIAN, EE_CHAR_FONTINFO_CJK, ::cppu::UnoType::get(), 0, MID_FONT_CHAR_SET }, \ + { UNO_NAME_EDIT_CHAR_FONTPITCH_ASIAN, EE_CHAR_FONTINFO_CJK, ::cppu::UnoType::get(), 0, MID_FONT_PITCH }, \ + { UNO_NAME_EDIT_CHAR_POSTURE_ASIAN, EE_CHAR_ITALIC_CJK, ::cppu::UnoType::get(),0, MID_POSTURE }, \ + { UNO_NAME_EDIT_CHAR_WEIGHT_ASIAN, EE_CHAR_WEIGHT_CJK, cppu::UnoType::get(), 0, MID_WEIGHT }, \ + { UNO_NAME_EDIT_CHAR_LOCALE_ASIAN, EE_CHAR_LANGUAGE_CJK, ::cppu::UnoType::get(),0, MID_LANG_LOCALE }, \ + { UNO_NAME_EDIT_CHAR_HEIGHT_COMPLEX, EE_CHAR_FONTHEIGHT_CTL, cppu::UnoType::get(), 0, MID_FONTHEIGHT|CONVERT_TWIPS }, \ + { UNO_NAME_EDIT_CHAR_FONTNAME_COMPLEX, EE_CHAR_FONTINFO_CTL, ::cppu::UnoType::get(), 0, MID_FONT_FAMILY_NAME },\ + { UNO_NAME_EDIT_CHAR_FONTSTYLENAME_COMPLEX,EE_CHAR_FONTINFO_CTL, ::cppu::UnoType::get(), 0, MID_FONT_STYLE_NAME }, \ + { UNO_NAME_EDIT_CHAR_FONTFAMILY_COMPLEX, EE_CHAR_FONTINFO_CTL, ::cppu::UnoType::get(), 0, MID_FONT_FAMILY }, \ + { UNO_NAME_EDIT_CHAR_FONTCHARSET_COMPLEX, EE_CHAR_FONTINFO_CTL, ::cppu::UnoType::get(), 0, MID_FONT_CHAR_SET }, \ + { UNO_NAME_EDIT_CHAR_FONTPITCH_COMPLEX, EE_CHAR_FONTINFO_CTL, ::cppu::UnoType::get(), 0, MID_FONT_PITCH }, \ + { UNO_NAME_EDIT_CHAR_POSTURE_COMPLEX, EE_CHAR_ITALIC_CTL, ::cppu::UnoType::get(),0, MID_POSTURE }, \ + { UNO_NAME_EDIT_CHAR_WEIGHT_COMPLEX, EE_CHAR_WEIGHT_CTL, cppu::UnoType::get(), 0, MID_WEIGHT }, \ + { UNO_NAME_EDIT_CHAR_LOCALE_COMPLEX, EE_CHAR_LANGUAGE_CTL, ::cppu::UnoType::get(),0, MID_LANG_LOCALE }, \ + { u"CharRelief", EE_CHAR_RELIEF, ::cppu::UnoType::get(), 0, MID_RELIEF }, \ + { u"CharInteropGrabBag", EE_CHAR_GRABBAG, cppu::UnoType>::get(), 0, 0} + + +#define SVX_UNOEDIT_FONT_PROPERTIES \ + { UNO_NAME_EDIT_FONT_DESCRIPTOR, WID_FONTDESC, cppu::UnoType::get(), 0, MID_FONT_FAMILY_NAME } + +#define SVX_UNOEDIT_PARA_PROPERTIES \ + { UNO_NAME_EDIT_PARA_ADJUST, EE_PARA_JUST, ::cppu::UnoType::get(), 0, MID_PARA_ADJUST }, \ + { UNO_NAME_EDIT_PARA_BMARGIN, EE_PARA_ULSPACE, ::cppu::UnoType::get(), 0, MID_LO_MARGIN, PropertyMoreFlags::METRIC_ITEM }, \ + { UNO_NAME_EDIT_PARA_IS_HYPHEN, EE_PARA_HYPHENATE, ::cppu::UnoType::get(), 0, 0 }, \ + {u"ParaHyphenationNoCaps", EE_PARA_HYPHENATE_NO_CAPS, ::cppu::UnoType::get(), 0, 0 }, \ + {u"ParaHyphenationNoLastWord", EE_PARA_HYPHENATE_NO_LAST_WORD, ::cppu::UnoType::get(), 0, 0 }, \ + { UNO_NAME_EDIT_PARA_LASTLINEADJ, EE_PARA_JUST, ::cppu::UnoType::get(), 0, MID_LAST_LINE_ADJUST }, \ + { UNO_NAME_EDIT_PARA_LMARGIN, EE_PARA_LRSPACE, ::cppu::UnoType::get(), 0, MID_TXT_LMARGIN, PropertyMoreFlags::METRIC_ITEM }, \ + { UNO_NAME_EDIT_PARA_LINESPACING, EE_PARA_SBL, cppu::UnoType::get(), 0, CONVERT_TWIPS}, \ + { UNO_NAME_EDIT_PARA_RMARGIN, EE_PARA_LRSPACE, ::cppu::UnoType::get(), 0, MID_R_MARGIN, PropertyMoreFlags::METRIC_ITEM }, \ + { UNO_NAME_EDIT_PARA_TAPSTOPS, EE_PARA_TABS, cppu::UnoType>::get(), 0, 0 }, \ + { UNO_NAME_EDIT_PARA_TMARGIN, EE_PARA_ULSPACE, ::cppu::UnoType::get(), 0, MID_UP_MARGIN, PropertyMoreFlags::METRIC_ITEM },\ + { UNO_NAME_EDIT_PARA_FIRST_LINE_INDENT, EE_PARA_LRSPACE, ::cppu::UnoType::get(), 0, MID_FIRST_LINE_INDENT, PropertyMoreFlags::METRIC_ITEM}, \ + { UNO_NAME_EDIT_PARA_IS_HANGING_PUNCTUATION,EE_PARA_HANGINGPUNCTUATION, cppu::UnoType::get(), 0 ,0 }, \ + { UNO_NAME_EDIT_PARA_IS_CHARACTER_DISTANCE, EE_PARA_ASIANCJKSPACING, cppu::UnoType::get(), 0 ,0 }, \ + { UNO_NAME_EDIT_PARA_IS_FORBIDDEN_RULES, EE_PARA_FORBIDDENRULES, cppu::UnoType::get(), 0 ,0 },\ + {u"WritingMode", EE_PARA_WRITINGDIR, ::cppu::UnoType::get(), 0, 0 } + +class SvxFieldItem; +class SvxFieldData; + +EDITENG_DLLPUBLIC void GetSelection( struct ESelection& rSel, SvxTextForwarder const * pForwarder ) noexcept; +EDITENG_DLLPUBLIC void CheckSelection( struct ESelection& rSel, SvxTextForwarder const * pForwarder ) noexcept; + + +// This class implements a SvxEditSource and SvxTextForwarder and does +// nothing otherwise + + +class SvxDummyTextSource final : public SvxEditSource, public SvxTextForwarder +{ +public: + + // SvxEditSource + virtual ~SvxDummyTextSource() override; + virtual std::unique_ptr Clone() const override; + virtual SvxTextForwarder* GetTextForwarder() override; + virtual void UpdateData() override; + + // SvxTextForwarder + virtual sal_Int32 GetParagraphCount() const override; + virtual sal_Int32 GetTextLen( sal_Int32 nParagraph ) const override; + virtual OUString GetText( const ESelection& rSel ) const override; + virtual SfxItemSet GetAttribs( const ESelection& rSel, EditEngineAttribs nOnlyHardAttrib = EditEngineAttribs::All ) const override; + virtual SfxItemSet GetParaAttribs( sal_Int32 nPara ) const override; + virtual void SetParaAttribs( sal_Int32 nPara, const SfxItemSet& rSet ) override; + virtual void RemoveAttribs( const ESelection& rSelection ) override; + virtual void GetPortions( sal_Int32 nPara, std::vector& rList ) const override; + + SfxItemState GetItemState( const ESelection& rSel, sal_uInt16 nWhich ) const override; + SfxItemState GetItemState( sal_Int32 nPara, sal_uInt16 nWhich ) const override; + + virtual SfxItemPool* GetPool() const override; + + virtual void QuickInsertText( const OUString& rText, const ESelection& rSel ) override; + virtual void QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel ) override; + virtual void QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel ) override; + virtual void QuickInsertLineBreak( const ESelection& rSel ) override; + + virtual OUString CalcFieldValue( const SvxFieldItem& rField, sal_Int32 nPara, sal_Int32 nPos, std::optional& rpTxtColor, std::optional& rpFldColor ) override; + virtual void FieldClicked( const SvxFieldItem& rField ) override; + + virtual bool IsValid() const override; + + virtual LanguageType GetLanguage( sal_Int32, sal_Int32 ) const override; + virtual sal_Int32 GetFieldCount( sal_Int32 nPara ) const override; + virtual EFieldInfo GetFieldInfo( sal_Int32 nPara, sal_uInt16 nField ) const override; + virtual EBulletInfo GetBulletInfo( sal_Int32 nPara ) const override; + virtual tools::Rectangle GetCharBounds( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual tools::Rectangle GetParaBounds( sal_Int32 nPara ) const override; + virtual MapMode GetMapMode() const override; + virtual OutputDevice* GetRefDevice() const override; + virtual bool GetIndexAtPoint( const Point&, sal_Int32& nPara, sal_Int32& nIndex ) const override; + virtual bool GetWordIndices( sal_Int32 nPara, sal_Int32 nIndex, sal_Int32& nStart, sal_Int32& nEnd ) const override; + virtual bool GetAttributeRun( sal_Int32& nStartIndex, sal_Int32& nEndIndex, sal_Int32 nPara, sal_Int32 nIndex, bool bInCell = false ) const override; + virtual sal_Int32 GetLineCount( sal_Int32 nPara ) const override; + virtual sal_Int32 GetLineLen( sal_Int32 nPara, sal_Int32 nLine ) const override; + virtual void GetLineBoundaries( /*out*/sal_Int32 &rStart, /*out*/sal_Int32 &rEnd, sal_Int32 nParagraph, sal_Int32 nLine ) const override; + virtual sal_Int32 GetLineNumberAtIndex( sal_Int32 nPara, sal_Int32 nIndex ) const override; + virtual bool Delete( const ESelection& ) override; + virtual bool InsertText( const OUString&, const ESelection& ) override; + virtual bool QuickFormatDoc( bool bFull = false ) override; + virtual sal_Int16 GetDepth( sal_Int32 nPara ) const override; + virtual bool SetDepth( sal_Int32 nPara, sal_Int16 nNewDepth ) override; + + virtual const SfxItemSet* GetEmptyItemSetPtr() override; + + // implementation functions for XParagraphAppend and XTextPortionAppend + virtual void AppendParagraph() override; + virtual sal_Int32 AppendTextPortion( sal_Int32 nPara, const OUString &rText, const SfxItemSet &rSet ) override; + //XTextCopy + virtual void CopyText(const SvxTextForwarder& rSource) override; +}; + +namespace accessibility +{ + class AccessibleEditableTextPara; +} + + +class EDITENG_DLLPUBLIC SvxUnoTextRangeBase : public css::text::XTextRange, + public css::beans::XPropertySet, + public css::beans::XMultiPropertySet, + public css::beans::XMultiPropertyStates, + public css::beans::XPropertyState, + public css::lang::XServiceInfo, + public css::text::XTextRangeCompare, + public css::lang::XUnoTunnel, + private osl::DebugBase + +{ + friend class SvxUnoTextRangeEnumeration; + friend class ::accessibility::AccessibleEditableTextPara; + const SvxItemPropertySet* mpPropSet; + +protected: + std::unique_ptr mpEditSource; + ESelection maSelection; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + void _setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue, sal_Int32 nPara = -1 ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + css::uno::Any _getPropertyValue( const OUString& PropertyName, sal_Int32 nPara = -1 ); + + /// @throws css::beans::PropertyVetoException + /// @throws css::lang::IllegalArgumentException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + void _setPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Sequence< css::uno::Any >& aValues, sal_Int32 nPara = -1 ); + /// @throws css::uno::RuntimeException + css::uno::Sequence< css::uno::Any > _getPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, sal_Int32 nPara = -1 ); + + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + css::beans::PropertyState _getPropertyState( const SfxItemPropertyMapEntry* pMap, sal_Int32 nPara = -1 ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + css::beans::PropertyState _getPropertyState( std::u16string_view PropertyName, sal_Int32 nPara = -1 ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + css::uno::Sequence< css::beans::PropertyState > _getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName, sal_Int32 nPara = -1 ); + // returns true if property found or false if unknown property + static bool _getOnePropertyStates(const SfxItemSet* pSet, const SfxItemPropertyMapEntry* pMap, css::beans::PropertyState& rState); + + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + void _setPropertyToDefault( const OUString& PropertyName, sal_Int32 nPara = -1 ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + void _setPropertyToDefault( SvxTextForwarder* pForwarder, const SfxItemPropertyMapEntry* pMap, sal_Int32 nPara ); + void SetEditSource( SvxEditSource* _pEditSource ) noexcept; + + /// @throws css::beans::UnknownPropertyException + /// @throws css::uno::RuntimeException + void getPropertyValue( const SfxItemPropertyMapEntry* pMap, css::uno::Any& rAny, const SfxItemSet& rSet ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::IllegalArgumentException + void setPropertyValue( const SfxItemPropertyMapEntry* pMap, const css::uno::Any& rValue, const ESelection& rSelection, const SfxItemSet& rOldSet, SfxItemSet& rNewSet ); + + SvxUnoTextRangeBase(const SvxItemPropertySet* _pSet); + SvxUnoTextRangeBase(const SvxEditSource* pSource, const SvxItemPropertySet* _pSet); + SvxUnoTextRangeBase(const SvxUnoTextRangeBase& rRange); + virtual ~SvxUnoTextRangeBase() noexcept; + +public: + // Internal + const ESelection& GetSelection() const noexcept + { + const SvxTextForwarder* pForwarder = mpEditSource ? mpEditSource->GetTextForwarder() : nullptr; + CheckSelection(const_cast(this)->maSelection, pForwarder); + return maSelection; + } + void SetSelection( const ESelection& rSelection ) noexcept; + + void CollapseToStart() noexcept; + void CollapseToEnd() noexcept; + bool IsCollapsed() noexcept; + bool GoLeft(sal_Int32 nCount, bool Expand) noexcept; + bool GoRight(sal_Int32 nCount, bool Expand) noexcept; + void GotoStart(bool Expand) noexcept; + void GotoEnd(bool Expand) noexcept; + + //const SfxItemPropertyMapEntry* getPropertyMapEntries() const throw() { return maPropSet.getPropertyMapEntries(); } + const SvxItemPropertySet* getPropertySet() const noexcept { return mpPropSet; } + SvxEditSource* GetEditSource() const noexcept { return mpEditSource.get(); } + + static bool SetPropertyValueHelper( const SfxItemPropertyMapEntry* pMap, const css::uno::Any& aValue, SfxItemSet& rNewSet, const ESelection* pSelection = nullptr, SvxEditSource* pEditSource = nullptr ); + /// @throws css::uno::RuntimeException + static bool GetPropertyValueHelper( SfxItemSet const & rSet, const SfxItemPropertyMapEntry* pMap, css::uno::Any& aAny, const ESelection* pSelection = nullptr, SvxEditSource* pEditSource = nullptr ); + + void attachField( std::unique_ptr pData ) noexcept; + + UNO3_GETIMPLEMENTATION_DECL( SvxUnoTextRangeBase ) + + // css::text::XTextRange + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getStart() override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getEnd() override; + virtual OUString SAL_CALL getString() override; + virtual void SAL_CALL setString( const OUString& aString ) override; + + // css::beans::XPropertySet + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override; + virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; + virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; + virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; + virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; + + // XMultiPropertySet + virtual void SAL_CALL setPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Sequence< css::uno::Any >& aValues ) override; + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames ) override; + virtual void SAL_CALL addPropertiesChangeListener( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL removePropertiesChangeListener( const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + virtual void SAL_CALL firePropertiesChangeEvent( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Reference< css::beans::XPropertiesChangeListener >& xListener ) override; + + // css::beans::XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState( const OUString& PropertyName ) override; + virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) override; + virtual void SAL_CALL setPropertyToDefault( const OUString& PropertyName ) override; + virtual css::uno::Any SAL_CALL getPropertyDefault( const OUString& aPropertyName ) override; + + // css::beans::XMultiPropertyStates + //virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) throw (css::beans::UnknownPropertyException, css::uno::RuntimeException); + virtual void SAL_CALL setAllPropertiesToDefault() override; + virtual void SAL_CALL setPropertiesToDefault( const css::uno::Sequence< OUString >& aPropertyNames ) override; + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyDefaults( const css::uno::Sequence< OUString >& aPropertyNames ) override; + + // XTextRangeCompare + virtual ::sal_Int16 SAL_CALL compareRegionStarts( const css::uno::Reference< css::text::XTextRange >& xR1, const css::uno::Reference< css::text::XTextRange >& xR2 ) override; + virtual ::sal_Int16 SAL_CALL compareRegionEnds( const css::uno::Reference< css::text::XTextRange >& xR1, const css::uno::Reference< css::text::XTextRange >& xR2 ) override; + + // css::lang::XServiceInfo + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + static css::uno::Sequence< OUString > getSupportedServiceNames_Static( ); +}; + + +class SvxUnoTextBase; +class EDITENG_DLLPUBLIC SvxUnoTextRange final : public SvxUnoTextRangeBase, + public css::lang::XTypeProvider, + public ::cppu::OWeakAggObject +{ + friend class SvxUnoTextRangeEnumeration; +private: + css::uno::Reference< css::text::XText > xParentText; + bool mbPortion; + +public: + SvxUnoTextRange(const SvxUnoTextBase& rParent, bool bPortion = false); + virtual ~SvxUnoTextRange() noexcept override; + + // css::uno::XInterface + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ) override; + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + // css::text::XTextRange + virtual css::uno::Reference< css::text::XText > SAL_CALL getText() override; + + // css::lang::XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + + // css::lang::XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; +}; + +class EDITENG_DLLPUBLIC SvxUnoTextBase : public SvxUnoTextRangeBase, + public css::text::XTextAppend, + public css::text::XTextCopy, + public css::container::XEnumerationAccess, + public css::text::XTextRangeMover, + public css::lang::XTypeProvider +{ + css::uno::Reference< css::text::XText > xParentText; + +protected: + SvxUnoTextBase(const SvxItemPropertySet* _pSet); + SvxUnoTextBase(const SvxEditSource* pSource, const SvxItemPropertySet* _pSet, css::uno::Reference < css::text::XText > const & xParent); + SvxUnoTextBase(const SvxUnoTextBase& rText); + virtual ~SvxUnoTextBase() noexcept override; + +public: + UNO3_GETIMPLEMENTATION_DECL( SvxUnoTextBase ) + + css::uno::Reference< css::text::XTextCursor > createTextCursorBySelection( const ESelection& rSel ); + + // css::uno::XInterface + /// @throws css::uno::RuntimeException + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ); + + // css::text::XSimpleText + virtual css::uno::Reference< css::text::XTextCursor > SAL_CALL createTextCursor( ) override; + virtual css::uno::Reference< css::text::XTextCursor > SAL_CALL createTextCursorByRange( const css::uno::Reference< css::text::XTextRange >& aTextPosition ) override; + virtual void SAL_CALL insertString( const css::uno::Reference< css::text::XTextRange >& xRange, const OUString& aString, sal_Bool bAbsorb ) override; + virtual void SAL_CALL insertControlCharacter( const css::uno::Reference< css::text::XTextRange >& xRange, sal_Int16 nControlCharacter, sal_Bool bAbsorb ) override; + + // css::text::XText + virtual void SAL_CALL insertTextContent( const css::uno::Reference< css::text::XTextRange >& xRange, const css::uno::Reference< css::text::XTextContent >& xContent, sal_Bool bAbsorb ) override; + virtual void SAL_CALL removeTextContent( const css::uno::Reference< css::text::XTextContent >& xContent ) override; + virtual OUString SAL_CALL getString() override; + virtual void SAL_CALL setString( const OUString& aString ) override; + + // css::text::XTextRange + virtual css::uno::Reference< css::text::XText > SAL_CALL getText( ) override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getStart() override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getEnd() override; + + // css::container::XEnumerationAccess + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration( ) override; + + // css::container::XElementAccess + virtual css::uno::Type SAL_CALL getElementType( ) override; + virtual sal_Bool SAL_CALL hasElements( ) override; + + // css::text::XTextRangeMover + virtual void SAL_CALL moveTextRange( const css::uno::Reference< css::text::XTextRange >& xRange, sal_Int16 nParagraphs ) override; + + // css::text::XParagraphAppend (new import API) + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL finishParagraph( const css::uno::Sequence< css::beans::PropertyValue >& CharacterAndParagraphProperties ) override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL finishParagraphInsert( const css::uno::Sequence< css::beans::PropertyValue >& CharacterAndParagraphProperties, const css::uno::Reference< css::text::XTextRange >& xInsertPosition ) override; + + // css::text::XTextPortionAppend (new import API) + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL appendTextPortion( const OUString& Text, const css::uno::Sequence< css::beans::PropertyValue >& CharacterAndParagraphProperties ) override; + + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL insertTextPortion( const OUString& Text, const css::uno::Sequence< css::beans::PropertyValue >& CharacterAndParagraphProperties, const css::uno::Reference< css::text::XTextRange>& rTextRange ) override; + + // css::text::XTextCopy + virtual void SAL_CALL copyText( const css::uno::Reference< css::text::XTextCopy >& xSource ) override; + + // css::lang::XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; + static css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames_Static( ); + + // css::lang::XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; +}; + + +class EDITENG_DLLPUBLIC SvxUnoText : public SvxUnoTextBase, + public ::cppu::OWeakAggObject +{ +public: + SvxUnoText( const SvxItemPropertySet* _pSet ) noexcept; + SvxUnoText( const SvxEditSource* pSource, const SvxItemPropertySet* _pSet, css::uno::Reference < css::text::XText > const & xParent ) noexcept; + SvxUnoText( const SvxUnoText& rText ) noexcept; + virtual ~SvxUnoText() noexcept override; + + // Internal + static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId() noexcept; + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + + // css::uno::XInterface + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ) override; + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + // css::lang::XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; +}; + + +class SvxUnoTextContent final : public SvxUnoTextRangeBase, + public css::text::XTextContent, + public css::container::XEnumerationAccess, + public css::lang::XTypeProvider, + public ::cppu::OWeakAggObject +{ + friend class SvxUnoTextContentEnumeration; +private: + css::uno::Reference< css::text::XText > mxParentText; + sal_Int32 mnParagraph; + const SvxUnoTextBase& mrParentText; + + // for xComponent + std::mutex maDisposeContainerMutex; + ::comphelper::OInterfaceContainerHelper4 maDisposeListeners; + bool mbDisposing; + +protected: + using SvxUnoTextRangeBase::setPropertyValue; + using SvxUnoTextRangeBase::getPropertyValue; + +public: + SvxUnoTextContent( const SvxUnoTextBase& rText, sal_Int32 nPara ) noexcept; + SvxUnoTextContent( const SvxUnoTextContent& rContent ) noexcept; + virtual ~SvxUnoTextContent() noexcept override; + + // css::uno::XInterface + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ) override; + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + // css::text::XTextRange + virtual css::uno::Reference< css::text::XText > SAL_CALL getText( ) override; + + // css::text::XTextContent -> css::lang::XComponent + virtual void SAL_CALL attach( const css::uno::Reference< css::text::XTextRange >& xTextRange ) override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getAnchor( ) override; + + // css::lang::XComponent + virtual void SAL_CALL dispose() override; + virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) override; + virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override; + + // css::container::XEnumerationAccess + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration( ) override; + + // css::container::XElementAccess + virtual css::uno::Type SAL_CALL getElementType() override; + virtual sal_Bool SAL_CALL hasElements() override; + + // css::beans::XPropertySet + virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; + virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; + + // XMultiPropertySet + virtual void SAL_CALL setPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames, const css::uno::Sequence< css::uno::Any >& aValues ) override; + virtual css::uno::Sequence< css::uno::Any > SAL_CALL getPropertyValues( const css::uno::Sequence< OUString >& aPropertyNames ) override; + + // css::beans::XPropertyState + virtual css::beans::PropertyState SAL_CALL getPropertyState( const OUString& PropertyName ) override; + virtual css::uno::Sequence< css::beans::PropertyState > SAL_CALL getPropertyStates( const css::uno::Sequence< OUString >& aPropertyName ) override; + virtual void SAL_CALL setPropertyToDefault( const OUString& PropertyName ) override; + + // css::lang::XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; + + // css::lang::XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; +}; + + +class SvxUnoTextContentEnumeration final : public ::cppu::WeakAggImplHelper1< css::container::XEnumeration > +{ +private: + css::uno::Reference< css::text::XText > mxParentText; + std::unique_ptr mpEditSource; + sal_Int32 mnNextParagraph; + std::vector< rtl::Reference > maContents; + +public: + SvxUnoTextContentEnumeration( const SvxUnoTextBase& _rText, const ESelection& rSel ) noexcept; + virtual ~SvxUnoTextContentEnumeration() noexcept override; + + // css::container::XEnumeration + virtual sal_Bool SAL_CALL hasMoreElements( ) override; + virtual css::uno::Any SAL_CALL nextElement( ) override; +}; + + +class SvxUnoTextRangeEnumeration final : public ::cppu::WeakAggImplHelper1< css::container::XEnumeration > +{ +private: + std::unique_ptr mpEditSource; + css::uno::Reference< css::text::XText > mxParentText; + std::vector< rtl::Reference > maPortions; + sal_uInt16 mnNextPortion; + +public: + SvxUnoTextRangeEnumeration(const SvxUnoTextBase& rText, sal_Int32 nPara, const ESelection& rSel); + virtual ~SvxUnoTextRangeEnumeration() noexcept override; + + // css::container::XEnumeration + virtual sal_Bool SAL_CALL hasMoreElements( ) override; + virtual css::uno::Any SAL_CALL nextElement( ) override; +}; + + +class EDITENG_DLLPUBLIC SvxUnoTextCursor : public SvxUnoTextRangeBase, + public css::text::XTextCursor, + public css::lang::XTypeProvider, + public ::cppu::OWeakAggObject +{ +private: + css::uno::Reference< css::text::XText > mxParentText; + +public: + SvxUnoTextCursor( const SvxUnoTextBase& rText ) noexcept; + SvxUnoTextCursor( const SvxUnoTextCursor& rCursor ) noexcept; + virtual ~SvxUnoTextCursor() noexcept override; + + // css::uno::XInterface + virtual css::uno::Any SAL_CALL queryAggregation( const css::uno::Type & rType ) override; + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type & rType ) override; + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + + // css::text::XTextRange + virtual css::uno::Reference< css::text::XText > SAL_CALL getText() override; + virtual OUString SAL_CALL getString() override; + virtual void SAL_CALL setString( const OUString& aString ) override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getStart() override; + virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getEnd() override; + + // css::text::XTextCursor -> css::text::XTextRange + virtual void SAL_CALL collapseToStart( ) override; + virtual void SAL_CALL collapseToEnd( ) override; + virtual sal_Bool SAL_CALL isCollapsed( ) override; + virtual sal_Bool SAL_CALL goLeft( sal_Int16 nCount, sal_Bool bExpand ) override; + virtual sal_Bool SAL_CALL goRight( sal_Int16 nCount, sal_Bool bExpand ) override; + virtual void SAL_CALL gotoStart( sal_Bool bExpand ) override; + virtual void SAL_CALL gotoEnd( sal_Bool bExpand ) override; + virtual void SAL_CALL gotoRange( const css::uno::Reference< css::text::XTextRange >& xRange, sal_Bool bExpand ) override; + + // css::lang::XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + + // css::lang::XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; + +}; + +EDITENG_DLLPUBLIC const SvxItemPropertySet* ImplGetSvxUnoOutlinerTextCursorSvxPropertySet(); +const SfxItemPropertyMapEntry* ImplGetSvxUnoOutlinerTextCursorPropertyMap(); +const SvxItemPropertySet* ImplGetSvxTextPortionSvxPropertySet(); +const SfxItemPropertyMapEntry* ImplGetSvxTextPortionPropertyMap(); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/unoviwou.hxx b/include/editeng/unoviwou.hxx new file mode 100644 index 000000000..674bec8cf --- /dev/null +++ b/include/editeng/unoviwou.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_UNOVIWOU_HXX +#define INCLUDED_EDITENG_UNOVIWOU_HXX + +#include +#include + +class OutlinerView; + +/// Specialization for Draw/Impress +class EDITENG_DLLPUBLIC SvxDrawOutlinerViewForwarder final : public SvxEditViewForwarder +{ +private: + OutlinerView& mrOutlinerView; + Point maTextShapeTopLeft; + + EDITENG_DLLPRIVATE Point GetTextOffset() const; + +public: + explicit SvxDrawOutlinerViewForwarder( OutlinerView& rOutl ); + SvxDrawOutlinerViewForwarder( OutlinerView& rOutl, const Point& rShapePosTopLeft ); + virtual ~SvxDrawOutlinerViewForwarder() override; + + virtual bool IsValid() const override; + + virtual Point LogicToPixel( const Point& rPoint, const MapMode& rMapMode ) const override; + virtual Point PixelToLogic( const Point& rPoint, const MapMode& rMapMode ) const override; + + virtual bool GetSelection( ESelection& rSelection ) const override; + virtual bool SetSelection( const ESelection& rSelection ) override; + virtual bool Copy() override; + virtual bool Cut() override; + virtual bool Paste() override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/urlfieldhelper.hxx b/include/editeng/urlfieldhelper.hxx new file mode 100644 index 000000000..9a1d53d15 --- /dev/null +++ b/include/editeng/urlfieldhelper.hxx @@ -0,0 +1,28 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include +#include + +class EDITENG_DLLPUBLIC URLFieldHelper +{ +public: + static void RemoveURLField(EditView& pEditView); + static bool IsCursorAtURLField(const EditView& pEditView); + static bool IsCursorAtURLField(const OutlinerView* pOLV) + { + return pOLV && IsCursorAtURLField(pOLV->GetEditView()); + } +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/editeng/wghtitem.hxx b/include/editeng/wghtitem.hxx new file mode 100644 index 000000000..6f5f4b31c --- /dev/null +++ b/include/editeng/wghtitem.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_WGHTITEM_HXX +#define INCLUDED_EDITENG_WGHTITEM_HXX + +#include +#include +#include + +// class SvxWeightItem --------------------------------------------------- + +/* [Description] + + This item describes the font weight. +*/ + +class EDITENG_DLLPUBLIC SvxWeightItem final : public SfxEnumItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxWeightItem( const FontWeight eWght /*= WEIGHT_NORMAL*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + SfxEnumItem + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + virtual SvxWeightItem* Clone( SfxItemPool *pPool = nullptr ) const override; + static OUString GetValueTextByPos( sal_uInt16 nPos ); + virtual sal_uInt16 GetValueCount() const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual bool HasBoolValue() const override; + virtual bool GetBoolValue() const override; + virtual void SetBoolValue( bool bVal ) override; + + // enum cast + FontWeight GetWeight() const { return GetValue(); } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + + virtual bool IsSortable() const override { return true; } + + virtual bool operator<(const SfxPoolItem& rCmp) const override + { + auto const & other = static_cast(rCmp); + return GetValue() < other.GetValue(); + } +}; + +#endif // INCLUDED_EDITENG_WGHTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/widwitem.hxx b/include/editeng/widwitem.hxx new file mode 100644 index 000000000..5d64962d3 --- /dev/null +++ b/include/editeng/widwitem.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_WIDWITEM_HXX +#define INCLUDED_EDITENG_WIDWITEM_HXX + +#include +#include + +// class SvxWidowsItem --------------------------------------------------- + +/* [Description] + + This item describes the number of lines for the widows control. +*/ + +class EDITENG_DLLPUBLIC SvxWidowsItem final : public SfxByteItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxWidowsItem( const sal_uInt8 nL /*= 0*/, const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxWidowsItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/writingmodeitem.hxx b/include/editeng/writingmodeitem.hxx new file mode 100644 index 000000000..f9e116d76 --- /dev/null +++ b/include/editeng/writingmodeitem.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_WRITINGMODEITEM_HXX +#define INCLUDED_EDITENG_WRITINGMODEITEM_HXX + +#include +#include +#include + +// class SvxWritingModeItem ---------------------------------------------- + +class EDITENG_DLLPUBLIC SvxWritingModeItem final : public SfxUInt16Item +{ +public: + SvxWritingModeItem( css::text::WritingMode eValue /*= css::text::WritingMode_LR_TB*/, + sal_uInt16 nWhich /*= SDRATTR_TEXTDIRECTION*/ ); + virtual ~SvxWritingModeItem() override; + + SvxWritingModeItem(SvxWritingModeItem const &) = default; + SvxWritingModeItem(SvxWritingModeItem &&) = default; + SvxWritingModeItem & operator =(SvxWritingModeItem const &) = delete; // due to SfxUInt16Item + SvxWritingModeItem & operator =(SvxWritingModeItem &&) = delete; // due to SfxUInt16Item + + virtual SvxWritingModeItem* Clone( SfxItemPool *pPool = nullptr ) const override; + css::text::WritingMode GetValue() const { return static_cast(SfxUInt16Item::GetValue()); } + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif // INCLUDED_EDITENG_WRITINGMODEITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/wrlmitem.hxx b/include/editeng/wrlmitem.hxx new file mode 100644 index 000000000..6226d3262 --- /dev/null +++ b/include/editeng/wrlmitem.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_EDITENG_WRLMITEM_HXX +#define INCLUDED_EDITENG_WRLMITEM_HXX + +#include +#include + +// class SvxWordLineModeItem --------------------------------------------- + +/* [Description] + + This item describes, whether underlined and strikethrough is limited + to word boundaries. +*/ + +class EDITENG_DLLPUBLIC SvxWordLineModeItem final : public SfxBoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SvxWordLineModeItem( const bool bWordLineMode /*= false*/, + const sal_uInt16 nId ); + + // "pure virtual Methods" from SfxPoolItem + virtual SvxWordLineModeItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/editeng/xmlcnitm.hxx b/include/editeng/xmlcnitm.hxx new file mode 100644 index 000000000..a0ee0a63f --- /dev/null +++ b/include/editeng/xmlcnitm.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EDITENG_XMLCNITM_HXX +#define INCLUDED_EDITENG_XMLCNITM_HXX + +#include +#include +#include + + +class EDITENG_DLLPUBLIC SvXMLAttrContainerItem final : public SfxPoolItem +{ + SvXMLAttrContainerData maContainerData; + +public: + + SvXMLAttrContainerItem( sal_uInt16 nWhich = 0 ); + SvXMLAttrContainerItem( const SvXMLAttrContainerItem& ); + virtual ~SvXMLAttrContainerItem() override; + + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual bool GetPresentation(SfxItemPresentation ePresentation, + MapUnit eCoreMetric, + MapUnit ePresentationMetric, + OUString &rText, + const IntlWrapper& rIntlWrapper) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual SvXMLAttrContainerItem* Clone( SfxItemPool * = nullptr) const override + { return new SvXMLAttrContainerItem( *this ); } + + bool AddAttr( const OUString& rLName, + const OUString& rValue ); + bool AddAttr( const OUString& rPrefix, + const OUString& rNamespace, + const OUString& rLName, + const OUString& rValue ); + + sal_uInt16 GetAttrCount() const; + OUString GetAttrNamespace( sal_uInt16 i ) const; + OUString GetAttrPrefix( sal_uInt16 i ) const; + const OUString& GetAttrLName( sal_uInt16 i ) const; + const OUString& GetAttrValue( sal_uInt16 i ) const; + + sal_uInt16 GetFirstNamespaceIndex() const; + sal_uInt16 GetNextNamespaceIndex( sal_uInt16 nIdx ) const; + const OUString& GetNamespace( sal_uInt16 i ) const; + const OUString& GetPrefix( sal_uInt16 i ) const; +}; + +#endif // INCLUDED_EDITENG_XMLCNITM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/embeddedobj/embeddedupdate.hxx b/include/embeddedobj/embeddedupdate.hxx new file mode 100644 index 000000000..1db3f36d6 --- /dev/null +++ b/include/embeddedobj/embeddedupdate.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +namespace com +{ +namespace sun +{ +namespace star +{ +namespace embed +{ +/** This class is only used to tell the OCommonEmbeddedObject class + that the following call is an Link- / Ole-refresh. + + @since LibreOffice 7.4 + */ +class EMBOBJ_DLLPUBLIC EmbeddedUpdate +{ + /** By "Refresh all" is used to perform an OLE update and a link update. + In the case of a link update, the class OCommonEmbeddedObject is + informed with true that a link update will take place next + + @param bIsOleUpdate + what kind of update, when true is OLE-Object + when false is Link-Object + */ +public: + virtual void SetOleState(bool bIsOleUpdate) = 0; + + EmbeddedUpdate() = default; + virtual ~EmbeddedUpdate() = default; + +private: + EmbeddedUpdate(const EmbeddedUpdate&) = delete; + EmbeddedUpdate& operator=(const EmbeddedUpdate&) = delete; +}; +}; +}; +}; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/embeddedobj/embobjdllapi.h b/include/embeddedobj/embobjdllapi.h new file mode 100644 index 000000000..36aa54217 --- /dev/null +++ b/include/embeddedobj/embobjdllapi.h @@ -0,0 +1,20 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#if defined(EMBOBJ_DLLIMPLEMENTATION) +#define EMBOBJ_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define EMBOBJ_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/filter/dllapi.h b/include/filter/dllapi.h new file mode 100644 index 000000000..526a1f7bd --- /dev/null +++ b/include/filter/dllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_DLLAPI_H +#define INCLUDED_FILTER_DLLAPI_H + +#include +#include + +#if defined FILTER_DLLIMPLEMENTATION +#define FILTER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define FILTER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/classids.hxx b/include/filter/msfilter/classids.hxx new file mode 100644 index 000000000..8394a716b --- /dev/null +++ b/include/filter/msfilter/classids.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_FILTER_MSFILTER_CLASSIDS_HXX +#define INCLUDED_FILTER_MSFILTER_CLASSIDS_HXX + +#define MSO_EQUATION2_CLASSID \ + 0x00021700L, 0x0000, 0x0000, \ + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 + +#define MSO_EQUATION3_CLASSID \ + 0x0002ce02L, 0x0000, 0x0000, \ + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 + +#define MSO_WW8_CLASSID \ + 0x00020906L, 0x0000, 0x0000, \ + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 + +#define MSO_EXCEL5_CLASSID \ + 0x00020810L, 0x0000, 0x0000, \ + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 + +#define MSO_EXCEL8_CLASSID \ + 0x00020820L, 0x0000, 0x0000, \ + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 + +#define MSO_EXCEL8_CHART_CLASSID \ + 0x00020821L, 0x0000, 0x0000, \ + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 + +#define MSO_PPT8_CLASSID \ + 0x64818d10L, 0x4f9b, 0x11cf, \ + 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8 + +#define MSO_PPT8_SLIDE_CLASSID \ + 0x64818d11L, 0x4f9b, 0x11cf, \ + 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8 + +#endif // INCLUDED_FILTER_MSFILTER_CLASSIDS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/countryid.hxx b/include/filter/msfilter/countryid.hxx new file mode 100644 index 000000000..b55e1d9cf --- /dev/null +++ b/include/filter/msfilter/countryid.hxx @@ -0,0 +1,307 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef INCLUDED_FILTER_MSFILTER_COUNTRYID_HXX +#define INCLUDED_FILTER_MSFILTER_COUNTRYID_HXX + +#include +#include +#include + + +namespace msfilter { + +// Windows Country IDs ======================================================== + +/** Represents a Windows country ID. + + The country IDs used in Windows are equal to the international calling + code of each country, i.e. the code 353 represents Ireland (+353). + + ATTENTION: These country codes are not supposed to be used anywhere in core + structures! They shall ONLY be used in the import/export filters for + Microsoft Office documents! + */ +typedef sal_uInt16 CountryId; + +const CountryId COUNTRY_DONTKNOW = 0; +const CountryId COUNTRY_USA = 1; +const CountryId COUNTRY_DOMINICAN_REPUBLIC = 1; // NANP +const CountryId COUNTRY_GUAM = 1; // NANP +const CountryId COUNTRY_JAMAICA = 1; // NANP +const CountryId COUNTRY_PUERTO_RICO = 1; // NANP +const CountryId COUNTRY_TRINIDAD_Y_TOBAGO = 1; // NANP +const CountryId COUNTRY_CANADA = 2; +const CountryId COUNTRY_RUSSIA = 7; +const CountryId COUNTRY_KAZAKHSTAN = 7; // no own ID +const CountryId COUNTRY_TATARSTAN = 7; // no own ID +const CountryId COUNTRY_EGYPT = 20; +const CountryId COUNTRY_SOUTH_AFRICA = 27; +const CountryId COUNTRY_GREECE = 30; +const CountryId COUNTRY_NETHERLANDS = 31; +const CountryId COUNTRY_BELGIUM = 32; +const CountryId COUNTRY_FRANCE = 33; +const CountryId COUNTRY_SPAIN = 34; +const CountryId COUNTRY_HUNGARY = 36; +const CountryId COUNTRY_ITALY = 39; +const CountryId COUNTRY_ROMANIA = 40; +const CountryId COUNTRY_SWITZERLAND = 41; +const CountryId COUNTRY_AUSTRIA = 43; +const CountryId COUNTRY_UNITED_KINGDOM = 44; +const CountryId COUNTRY_DENMARK = 45; +const CountryId COUNTRY_SWEDEN = 46; +const CountryId COUNTRY_NORWAY = 47; +const CountryId COUNTRY_POLAND = 48; +const CountryId COUNTRY_GERMANY = 49; +const CountryId COUNTRY_PERU = 51; +const CountryId COUNTRY_MEXICO = 52; +const CountryId COUNTRY_CUBA = 53; +const CountryId COUNTRY_ARGENTINA = 54; +const CountryId COUNTRY_BRAZIL = 55; +const CountryId COUNTRY_CHILE = 56; +const CountryId COUNTRY_COLOMBIA = 57; +const CountryId COUNTRY_VENEZUELA = 58; +const CountryId COUNTRY_MALAYSIA = 60; +const CountryId COUNTRY_AUSTRALIA = 61; +const CountryId COUNTRY_INDONESIA = 62; +const CountryId COUNTRY_PHILIPPINES = 63; +const CountryId COUNTRY_NEW_ZEALAND = 64; +const CountryId COUNTRY_SINGAPORE = 65; +const CountryId COUNTRY_THAILAND = 66; +const CountryId COUNTRY_JAPAN = 81; +const CountryId COUNTRY_SOUTH_KOREA = 82; +const CountryId COUNTRY_VIET_NAM = 84; +const CountryId COUNTRY_PR_CHINA = 86; +const CountryId COUNTRY_TIBET = 86; // no own ID +const CountryId COUNTRY_TURKEY = 90; +const CountryId COUNTRY_INDIA = 91; +const CountryId COUNTRY_PAKISTAN = 92; +const CountryId COUNTRY_AFGHANISTAN = 93; +const CountryId COUNTRY_SRI_LANKA = 94; +const CountryId COUNTRY_MYANMAR = 95; +const CountryId COUNTRY_MOROCCO = 212; +const CountryId COUNTRY_ALGERIA = 213; +const CountryId COUNTRY_TUNISIA = 216; +const CountryId COUNTRY_LIBYA = 218; +const CountryId COUNTRY_GAMBIA = 220; +const CountryId COUNTRY_SENEGAL = 221; +const CountryId COUNTRY_MAURITANIA = 222; +const CountryId COUNTRY_MALI = 223; +const CountryId COUNTRY_GUINEA = 224; +const CountryId COUNTRY_COTE_D_IVOIRE = 225; +const CountryId COUNTRY_BURKINA_FARSO = 226; +const CountryId COUNTRY_NIGER = 227; +const CountryId COUNTRY_TOGO = 228; +const CountryId COUNTRY_BENIN = 229; +const CountryId COUNTRY_MAURITIUS = 230; +const CountryId COUNTRY_LIBERIA = 231; +const CountryId COUNTRY_SIERRA_LEONE = 232; +const CountryId COUNTRY_GHANA = 233; +const CountryId COUNTRY_NIGERIA = 234; +const CountryId COUNTRY_CHAD = 235; +const CountryId COUNTRY_CENTRAL_AFR_REP = 236; +const CountryId COUNTRY_CAMEROON = 237; +const CountryId COUNTRY_CAPE_VERDE = 238; +const CountryId COUNTRY_SAO_TOME = 239; +const CountryId COUNTRY_EQUATORIAL_GUINEA = 240; +const CountryId COUNTRY_GABON = 241; +const CountryId COUNTRY_CONGO = 242; +const CountryId COUNTRY_ZAIRE = 243; +const CountryId COUNTRY_ANGOLA = 244; +const CountryId COUNTRY_GUINEA_BISSAU = 245; +const CountryId COUNTRY_DIEGO_GARCIA = 246; +const CountryId COUNTRY_ASCENSION_ISLAND = 247; +const CountryId COUNTRY_SEYCHELLES = 248; +const CountryId COUNTRY_SUDAN = 249; +const CountryId COUNTRY_RWANDA = 250; +const CountryId COUNTRY_ETHIOPIA = 251; +const CountryId COUNTRY_SOMALIA = 252; +const CountryId COUNTRY_DJIBOUTI = 253; +const CountryId COUNTRY_KENYA = 254; +const CountryId COUNTRY_TANZANIA = 255; +const CountryId COUNTRY_UGANDA = 256; +const CountryId COUNTRY_BURUNDI = 257; +const CountryId COUNTRY_MOZAMBIQUE = 258; +const CountryId COUNTRY_ZANZIBAR = 259; +const CountryId COUNTRY_ZAMBIA = 260; +const CountryId COUNTRY_MADAGASCAR = 261; +const CountryId COUNTRY_REUNION = 262; +const CountryId COUNTRY_ZIMBABWE = 263; +const CountryId COUNTRY_NAMIBIA = 264; +const CountryId COUNTRY_MALAWI = 265; +const CountryId COUNTRY_LESOTHO = 266; +const CountryId COUNTRY_BOTSWANA = 267; +const CountryId COUNTRY_SWAZILAND = 268; +const CountryId COUNTRY_COMOROS_MAYOTTE = 269; +const CountryId COUNTRY_ST_HELENA = 290; +const CountryId COUNTRY_ERITREA = 291; +const CountryId COUNTRY_ARUBA = 297; +const CountryId COUNTRY_FAEROE_ISLANDS = 298; +const CountryId COUNTRY_GREEN_ISLAND = 299; +const CountryId COUNTRY_GIBRALTAR = 350; +const CountryId COUNTRY_PORTUGAL = 351; +const CountryId COUNTRY_LUXEMBOURG = 352; +const CountryId COUNTRY_IRELAND = 353; +const CountryId COUNTRY_ICELAND = 354; +const CountryId COUNTRY_ALBANIA = 355; +const CountryId COUNTRY_MALTA = 356; +const CountryId COUNTRY_CYPRUS = 357; +const CountryId COUNTRY_FINLAND = 358; +const CountryId COUNTRY_BULGARIA = 359; +const CountryId COUNTRY_LITHUANIA = 370; +const CountryId COUNTRY_LATVIA = 371; +const CountryId COUNTRY_ESTONIA = 372; +const CountryId COUNTRY_MOLDOVA = 373; +const CountryId COUNTRY_ARMENIA = 374; +const CountryId COUNTRY_BELARUS = 375; +const CountryId COUNTRY_ANDORRA = 376; +const CountryId COUNTRY_MONACO = 377; +const CountryId COUNTRY_SAN_MARINO = 378; +const CountryId COUNTRY_VATICAN_CITY = 379; +const CountryId COUNTRY_UKRAINE = 380; +const CountryId COUNTRY_SERBIA = 381; +const CountryId COUNTRY_CROATIA = 385; +const CountryId COUNTRY_SLOVENIA = 386; +const CountryId COUNTRY_BOSNIA = 387; +const CountryId COUNTRY_MACEDONIA = 389; +const CountryId COUNTRY_CZECH = 420; +const CountryId COUNTRY_SLOVAK = 421; +const CountryId COUNTRY_LIECHTENSTEIN = 423; +const CountryId COUNTRY_FALKLAND_ISLANDS = 500; +const CountryId COUNTRY_BELIZE = 501; +const CountryId COUNTRY_GUATEMALA = 502; +const CountryId COUNTRY_EL_SALVADOR = 503; +const CountryId COUNTRY_HONDURAS = 504; +const CountryId COUNTRY_NICARAGUA = 505; +const CountryId COUNTRY_COSTA_RICA = 506; +const CountryId COUNTRY_PANAMA = 507; +const CountryId COUNTRY_ST_PIERRE = 508; +const CountryId COUNTRY_HAITI = 509; +const CountryId COUNTRY_GUADELOUPE = 590; +const CountryId COUNTRY_BOLIVIA = 591; +const CountryId COUNTRY_GUYANA = 592; +const CountryId COUNTRY_ECUADOR = 593; +const CountryId COUNTRY_FRENCH_GUIANA = 594; +const CountryId COUNTRY_PARAGUAY = 595; +const CountryId COUNTRY_MARTINIQUE = 596; +const CountryId COUNTRY_SURINAME = 597; +const CountryId COUNTRY_URUGUAY = 598; +const CountryId COUNTRY_NETHERL_ANTILLES = 599; +const CountryId COUNTRY_EAST_TIMOR = 670; +const CountryId COUNTRY_ANTARCTICA = 672; +const CountryId COUNTRY_BRUNEI_DARUSSALAM = 673; +const CountryId COUNTRY_NARUPU = 674; +const CountryId COUNTRY_PAPUA_NEW_GUINEA = 675; +const CountryId COUNTRY_TONGA = 676; +const CountryId COUNTRY_SOLOMON_ISLANDS = 677; +const CountryId COUNTRY_VANUATU = 678; +const CountryId COUNTRY_FIJI = 679; +const CountryId COUNTRY_PALAU = 680; +const CountryId COUNTRY_WALLIS_AND_FUTUNA = 681; +const CountryId COUNTRY_COOK_ISLANDS = 682; +const CountryId COUNTRY_NIUE_ISLAND = 683; +const CountryId COUNTRY_AMERICAN_SAMOA = 684; +const CountryId COUNTRY_WESTERN_SAMOA = 685; +const CountryId COUNTRY_KIRIBATI = 686; +const CountryId COUNTRY_NEW_CALEDONIA = 687; +const CountryId COUNTRY_TUVALU = 688; +const CountryId COUNTRY_FRENCH_POLYNESIA = 689; +const CountryId COUNTRY_TOKELAU = 690; +const CountryId COUNTRY_MICRONESIA = 691; +const CountryId COUNTRY_MARSHALL_ISLANDS = 692; +const CountryId COUNTRY_NORTH_KOREA = 850; +const CountryId COUNTRY_HONG_KONG = 852; +const CountryId COUNTRY_MACAU = 853; +const CountryId COUNTRY_CAMBODIA = 855; +const CountryId COUNTRY_LAOS = 856; +const CountryId COUNTRY_BANGLADESH = 880; +const CountryId COUNTRY_TAIWAN = 886; +const CountryId COUNTRY_MALDIVES = 960; +const CountryId COUNTRY_LEBANON = 961; +const CountryId COUNTRY_JORDAN = 962; +const CountryId COUNTRY_SYRIA = 963; +const CountryId COUNTRY_IRAQ = 964; +const CountryId COUNTRY_KUWAIT = 965; +const CountryId COUNTRY_SAUDI_ARABIA = 966; +const CountryId COUNTRY_YEMEN = 967; +const CountryId COUNTRY_OMAN = 968; +const CountryId COUNTRY_PALESTINE = 970; +const CountryId COUNTRY_UAE = 971; +const CountryId COUNTRY_ISRAEL = 972; +const CountryId COUNTRY_BAHRAIN = 973; +const CountryId COUNTRY_QATAR = 974; +const CountryId COUNTRY_BHUTAN = 975; +const CountryId COUNTRY_MONGOLIA = 976; +const CountryId COUNTRY_NEPAL = 977; +const CountryId COUNTRY_IRAN = 981; +const CountryId COUNTRY_TAJIKISTAN = 992; +const CountryId COUNTRY_TURKMENISTAN = 993; +const CountryId COUNTRY_AZERBAIJAN = 994; +const CountryId COUNTRY_GEORGIA = 995; +const CountryId COUNTRY_KYRGYZSTAN = 996; +const CountryId COUNTRY_UZBEKISTAN = 998; + +// Country ID <-> Language type conversion ==================================== + +/** Converts a language type to a Windows country ID. + + The function regards the sub type of the passed language, and tries to + return the appropriate country, i.e. COUNTRY_IRELAND for + LANGUAGE_ENGLISH_EIRE. + + A few countries do not have an own associated country ID. Most of these + countries are mapped to another related country, i.e. Kazakhstan is + mapped to Russia. + + If no country can be found, the value COUNTRY_DONTKNOW will be returned. + + @param eLanguage + A language type, defined in tools/lang.hxx. + + @return + The best Windows country ID for the passed language type, or + COUNTRY_DONTKNOW on error. + */ +MSFILTER_DLLPUBLIC CountryId ConvertLanguageToCountry( LanguageType eLanguage ); + +/** Converts a Windows country ID to a language type. + + The function returns the most used language for the passed country + (hopefully), i.e. LANGUAGE_ENGLISH_EIRE for COUNTRY_IRELAND. + + If the passed country ID is not valid, the value LANGUAGE_DONTKNOW will be + returned. + + @param eCountry + A Windows country ID, defined above. + + @return + The most used language type in the passed country, or LANGUAGE_DONTKNOW + on error. + */ +MSFILTER_DLLPUBLIC LanguageType ConvertCountryToLanguage( CountryId eCountry ); + + +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/dffpropset.hxx b/include/filter/msfilter/dffpropset.hxx new file mode 100644 index 000000000..6e7ca4a41 --- /dev/null +++ b/include/filter/msfilter/dffpropset.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_FILTER_MSFILTER_DFFPROPSET_HXX +#define INCLUDED_FILTER_MSFILTER_DFFPROPSET_HXX + +#include + +#include +#include +#include +#include + +class SvStream; + +struct DffPropFlags +{ + bool bSet : 1; + bool bComplex : 1; + bool bBlip : 1; + bool bSoftAttr : 1; +}; + +struct DffPropSetEntry +{ + DffPropFlags aFlags; + sal_uInt16 nComplexIndexOrFlagsHAttr; + sal_uInt32 nContent; +}; + +class MSFILTER_DLLPUBLIC DffPropSet +{ + private: + DffPropSetEntry* mpPropSetEntries; + std::vector< sal_uInt32 > maOffsets; + + void ReadPropSet( SvStream&, bool ); + + public: + explicit DffPropSet(); + ~DffPropSet(); + + bool IsProperty( sal_uInt32 nRecType ) const { return ( mpPropSetEntries[ nRecType & 0x3ff ].aFlags.bSet ); }; + bool IsHardAttribute( sal_uInt32 nId ) const; + sal_uInt32 GetPropertyValue( sal_uInt32 nId, sal_uInt32 nDefault ) const; + /** Returns a boolean property by its real identifier. */ + bool GetPropertyBool( sal_uInt32 nId ) const; + /** Returns a string property. */ + OUString GetPropertyString( sal_uInt32 nId, SvStream& rStrm ) const; + bool SeekToContent( sal_uInt32 nRecType, SvStream& rSt ) const; + void InitializePropSet( sal_uInt16 nPropSetType ) const; + static sal_uLong SanitizeEndPos(SvStream &rIn, sal_uLong nEndRecPos); + + friend SvStream& ReadDffPropSet( SvStream& rIn, DffPropSet& rPropSet ); + friend SvStream& operator|=( SvStream& rIn, DffPropSet& rPropSet ); +}; + +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/dffrecordheader.hxx b/include/filter/msfilter/dffrecordheader.hxx new file mode 100644 index 000000000..acd0d2539 --- /dev/null +++ b/include/filter/msfilter/dffrecordheader.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_DFFRECORDHEADER_HXX +#define INCLUDED_FILTER_MSFILTER_DFFRECORDHEADER_HXX + +#include +#include +#include +#include +#include + +class MSFILTER_DLLPUBLIC DffRecordHeader +{ +public: + sal_uInt8 nRecVer; // may be DFF_PSFLAG_CONTAINER + sal_uInt16 nRecInstance; + sal_uInt16 nImpVerInst; + sal_uInt16 nRecType; + sal_uInt32 nRecLen; + sal_uLong nFilePos; + + DffRecordHeader() : nRecVer(0), nRecInstance(0), nImpVerInst(0), + nRecType(0), nRecLen(0), nFilePos(0) {} + bool IsContainer() const { return nRecVer == DFF_PSFLAG_CONTAINER; } + sal_uLong GetRecBegFilePos() const { return nFilePos; } + sal_uLong GetRecEndFilePos() const + { return nFilePos + DFF_COMMON_RECORD_HEADER_SIZE + nRecLen; } + bool SeekToEndOfRecord(SvStream& rIn) const + { + sal_uInt64 const nPos = nFilePos + DFF_COMMON_RECORD_HEADER_SIZE + nRecLen; + return checkSeek(rIn, nPos); + } + bool SeekToContent(SvStream& rIn) const + { + sal_uInt64 const nPos = nFilePos + DFF_COMMON_RECORD_HEADER_SIZE; + return checkSeek(rIn, nPos); + } + bool SeekToBegOfRecord(SvStream& rIn) const + { + return checkSeek(rIn, nFilePos); + } + + MSFILTER_DLLPUBLIC friend bool ReadDffRecordHeader(SvStream& rIn, DffRecordHeader& rRec); +}; + +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/escherex.hxx b/include/filter/msfilter/escherex.hxx new file mode 100644 index 000000000..ac6b4cc00 --- /dev/null +++ b/include/filter/msfilter/escherex.hxx @@ -0,0 +1,1221 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_ESCHEREX_HXX +#define INCLUDED_FILTER_MSFILTER_ESCHEREX_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Color; + +namespace com::sun::star { + namespace awt { struct Rectangle; } + namespace beans { class XPropertySet; } + namespace drawing { struct EnhancedCustomShapeParameter; } + namespace drawing { struct Hatch; } +} + +namespace tools { + class Polygon; + class PolyPolygon; +} + + /*Record Name FBT-Value Instance Contents Wrd Exl PPT Ver*/ +// In the Microsoft documentation the naming scheme is msofbt... instead of ESCHER_... +#define ESCHER_DggContainer 0xF000u /* per-document data X X X */ +#define ESCHER_Dgg 0xF006u /* an FDGG and several FIDCLs X X X 0 */ +#define ESCHER_OPT 0xF00Bu /* count of properties the document-wide default shape properties X X X 3 */ +#define ESCHER_SplitMenuColors 0xF11Eu /* count of colors the colors in the top-level split menus X X X 0 */ +#define ESCHER_BstoreContainer 0xF001u /* count of BLIPs all images in the document (JPEGs, metafiles, etc.) X X X */ +#define ESCHER_BSE 0xF007u /* BLIP type an FBSE (one per BLIP) X X X 2 */ +#define ESCHER_BlipFirst 0xF018u /* range of fbts reserved for various kinds of BLIPs X X X */ + +#define ESCHER_DgContainer 0xF002u /* per-sheet/page/slide data X X X */ +#define ESCHER_Dg 0xF008u /* drawing ID an FDG X X X 0 */ +#define ESCHER_SpgrContainer 0xF003u /* several SpContainers, the first of which is the group shape itself X X X */ +#define ESCHER_SpContainer 0xF004u /* a shape X X X */ +#define ESCHER_Spgr 0xF009u /* an FSPGR; only present if the shape is a group shape X X X 1 */ +#define ESCHER_Sp 0xF00Au /* shape type an FSP X X X 2 */ +//#define ESCHER_OPT 0xF00Bu /* count of properties a shape property table X X X 3 */ +#define ESCHER_ClientTextbox 0xF00Du /* host-defined the text in the textbox, in host-defined format X X X */ +#define ESCHER_ChildAnchor 0xF00Fu /* a RECT, in units relative to the parent group X X X 0 */ +#define ESCHER_ClientAnchor 0xF010u /* host-defined the location of the shape, in a host-defined format X X X */ +#define ESCHER_ClientData 0xF011u /* host-defined host-specific data X X X */ +#define ESCHER_SolverContainer 0xF005u /* count of rules the rules governing shapes X X X */ +#define ESCHER_ConnectorRule 0xF012u /* an FConnectorRule X X 1 */ +#define ESCHER_UDefProp 0xF122u + +enum class ShapeFlag : sal_uInt32 +{ + NONE = 0x000, + Group = 0x001, /* shape is a group shape */ + Child = 0x002, /* shape is a child shape */ + Patriarch = 0x004, /* shape is the topmost group shape. + Exactly one of these per drawing. */ + Deleted = 0x008, /* shape has been deleted */ + OLEShape = 0x010, /* shape is an OLE object */ + HaveMaster = 0x020, /* shape has a valid master in hspMaster property */ + FlipH = 0x040, /* shape is flipped horizontally */ + FlipV = 0x080, /* shape is flipped vertically */ + Connector = 0x100, /* shape is a connector shape */ + HaveAnchor = 0x200, /* shape has an anchor of some kind */ + Background = 0x400, /* shape is a background shape */ + HaveShapeProperty = 0x800 /* shape has a shape type property */ +}; /* 20 bits unused */ +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +#define ESCHER_ShpInst_Min 0 +#define ESCHER_ShpInst_NotPrimitive ESCHER_ShpInst_Min +#define ESCHER_ShpInst_Rectangle 1 +#define ESCHER_ShpInst_RoundRectangle 2 +#define ESCHER_ShpInst_Ellipse 3 +#define ESCHER_ShpInst_Arc 19 +#define ESCHER_ShpInst_Line 20 +#define ESCHER_ShpInst_StraightConnector1 32 +#define ESCHER_ShpInst_BentConnector2 33 +#define ESCHER_ShpInst_BentConnector3 34 +#define ESCHER_ShpInst_CurvedConnector3 38 +#define ESCHER_ShpInst_PictureFrame 75 +#define ESCHER_ShpInst_TextPlainText 136 +#define ESCHER_ShpInst_TextDeflateInflateDeflate 167 +#define ESCHER_ShpInst_TextSlantUp 172 +#define ESCHER_ShpInst_HostControl 201 +#define ESCHER_ShpInst_TextBox 202 +#define ESCHER_ShpInst_COUNT 203 +#define ESCHER_ShpInst_Max 0x0FFF +#define ESCHER_ShpInst_Nil ESCHER_ShpInst_Max + +enum ESCHER_BlibType +{ // GEL provided types... + ERROR = 0, // An error occurred during loading + UNKNOWN, // An unknown blip type + EMF, // Windows Enhanced Metafile + WMF, // Windows Metafile + PICT, // Macintosh PICT + PEG, // JFIF + PNG, // PNG + DIB, // Windows DIB + FirstClient = 32, // First client defined blip type + LastClient = 255 // Last client defined blip type +}; + + +enum ESCHER_FillStyle +{ + ESCHER_FillSolid, // Fill with a solid color + ESCHER_FillPattern, // Fill with a pattern (bitmap) + ESCHER_FillTexture, // A texture (pattern with its own color map) + ESCHER_FillPicture, // Center a picture in the shape + ESCHER_FillShade, // Shade from start to end points + ESCHER_FillShadeCenter, // Shade from bounding rectangle to end point + ESCHER_FillShadeShape, // Shade from shape outline to end point + ESCHER_FillShadeScale, + ESCHER_FillShadeTitle, + ESCHER_FillBackground +}; + +enum ESCHER_wMode +{ + ESCHER_wColor, // only used for predefined shades + ESCHER_wAutomatic, // depends on object type + ESCHER_wGrayScale, // shades of gray only + ESCHER_wLightGrayScale, // shades of light gray only + ESCHER_wInverseGray, // dark gray mapped to light gray, etc. + ESCHER_wGrayOutline, // pure gray and white + ESCHER_wBlackTextLine, // black text and lines, all else grayscale + ESCHER_wHighContrast, // pure black and white mode (no grays) + ESCHER_wBlack, // solid black msobwWhite, // solid white + ESCHER_wDontShow, // object not drawn + ESCHER_wNumModes // number of Black and white modes +}; + + +enum ESCHER_ShapePath +{ + ESCHER_ShapeLines, // A line of straight segments + ESCHER_ShapeLinesClosed, // A closed polygonal object + ESCHER_ShapeCurves, // A line of Bezier curve segments + ESCHER_ShapeCurvesClosed, // A closed shape with curved edges + ESCHER_ShapeComplex // pSegmentInfo must be non-empty +}; + + +enum ESCHER_WrapMode +{ + ESCHER_WrapSquare, + ESCHER_WrapByPoints, + ESCHER_WrapNone, + ESCHER_WrapTopBottom, + ESCHER_WrapThrough +}; + + +enum ESCHER_bwMode +{ + ESCHER_bwColor, // only used for predefined shades + ESCHER_bwAutomatic, // depends on object type + ESCHER_bwGrayScale, // shades of gray only + ESCHER_bwLightGrayScale, // shades of light gray only + ESCHER_bwInverseGray, // dark gray mapped to light gray, etc. + ESCHER_bwGrayOutline, // pure gray and white + ESCHER_bwBlackTextLine, // black text and lines, all else grayscale + ESCHER_bwHighContrast, // pure black and white mode (no grays) + ESCHER_bwBlack, // solid black + ESCHER_bwWhite, // solid white + ESCHER_bwDontShow, // object not drawn + ESCHER_bwNumModes // number of Black and white modes +}; + + +enum ESCHER_AnchorText +{ + ESCHER_AnchorTop, + ESCHER_AnchorMiddle, + ESCHER_AnchorBottom, + ESCHER_AnchorTopCentered, + ESCHER_AnchorMiddleCentered, + ESCHER_AnchorBottomCentered, + ESCHER_AnchorTopBaseline, + ESCHER_AnchorBottomBaseline, + ESCHER_AnchorTopCenteredBaseline, + ESCHER_AnchorBottomCenteredBaseline +}; + +// connector style +enum ESCHER_cxSTYLE +{ + ESCHER_cxstyleStraight = 0, + ESCHER_cxstyleBent, + ESCHER_cxstyleCurved, + ESCHER_cxstyleNone +}; + +// text flow +enum ESCHER_txfl +{ + ESCHER_txflHorzN, // Horizontal non-@ + ESCHER_txflTtoBA, // Top to Bottom @-font + ESCHER_txflBtoT, // Bottom to Top non-@ + ESCHER_txflTtoBN, // Top to Bottom non-@ + ESCHER_txflHorzA, // Horizontal @-font + ESCHER_txflVertN // Vertical, non-@ +}; + + +// flags for pictures +enum ESCHER_BlipFlags +{ + ESCHER_BlipFlagDefault = 0, + ESCHER_BlipFlagComment = 0, // Blip name is a comment + ESCHER_BlipFlagFile, // Blip name is a file name + ESCHER_BlipFlagURL, // Blip name is a full URL + ESCHER_BlipFlagType = 3, // Mask to extract type + /* Or the following flags with any of the above. */ + ESCHER_BlipFlagDoNotSave = 4, + ESCHER_BlipFlagLinkToFile = 8 +}; + +// dashed line style +enum ESCHER_LineDashing +{ + ESCHER_LineSolid, // Solid (continuous) pen + ESCHER_LineDashSys, // PS_DASH system dash style + ESCHER_LineDotSys, // PS_DOT system dash style + ESCHER_LineDashDotSys, // PS_DASHDOT system dash style + ESCHER_LineDashDotDotSys, // PS_DASHDOTDOT system dash style + ESCHER_LineDotGEL, // square dot style + ESCHER_LineDashGEL, // dash style + ESCHER_LineLongDashGEL, // long dash style + ESCHER_LineDashDotGEL, // dash short dash + ESCHER_LineLongDashDotGEL, // long dash short dash + ESCHER_LineLongDashDotDotGEL // long dash short dash short dash +}; + +// line end effect +enum ESCHER_LineEnd +{ + ESCHER_LineNoEnd, + ESCHER_LineArrowEnd, + ESCHER_LineArrowStealthEnd, + ESCHER_LineArrowDiamondEnd, + ESCHER_LineArrowOvalEnd, + ESCHER_LineArrowOpenEnd +}; + +// size of arrowhead +enum ESCHER_LineWidth +{ + ESCHER_LineNarrowArrow, + ESCHER_LineMediumWidthArrow, + ESCHER_LineWideArrow +}; + +// size of arrowhead +enum ESCHER_LineEndLength +{ + ESCHER_LineShortArrow, + ESCHER_LineMediumLenArrow, + ESCHER_LineLongArrow +}; + +// line join style. +enum ESCHER_LineJoin +{ + ESCHER_LineJoinBevel, // Join edges by a straight line + ESCHER_LineJoinMiter, // Extend edges until they join + ESCHER_LineJoinRound // Draw an arc between the two edges +}; + +// line cap style (applies to ends of dash segments too). +enum ESCHER_LineCap +{ + ESCHER_LineEndCapRound, // Rounded ends - the default + ESCHER_LineEndCapSquare, // Square protrudes by half line width + ESCHER_LineEndCapFlat // Line ends at end point +}; + +enum MSOPATHTYPE +{ + msopathLineTo, // Draw a straight line (one point) + msopathCurveTo, // Draw a cubic Bezier curve (three points) + msopathMoveTo, // Move to a new point (one point) + msopathClose, // Close a sub - path (no points) + msopathEnd, // End a path (no points) + msopathEscape, // Escape code + msopathClientEscape, // Escape code interpreted by the client + msopathInvalid // Invalid - should never be found +}; + +// Shape Properties +// 1pt = 12700 EMU (English Metric Units) +// 1pt = 20 Twip = 20/1440" = 1/72" +// 1twip=635 EMU +// 1" = 12700*72 = 914400 EMU +// 1" = 25.4mm +// 1mm = 36000 EMU +// Transform +#define ESCHER_Prop_Rotation 4 /* Fixed Point 16.16 degrees */ +// Protection +#define ESCHER_Prop_LockAgainstGrouping 127 /* bool Do not group this shape */ +// Text +#define ESCHER_Prop_lTxid 128 /* LONG id for the text, value determined by the host */ +#define ESCHER_Prop_dxTextLeft 129 /* LONG margins relative to shape's inscribed */ +#define ESCHER_Prop_dyTextTop 130 /* LONG text rectangle (in EMUs) */ +#define ESCHER_Prop_dxTextRight 131 /* LONG */ +#define ESCHER_Prop_dyTextBottom 132 /* LONG */ +#define ESCHER_Prop_WrapText 133 /* MSOWRAPMODE Wrap text at shape margins */ +#define ESCHER_Prop_AnchorText 135 /* ESCHER_AnchorText How to anchor the text */ +#define ESCHER_Prop_txflTextFlow 136 /* MSOTXFL Text flow */ +#define ESCHER_Prop_hspNext 138 /* MSOHSP ID of the next shape (used by Word for linked textboxes) */ +#define ESCHER_Prop_FitTextToShape 191 /* bool Size text to fit shape size */ +// GeoText +#define ESCHER_Prop_gtextUNICODE 192 /* WCHAR* UNICODE text string */ +#define ESCHER_Prop_gtextSize 195 /* LONG default point size */ +#define ESCHER_Prop_gtextFont 197 /* WCHAR* font family name */ +// Blip +#define ESCHER_Prop_cropFromTop 256 /* LONG 16.16 fraction times total */ +#define ESCHER_Prop_cropFromBottom 257 /* LONG image width or height, */ +#define ESCHER_Prop_cropFromLeft 258 /* LONG as appropriate. */ +#define ESCHER_Prop_cropFromRight 259 /* LONG */ +#define ESCHER_Prop_pib 260 /* IMsoBlip* Blip to display */ +#define ESCHER_Prop_pibName 261 /* WCHAR* Blip file name */ +#define ESCHER_Prop_pibFlags 262 /* MSOBLIPFLAGS Blip flags */ +#define ESCHER_Prop_pictureContrast 264 /* LONG contrast setting */ +#define ESCHER_Prop_pictureBrightness 265 /* LONG brightness setting */ +#define ESCHER_Prop_pictureId 267 /* LONG Host-defined ID for OLE objects (usually a pointer) */ +#define ESCHER_Prop_pictureActive 319 /* bool Server is active (OLE objects only) */ +// Geometry +#define ESCHER_Prop_geoLeft 320 /* LONG Defines the G (geometry) coordinate space. */ +#define ESCHER_Prop_geoTop 321 /* LONG */ +#define ESCHER_Prop_geoRight 322 /* LONG */ +#define ESCHER_Prop_geoBottom 323 /* LONG */ +#define ESCHER_Prop_shapePath 324 /* MSOSHAPEPATH */ +#define ESCHER_Prop_pVertices 325 /* IMsoArray An array of points, in G units. */ +#define ESCHER_Prop_pSegmentInfo 326 /* IMsoArray */ +#define ESCHER_Prop_adjustValue 327 /* LONG Adjustment values corresponding to */ +#define ESCHER_Prop_adjust2Value 328 /* LONG the positions of the adjust handles */ +#define ESCHER_Prop_fFillOK 383 /* bool OK to fill the shape through the UI or VBA? */ +// FillStyle +#define ESCHER_Prop_fillType 384 /* ESCHER_FillStyle Type of fill */ +#define ESCHER_Prop_fillColor 385 /* MSOCLR Foreground color */ +#define ESCHER_Prop_fillOpacity 386 /* LONG Fixed 16.16 */ +#define ESCHER_Prop_fillBackColor 387 /* MSOCLR Background color */ +#define ESCHER_Prop_fillBackOpacity 388 /* LONG Shades only */ +#define ESCHER_Prop_fillBlip 390 /* IMsoBlip* Pattern/texture */ +#define ESCHER_Prop_fillAngle 395 /* LONG Fade angle - degrees in 16.16 */ +#define ESCHER_Prop_fillFocus 396 /* LONG Linear shaded fill focus percent */ +#define ESCHER_Prop_fillToLeft 397 /* LONG Fraction 16.16 */ +#define ESCHER_Prop_fillToTop 398 /* LONG Fraction 16.16 */ +#define ESCHER_Prop_fillToRight 399 /* LONG Fraction 16.16 */ +#define ESCHER_Prop_fillToBottom 400 /* LONG Fraction 16.16 */ +#define ESCHER_Prop_fillRectRight 403 /* LONG define how large the fade is going to be. */ +#define ESCHER_Prop_fillRectBottom 404 /* LONG */ +#define ESCHER_Prop_fNoFillHitTest 447 /* bool Hit test a shape as though filled */ +// LineStyle +#define ESCHER_Prop_lineColor 448 /* MSOCLR Color of line */ +#define ESCHER_Prop_lineOpacity 449 /* LONG Not implemented */ +#define ESCHER_Prop_lineBackColor 450 /* MSOCLR Background color */ +#define ESCHER_Prop_lineWidth 459 /* LONG A units; 1pt == 12700 EMUs */ +#define ESCHER_Prop_lineStyle 461 /* MSOLINESTYLE Draw parallel lines? */ +#define ESCHER_Prop_lineDashing 462 /* MSOLINEDASHING Can be overridden by: */ +#define ESCHER_Prop_lineStartArrowhead 464 /* MSOLINEEND Arrow at start */ +#define ESCHER_Prop_lineEndArrowhead 465 /* MSOLINEEND Arrow at end */ +#define ESCHER_Prop_lineStartArrowWidth 466 /* MSOLINEENDWIDTH Arrow at start */ +#define ESCHER_Prop_lineStartArrowLength 467 /* MSOLINEENDLENGTH Arrow at end */ +#define ESCHER_Prop_lineEndArrowWidth 468 /* MSOLINEENDWIDTH Arrow at start */ +#define ESCHER_Prop_lineEndArrowLength 469 /* MSOLINEENDLENGTH Arrow at end */ +#define ESCHER_Prop_lineJoinStyle 470 /* MSOLINEJOIN How to join lines */ +#define ESCHER_Prop_lineEndCapStyle 471 /* MSOLINECAP How to end lines */ +#define ESCHER_Prop_fNoLineDrawDash 511 /* bool Draw a dashed line if no line */ +// ShadowStyle +#define ESCHER_Prop_shadowColor 513 /* MSOCLR Foreground color */ +#define ESCHER_Prop_shadowOpacity 516 /* LONG Fixed 16.16 */ +#define ESCHER_Prop_shadowOffsetX 517 /* LONG Offset shadow */ +#define ESCHER_Prop_shadowOffsetY 518 /* LONG Offset shadow */ +#define ESCHER_Prop_fshadowObscured 575 /* bool Excel5-style shadow */ +// 3D Object +#define ESCHER_Prop_fc3DLightFace 703 /* bool */ +// Shape +#define ESCHER_Prop_hspMaster 769 /* MSOHSP master shape */ +#define ESCHER_Prop_cxstyle 771 /* MSOCXSTYLE Type of connector */ +#define ESCHER_Prop_bWMode 772 /* ESCHERwMode Settings for modifications to */ +#define ESCHER_Prop_fBackground 831 /* bool If sal_True, this is the background shape. */ +// GroupShape +#define ESCHER_Prop_wzName 896 /* WCHAR* Shape Name (present only if explicitly set) */ +#define ESCHER_Prop_wzDescription 897 /* WCHAR* alternate text */ +#define ESCHER_Prop_pihlShape 898 /* IHlink* The hyperlink in the shape. */ +#define ESCHER_Prop_dxWrapDistLeft 900 /* LONG Left wrapping distance from text (Word) */ +#define ESCHER_Prop_dyWrapDistTop 901 /* LONG Top wrapping distance from text (Word) */ +#define ESCHER_Prop_dxWrapDistRight 902 /* LONG Right wrapping distance from text (Word) */ +#define ESCHER_Prop_dyWrapDistBottom 903 /* LONG Bottom wrapping distance from text (Word) */ +#define ESCHER_Prop_tableProperties 927 +#define ESCHER_Prop_tableRowProperties 928 +#define ESCHER_Prop_fHidden 958 /* bool Do not display */ +#define ESCHER_Prop_fPrint 959 /* bool Print this shape */ + + +#define ESCHER_Persist_PrivateEntry 0x80000000 +#define ESCHER_Persist_Dgg 0x00010000 +#define ESCHER_Persist_Dg 0x00020000 +#define ESCHER_Persist_CurrentPosition 0x00040000 +#define ESCHER_Persist_Grouping_Snap 0x00050000 +#define ESCHER_Persist_Grouping_Logic 0x00060000 + +const sal_uInt32 DFF_DGG_CLUSTER_SIZE = 0x00000400; /// Shape IDs per cluster in DGG atom. + +namespace com::sun::star { + namespace awt { + struct Gradient; + } + namespace drawing { + struct EnhancedCustomShapeAdjustmentValue; + class XShape; + class XShapes; + } +} + +struct MSFILTER_DLLPUBLIC EscherConnectorListEntry +{ + css::uno::Reference< css::drawing::XShape > mXConnector; + css::awt::Point maPointA; + css::uno::Reference< css::drawing::XShape > mXConnectToA; + css::awt::Point maPointB; + css::uno::Reference< css::drawing::XShape > mXConnectToB; + + sal_uInt32 GetConnectorRule( bool bFirst ); + + EscherConnectorListEntry( css::uno::Reference< css::drawing::XShape > xC, + const css::awt::Point& rPA, + css::uno::Reference< css::drawing::XShape > xSA , + const css::awt::Point& rPB, + css::uno::Reference< css::drawing::XShape > xSB ) : + mXConnector (std::move( xC )), + maPointA ( rPA ), + mXConnectToA(std::move( xSA )), + maPointB ( rPB ), + mXConnectToB(std::move( xSB )) {} + + static sal_uInt32 GetClosestPoint( const tools::Polygon& rPoly, const css::awt::Point& rP ); +}; + +struct MSFILTER_DLLPUBLIC EscherExContainer +{ + sal_uInt32 nContPos; + SvStream& rStrm; + + EscherExContainer( SvStream& rSt, const sal_uInt16 nRecType, const sal_uInt16 nInstance = 0 ); + ~EscherExContainer(); +}; + +struct MSFILTER_DLLPUBLIC EscherExAtom +{ + sal_uInt32 nContPos; + SvStream& rStrm; + + EscherExAtom( SvStream& rSt, const sal_uInt16 nRecType, const sal_uInt16 nInstance = 0, const sal_uInt8 nVersion = 0 ); + ~EscherExAtom(); +}; + +struct EscherPropertyValueHelper +{ + static bool GetPropertyValue( + css::uno::Any& rAny, + const css::uno::Reference< css::beans::XPropertySet > &, + const OUString& rPropertyName, + bool bTestPropertyAvailability = false + ); + + static css::beans::PropertyState GetPropertyState( + const css::uno::Reference < css::beans::XPropertySet > &, + const OUString& rPropertyName + ); +}; + + +struct EscherPersistEntry +{ + sal_uInt32 mnID; + sal_uInt32 mnOffset; + + EscherPersistEntry( sal_uInt32 nId, sal_uInt32 nOffset ) { mnID = nId; mnOffset = nOffset; }; + +}; + + +class EscherBlibEntry +{ + friend class EscherGraphicProvider; + friend class EscherEx; + + MapMode maPrefMapMode; + Size maPrefSize; + + sal_uInt32 mnIdentifier[ 4 ]; + sal_uInt32 mnPictureOffset; // offset to the graphic in PictureStreams + sal_uInt32 mnSize; // size of real graphic + + sal_uInt32 mnRefCount; // !! reference count + sal_uInt32 mnSizeExtra; // !! size of preceding header + + ESCHER_BlibType meBlibType; + + bool mbIsEmpty; + bool mbIsNativeGraphicPossible; + +public: + + EscherBlibEntry( + sal_uInt32 nPictureOffset, + const GraphicObject& rObj, + const OString& rId, + const GraphicAttr* pAttr + ); + + ~EscherBlibEntry(); + + void WriteBlibEntry( SvStream& rSt, bool bWritePictureOffset, sal_uInt32 nResize = 0 ); + bool IsEmpty() const { return mbIsEmpty; }; + + bool operator==( const EscherBlibEntry& ) const; +}; + + +enum class EscherGraphicProviderFlags { + NONE = 0, + UseInstances = 1, +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +class MSFILTER_DLLPUBLIC EscherGraphicProvider +{ + EscherGraphicProviderFlags + mnFlags; + std::vector> + mvBlibEntrys; + OUString maBaseURI; + +protected: + + sal_uInt32 ImplInsertBlib( EscherBlibEntry* p_EscherBlibEntry ); + +public: + + sal_uInt32 GetBlibStoreContainerSize( SvStream const * pMergePicStreamBSE = nullptr ) const; + void WriteBlibStoreContainer( SvStream& rStrm, SvStream* pMergePicStreamBSE = nullptr ); + void WriteBlibStoreEntry(SvStream& rStrm, sal_uInt32 nBlipId, sal_uInt32 nResize); + sal_uInt32 GetBlibID( + SvStream& rPicOutStream, + GraphicObject const & pGraphicObject, + const css::awt::Rectangle* pVisArea = nullptr, + const GraphicAttr* pGrafikAttr = nullptr, + const bool ooxmlExport = false + ); + bool HasGraphics() const { return !mvBlibEntrys.empty(); }; + + void SetNewBlipStreamOffset( sal_Int32 nOffset ); + + bool GetPrefSize( const sal_uInt32 nBlibId, Size& rSize, MapMode& rMapMode ); + + void SetBaseURI( const OUString& rBaseURI ) { maBaseURI = rBaseURI; }; + const OUString& GetBaseURI() const { return maBaseURI; }; + + EscherGraphicProvider( EscherGraphicProviderFlags nFlags = EscherGraphicProviderFlags::NONE ); + virtual ~EscherGraphicProvider(); + + EscherGraphicProvider& operator=( EscherGraphicProvider const & ) = delete; // MSVC2015 workaround + EscherGraphicProvider( EscherGraphicProvider const & ) = delete; // MSVC2015 workaround +}; + +struct EscherShapeListEntry; + +class MSFILTER_DLLPUBLIC EscherSolverContainer +{ + ::std::vector< std::unique_ptr > maShapeList; + ::std::vector< std::unique_ptr > maConnectorList; + +public: + + sal_uInt32 GetShapeId( + const css::uno::Reference< css::drawing::XShape > & rShape + ) const; + + void AddShape( + const css::uno::Reference< css::drawing::XShape > &, + sal_uInt32 nId + ); + + void AddConnector( + const css::uno::Reference< css::drawing::XShape > &, + const css::awt::Point& rA, + css::uno::Reference< css::drawing::XShape > const &, + const css::awt::Point& rB, + css::uno::Reference< css::drawing::XShape > const & rConB + ); + + void WriteSolver( SvStream& ); + + EscherSolverContainer(); + ~EscherSolverContainer(); + + EscherSolverContainer& operator=( EscherSolverContainer const & ) = delete; // MSVC2015 workaround + EscherSolverContainer( EscherSolverContainer const & ) = delete; // MSVC2015 workaround +}; + + +#define ESCHER_CREATEPOLYGON_LINE 1 +#define ESCHER_CREATEPOLYGON_POLYLINE 2 +#define ESCHER_CREATEPOLYGON_POLYPOLYGON 4 + +class SdrObjCustomShape; + +struct EscherPropSortStruct +{ + std::vector nProp; + sal_uInt32 nPropValue; + sal_uInt16 nPropId; +}; + +typedef std::vector< EscherPropSortStruct > EscherProperties; + +class MSFILTER_DLLPUBLIC EscherPropertyContainer +{ + EscherGraphicProvider* pGraphicProvider; + SvStream* pPicOutStrm; + tools::Rectangle* pShapeBoundRect; + + sal_uInt32 nCountCount; + sal_uInt32 nCountSize; + + std::vector + pSortStruct; + + bool bHasComplexData; + + + static sal_uInt32 ImplGetColor( const sal_uInt32 rColor, bool bSwap = true ); + void ImplCreateGraphicAttributes( + const css::uno::Reference< css::beans::XPropertySet > & rXPropSet, + sal_uInt32 nBlibId, + bool bCreateCroppingAttributes + ); + bool ImplCreateEmbeddedBmp(GraphicObject const & rGraphicObject); + + SAL_DLLPRIVATE explicit EscherPropertyContainer( + EscherGraphicProvider * pGraphProv, SvStream * pPiOutStrm, + tools::Rectangle * pBoundRect); + +public: + + EscherPropertyContainer(); + EscherPropertyContainer( + EscherGraphicProvider& rGraphicProvider, // the PropertyContainer needs to know + SvStream* pPicOutStrm, // the GraphicProvider to be able to write + tools::Rectangle& rShapeBoundRect // FillBitmaps or GraphicObjects. + ); // under some circumstances the ShapeBoundRect + // is adjusted this will happen when rotated + // GraphicObjects are saved to PowerPoint + ~EscherPropertyContainer(); + + void AddOpt( + sal_uInt16 nPropID, + bool bBlib, + sal_uInt32 nSizeReduction, + SvMemoryStream& rStream); + + void AddOpt( + sal_uInt16 nPropertyID, + const OUString& rString); + + void AddOpt( + sal_uInt16 nPropertyID, + sal_uInt32 nPropValue, + bool bBlib = false); + + void AddOpt( + sal_uInt16 nPropertyID, + bool bBlib, + sal_uInt32 nPropValue, + const std::vector& rProp); + + bool GetOpt( sal_uInt16 nPropertyID, sal_uInt32& rPropValue ) const; + + bool GetOpt( sal_uInt16 nPropertyID, EscherPropSortStruct& rPropValue ) const; + + const EscherProperties & GetOpts() const; + + void Commit( SvStream& rSt, sal_uInt16 nVersion = 3, sal_uInt16 nRecType = ESCHER_OPT ); + + void CreateShapeProperties( + const css::uno::Reference< css::drawing::XShape > & rXShape + ); + bool CreateOLEGraphicProperties( + const css::uno::Reference< css::drawing::XShape > & rXOleObject + ); + bool CreateGraphicProperties( + const css::uno::Reference< css::drawing::XShape > & rXShape, + const GraphicObject& rGraphicObj + ); + bool CreateMediaGraphicProperties( + const css::uno::Reference< css::drawing::XShape > & rXMediaObject + ); + + /** Creates a complex ESCHER_Prop_fillBlip containing the BLIP directly (for Excel charts). */ + void CreateEmbeddedBitmapProperties( + css::uno::Reference const & rxBitmap, + css::drawing::BitmapMode eBitmapMode + ); + /** Creates a complex ESCHER_Prop_fillBlip containing a hatch style (for Excel charts). */ + void CreateEmbeddedHatchProperties( + const css::drawing::Hatch& rHatch, + const Color& rBackColor, + bool bFillBackground + ); + + // the GraphicProperties will only be created if a GraphicProvider and PicOutStrm is known + // DR: #99897# if no GraphicProvider is present, a complex ESCHER_Prop_fillBlip + // will be created, containing the BLIP directly (e.g. for Excel charts). + bool CreateGraphicProperties( + const css::uno::Reference< css::beans::XPropertySet > & rXPropSet, + const OUString& rSource, + const bool bCreateFillBitmap, + const bool bCreateCroppingAttributes = false, + const bool bFillBitmapModeAllowed = true, + const bool bOOxmlExport = false + ); + + bool CreateBlipPropertiesforOLEControl( const css::uno::Reference< css::beans::XPropertySet > & rXPropSet, const css::uno::Reference< css::drawing::XShape > & rXShape); + + bool CreatePolygonProperties( + const css::uno::Reference< css::beans::XPropertySet > & rXPropSet, + sal_uInt32 nFlags, + bool bBezier, + css::awt::Rectangle& rGeoRect, + tools::Polygon const * pPolygon = nullptr + ); + + static sal_uInt32 GetGradientColor( + const css::awt::Gradient* pGradient, + sal_uInt32 nStartColor + ); + + void CreateGradientProperties( const css::awt::Gradient & rGradient ); + void CreateGradientProperties( + const css::uno::Reference< css::beans::XPropertySet > &, + bool bTransparentGradient = false + ); + + void CreateLineProperties( + const css::uno::Reference< css::beans::XPropertySet > &, + bool bEdge + ); + void CreateFillProperties( + const css::uno::Reference< css::beans::XPropertySet > &, + bool bEdge, + bool bTransparentGradient = false ); + void CreateFillProperties( + const css::uno::Reference< css::beans::XPropertySet > &, + bool bEdge, + const css::uno::Reference< css::drawing::XShape > & rXShape ); + void CreateTextProperties( + const css::uno::Reference< css::beans::XPropertySet > &, + sal_uInt32 nText, + const bool bIsCustomShape = false, + const bool bIsTextFrame = true + ); + + bool CreateConnectorProperties( + const css::uno::Reference< css::drawing::XShape > & rXShape, + EscherSolverContainer& rSolver, + css::awt::Rectangle& rGeoRect, + sal_uInt16& rShapeType, + ShapeFlag& rShapeFlags + ); + + // Because shadow properties depends to the line and fillstyle, the CreateShadowProperties method should be called at last. + // It's active only when at least a FillStyle or LineStyle is set. + void CreateShadowProperties( + const css::uno::Reference< css::beans::XPropertySet > & + ); + + sal_Int32 GetValueForEnhancedCustomShapeParameter( const css::drawing::EnhancedCustomShapeParameter& rParameter, + const std::vector< sal_Int32 >& rEquationOrder, bool bAdjustTrans = false ); + // creates all necessary CustomShape properties, this includes also Text-, Shadow-, Fill-, and LineProperties + void CreateCustomShapeProperties( + const MSO_SPT eShapeType, + const css::uno::Reference< css::drawing::XShape > & + ); + bool IsFontWork() const; + + // helper functions which are also used by the escher import + static tools::PolyPolygon GetPolyPolygon( + const css::uno::Reference< css::drawing::XShape > & rXShape + ); + static tools::PolyPolygon GetPolyPolygon( const css::uno::Any& rSource ); + static MSO_SPT GetCustomShapeType( + const css::uno::Reference< css::drawing::XShape > & rXShape, + ShapeFlag& nMirrorFlags, + OUString& rShapeType, + bool bOOXML = false + ); + + // helper functions which are also used in ooxml export + static bool GetLineArrow( + const bool bLineStart, + const css::uno::Reference< css::beans::XPropertySet > & rXPropSet, + ESCHER_LineEnd& reLineEnd, + sal_Int32& rnArrowLength, + sal_Int32& rnArrowWidth + ); + + static bool IsDefaultObject( + const SdrObjCustomShape& rSdrObjCustomShape, + const MSO_SPT eShapeType); + + static void LookForPolarHandles( + const MSO_SPT eShapeType, + sal_Int32& nAdjustmentsWhichNeedsToBeConverted + ); + static bool GetAdjustmentValue( const css::drawing::EnhancedCustomShapeAdjustmentValue & rkProp, sal_Int32 nIndex, sal_Int32 nAdjustmentsWhichNeedsToBeConverted, sal_Int32& nValue ); +}; + + +class MSFILTER_DLLPUBLIC EscherPersistTable +{ + +public: + ::std::vector< std::unique_ptr > maPersistTable; + + bool PtIsID( sal_uInt32 nID ); + void PtInsert( sal_uInt32 nID, sal_uInt32 nOfs ); + void PtDelete( sal_uInt32 nID ); + sal_uInt32 PtGetOffsetByID( sal_uInt32 nID ); + void PtReplace( sal_uInt32 nID, sal_uInt32 nOfs ); + void PtReplaceOrInsert( sal_uInt32 nID, sal_uInt32 nOfs ); + + EscherPersistTable(); + virtual ~EscherPersistTable(); + + EscherPersistTable& operator=( EscherPersistTable const & ) = delete; // MSVC2015 workaround + EscherPersistTable( EscherPersistTable const & ) = delete; // MSVC2015 workaround +}; + + +class EscherEx; + +/// abstract base class for ESCHER_ClientTextbox, ESCHER_ClientData +class MSFILTER_DLLPUBLIC EscherExClientRecord_Base +{ +public: + virtual ~EscherExClientRecord_Base(); + + /// Application writes the record header + /// using rEx.AddAtom(...) followed by + /// record data written to rEx.GetStream() + virtual void WriteData( EscherEx& rEx ) const = 0; +}; + + +/// abstract base class for ESCHER_ClientAnchor +class MSFILTER_DLLPUBLIC EscherExClientAnchor_Base +{ +public: + virtual ~EscherExClientAnchor_Base(); + + /// Application writes the record header + /// using rEx.AddAtom(...) followed by + /// record data written to rEx.GetStream() + virtual void WriteData( EscherEx& rEx, + const tools::Rectangle& rRect ) = 0; +}; + +class InteractionInfo +{ + std::unique_ptr mpHyperlinkRecord; + +public: + InteractionInfo( SvMemoryStream* pStream ) + { + mpHyperlinkRecord.reset( pStream ); + } + const std::unique_ptr< SvMemoryStream >& getHyperlinkRecord() const { return mpHyperlinkRecord; } +}; + +class EscherExHostAppData +{ +private: + EscherExClientAnchor_Base* pClientAnchor; + EscherExClientRecord_Base* pClientData; + EscherExClientRecord_Base* pClientTextbox; + InteractionInfo* pInteractionInfo; + // ignore single shape if entire pages are written + bool bDontWriteShape; + +public: + EscherExHostAppData() : pClientAnchor(nullptr), pClientData(nullptr), + pClientTextbox(nullptr), pInteractionInfo(nullptr), bDontWriteShape(false) + {} + + void SetInteractionInfo( InteractionInfo* p ) + { pInteractionInfo = p; } + void SetClientAnchor( EscherExClientAnchor_Base* p ) + { pClientAnchor = p; } + void SetClientData( EscherExClientRecord_Base* p ) + { pClientData = p; } + void SetClientTextbox( EscherExClientRecord_Base* p ) + { pClientTextbox = p; } + void SetDontWriteShape( bool b ) + { bDontWriteShape = b; } + InteractionInfo* GetInteractionInfo() const + { return pInteractionInfo; } + EscherExClientAnchor_Base* GetClientAnchor() const + { return pClientAnchor; } + EscherExClientRecord_Base* GetClientTextbox() const + { return pClientTextbox; } + + void WriteClientAnchor( EscherEx& rEx, const tools::Rectangle& rRect ) + { if( pClientAnchor ) pClientAnchor->WriteData( rEx, rRect ); } + void WriteClientData( EscherEx& rEx ) + { if( pClientData ) pClientData->WriteData( rEx ); } + void WriteClientTextbox( EscherEx& rEx ) + { if( pClientTextbox ) pClientTextbox->WriteData( rEx ); } + + bool DontWriteShape() const { return bDontWriteShape; } +}; + + +/** Instance for global DFF data, shared through various instances of EscherEx. */ +class MSFILTER_DLLPUBLIC EscherExGlobal : public EscherGraphicProvider +{ +public: + explicit EscherExGlobal(); + virtual ~EscherExGlobal() override; + + /** Returns a new drawing ID for a new drawing container (DGCONTAINER). */ + sal_uInt32 GenerateDrawingId(); + /** Creates and returns a new shape identifier, updates the internal shape + counters and registers the identifier in the DGG cluster table. + @param nDrawingId Drawing identifier has to be passed to be able to + generate shape identifiers for multiple drawings simultaneously. */ + sal_uInt32 GenerateShapeId( sal_uInt32 nDrawingId, bool bIsInSpgr ); + /** Returns the number of shapes in the current drawing, based on number of + calls to the GenerateShapeId() function. */ + sal_uInt32 GetDrawingShapeCount( sal_uInt32 nDrawingId ) const; + /** Returns the last shape identifier generated by the GenerateShapeId() + function. */ + sal_uInt32 GetLastShapeId( sal_uInt32 nDrawingId ) const; + + /** Sets the flag indicating that the DGGCONTAINER exists. */ + void SetDggContainer() { mbHasDggCont = true; } + /** Sets the flag indicating that the DGGCONTAINER exists. */ + bool HasDggContainer() const { return mbHasDggCont; } + /** Returns the total size of the DGG atom (including header). */ + sal_uInt32 GetDggAtomSize() const; + /** Writes the complete DGG atom to the passed stream (overwrites existing data!). */ + void WriteDggAtom( SvStream& rStrm ) const; + + /** Called if a picture shall be written and no picture stream is set at + class ImplEESdrWriter. + + On first invocation, this function calls the virtual member function + ImplQueryPictureStream(). The return value will be cached internally + for subsequent calls and for the GetPictureStream() function. + */ + SvStream* QueryPictureStream(); + + /** Returns the picture stream if existing (queried), otherwise null. */ + SvStream* GetPictureStream() { return mpPicStrm; } + +private: + /** Derived classes may implement to create a new stream used to store the + picture data. + + The implementation has to take care about lifetime of the returned + stream (it will not be destructed automatically). This function is + called exactly once. The return value will be cached internally for + repeated calls of the public QueryPictureStream() function. + */ + virtual SvStream* ImplQueryPictureStream(); + +private: + struct ClusterEntry + { + sal_uInt32 mnDrawingId; /// Identifier of drawing this cluster belongs to (one-based index into maDrawingInfos). + sal_uInt32 mnNextShapeId; /// Next free shape identifier in this cluster. + explicit ClusterEntry( sal_uInt32 nDrawingId ) : mnDrawingId( nDrawingId ), mnNextShapeId( 0 ) {} + }; + + struct DrawingInfo + { + sal_uInt32 mnClusterId; /// Currently used cluster (one-based index into maClusterTable). + sal_uInt32 mnShapeCount; /// Current number of shapes in this drawing. + sal_uInt32 mnLastShapeId; /// Last shape identifier generated for this drawing. + explicit DrawingInfo( sal_uInt32 nClusterId ) : mnClusterId( nClusterId ), mnShapeCount( 0 ), mnLastShapeId( 0 ) {} + }; + typedef ::std::vector< DrawingInfo > DrawingInfoVector; + + std::vector< ClusterEntry > maClusterTable; /// List with cluster IDs (used object IDs in drawings). + DrawingInfoVector maDrawingInfos; /// Data about all used drawings. + SvStream* mpPicStrm; /// Cached result of ImplQueryPictureStream(). + bool mbHasDggCont; /// True = the DGGCONTAINER has been initialized. + bool mbPicStrmQueried; /// True = ImplQueryPictureStream() has been called. +}; + +class SdrObject; +class SdrPage; +class ImplEESdrWriter; + +class MSFILTER_DLLPUBLIC EscherEx : public EscherPersistTable +{ + protected: + std::shared_ptr mxGlobal; + ::std::unique_ptr< ImplEESdrWriter > mpImplEESdrWriter; + SvStream* mpOutStrm; + bool mbOwnsStrm; + sal_uInt32 mnStrmStartOfs; + std::vector< sal_uInt32 > mOffsets; + std::vector< sal_uInt16 > mRecTypes; + + sal_uInt32 mnCurrentDg; + sal_uInt32 mnCountOfs; + + sal_uInt32 mnGroupLevel; + SdrLayerID mnHellLayerId; + + bool mbEscherSpgr; + bool mbEscherDg; + bool mbOOXML; + OUString mEditAs; + + + bool DoSeek( sal_uInt32 nKey ); + +public: + explicit EscherEx( std::shared_ptr xGlobal, SvStream* pOutStrm, bool bOOXML = false ); + virtual ~EscherEx() override; + + /** Creates and returns a new shape identifier, updates the internal shape + counters and registers the identifier in the DGG cluster table. */ + virtual sal_uInt32 GenerateShapeId() { return mxGlobal->GenerateShapeId( mnCurrentDg, mbEscherSpgr ); } + + /** Returns the graphic provider from the global object that has been + passed to the constructor. + */ + EscherGraphicProvider& GetGraphicProvider() { return *mxGlobal; } + + /** Called if a picture shall be written and no picture stream is set at + class ImplEESdrWriter. + */ + SvStream* QueryPictureStream() { return mxGlobal->QueryPictureStream(); } + + /// Inserts internal data into the EscherStream, this process + /// may and has to be executed only once + /// If pPicStreamMergeBSE is known, the BLIPs from this stream are being + /// merged into the MsofbtBSE Records of the EscherStream like it's + /// required for Excel (and maybe Word?) + void Flush( SvStream* pPicStreamMergeBSE = nullptr ); + + /** Inserts the passed number of bytes at the current position of the + output stream. + + Inserts dummy bytes and moves all following stream data, and updates + all internal stream offsets stored in the PersistTable and the affected + container sizes, which makes this operation very expensive. (!) + + @param nBytes The number of bytes to be inserted into the stream. + + An atom that currently ends + exactly at the current stream position will not be expanded to + include the inserted data (used to insert e.g. a new atom after an + existing atom). Note that containers that end exactly at the + current stream position are always expanded to include the inserted + data. + */ + void InsertAtCurrentPos( sal_uInt32 nBytes ); + + void InsertPersistOffset( sal_uInt32 nKey, sal_uInt32 nOffset ); // It is not being checked if this key is already in the PersistantTable + void ReplacePersistOffset( sal_uInt32 nKey, sal_uInt32 nOffset ); + sal_uInt32 GetPersistOffset( sal_uInt32 nKey ); + bool SeekToPersistOffset( sal_uInt32 nKey ); + void InsertAtPersistOffset( sal_uInt32 nKey, sal_uInt32 nValue ); // nValue is being inserted into the Stream where it's appropriate (overwrite mode), without that the + // current StreamPosition changes + void SetEditAs( const OUString& rEditAs ); + const OUString& GetEditAs() const { return mEditAs; } + SvStream& GetStream() const { return *mpOutStrm; } + sal_uInt64 GetStreamPos() const { return mpOutStrm->Tell(); } + + // features during the creation of the following Containers: + + // ESCHER_DggContainer: an EscherDgg Atom is automatically being created and managed + // ESCHER_DgContainer: an EscherDg Atom is automatically being created and managed + // ESCHER_SpgrContainer: + // ESCHER_SpContainer: + + virtual void OpenContainer( sal_uInt16 nEscherContainer, int nRecInstance = 0 ); + virtual void CloseContainer(); + + void BeginAtom(); + void EndAtom( sal_uInt16 nRecType, int nRecVersion = 0, int nRecInstance = 0 ); + void AddAtom( sal_uInt32 nAtomSitze, sal_uInt16 nRecType, int nRecVersion = 0, int nRecInstance = 0 ); + void AddChildAnchor( const tools::Rectangle& rRectangle ); + void AddClientAnchor( const tools::Rectangle& rRectangle ); + + virtual sal_uInt32 EnterGroup( const OUString& rShapeName, const tools::Rectangle* pBoundRect ); + sal_uInt32 EnterGroup( const tools::Rectangle* pBoundRect = nullptr ); + sal_uInt32 GetGroupLevel() const { return mnGroupLevel; }; + void SetGroupSnapRect( sal_uInt32 nGroupLevel, const tools::Rectangle& rRect ); + void SetGroupLogicRect( sal_uInt32 nGroupLevel, const tools::Rectangle& rRect ); + virtual void LeaveGroup(); + + // a ESCHER_Sp is being written ( a ESCHER_DgContainer has to be opened for this purpose!) + virtual void AddShape( sal_uInt32 nShpInstance, ShapeFlag nFlagIds, sal_uInt32 nShapeID = 0 ); + + virtual void Commit( EscherPropertyContainer& rProps, const tools::Rectangle& rRect); + + static sal_uInt32 GetColor( const sal_uInt32 nColor ); + static sal_uInt32 GetColor( const Color& rColor ); + + // ...Sdr... implemented in eschesdo.cxx + + void AddSdrPage( const SdrPage& rPage, bool ooxmlExport = false ); + void AddUnoShapes( const css::uno::Reference< css::drawing::XShapes >& rxShapes, bool ooxmlExport = false ); + + /// returns the ShapeID + sal_uInt32 AddSdrObject( const SdrObject& rObj, bool ooxmlExport = false ); + virtual void AddSdrObjectVMLObject( const SdrObject& /*rObj*/) + { + // Required for Exporting VML shape + } + + /// If objects are written through AddSdrObject the + /// SolverContainer has to be written, and maybe some + /// maintenance to be done. + void EndSdrObjectPage(); + + /// Called before a shape is written, application supplies + /// ClientRecords. May set AppData::bDontWriteShape so the + /// shape is ignored. + virtual EscherExHostAppData* StartShape( + const css::uno::Reference< css::drawing::XShape >& rShape, + const tools::Rectangle* pChildAnchor ); + + /// Called after a shape is written to inform the application + /// of the resulted shape type and ID. + virtual void EndShape( sal_uInt16 nShapeType, sal_uInt32 nShapeID ); + + /// Called before an AdditionalText EnterGroup occurs. + /// The current shape will be written in three parts: + /// a group shape, the shape itself, and an extra textbox shape. + /// The complete flow is: + /// StartShape sets HostData1. + /// EnterAdditionalTextGroup sets HostData2, App may modify + /// HostData1 and keep track of the change. + /// The group shape is written with HostData2. + /// Another StartShape with the same (!) object sets HostData3. + /// The current shape is written with HostData3. + /// EndShape is called for the current shape. + /// Another StartShape with the same (!) object sets HostData4. + /// The textbox shape is written with HostData4. + /// EndShape is called for the textbox shape. + /// EndShape is called for the group shape, this provides + /// the same functionality as an ordinary recursive group. + virtual EscherExHostAppData* EnterAdditionalTextGroup(); + + /// Called if an ESCHER_Prop_lTxid shall be written + virtual sal_uInt32 QueryTextID( const css::uno::Reference< css::drawing::XShape >&, sal_uInt32 nShapeId ); + // add a dummy rectangle shape into the escher stream + sal_uInt32 AddDummyShape(); + + static const SdrObject* GetSdrObject( const css::uno::Reference< css::drawing::XShape >& rXShape ); + + void SetHellLayerId( SdrLayerID nId ) { mnHellLayerId = nId; } + SdrLayerID GetHellLayerId() const { return mnHellLayerId; } + +private: + EscherEx( const EscherEx& ) = delete; + EscherEx& operator=( const EscherEx& ) = delete; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/mscodec.hxx b/include/filter/msfilter/mscodec.hxx new file mode 100644 index 000000000..90c39a8cc --- /dev/null +++ b/include/filter/msfilter/mscodec.hxx @@ -0,0 +1,499 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_MSCODEC_HXX +#define INCLUDED_FILTER_MSFILTER_MSCODEC_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { struct NamedValue; } +} + +namespace msfilter { + + +/** Encodes and decodes data from protected MSO 95- documents. + */ +class MSFILTER_DLLPUBLIC MSCodec_Xor95 +{ +public: + explicit MSCodec_Xor95(int nRotateDistance); + virtual ~MSCodec_Xor95(); + + /** Initializes the algorithm with the specified password. + + @param pPassData + Character array containing the password. Must be zero terminated, + which results in a maximum length of 15 characters. + */ + void InitKey( const sal_uInt8 pnPassData[ 16 ] ); + + /** Initializes the algorithm with the encryption data. + + @param aData + The sequence contains the necessary data to initialize + the codec. + */ + bool InitCodec( const css::uno::Sequence< css::beans::NamedValue >& aData ); + + /** Retrieves the encryption data + + @return + The sequence contains the necessary data to initialize + the codec. + */ + css::uno::Sequence< css::beans::NamedValue > GetEncryptionData(); + + + /** Verifies the validity of the password using the passed key and hash. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param nKey + Password key value read from the file. + @param nHash + Password hash value read from the file. + + @return + true = Test was successful. + */ + bool VerifyKey( sal_uInt16 nKey, sal_uInt16 nHash ) const; + + /** Reinitializes the codec to start a new memory block. + + Resets the internal key offset to 0. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + */ + void InitCipher(); + + /** Decodes a block of memory inplace. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param pnData + Encrypted data block. Will contain the decrypted data afterwards. + @param nBytes + Size of the passed data block. + */ + virtual void Decode( sal_uInt8* pnData, std::size_t nBytes )=0; + + /** Lets the cipher skip a specific amount of bytes. + + This function sets the cipher to the same state as if the specified + amount of data has been decoded with one or more calls of Decode(). + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param nBytes + Number of bytes to be skipped (cipher "seeks" forward). + */ + void Skip( std::size_t nBytes ); + +protected: + sal_uInt8 mpnKey[ 16 ] = {}; /// Encryption key. + std::size_t mnOffset; /// Key offset. + +private: + MSCodec_Xor95( const MSCodec_Xor95& ) = delete; + MSCodec_Xor95& operator=( const MSCodec_Xor95& ) = delete; + + sal_uInt16 mnKey; /// Base key from password. + sal_uInt16 mnHash; /// Hash value from password. + int mnRotateDistance; +}; + +/** Encodes and decodes data from protected MSO XLS 95- documents. + */ +class MSFILTER_DLLPUBLIC MSCodec_XorXLS95 final : public MSCodec_Xor95 +{ +public: + explicit MSCodec_XorXLS95() : MSCodec_Xor95(2) {} + + /** Decodes a block of memory inplace. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param pnData + Encrypted data block. Will contain the decrypted data afterwards. + @param nBytes + Size of the passed data block. + */ + virtual void Decode( sal_uInt8* pnData, std::size_t nBytes ) override; +}; + +/** Encodes and decodes data from protected MSO Word 95- documents. + */ +class MSFILTER_DLLPUBLIC MSCodec_XorWord95 final : public MSCodec_Xor95 +{ +public: + explicit MSCodec_XorWord95() : MSCodec_Xor95(7) {} + + /** Decodes a block of memory inplace. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param pnData + Encrypted data block. Will contain the decrypted data afterwards. + @param nBytes + Size of the passed data block. + */ + virtual void Decode( sal_uInt8* pnData, std::size_t nBytes ) override; +}; + +class MSFILTER_DLLPUBLIC MSCodec97 +{ +public: + MSCodec97(size_t nHashLen, OUString aEncKeyName); + virtual ~MSCodec97(); + + /** Initializes the algorithm with the encryption data. + + @param aData + The sequence contains the necessary data to initialize + the codec. + */ + bool InitCodec(const css::uno::Sequence< css::beans::NamedValue >& aData); + + /** Retrieves the encryption data + + @return + The sequence contains the necessary data to initialize + the codec. + */ + virtual css::uno::Sequence GetEncryptionData(); + + /** Initializes the algorithm with the specified password and document ID. + + @param pPassData + Wide character array containing the password. Must be zero + terminated, which results in a maximum length of 15 characters. + @param pDocId + Unique document identifier read from or written to the file. + */ + virtual void InitKey(const sal_uInt16 pPassData[16], + const sal_uInt8 pDocId[16]) = 0; + + + /** Verifies the validity of the password using the passed salt data. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param pSaltData + Salt data block read from the file. + @param pSaltDigest + Salt digest read from the file. + + @return + true = Test was successful. + */ + bool VerifyKey(const sal_uInt8* pSaltData, const sal_uInt8* pSaltDigest); + + virtual void GetDigestFromSalt(const sal_uInt8* pSaltData, sal_uInt8* pDigest) = 0; + + /** Rekeys the codec using the specified counter. + + After reading a specific amount of data the cipher algorithm needs to + be rekeyed using a counter that counts the data blocks. + + The block size is for example 512 Bytes for Word files and 1024 Bytes + for Excel files. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param nCounter + Block counter used to rekey the cipher. + */ + virtual bool InitCipher(sal_uInt32 nCounter) = 0; + + /** Encodes a block of memory. + + @see rtl_cipher_encode() + + @precond + The codec must be initialized with InitKey() before this function + can be used. The destination buffer must be able to take all + unencoded data from the source buffer (usually this means it must be + as long as or longer than the source buffer). + + @param pData + Unencrypted source data block. + @param nDatLen + Size of the passed source data block. + @param pBuffer + Destination buffer for the encrypted data. + @param nBufLen + Size of the destination buffer. + + @return + true = Encoding was successful (no error occurred). + */ + bool Encode(const void* pData, std::size_t nDatLen, + sal_uInt8* pBuffer, std::size_t nBufLen); + + /** Decodes a block of memory. + + @see rtl_cipher_decode() + + @precond + The codec must be initialized with InitKey() before this function + can be used. The destination buffer must be able to take all + encoded data from the source buffer (usually this means it must be + as long as or longer than the source buffer). + + @param pData + Encrypted source data block. + @param nDatLen + Size of the passed source data block. + @param pBuffer + Destination buffer for the decrypted data. + @param nBufLen + Size of the destination buffer. + + @return + true = Decoding was successful (no error occurred). + */ + bool Decode(const void* pData, std::size_t nDatLen, + sal_uInt8* pBuffer, std::size_t nBufLen); + + /** Lets the cipher skip a specific amount of bytes. + + This function sets the cipher to the same state as if the specified + amount of data has been decoded with one or more calls of Decode(). + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param nDatLen + Number of bytes to be skipped (cipher "seeks" forward). + */ + bool Skip(std::size_t nDatLen); + + /* allows to get the unique document id from the codec + */ + void GetDocId( sal_uInt8 pDocId[16] ); + +private: + MSCodec97(const MSCodec97&) = delete; + MSCodec97& operator=(const MSCodec97&) = delete; + +protected: + OUString m_sEncKeyName; + size_t m_nHashLen; + rtlCipher m_hCipher; + std::vector m_aDocId; + std::vector m_aDigestValue; +}; + +/** Encodes and decodes data from protected MSO 97+ documents. + + This is a wrapper class around low level cryptographic functions from RTL. + Implementation is based on the wvDecrypt package by Caolan McNamara: + http://www.csn.ul.ie/~caolan/docs/wvDecrypt.html + */ +class MSFILTER_DLLPUBLIC MSCodec_Std97 final : public MSCodec97 +{ +public: + MSCodec_Std97(); + virtual ~MSCodec_Std97() override; + + /** Initializes the algorithm with the specified password and document ID. + + @param pPassData + Wide character array containing the password. Must be zero + terminated, which results in a maximum length of 15 characters. + @param pDocId + Unique document identifier read from or written to the file. + */ + virtual void InitKey(const sal_uInt16 pPassData[16], + const sal_uInt8 pDocId[16]) override; + + /** Rekeys the codec using the specified counter. + + After reading a specific amount of data the cipher algorithm needs to + be rekeyed using a counter that counts the data blocks. + + The block size is for example 512 Bytes for Word files and 1024 Bytes + for Excel files. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param nCounter + Block counter used to rekey the cipher. + */ + virtual bool InitCipher(sal_uInt32 nCounter) override; + + /** Creates an MD5 digest of salt digest. */ + void CreateSaltDigest( + const sal_uInt8 nSaltData[16], sal_uInt8 nSaltDigest[16] ); + + /** Gets salt data and salt digest. + + @precond + The codec must be initialized with InitKey() before this function + can be used. + + @param pSalt + Salt, a random number. + @param pSaltData + Salt data block generated from the salt. + @param pSaltDigest + Salt digest generated from the salt. + */ + void GetEncryptKey ( + const sal_uInt8 pSalt[16], + sal_uInt8 pSaltData[16], + sal_uInt8 pSaltDigest[16]); + + virtual void GetDigestFromSalt(const sal_uInt8* pSaltData, sal_uInt8* pDigest) override; + +private: + MSCodec_Std97( const MSCodec_Std97& ) = delete; + MSCodec_Std97& operator=( const MSCodec_Std97& ) = delete; + + rtlDigest m_hDigest; +}; + +class MSFILTER_DLLPUBLIC MSCodec_CryptoAPI final : public MSCodec97 +{ +private: + css::uno::Sequence m_aStd97Key; +public: + MSCodec_CryptoAPI(); + + virtual void InitKey(const sal_uInt16 pPassData[16], + const sal_uInt8 pDocId[16]) override; + virtual bool InitCipher(sal_uInt32 nCounter) override; + virtual void GetDigestFromSalt(const sal_uInt8* pSaltData, sal_uInt8* pDigest) override; + virtual css::uno::Sequence GetEncryptionData() override; +}; + +const sal_uInt32 ENCRYPTINFO_CRYPTOAPI = 0x00000004; +const sal_uInt32 ENCRYPTINFO_DOCPROPS = 0x00000008; +const sal_uInt32 ENCRYPTINFO_EXTERNAL = 0x00000010; +const sal_uInt32 ENCRYPTINFO_AES = 0x00000020; + +const sal_uInt32 ENCRYPT_ALGO_AES128 = 0x0000660E; +const sal_uInt32 ENCRYPT_ALGO_AES192 = 0x0000660F; +const sal_uInt32 ENCRYPT_ALGO_AES256 = 0x00006610; +const sal_uInt32 ENCRYPT_ALGO_RC4 = 0x00006801; + +const sal_uInt32 ENCRYPT_HASH_SHA1 = 0x00008004; + +const sal_uInt32 ENCRYPT_KEY_SIZE_AES_128 = 0x00000080; +const sal_uInt32 ENCRYPT_KEY_SIZE_AES_192 = 0x000000C0; +const sal_uInt32 ENCRYPT_KEY_SIZE_AES_256 = 0x00000100; + +const sal_uInt32 ENCRYPT_PROVIDER_TYPE_AES = 0x00000018; +const sal_uInt32 ENCRYPT_PROVIDER_TYPE_RC4 = 0x00000001; + +// version of encryption info used in MS Office 1997 (major = 1, minor = 1) +const sal_uInt32 VERSION_INFO_1997_FORMAT = 0x00010001; +// version of encryption info used in MS Office 2007 (major = 3, minor = 2) +const sal_uInt32 VERSION_INFO_2007_FORMAT = 0x00020003; +// version of encryption info used in MS Office 2007 SP2 and older (major = 4, minor = 2) +const sal_uInt32 VERSION_INFO_2007_FORMAT_SP2 = 0x00020004; + +// version of encryption info - agile (major = 4, minor = 4) +const sal_uInt32 VERSION_INFO_AGILE = 0x00040004; + +const sal_uInt32 AGILE_ENCRYPTION_RESERVED = 0x00000040; + +const sal_uInt32 SALT_LENGTH = 16; +const sal_uInt32 ENCRYPTED_VERIFIER_LENGTH = 16; + +struct MSFILTER_DLLPUBLIC EncryptionStandardHeader +{ + sal_uInt32 flags; + sal_uInt32 sizeExtra; // 0 + sal_uInt32 algId; // if flag AES && CRYPTOAPI this defaults to 128-bit AES + sal_uInt32 algIdHash; // 0: determine by flags - defaults to SHA-1 if not external + sal_uInt32 keyBits; // key size in bits: 0 (determine by flags), 128, 192, 256 + sal_uInt32 providedType; // AES or RC4 + sal_uInt32 reserved1; // 0 + sal_uInt32 reserved2; // 0 + + EncryptionStandardHeader(); +}; + +struct MSFILTER_DLLPUBLIC EncryptionVerifierAES +{ + sal_uInt32 saltSize; // must be 0x00000010 + sal_uInt8 salt[SALT_LENGTH] = {}; // random generated salt value + sal_uInt8 encryptedVerifier[ENCRYPTED_VERIFIER_LENGTH] = {}; // randomly generated verifier value + sal_uInt32 encryptedVerifierHashSize; // actually written hash size - depends on algorithm + sal_uInt8 encryptedVerifierHash[comphelper::SHA256_HASH_LENGTH] = {}; // verifier value hash - itself also encrypted + + EncryptionVerifierAES(); +}; + +struct MSFILTER_DLLPUBLIC EncryptionVerifierRC4 +{ + sal_uInt32 saltSize; // must be 0x00000010 + sal_uInt8 salt[SALT_LENGTH] = {}; // random generated salt value + sal_uInt8 encryptedVerifier[ENCRYPTED_VERIFIER_LENGTH] = {}; // randomly generated verifier value + sal_uInt32 encryptedVerifierHashSize; // actually written hash size - depends on algorithm + sal_uInt8 encryptedVerifierHash[comphelper::SHA1_HASH_LENGTH] = {}; // verifier value hash - itself also encrypted + + EncryptionVerifierRC4(); +}; + +struct MSFILTER_DLLPUBLIC StandardEncryptionInfo +{ + EncryptionStandardHeader header; + EncryptionVerifierAES verifier; +}; + +struct MSFILTER_DLLPUBLIC RC4EncryptionInfo +{ + EncryptionStandardHeader header; + EncryptionVerifierRC4 verifier; +}; + +} // namespace msfilter + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/msdffimp.hxx b/include/filter/msfilter/msdffimp.hxx new file mode 100644 index 000000000..3dfd170bc --- /dev/null +++ b/include/filter/msfilter/msdffimp.hxx @@ -0,0 +1,809 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_MSDFFIMP_HXX +#define INCLUDED_FILTER_MSFILTER_MSDFFIMP_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Color; +class GDIMetaFile; +class SotStorage; +class SvStream; +class SdrObject; +class SdrOle2Obj; +class SdrModel; +class SwFlyFrameFormat; + +struct SvxMSDffBLIPInfos; +struct SvxMSDffShapeInfo; +struct SvxMSDffShapeOrder; + +class SvxMSDffManager; +class SfxItemSet; +struct DffObjData; +class SvGlobalName; + +namespace com::sun::star { + namespace beans { class XPropertySet; } + namespace embed { class XEmbeddedObject; } + namespace embed { class XStorage; } +} + +class MSFILTER_DLLPUBLIC SvxMSDffClientData +{ +public: + virtual void NotifyFreeObj(SdrObject* pObj) = 0; + virtual ~SvxMSDffClientData() {} +}; + +class MSFILTER_DLLPUBLIC DffPropertyReader : public DffPropSet +{ + const SvxMSDffManager& rManager; + std::unique_ptr pDefaultPropSet; + + void ApplyCustomShapeTextAttributes( SfxItemSet& rSet ) const; + void CheckAndCorrectExcelTextRotation( SvStream& rIn, SfxItemSet& rSet, DffObjData const & rObjData ) const; + void ApplyCustomShapeGeometryAttributes( SvStream& rIn, + SfxItemSet& rSet, + const DffObjData& rObjData ) const; + void ApplyLineAttributes( SfxItemSet& rSet, const MSO_SPT eShapeType ) const; // #i28269# + void ApplyFillAttributes( SvStream& rIn, SfxItemSet& rSet, const DffObjData& rObjData ) const; + +public: + Degree100 mnFix16Angle; + bool mbRotateGranientFillWithAngle; + + explicit DffPropertyReader( const SvxMSDffManager& rManager ); + ~DffPropertyReader(); + + DffPropertyReader& operator=( DffPropertyReader const & ) = delete; // MSVC2015 workaround + DffPropertyReader( DffPropertyReader const & ) = delete; // MSVC2015 workaround + + static Degree100 Fix16ToAngle( sal_Int32 nAngle ); + +#ifdef DBG_CUSTOMSHAPE + void ReadPropSet( SvStream& rIn, SvxMSDffClientData* pClientData, sal_uInt32 nShapeType = 0 ) const; +#else + void ReadPropSet( SvStream& rIn, SvxMSDffClientData* pClientData ) const; +#endif + + void SetDefaultPropSet( SvStream& rIn, sal_uInt32 nOffDgg ) const; + void ApplyAttributes( SvStream& rIn, SfxItemSet& rSet ) const; + void ApplyAttributes( SvStream& rIn, SfxItemSet& rSet, DffObjData const & rObjData ) const; + void ImportGradientColor( SfxItemSet& aSet, sal_uInt32 eMSO_FillType, double dTrans, double dBackTrans ) const; +}; + +#define COL_DEFAULT ::Color( 0xFA, 0xFB, 0xFC ) + +typedef ::std::map< sal_Int32, SdrObject* > SvxMSDffShapeIdContainer; + +inline constexpr OUStringLiteral SVEXT_PERSIST_STREAM = u"\002OlePres000"; + +/// the following will be sorted by the order of their appearance: +typedef std::vector> SvxMSDffShapeOrders; + +struct MSFILTER_DLLPUBLIC CompareSvxMSDffShapeInfoById +{ + bool operator()(std::shared_ptr const& lhs, + std::shared_ptr const& rhs) const; +}; +struct CompareSvxMSDffShapeInfoByTxBxComp +{ + bool operator()(std::shared_ptr const& lhs, + std::shared_ptr const& rhs) const; +}; + +// the following will be sorted explicitly: +typedef ::std::set< std::shared_ptr, + CompareSvxMSDffShapeInfoById > SvxMSDffShapeInfos_ById; +typedef ::std::multiset< std::shared_ptr, + CompareSvxMSDffShapeInfoByTxBxComp> SvxMSDffShapeInfos_ByTxBxComp; + +#define SVXMSDFF_SETTINGS_CROP_BITMAPS 1 +#define SVXMSDFF_SETTINGS_IMPORT_PPT 2 +#define SVXMSDFF_SETTINGS_IMPORT_EXCEL 4 + +// for the CreateSdrOLEFromStorage we need the information, how we handle +// convert able OLE-Objects - this is stored in +#define OLE_MATHTYPE_2_STARMATH 0x0001 +#define OLE_WINWORD_2_STARWRITER 0x0002 +#define OLE_EXCEL_2_STARCALC 0x0004 +#define OLE_POWERPOINT_2_STARIMPRESS 0x0008 + +struct SvxMSDffConnectorRule +{ + sal_uInt32 nShapeA; ///< SPID of shape A + sal_uInt32 nShapeB; ///< SPID of shape B + sal_uInt32 nShapeC; ///< SPID of connector shape + sal_uInt32 ncptiA; ///< Connection site Index of shape A + sal_uInt32 ncptiB; ///< Connection site Index of shape B + ShapeFlag nSpFlagsA; ///< SpFlags of shape A (the original mirror flags + ///< must be known when solving the Solver Container) + ShapeFlag nSpFlagsB; ///< SpFlags of shape B + + SdrObject* pAObj; ///< pPtr of object (corresponding to shape A) + SdrObject* pBObj; ///< pPtr of object (corresponding to shape B) + SdrObject* pCObj; ///< pPtr of connector object + + SvxMSDffConnectorRule() + : nShapeA(0) + , nShapeB(0) + , nShapeC(0) + , ncptiA(0) + , ncptiB(0) + , nSpFlagsA( ShapeFlag::NONE ) + , nSpFlagsB( ShapeFlag::NONE ) + , pAObj( nullptr ) + , pBObj( nullptr ) + , pCObj( nullptr ) + {}; + +}; + +struct MSFILTER_DLLPUBLIC SvxMSDffSolverContainer +{ + ::std::vector< std::unique_ptr > aCList; + + SvxMSDffSolverContainer(); + ~SvxMSDffSolverContainer(); + + SvxMSDffSolverContainer& operator=( SvxMSDffSolverContainer const & ) = delete; // MSVC2015 workaround + SvxMSDffSolverContainer( SvxMSDffSolverContainer const & ) = delete; // MSVC2015 workaround + + MSFILTER_DLLPUBLIC friend SvStream& ReadSvxMSDffSolverContainer( SvStream& rIn, SvxMSDffSolverContainer& rAtom ); +}; + +struct FIDCL +{ + sal_uInt32 dgid; ///< DG owning the SPIDs in this cluster +}; + +/// provided by SvxMSDffManager for each shape in a group +struct MSDffTxId +{ + sal_uInt16 nTxBxS; + sal_uInt16 nSequence; + MSDffTxId() + : nTxBxS( 0 ), nSequence( 0 ) {} + MSDffTxId( const MSDffTxId& rCopy ) + : nTxBxS( rCopy.nTxBxS ), nSequence( rCopy.nSequence ) {} +}; + +struct MSFILTER_DLLPUBLIC SvxMSDffImportRec +{ + static const int RELTO_DEFAULT = 2; + + SdrObject* pObj; + std::optional + pWrapPolygon; + std::unique_ptr + pClientAnchorBuffer; + sal_uInt32 nClientAnchorLen; + std::unique_ptr + pClientDataBuffer; + sal_uInt32 nClientDataLen; + sal_uInt32 nXAlign; + std::optional nXRelTo; + sal_uInt32 nYAlign; + std::optional nYRelTo; + sal_uInt32 nGroupShapeBooleanProperties; + ShapeFlag nFlags; + sal_Int32 nDxTextLeft; ///< distance of text box from surrounding shape + sal_Int32 nDyTextTop; + sal_Int32 nDxTextRight; + sal_Int32 nDyTextBottom; + sal_Int32 nDxWrapDistLeft; + sal_Int32 nDyWrapDistTop; + sal_Int32 nDxWrapDistRight; + sal_Int32 nDyWrapDistBottom; + sal_Int32 nCropFromTop; + sal_Int32 nCropFromBottom; + sal_Int32 nCropFromLeft; + sal_Int32 nCropFromRight; + MSDffTxId aTextId; ///< identifier for text boxes + sal_uLong nNextShapeId; ///< for linked text boxes + sal_uLong nShapeId; + MSO_SPT eShapeType; + MSO_LineStyle eLineStyle; ///< border types + MSO_LineDashing eLineDashing; + bool bDrawHell :1; + bool bHidden :1; + bool bReplaceByFly :1; + bool bVFlip :1; + bool bHFlip :1; + bool bAutoWidth :1; + int relativeHorizontalWidth; ///< in 0.1% or -1 for none + bool isHorizontalRule; + + SvxMSDffImportRec(); + SvxMSDffImportRec(const SvxMSDffImportRec& rCopy); + ~SvxMSDffImportRec(); + + bool operator<( const SvxMSDffImportRec& rEntry ) const + { return nShapeId < rEntry.nShapeId; } + +private: + SvxMSDffImportRec &operator=(const SvxMSDffImportRec&) = delete; +}; + +/** block of parameters for import/export for a single call of + ImportObjAtCurrentStreamPos() */ +class MSFILTER_DLLPUBLIC SvxMSDffImportData final : public SvxMSDffClientData +{ +private: + /** list of all SvxMSDffImportRec instances of/for a group */ + typedef std::set, + comphelper::UniquePtrValueLess> MSDffImportRecords; + MSDffImportRecords m_Records; ///< Shape pointer, Shape ids and private data + std::map m_ObjToRecMap; +public: + tools::Rectangle aParentRect;///< Rectangle of the surrounding groups, + ///< which might have been provided externally + + explicit SvxMSDffImportData(const tools::Rectangle& rParentRect); + SvxMSDffImportData& operator=( SvxMSDffImportData const & ) = delete; // MSVC2015 workaround + SvxMSDffImportData( SvxMSDffImportData const & ) = delete; // MSVC2015 workaround + virtual ~SvxMSDffImportData() override; + bool empty() const { return m_Records.empty(); } + void insert(std::unique_ptr pImpRec); + size_t size() const { return m_Records.size(); } + SvxMSDffImportRec* find(const SdrObject* pObj); + MSDffImportRecords::const_iterator begin() const { return m_Records.begin(); } + MSDffImportRecords::const_iterator end() const { return m_Records.end(); } + virtual void NotifyFreeObj(SdrObject* pObj) override; +}; + +struct DffObjData +{ + const DffRecordHeader& rSpHd; + + tools::Rectangle aBoundRect; + tools::Rectangle aChildAnchor; + + sal_uInt32 nShapeId; + ShapeFlag nSpFlags; + MSO_SPT eShapeType; + + bool bShapeType : 1; + bool bClientAnchor : 1; + bool bClientData : 1; + bool bChildAnchor : 1; + bool bOpt : 1; + bool bOpt2 : 1; + bool bRotateTextWithShape : 1; + bool bPageAnchor; + int nCalledByGroup; + + DffObjData( const DffRecordHeader& rObjHd, + const tools::Rectangle& rBoundRect, + int nClByGroup ) : + rSpHd( rObjHd ), + aBoundRect( rBoundRect ), + nShapeId( 0 ), + nSpFlags( ShapeFlag::NONE ), + eShapeType( mso_sptNil ), + bShapeType( false ), + bClientAnchor( false ), + bClientData( false ), + bChildAnchor( false ), + bOpt( false ), + bOpt2( false ), + bRotateTextWithShape( true ), + bPageAnchor( true ), + nCalledByGroup( nClByGroup ){} + + // Clone a DffObjData _o_ by replacing its rSpHd with a shared_ptr to another one + DffObjData( const std::shared_ptr& rObjHd, const DffObjData& o) : + rSpHd( *rObjHd ), + aBoundRect( o.aBoundRect ), + nShapeId( o.nShapeId ), + nSpFlags( o.nSpFlags ), + eShapeType( o.eShapeType ), + bShapeType( o.bShapeType ), + bClientAnchor( o.bClientAnchor ), + bClientData( o.bClientData ), + bChildAnchor( o.bChildAnchor ), + bOpt( o.bOpt ), + bOpt2( o.bOpt2 ), + bRotateTextWithShape( o.bRotateTextWithShape ), + bPageAnchor( o.bPageAnchor ), + nCalledByGroup( o.nCalledByGroup ){} +}; + +#define DFF_RECORD_MANAGER_BUF_SIZE 64 + +struct DffRecordList +{ + sal_uInt32 nCount; + sal_uInt32 nCurrent; + DffRecordList* pPrev; + std::unique_ptr + pNext; + + DffRecordHeader mHd[ DFF_RECORD_MANAGER_BUF_SIZE ]; + + explicit DffRecordList( DffRecordList* pList ); + ~DffRecordList(); +}; + +enum DffSeekToContentMode +{ + SEEK_FROM_BEGINNING, + SEEK_FROM_CURRENT, + SEEK_FROM_CURRENT_AND_RESTART +}; + +class MSFILTER_DLLPUBLIC DffRecordManager : public DffRecordList +{ +public: + DffRecordList* pCList; + + void Clear(); + void Consume( SvStream& rIn, + sal_uInt32 nStOfs = 0 ); + + bool SeekToContent( SvStream& rIn, + sal_uInt16 nRecType, + DffSeekToContentMode eMode = SEEK_FROM_BEGINNING ); + DffRecordHeader* GetRecordHeader( sal_uInt16 nRecType, + DffSeekToContentMode eMode = SEEK_FROM_BEGINNING ); + + DffRecordManager(); + explicit DffRecordManager( SvStream& rIn ); + + DffRecordHeader* Current(); + DffRecordHeader* First(); + DffRecordHeader* Next(); + DffRecordHeader* Prev(); + DffRecordHeader* Last(); +}; + +/** abstract base class for Escher imports + + Purpose: access to objects in Drawing File Format + + Note: The method ProcessUserDefinedRecord() _has_ to be implemented in the + inheriting class(es) that is/are eventually used for PowerPoint, Word, + or Excel importing. + + Status: Currently only access to BLIPs (will be extended later) +*/ +class MSFILTER_DLLPUBLIC SvxMSDffManager : public DffPropertyReader +{ + std::unique_ptr m_pBLIPInfos; + std::unique_ptr m_xShapeInfosByTxBxComp; + std::unique_ptr m_xShapeInfosById; + SvxMSDffShapeOrders m_aShapeOrders; + sal_uInt32 nOffsDgg; + sal_uInt16 nBLIPCount; + ShapeFlag nGroupShapeFlags; + + void CheckTxBxStoryChain(); + void GetFidclData(sal_uInt32 nOffsDgg); + +protected: + typedef std::map OffsetMap; + + OUString maBaseURL; + sal_uInt32 mnIdClusters; // while only knowing the shapeid + std::vector maFidcls; + OffsetMap maDgOffsetTable; ///< array of fileoffsets + + /** When importing Excel files, cell anchor computations for non-page-anchored + groups must be done after all nested groups have been processed; for each open + group, the pending data is stored here. The storage also holds a shared_ptr to + the DffObjData ow DffRecordHeader to avoid it going out of scope except when needed + */ + std::vector< std::pair > > maPendingGroupData; + + friend class DffPropertyReader; + + SvStream& rStCtrl; + SvStream* pStData; + SvStream* pStData2; + SdrModel* pSdrModel; + + tools::Long nMapMul; + tools::Long nMapDiv; + tools::Long nMapXOfs; + tools::Long nMapYOfs; + tools::Long nEmuMul; + tools::Long nEmuDiv; + tools::Long nPntMul; + tools::Long nPntDiv; + bool bNeedMap; + sal_uInt32 nSvxMSDffSettings; + sal_uInt32 nSvxMSDffOLEConvFlags; + + /** stores a reference to an imported SdrObject + with its shape id if it has one */ + SvxMSDffShapeIdContainer maShapeIdContainer; + + void GetCtrlData(sal_uInt32 nOffsDgg); + void GetDrawingGroupContainerData( SvStream& rSt, + sal_uInt32 nLenDgg ); + // Add internal drawing container id as parameter to the sub methods of + // reading the control information about the drawing objects. + // The drawing container id is used to distinguish the text ids of drawing + // objects in different drawing containers. + void GetDrawingContainerData( SvStream& rSt, + sal_uInt32 nLenDg, + sal_uInt16 nDrawingContainerId ); + bool GetShapeGroupContainerData( SvStream& rSt, + sal_uInt32 nLenShapeGroupCont, + bool bPatriarch, + sal_uInt16 nDrawingContainerId ); + bool GetShapeContainerData( SvStream& rSt, + sal_uInt32 nLenShapeCont, + sal_uInt64 nPosGroup, + sal_uInt16 nDrawingContainerId ); + + SdrObject* ImportGraphic( SvStream&, SfxItemSet&, const DffObjData& ); + // #i32596# - pass to method + // Needed in Writer's Microsoft Word import to avoid import of OLE objects + // inside groups. Instead a graphic object is created. + virtual SdrObject* ImportOLE( sal_uInt32 nOLEId, + const Graphic& rGraf, + const tools::Rectangle& rBoundRect, + const tools::Rectangle& rVisArea, + const int _nCalledByGroup ) const; + static css::uno::Reference < css::embed::XEmbeddedObject > CheckForConvertToSOObj( + sal_uInt32 nConvertFlags, SotStorage& rSrcStg, + const css::uno::Reference < css::embed::XStorage >& xDestStg, + const Graphic& rGrf, + const tools::Rectangle& rVisArea, + OUString const& rBaseURL); + +// the following methods need to be overridden for Excel imports + static void ProcessClientAnchor( SvStream& rStData, + sal_uInt32 nDatLen, + std::unique_ptr& rpBuff, + sal_uInt32& rBuffLen ); + virtual void ProcessClientAnchor2( SvStream& rStData, + DffRecordHeader& rHd, + DffObjData& ); + static void ProcessClientData( SvStream& rStData, + sal_uInt32 nDatLen, + std::unique_ptr& rpBuff, + sal_uInt32& rBuffLen ); + virtual SdrObject* ProcessObj( SvStream& rSt, + DffObjData& rData, + SvxMSDffClientData& rClientData, + tools::Rectangle& rTextRect, + SdrObject* pObj); + void NotifyFreeObj(SvxMSDffClientData& rData, SdrObject* pObj); + void FreeObj(SvxMSDffClientData& rData, SdrObject* pObj); + + + /** Object finalization, used by the Excel filter to correctly + compute the object anchoring after nested objects have been imported. + */ + virtual SdrObject* FinalizeObj(DffObjData& rData, + SdrObject* pObj); + + virtual bool GetColorFromPalette(sal_uInt16 nNum, Color& rColor) const; + + // Fontwork objects use a new implementation of ReadObjText because the old + // one does not properly import multiple paragraphs. + static void ReadObjText( const OUString& rText, SdrObject* pObj ); + +// the following method needs to be overridden for the import of OLE objects + virtual bool GetOLEStorageName( sal_uInt32 nOLEId, + OUString& rStorageName, + tools::SvRef& rSrcStorage, + css::uno::Reference < css::embed::XStorage >& xDestStg + ) const; + + /** Prevent that (rounded) rectangles with wrapped text will always be + converted into SdrRectObj( SdrObjKind::Text ). + + @return true means "conversion". + */ + virtual bool ShapeHasText(sal_uLong nShapeId, sal_uLong nFilePos) const; + +public: + std::unique_ptr pSecPropSet; + std::unordered_map aEscherBlipCache; + + DffRecordManager maShapeRecords; + Color mnDefaultColor; + + bool mbSkipImages; + + Color MSO_TEXT_CLR_ToColor( sal_uInt32 nColorCode ) const; + Color MSO_CLR_ToColor( sal_uInt32 nColorCode, + sal_uInt16 nContextProperty = DFF_Prop_lineColor ) const; + virtual bool SeekToShape( SvStream& rSt, + SvxMSDffClientData* pClientData, + sal_uInt32 nId ) const; + static bool SeekToRec( SvStream& rSt, + sal_uInt16 nRecId, + sal_uLong nMaxFilePos, + DffRecordHeader* pRecHd = nullptr, + sal_uLong nSkipCount = 0 ); + bool SeekToRec2( sal_uInt16 nRecId1, + sal_uInt16 nRecId2, + sal_uLong nMaxFilePos ) const; + + static OUString MSDFFReadZString( SvStream& rIn, + sal_uInt32 nMaxLen, + bool bUniCode); + + [[nodiscard]] static bool ReadCommonRecordHeader( SvStream& rSt, + sal_uInt8& rVer, + sal_uInt16& rInst, + sal_uInt16& rFbt, + sal_uInt32& rLength); + +// TODO: provide proper documentation here + /** constructor + + sets nBLIPCount + + @param rStCtrl Management stream with containers, FBSE + objects and shapes (mandatory; stream needs + to be open already) + @param rBaseURL ??? + @param nOffsDgg offset in rStrCtrl; beginning of the drawing + group container + @param pStData data stream in that the BLIPs are stored (if + NULL it is assumed that all BLIPs are also in + the rStCtrl; stream needs to be open already) + @param pSdrModel_ ??? (can be empty during Ctor call but needs + to be set via SetModel() later in that case!) + @param nApplicationScale ??? + @param mnDefaultColor_ ??? + @param nDefaultFontHeight_ ??? + @param pStData2_ ??? + @param bSkipImages skipping images for text extraction/indexing + */ + SvxMSDffManager( SvStream& rStCtrl, + OUString aBaseURL, + sal_uInt32 nOffsDgg, + SvStream* pStData, + SdrModel* pSdrModel_, + tools::Long nApplicationScale, + Color mnDefaultColor_, + SvStream* pStData2_ = nullptr, + bool bSkipImages = false ); + + // in PPT the parameters DGGContainerOffset and PicStream are provided by an + // init method + SvxMSDffManager( SvStream& rStCtrl, OUString aBaseURL ); + void InitSvxMSDffManager( sal_uInt32 nOffsDgg_, + SvStream* pStData_, + sal_uInt32 nSvxMSDffOLEConvFlags); + void SetDgContainer( SvStream& rSt ); + + virtual ~SvxMSDffManager(); + + sal_uInt32 GetSvxMSDffSettings() const { return nSvxMSDffSettings; }; + void SetSvxMSDffSettings( sal_uInt32 nSettings ) { nSvxMSDffSettings = nSettings; }; + + static bool MakeContentStream( SotStorage * pStor, const GDIMetaFile & ); + static void ReadObjText( SvStream& rStream, SdrObject* pObj ); + static bool ConvertToOle2( SvStream& rStm, + sal_uInt32 nLen, + const GDIMetaFile*, + const tools::SvRef & rDest ); + + void SetModel(SdrModel* pModel, tools::Long nApplicationScale); + SdrModel* GetModel() const { return pSdrModel; } + void Scale(sal_Int32& rVal) const; + void Scale(Point& rPos) const; + void Scale(Size& rSiz) const; + void ScaleEmu(sal_Int32& rVal) const; + sal_uInt32 ScalePt( sal_uInt32 nPt ) const; + sal_Int32 ScalePoint( sal_Int32 nVal ) const; + +// TODO: provide proper documentation here + /** Request for a specific BLIP. + + @param[in] nIdx number of the requested BLIP (mandatory) + @param[out] rData already converted data (insert directly as graphics + into our documents) + @param pVisArea ??? + + @return true if successful, false otherwise + */ + bool GetBLIP( sal_uLong nIdx, Graphic& rData, tools::Rectangle* pVisArea = nullptr ); + +// TODO: provide proper documentation here + /** read a BLIP out of an already positioned stream + + @param[in] rBLIPStream already positioned stream (mandatory) + @param[out] rData already converted data (insert directly as + graphics into our documents) + @param pVisArea ??? + + @return true if successful, false otherwise + */ + static bool GetBLIPDirect(SvStream& rBLIPStream, Graphic& rData, tools::Rectangle* pVisArea = nullptr ); + + bool GetShape(sal_uLong nId, SdrObject*& rpData, SvxMSDffImportData& rData); + + SdrObject* ImportObj( SvStream& rSt, + SvxMSDffClientData& rData, + tools::Rectangle& rClientRect, + const tools::Rectangle& rGlobalChildRect, + int nCalledByGroup, + sal_Int32* pShapeId); + SdrObject* ImportGroup( const DffRecordHeader& rHd, + SvStream& rSt, + SvxMSDffClientData& rData, + tools::Rectangle& rClientRect, + const tools::Rectangle& rGlobalChildRect, + int nCalledByGroup, + sal_Int32* pShapeId ); + SdrObject* ImportShape( const DffRecordHeader& rHd, + SvStream& rSt, + SvxMSDffClientData& rData, + tools::Rectangle& rClientRect, + const tools::Rectangle& rGlobalChildRect, + int nCalledByGroup, + sal_Int32* pShapeId); + + tools::Rectangle GetGlobalChildAnchor( const DffRecordHeader& rHd, + SvStream& rSt, + tools::Rectangle& aClientRect ); + void GetGroupAnchors( const DffRecordHeader& rHd, + SvStream& rSt, + tools::Rectangle& rGroupClientAnchor, + tools::Rectangle& rGroupChildAnchor, + const tools::Rectangle& rClientRect, + const tools::Rectangle& rGlobalChildRect ); + + const SvxMSDffShapeInfos_ById* GetShapeInfos() const + { return m_xShapeInfosById.get(); } + + const SvxMSDffShapeOrders* GetShapeOrders() const + { return &m_aShapeOrders; } + + void StoreShapeOrder(sal_uLong nId, + sal_uLong nTxBx, + SdrObject* pObject, + SwFlyFrameFormat* pFly = nullptr) const; + + void ExchangeInShapeOrder(SdrObject const * pOldObject, + sal_uLong nTxBx, + SdrObject* pObject) const; + + void RemoveFromShapeOrder( SdrObject const * pObject ) const; + + static SdrOle2Obj* CreateSdrOLEFromStorage( + SdrModel& rSdrModel, + const OUString& rStorageName, + tools::SvRef const & rSrcStorage, + const css::uno::Reference < css::embed::XStorage >& xDestStg, + const Graphic& rGraf, + const tools::Rectangle& rBoundRect, + const tools::Rectangle& rVisArea, + SvStream* pDataStrrm, + ErrCode& rError, + sal_uInt32 nConvertFlags, + sal_Int64 nAspect, + OUString const& rBaseURL); + + /** Create connections between shapes. + This method should be called after a page is imported. + + @param rSolver contains necessary data that is collected during the + import of each shape + */ + static void SolveSolver( const SvxMSDffSolverContainer& rSolver ); + + static bool SetPropValue( + const css::uno::Any& rAny, + const css::uno::Reference< css::beans::XPropertySet > & rXPropSet, + const OUString& rPropertyName + ); + + /// Determines an ODF filter name (if there is one) for aGlobName. + static OUString GetFilterNameFromClassID(const SvGlobalName& aGlobName); + /// Extracts ODF data from rSrcStg. + static void ExtractOwnStream(SotStorage& rSrcStg, SvMemoryStream& rMemStream); + + void insertShapeId( sal_Int32 nShapeId, SdrObject* pShape ); + void removeShapeId( SdrObject const * pShape ); + SdrObject* getShapeForId( sal_Int32 nShapeId ); +}; + +struct SvxMSDffShapeInfo +{ + sal_uInt32 nShapeId; ///< shape id, used in PLCF SPA and in mso_fbtSp (FSP) + sal_uInt64 nFilePos; ///< offset of the shape in control stream for + ///< potential later access to it + sal_uInt32 nTxBxComp; + + bool bReplaceByFly :1; ///< shape can be replaced by a frame in Writer + + explicit SvxMSDffShapeInfo(sal_uInt64 nFPos, sal_uInt32 nId=0, // sal_uLong nBIdx=0, + sal_uInt16 nSeqId=0, sal_uInt16 nBoxId=0): + nShapeId( nId ), + nFilePos( nFPos ), + nTxBxComp( (nSeqId << 16) + nBoxId ) + { + bReplaceByFly = false; + } + SvxMSDffShapeInfo(const SvxMSDffShapeInfo& rInfo): + nShapeId( rInfo.nShapeId ), + nFilePos( rInfo.nFilePos ), + nTxBxComp( rInfo.nTxBxComp ), + bReplaceByFly( rInfo.bReplaceByFly ) + { + } +}; + + +struct SvxMSDffShapeOrder +{ + sal_uLong nShapeId; ///< shape id used in PLCF SPA and in mso_fbtSp (FSP) + sal_uLong nTxBxComp; ///< chain or box number in the Text-Box-Story (or NULL) + SwFlyFrameFormat* pFly; ///< format of frame that was inserted as a replacement + ///< for a Sdr-Text object in Writer - needed for + ///< chaining! + SdrObject* pObj; ///< pointer to the draw object (or NULL if not used) + + // Approach: In the Ctor of SvxMSDffManager only the shape ids are stored in + // the shape order array. The Text-Box number and the object + // pointer are only stored if the shape is really imported. + explicit SvxMSDffShapeOrder( sal_uLong nId ): + nShapeId( nId ), nTxBxComp( 0 ), pFly( nullptr ), pObj( nullptr ){} + + bool operator<( const SvxMSDffShapeOrder& rEntry ) const + { return (nTxBxComp < rEntry.nTxBxComp); } +}; + +// the following will be sorted explicitly: +struct CompareSvxMSDffShapeTxBxSort +{ + bool operator()( SvxMSDffShapeOrder* const& lhs, SvxMSDffShapeOrder* const& rhs ) const { return (*lhs)<(*rhs); } +}; +class MSFILTER_DLLPUBLIC SvxMSDffShapeTxBxSort : public std::set {}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/msfilterdllapi.h b/include/filter/msfilter/msfilterdllapi.h new file mode 100644 index 000000000..10532d165 --- /dev/null +++ b/include/filter/msfilter/msfilterdllapi.h @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_MSFILTERDLLAPI_H +#define INCLUDED_FILTER_MSFILTER_MSFILTERDLLAPI_H + +#include + +#if defined MSFILTER_DLLIMPLEMENTATION +#define MSFILTER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define MSFILTER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#define MSFILTER_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/msocximex.hxx b/include/filter/msfilter/msocximex.hxx new file mode 100644 index 000000000..18bf41569 --- /dev/null +++ b/include/filter/msfilter/msocximex.hxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_FILTER_MSFILTER_MSOCXIMEX_HXX +#define INCLUDED_FILTER_MSFILTER_MSOCXIMEX_HXX + +#include +#include + +namespace com::sun::star { + namespace drawing{ + class XDrawPage; + class XShape; + class XShapes; + } + namespace form{ + class XFormComponent; + } + namespace lang{ + class XMultiServiceFactory; + } + namespace container{ + class XIndexContainer; + } + namespace awt{ + struct Size; + } + namespace frame{ + class XModel; + } +} + +class MSFILTER_DLLPUBLIC SvxMSConvertOCXControls +{ +public: + SvxMSConvertOCXControls( css::uno::Reference< css::frame::XModel > xModel ); + virtual ~SvxMSConvertOCXControls(); + + virtual bool InsertControl( + const css::uno::Reference< + css::form::XFormComponent >& /*rFComp*/, + const css::awt::Size& /*rSize*/, + css::uno::Reference< + css::drawing::XShape >* /*pShape*/, + bool /*bFloatingCtrl*/ ) {return false;} + + /*begin: Backwards compatibility with office 95 import, modify later*/ + const css::uno::Reference< css::lang::XMultiServiceFactory > & GetServiceFactory(); +protected: + const css::uno::Reference< css::drawing::XShapes > & GetShapes(); + + const css::uno::Reference< css::container::XIndexContainer > & GetFormComps(); + + css::uno::Reference< css::frame::XModel > mxModel; + + // cached interfaces + css::uno::Reference< css::drawing::XDrawPage > xDrawPage; + css::uno::Reference< css::drawing::XShapes > xShapes; + css::uno::Reference< css::lang::XMultiServiceFactory > xServiceFactory; + + // the only form + css::uno::Reference< css::container::XIndexContainer > xFormComps; + + virtual void GetDrawPage(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/msoleexp.hxx b/include/filter/msfilter/msoleexp.hxx new file mode 100644 index 000000000..77b2cc3b4 --- /dev/null +++ b/include/filter/msfilter/msoleexp.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_FILTER_MSFILTER_MSOLEEXP_HXX +#define INCLUDED_FILTER_MSFILTER_MSOLEEXP_HXX + +#include +#include +#include + +namespace com::sun::star { + namespace embed { class XEmbeddedObject; } +} + +namespace svt { + class EmbeddedObjectRef; +} + +class SotStorage; + +// for the CreateSdrOLEFromStorage we need the information, how we handle +// convert able OLE-Objects - this is stored in +#define OLE_STARMATH_2_MATHTYPE 0x0001 +#define OLE_STARWRITER_2_WINWORD 0x0002 +#define OLE_STARCALC_2_EXCEL 0x0004 +#define OLE_STARIMPRESS_2_POWERPOINT 0x0008 + +class MSFILTER_DLLPUBLIC SvxMSExportOLEObjects +{ + sal_uInt32 nConvertFlags; +public: + SvxMSExportOLEObjects( sal_uInt32 nCnvrtFlgs ) : nConvertFlags(nCnvrtFlgs) {} + + void ExportOLEObject( svt::EmbeddedObjectRef const & rObj, SotStorage& rDestStg ); + void ExportOLEObject( const css::uno::Reference < css::embed::XEmbeddedObject>& rObj, SotStorage& rDestStg ); +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/mstoolbar.hxx b/include/filter/msfilter/mstoolbar.hxx new file mode 100644 index 000000000..46966d648 --- /dev/null +++ b/include/filter/msfilter/mstoolbar.hxx @@ -0,0 +1,355 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_FILTER_MSFILTER_MSTOOLBAR_HXX +#define INCLUDED_FILTER_MSFILTER_MSTOOLBAR_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { struct PropertyValue; } + namespace container { class XIndexAccess; } + namespace graphic { class XGraphic; } + namespace ui { class XUIConfigurationManager; } + namespace ui { class XUIConfigurationManagerSupplier; } +} + +class TBCHeader; + +class MSOCommandConvertor +{ +public: + virtual ~MSOCommandConvertor() {} + virtual OUString MSOCommandToOOCommand( sal_Int16 msoCmd ) = 0; + virtual OUString MSOTCIDToOOCommand( sal_Int16 msoTCID ) = 0; +}; + +class SfxObjectShell; + +class MSFILTER_DLLPUBLIC CustomToolBarImportHelper +{ + struct iconcontrolitem + { + OUString sCommand; + css::uno::Reference< css::graphic::XGraphic > image; + }; + std::vector< iconcontrolitem > iconcommands; + std::unique_ptr< MSOCommandConvertor > pMSOCmdConvertor; + css::uno::Reference< css::ui::XUIConfigurationManagerSupplier > m_xCfgSupp; + css::uno::Reference< css::ui::XUIConfigurationManager > m_xAppCfgMgr; + SfxObjectShell& mrDocSh; + static void ScaleImage( css::uno::Reference< css::graphic::XGraphic >& xGraphic, tools::Long nNewSize ); +public: + CustomToolBarImportHelper( SfxObjectShell& rDocSh, const css::uno::Reference< css::ui::XUIConfigurationManager >& rxAppCfgMgr ); + + void setMSOCommandMap( MSOCommandConvertor* pCnvtr ) { pMSOCmdConvertor.reset( pCnvtr ); } + css::uno::Reference< css::ui::XUIConfigurationManager > getCfgManager(); + const css::uno::Reference< css::ui::XUIConfigurationManager >& getAppCfgManager() const { return m_xAppCfgMgr;} + + + static css::uno::Any createCommandFromMacro( std::u16string_view sCmd ); + + void addIcon( const css::uno::Reference< css::graphic::XGraphic >& xImage, const OUString& sString ); + void applyIcons(); + OUString MSOCommandToOOCommand( sal_Int16 msoCmd ); + OUString MSOTCIDToOOCommand( sal_Int16 msoTCID ); + SfxObjectShell& GetDocShell() { return mrDocSh; } + bool createMenu( const OUString& rName, const css::uno::Reference< css::container::XIndexAccess >& xMenuDesc ); +}; + +class MSFILTER_DLLPUBLIC TBBase +{ +friend class Indent; + static int nIndent; // num spaces to indent before printing +protected: +#ifdef DEBUG_FILTER_MSTOOLBAR + static void indent_printf(FILE* fp, const char* format, ... ); +#endif + sal_uInt32 nOffSet; // usually for debug we can store the offset in the stream to this record +public: + TBBase() : nOffSet( 0 ) {} + virtual ~TBBase(){} + + TBBase(TBBase const &) = default; + TBBase(TBBase &&) = default; + TBBase & operator =(TBBase const &) = default; + TBBase & operator =(TBBase &&) = default; + + virtual bool Read(SvStream &rS) = 0; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) {} // #FIXME remove this an implement the debug routines in all the classes below to enable some sort of readable output +#endif + sal_uInt32 GetOffset() const { return nOffSet; } +}; + +class Indent +{ +public: + Indent( bool binit ) + { + if ( binit ) + TBBase::nIndent = 0; + else + TBBase::nIndent = TBBase::nIndent + 2; + } + ~Indent() { TBBase::nIndent = TBBase::nIndent - 2; } +}; + + +class MSFILTER_DLLPUBLIC WString final : public TBBase +{ + OUString sString; + +public: + WString(){}; + bool Read(SvStream &rS) override; + const OUString& getString() const { return sString; } +}; + +class MSFILTER_DLLPUBLIC TBCExtraInfo final : public TBBase +{ + WString wstrHelpFile; + sal_Int32 idHelpContext; + WString wstrTag; + WString wstrOnAction; + WString wstrParam; + sal_Int8 tbcu; + sal_Int8 tbmg; + + TBCExtraInfo(const TBCExtraInfo&) = delete; + TBCExtraInfo& operator = ( const TBCExtraInfo&) = delete; +public: + TBCExtraInfo(); + bool Read(SvStream &rS) override; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) override; +#endif + OUString const & getOnAction() const; +}; + +class MSFILTER_DLLPUBLIC TBCGeneralInfo final : public TBBase +{ + sal_uInt8 bFlags; + WString customText; + WString descriptionText; + WString tooltip; + TBCExtraInfo extraInfo; + +public: + TBCGeneralInfo(); + bool Read(SvStream &rS) override; + void ImportToolBarControlData( CustomToolBarImportHelper&, std::vector< css::beans::PropertyValue >& ); + OUString const & CustomText() { return customText.getString(); } +}; + +class TBCBitMap final : public TBBase +{ +friend class TBCBSpecific; // #FIXME hacky access, need to fix + sal_Int32 cbDIB; + BitmapEx mBitMap; +public: + TBCBitMap(); + virtual ~TBCBitMap() override; + bool Read(SvStream &rS) override; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) override; +#endif + // #FIXME Const-ness + BitmapEx& getBitMap() { return mBitMap;} +}; + +class MSFILTER_DLLPUBLIC TBCMenuSpecific final : public TBBase +{ + sal_Int32 tbid; + std::shared_ptr< WString > name; //exist only if tbid equals 0x00000001 +public: + TBCMenuSpecific(); + bool Read(SvStream &rS) override; + OUString Name(); +}; + +class TBCCDData final : public TBBase +{ + sal_Int16 cwstrItems; //Signed integer that specifies the number of items in wstrList. MUST be positive. + std::vector< WString > wstrList; // Zero-based index array of WString structures. Number of elements MUST be equal to cwstrItems. + sal_Int16 cwstrMRU; // Signed integer that specifies the number of most recently used string + sal_Int16 iSel ; // Signed integer that specifies the zero-based index of the selected item in the wstrList field. MUST be equal to 0xFFFF (-1) or greater than or equal to 0x0000. + sal_Int16 cLines; // Signed integer that specifies the suggested number of lines that the toolbar control will display at any time when displaying the elements of wstrList of available items. + sal_Int16 dxWidth; // Signed integer that specifies the width in pixels that the interior of the dropdown has. This excludes the width of the toolbar control border and scroll bar. + WString wstrEdit; //Structure of type WString. Editable text for editable area of the ComboBox toolbar control. + +public: + TBCCDData(); + virtual ~TBCCDData() override; + bool Read(SvStream &rS) override; +}; + +class TBCComboDropdownSpecific final : public TBBase +{ + std::shared_ptr< TBCCDData > data; +public: + TBCComboDropdownSpecific( const TBCHeader& header ); + bool Read(SvStream &rS) override; +}; + +class TBCBSpecific final : public TBBase +{ + sal_uInt8 bFlags; + std::shared_ptr< TBCBitMap > icon; // optional + std::shared_ptr< TBCBitMap > iconMask; // optional + std::shared_ptr< sal_uInt16 > iBtnFace; // optional + std::shared_ptr< WString > wstrAcc; // optional + +public: + TBCBSpecific(); + bool Read(SvStream &rS) override; + // #TODO just add a getGraphic member here + TBCBitMap* getIcon(); + TBCBitMap* getIconMask(); + sal_uInt16* getBtnFace() { return iBtnFace.get(); } +}; + +/* TBCHeader.tct controlSpecificInfo type + +0x01 (Button control) TBCBSpecific +0x10 (ExpandingGrid control) TBCBSpecific +0x0A (Popup control) TBCMenuSpecific +0x0C (ButtonPopup control) TBCMenuSpecific +0x0D (SplitButtonPopup control) TBCMenuSpecific +0x0E (SplitButtonMRUPopup control) TBCMenuSpecific +0x02 (Edit control) TBCComboDropdow nSpecific +0x04 (ComboBox control) TBCComboDropdow nSpecific +0x14 (GraphicCombo control) TBCComboDropdow nSpecific +0x03 (DropDown control) TBCComboDropdow nSpecific +0x06 (SplitDropDown control) TBCComboDropdow nSpecific +0x09 (GraphicDropDown control) TBCComboDropdow nSpecific +0x07 (OCXDropDown control) controlSpecificInfo MUST NOT exist +0x0F (Label control) controlSpecificInfo MUST NOT exist +0x12 (Grid control) controlSpecificInfo MUST NOT exist +0x13 (Gauge control) controlSpecificInfo MUST NOT exist +0x16 (ActiveX control) controlSpecificInfo MUST NOT exist + +*/ +class MSFILTER_DLLPUBLIC TBCHeader final : public TBBase +{ + sal_Int8 bSignature; + sal_Int8 bVersion; + sal_uInt8 bFlagsTCR; + sal_uInt8 tct; + sal_uInt16 tcid; + sal_uInt32 tbct; + sal_uInt8 bPriority; + std::shared_ptr< sal_uInt16 > width; //optional + std::shared_ptr< sal_uInt16 > height; //optional + +public: + TBCHeader(); + virtual ~TBCHeader() override; + + TBCHeader(TBCHeader const &) = default; + TBCHeader(TBCHeader &&) = default; + TBCHeader & operator =(TBCHeader const &) = default; + TBCHeader & operator =(TBCHeader &&) = default; + + sal_uInt8 getTct() const { return tct; } + sal_uInt16 getTcID() const { return tcid; } + bool isVisible() const { return !( bFlagsTCR & 0x1 ); } + bool isBeginGroup() const { return ( bFlagsTCR & 0x2 ) != 0; } + bool Read(SvStream &rS) override; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) override; +#endif + sal_uInt32 getTbct() const { return tbct; }; +}; + +class MSFILTER_DLLPUBLIC TBCData final : public TBBase +{ + TBCHeader rHeader; + TBCGeneralInfo controlGeneralInfo; + std::shared_ptr< TBBase > controlSpecificInfo; // can be one of TBCBSpecific, TBCMenuSpecific or TBCComboDropdow nSpecific depending on the control type specified by TBCHeader.tct + TBCData(const TBCData&) = delete; + TBCData& operator = ( const TBCData&) = delete; +public: + TBCData( TBCHeader Header ); + bool Read(SvStream &rS) override; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) override; +#endif + void ImportToolBarControl( CustomToolBarImportHelper&, std::vector< css::beans::PropertyValue >&, bool& bBeginGroup, bool bIsMenuBar ); + TBCGeneralInfo& getGeneralInfo() { return controlGeneralInfo; } + TBCMenuSpecific* getMenuSpecific(); +}; + +class MSFILTER_DLLPUBLIC TB final : public TBBase +{ + sal_uInt8 bSignature;// Signed integer that specifies the toolbar signature number. MUST be 0x02. + sal_uInt8 bVersion; // Signed integer that specifies the toolbar version number. MUST be 0x01. + sal_Int16 cCL; // Signed integer that SHOULD specify the number of toolbar controls contained in this toolbar. + sal_Int32 ltbid;// Signed integer that specifies the toolbar ID. MUST be 0x0001 (custom toolbar ID). + sal_uInt32 ltbtr;// Unsigned integer of type TBTRFlags that specifies the toolbar type and toolbar restrictions. + sal_uInt16 cRowsDefault;// Unsigned integer that specifies the number of preferred rows for the toolbar when the toolbar is not docked. MUST be less than or equal to 255. + sal_uInt16 bFlags; //Unsigned integer of type TBFlags. + WString name; //Structure of type WString that specifies the toolbar name +public: + TB(); + bool Read(SvStream &rS) override; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) override; +#endif + sal_Int16 getcCL() const { return cCL; } + WString& getName(){ return name; } + bool IsEnabled() const; + bool IsMenuToolbar() const { return ( ( ltbtr & 0x2000000 ) == 0x2000000 ); } +}; + +class MSFILTER_DLLPUBLIC SRECT final : public TBBase +{ +public: + SRECT() : left(0), top(0), right(0), bottom(0) {} + sal_Int16 left; + sal_Int16 top; + sal_Int16 right; + sal_Int16 bottom; + bool Read( SvStream &rS ) override { rS.ReadInt16( left ).ReadInt16( top ).ReadInt16( right ).ReadInt16( bottom ); return true; } +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* fo ) override; +#endif +}; + + +class MSFILTER_DLLPUBLIC TBVisualData final : public TBBase +{ + sal_Int8 tbds; + sal_Int8 tbv; + sal_Int8 tbdsDock; + sal_Int8 iRow; + + SRECT rcDock; + SRECT rcFloat; + +public: + TBVisualData(); + bool Read(SvStream &rS) override; +#ifdef DEBUG_FILTER_MSTOOLBAR + virtual void Print( FILE* ) override; +#endif +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/msvbahelper.hxx b/include/filter/msfilter/msvbahelper.hxx new file mode 100644 index 000000000..d5cb1e96f --- /dev/null +++ b/include/filter/msfilter/msvbahelper.hxx @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_FILTER_MSFILTER_MSVBAHELPER_HXX +#define INCLUDED_FILTER_MSFILTER_MSVBAHELPER_HXX + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace frame { class XModel; } + namespace uno { class XComponentContext; } + namespace uno { class XInterface; } +} + +class SfxObjectShell; + +namespace ooo::vba { + + +struct MSFILTER_DLLPUBLIC MacroResolvedInfo +{ + SfxObjectShell* mpDocContext; + OUString msResolvedMacro; + bool mbFound; + + explicit MacroResolvedInfo( SfxObjectShell* pDocContext = nullptr ) : mpDocContext( pDocContext ), mbFound( false ) {} +}; + +MSFILTER_DLLPUBLIC OUString makeMacroURL( std::u16string_view sMacroName ); +MSFILTER_DLLPUBLIC OUString extractMacroName( const OUString& rMacroUrl ); +MSFILTER_DLLPUBLIC OUString getDefaultProjectName( SfxObjectShell const * pShell ); +MSFILTER_DLLPUBLIC OUString resolveVBAMacro( SfxObjectShell const * pShell, const OUString& rLibName, const OUString& rModuleName, const OUString& rMacroName ); +MSFILTER_DLLPUBLIC MacroResolvedInfo resolveVBAMacro( SfxObjectShell* pShell, const OUString& rMacroName, bool bSearchGlobalTemplates = false ); +MSFILTER_DLLPUBLIC bool executeMacro( SfxObjectShell* pShell, const OUString& sMacroName, css::uno::Sequence< css::uno::Any >& aArgs, css::uno::Any& aRet, const css::uno::Any& aCaller ); +/// @throws css::uno::RuntimeException +MSFILTER_DLLPUBLIC css::awt::KeyEvent parseKeyEvent( const OUString& sKey ); +/// @throws css::uno::RuntimeException +MSFILTER_DLLPUBLIC void applyShortCutKeyBinding ( const css::uno::Reference< css::frame::XModel >& rxDoc, const css::awt::KeyEvent& rKeyEvent, const OUString& sMacro ); + + +typedef ::cppu::WeakImplHelper< + css::lang::XServiceInfo, + css::lang::XInitialization, + css::script::vba::XVBAMacroResolver > VBAMacroResolverBase; + +class VBAMacroResolver final : public VBAMacroResolverBase +{ +public: + explicit VBAMacroResolver(); + virtual ~VBAMacroResolver() override; + + // com.sun.star.lang.XServiceInfo interface ------------------------------- + + virtual OUString SAL_CALL + getImplementationName() override; + + virtual sal_Bool SAL_CALL + supportsService( const OUString& rService ) override; + + virtual css::uno::Sequence< OUString > SAL_CALL + getSupportedServiceNames() override; + + // com.sun.star.lang.XInitialization interface ---------------------------- + + virtual void SAL_CALL initialize( + const css::uno::Sequence< css::uno::Any >& rArgs ) override; + + // com.sun.star.script.vba.XVBAMacroResolver interface -------------------- + + virtual OUString SAL_CALL + resolveVBAMacroToScriptURL( const OUString& rVBAMacroName ) override; + + virtual OUString SAL_CALL + resolveScriptURLtoVBAMacro( const OUString& rScriptURL ) override; + +private: + css::uno::Reference< css::frame::XModel > mxModel; + SfxObjectShell* mpObjShell; + OUString maProjectName; +}; + + +} // namespace ooo::vba + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/rtfutil.hxx b/include/filter/msfilter/rtfutil.hxx new file mode 100644 index 000000000..fd7473149 --- /dev/null +++ b/include/filter/msfilter/rtfutil.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_FILTER_MSFILTER_RTFUTIL_HXX +#define INCLUDED_FILTER_MSFILTER_RTFUTIL_HXX + +#include +#include +#include +#include +#include +#include + +// RTF values are often multiplied by 2^16 +#define RTF_MULTIPLIER 65536 + +class SvStream; + +namespace msfilter::rtfutil +{ +/// Outputs a single character in hex form. +MSFILTER_DLLPUBLIC OString OutHex(sal_uLong nHex, sal_uInt8 nLen); + +/// Handles correct unicode and legacy export of a single character. +MSFILTER_DLLPUBLIC OString OutChar(sal_Unicode c, int* pUCMode, rtl_TextEncoding eDestEnc, + bool* pSuccess, bool bUnicode = true); + +/** + * Handles correct unicode and legacy export of a string. + * + * @param rStr the string to export + * @param eDestEnc the legacy encoding to use + * @param bUnicode if unicode output is wanted as well, or just legacy + */ +MSFILTER_DLLPUBLIC OString OutString(const OUString& rStr, rtl_TextEncoding eDestEnc, + bool bUnicode = true); + +/** + * Handles correct unicode and legacy export of a string, when a + * '{' \upr '{' keyword ansi_text '}{\*' \ud '{' keyword Unicode_text '}}}' + * construct should be used. + * + * @param pToken the keyword + * @param rStr the text to export + * @param eDestEnc the legacy encoding to use + */ +MSFILTER_DLLPUBLIC OString OutStringUpr(const char* pToken, const OUString& rStr, + rtl_TextEncoding eDestEnc); + +/** + * Get the numeric value of a single character, representing a hex value. + * + * @return -1 on failure + */ +MSFILTER_DLLPUBLIC int AsHex(char ch); + +/// Writes binary data as a hex dump. +MSFILTER_DLLPUBLIC OString WriteHex(const sal_uInt8* pData, sal_uInt32 nSize, + SvStream* pStream = nullptr, sal_uInt32 nLimit = 64); + +/** + * Extract OLE2 data from an \objdata hex dump. + */ +MSFILTER_DLLPUBLIC bool ExtractOLE2FromObjdata(const OString& rObjdata, SvStream& rOle2); + +/// Strips the header of a WMF file. +MSFILTER_DLLPUBLIC bool StripMetafileHeader(const sal_uInt8*& rpGraphicAry, sal_uInt64& rSize); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/svdfppt.hxx b/include/filter/msfilter/svdfppt.hxx new file mode 100644 index 000000000..6fa9ffaf4 --- /dev/null +++ b/include/filter/msfilter/svdfppt.hxx @@ -0,0 +1,1488 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_SVDFPPT_HXX +#define INCLUDED_FILTER_MSFILTER_SVDFPPT_HXX + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Size; } + namespace drawing { class XShape; } + namespace form { class XFormComponent; } + namespace frame { class XModel; } +} + +class SdrPage; +class SdrObject; +class SvStream; +class SfxItemSet; +class SdrOutliner; +class SfxStyleSheet; +class SotStorage; +class SvMemoryStream; +class SvxNumberFormat; +class PPTTextObj; +enum class PptSlideLayout; +enum class PptPlaceholder : sal_uInt8; + +#define PPT_IMPORTFLAGS_NO_TEXT_ASSERT 1 + +struct MSFILTER_DLLPUBLIC PptCurrentUserAtom +{ + sal_uInt32 nMagic; + sal_uInt32 nCurrentUserEdit; + sal_uInt16 nDocFileVersion; + sal_uInt8 nMajorVersion; + sal_uInt8 nMinorVersion; + OUString aCurrentUser; + +public: + + PptCurrentUserAtom() : nMagic ( 0 ), + nCurrentUserEdit ( 0 ), + nDocFileVersion ( 0 ), + nMajorVersion ( 0 ), + nMinorVersion ( 0 ) {} + + MSFILTER_DLLPUBLIC friend SvStream& ReadPptCurrentUserAtom( SvStream& rIn, PptCurrentUserAtom& rAtom ); +}; + +struct MSFILTER_DLLPUBLIC PowerPointImportParam +{ + SvStream& rDocStream; + sal_uInt32 nImportFlags; + PptCurrentUserAtom aCurrentUserAtom; + + PowerPointImportParam( SvStream& rDocStream ); +}; + +struct SdHyperlinkEntry +{ + sal_uInt32 nIndex; + sal_Int32 nPrivate1; + sal_Int32 nPrivate2; + sal_Int32 nPrivate3; + sal_Int32 nInfo; + OUString aTarget; + OUString aSubAddress; + + OUString aConvSubString; +}; + +// Helper class for reading the PPT InteractiveInfoAtom +struct MSFILTER_DLLPUBLIC PptInteractiveInfoAtom +{ + sal_uInt32 nSoundRef; + sal_uInt32 nExHyperlinkId; + sal_uInt8 nAction; + sal_uInt8 nOleVerb; + sal_uInt8 nJump; + sal_uInt8 nFlags; + sal_uInt8 nHyperlinkType; + + // unknown, because total size is 16 + sal_uInt8 nUnknown1; + sal_uInt8 nUnknown2; + sal_uInt8 nUnknown3; + +public: + + MSFILTER_DLLPUBLIC friend SvStream& ReadPptInteractiveInfoAtom( SvStream& rIn, PptInteractiveInfoAtom& rAtom ); +}; + +enum PptPageKind { PPT_MASTERPAGE, PPT_SLIDEPAGE, PPT_NOTEPAGE }; + +enum PptPageFormat +{ PPTPF_SCREEN, + PPTPF_USLETTER, // 8.5x11" + PPTPF_A4, // 210x297mm + PPTPF_35MMDIA, // DIA + PPTPF_OVERHEAD, + PPTPF_CUSTOM +}; + +// values for PPT_PST_TextHeaderAtom's sal_uLong +enum PPT_TextHeader +{ + PPTTH_TITLE, + PPTTH_BODY, + PPTTH_NOTES, + PPTTH_NOTUSED, + PPTTH_OTHER, // Text in a Shape + PPTTH_CENTERBODY, // Subtitle in Title-Slide + PPTTH_CENTERTITLE, // Title in Title-Slide + PPTTH_HALFBODY, // Body in two-column slide + PPTTH_QUARTERBODY // Body in four-body slide +}; + +enum class TSS_Type : unsigned { + PageTitle = 0, + Body = 1, + Notes = 2, + Unused = 3, + TextInShape = 4, + Subtitle = 5, + Title = 6, + HalfBody = 7, + QuarterBody = 8, + LAST = QuarterBody, + Unknown = 0xffffffff // or invalid +}; + +const int nMaxPPTLevels = 10; + +// Object IDs for StarDraw UserData +#define PPT_OBJECTINFO_ID (1) + +struct MSFILTER_DLLPUBLIC PptDocumentAtom +{ + Size aSlidesPageSize; // page size of the slides in 576DPI + Size aNotesPageSize; // page size of the notes in 576DPI + // avoid RatioAtom for the time being + sal_uInt32 nNotesMasterPersist; // 0=non-existent + sal_uInt32 nHandoutMasterPersist; // 0=non-existent + sal_uInt16 n1stPageNumber; // page number of the first slide + PptPageFormat eSlidesPageFormat; // page format of the slides + bool bEmbeddedTrueType : 1; // TrueType directly within the File? + bool bTitlePlaceholdersOmitted : 1; + bool bRightToLeft : 1; + bool bShowComments : 1; + +public: + + PptDocumentAtom() + : nNotesMasterPersist(0) + , nHandoutMasterPersist(0) + , n1stPageNumber(0) + , eSlidesPageFormat(PPTPF_SCREEN) + , bEmbeddedTrueType(false) + , bTitlePlaceholdersOmitted(false) + , bRightToLeft(false) + , bShowComments(false) + { + } + + Size const & GetSlidesPageSize() const { return aSlidesPageSize; } + Size const & GetNotesPageSize() const { return aNotesPageSize; } + + friend SvStream& ReadPptDocumentAtom( SvStream& rIn, PptDocumentAtom& rAtom ); +}; + +struct PptSlideLayoutAtom +{ + PptSlideLayout eLayout; // 0..18 + PptPlaceholder aPlaceholderId[ 8 ]; + +public: + PptSlideLayoutAtom() { Clear(); } + void Clear(); + + // SlideLayoutAtom is read without header! + friend SvStream& ReadPptSlideLayoutAtom( SvStream& rIn, PptSlideLayoutAtom& rAtom ); +}; + +struct PptSlideAtom +{ + PptSlideLayoutAtom aLayout; + sal_uInt32 nMasterId; + sal_uInt32 nNotesId; + sal_uInt16 nFlags; + +public: + PptSlideAtom() { Clear(); } + void Clear(); + + friend SvStream& ReadPptSlideAtom(SvStream& rIn, PptSlideAtom& rAtom); +}; + +struct PptSlidePersistAtom +{ + sal_uInt32 nPsrReference; + sal_uInt32 nFlags; + sal_uInt32 nNumberTexts; + sal_uInt32 nSlideId; + sal_uInt32 nReserved; // we will use nReserved temporarily to set the offset to SSSlideInfoAtom ( if possible ) + +public: + PptSlidePersistAtom() { Clear(); } + void Clear(); + + friend SvStream& ReadPptSlidePersistAtom(SvStream& rIn, PptSlidePersistAtom& rAtom); +}; + +struct PptNotesAtom +{ + sal_uInt32 nSlideId; + sal_uInt16 nFlags; + +public: + PptNotesAtom() { Clear(); } + void Clear(); + + friend SvStream& ReadPptNotesAtom(SvStream& rIn, PptNotesAtom& rAtom); +}; + +struct PptColorSchemeAtom +{ + sal_uInt8 aData[32] = {}; + +public: + PptColorSchemeAtom(); + Color GetColor( sal_uInt16 nNum ) const; + + friend SvStream& ReadPptColorSchemeAtom(SvStream& rIn, PptColorSchemeAtom& rAtom); +}; + +struct PptFontEntityAtom +{ + OUString aName; + sal_uInt8 lfClipPrecision; + sal_uInt8 lfQuality; + + rtl_TextEncoding eCharSet; + FontFamily eFamily; + FontPitch ePitch; + bool bAvailable; + + friend SvStream& ReadPptFontEntityAtom(SvStream& rIn, PptFontEntityAtom& rAtom); +}; + +enum class PptViewTypeEnum : sal_uInt16 +{ + NONE = 0, + Slide = 1, + SlideMaster = 2, + Notes = 3, + Handout = 4, + NotesMaster = 5, + OutlineMaster = 6, + Outline = 7, + SlideSorter = 8, + VisualBasic = 9, + TitleMaster = 10, + SlideShow = 11, + SlideShowFullScreen = 12, + NotesText = 13, + PrintPreview = 14, + Thumbnails = 15, + MasterThumbnails = 16, + PodiumSlideView = 17, + PodiumNotesView = 18, +}; + +struct PptUserEditAtom +{ + DffRecordHeader aHd; + sal_Int32 nLastSlideID; // ID of last visible slide + sal_uInt32 nVersion; // This is major/minor/build which did the edit + sal_uInt32 nOffsetLastEdit; // File offset of prev PptUserEditAtom + sal_uInt32 nOffsetPersistDirectory; // Offset to PersistPtrs for this file version. + sal_uInt32 nDocumentRef; + sal_uInt32 nMaxPersistWritten; // total number of Persist entries up to this point + PptViewTypeEnum eLastViewType; // enum view type + +public: + PptUserEditAtom() + : nLastSlideID( 0 ) + , nVersion( 0 ) + , nOffsetLastEdit( 0 ) + , nOffsetPersistDirectory( 0 ) + , nDocumentRef( 0 ) + , nMaxPersistWritten( 0 ) + , eLastViewType( PptViewTypeEnum::NONE ) + {} + + friend SvStream& ReadPptUserEditAtom( SvStream& rIn, PptUserEditAtom& rAtom ); +}; + +struct PptOEPlaceholderAtom +{ + sal_uInt32 nPlacementId; + PptPlaceholder nPlaceholderId; + sal_uInt8 nPlaceholderSize; // 0=Full size, 1=Half size, 2=Quarter of Slide + +public: + PptOEPlaceholderAtom() { Clear(); } + void Clear(); + + friend SvStream& ReadPptOEPlaceholderAtom( SvStream& rIn, PptOEPlaceholderAtom& rAtom ); +}; + +struct PPTStyleSheet; +struct HeaderFooterEntry; +struct PptSlidePersistEntry +{ + PptSlidePersistEntry(const PptSlidePersistEntry&) = delete; + PptSlidePersistEntry& operator=( const PptSlidePersistEntry& ) = delete; + + PptSlidePersistAtom aPersistAtom; + PptSlideAtom aSlideAtom; + PptNotesAtom aNotesAtom; + PptColorSchemeAtom aColorScheme; // each slide includes this colorscheme atom + std::unique_ptr xStyleSheet; // stylesheet of this page (only in masterpages), since XP supports more than one masterpage + + sal_uInt32 HeaderFooterOfs[ 4 ]; // containing the ofs to the placeholder (only masterpage) + std::unique_ptr xHeaderFooterEntry; + std::unique_ptr xSolverContainer; + sal_uInt32 nSlidePersistStartOffset;// is an array to the end of the SlidePersistAtom of this page, TextHeaderAtom is following + sal_uInt32 nSlidePersistEndOffset; + sal_uInt32 nBackgroundOffset; // fileoffset + sal_uInt32 nDrawingDgId; // valid, if not -1 + std::unique_ptr + pPresentationObjects; // if valid, this is a pointer to an array that includes the offsets to the presentation objects + // on this masterpage for each instance (0 - 8); + SdrObject* pBObj; + + PptPageKind ePageKind; + + bool bNotesMaster : 1; // for NotesMaster + bool bHandoutMaster : 1; // for HandoutMaster + bool bStarDrawFiller : 1; // special for StarDraw +public: + PptSlidePersistEntry(); + ~PptSlidePersistEntry(); + sal_uInt32 GetSlideId() const { return aPersistAtom.nSlideId; } +}; + +#define PPTSLIDEPERSIST_ENTRY_NOTFOUND 0xFFFF + +class MSFILTER_DLLPUBLIC PptSlidePersistList +{ +private: + PptSlidePersistList(const PptSlidePersistList&) = delete; + PptSlidePersistList& operator=( const PptSlidePersistList& ) = delete; + + typedef std::vector> Entries_t; + Entries_t mvEntries; + +public: + PptSlidePersistList(); + ~PptSlidePersistList(); + + size_t size() const { return mvEntries.size(); } + bool is_null( size_t nIdx ) const { return mvEntries[ nIdx ] == nullptr; } + const PptSlidePersistEntry& operator[](size_t nIdx) const { return *mvEntries[ nIdx ]; } + PptSlidePersistEntry& operator[](size_t nIdx) { return *mvEntries[ nIdx ]; } + Entries_t::iterator begin() { return mvEntries.begin(); } + void insert( Entries_t::iterator it, + std::unique_ptr pEntry ) + { + mvEntries.insert(it, std::move(pEntry)); + } + void push_back(std::unique_ptr pEntry) + { + mvEntries.push_back(std::move(pEntry)); + } + + sal_uInt16 FindPage( sal_uInt32 nId ) const; +}; + +class SfxObjectShell; +struct PPTOleEntry +{ + sal_uInt32 nId; // OleId + sal_uInt32 nRecHdOfs; // points to the record header: ExObjListHd + SfxObjectShell* pShell; + sal_uInt16 nType; // maybe PPT_PST_ExEmbed or PPT_PST_ExControl + sal_uInt32 nAspect; // the aspect of the OLE object + + PPTOleEntry( sal_uInt32 nid, sal_uInt32 nOfs, SfxObjectShell* pSh, sal_uInt16 nT, sal_uInt32 nAsp ) + : nId(nid) + , nRecHdOfs(nOfs) + , pShell(pSh) + , nType(nT) + , nAspect(nAsp) + {} +}; + +struct PptExOleObjAtom +{ + sal_uInt32 nAspect; + sal_uInt32 nId; + sal_uInt32 nPersistPtr; + +public: + + friend SvStream& ReadPptExOleObjAtom( SvStream& rIn, PptExOleObjAtom& rAtom ); +}; + +// SdPage derives from SdrPage, is only known inside sd, and needs to be carried +// around as an opaque pointer here: +struct SdPageCapsule { + explicit SdPageCapsule(SdrPage * thePage): page(thePage) {} + + SdrPage * page; +}; + +class MSFILTER_DLLPUBLIC SdrEscherImport : public SvxMSDffManager +{ +protected: + + friend class PPTTextObj; + friend class PPTPortionObj; + friend struct PPTStyleTextPropReader; + friend class ImplSdPPTImport; + + PptDocumentAtom aDocAtom; + DffRecordManager aDocRecManager; // contains all first level container and atoms of the document container + + ::std::vector< PPTOleEntry > aOleObjectList; + + std::optional> m_xFonts; + + sal_uInt32 nStreamLen; + + bool ReadString( OUString& rStr ) const; + // only for PowerPoint filter: + virtual const PptSlideLayoutAtom* GetSlideLayoutAtom() const; + +public: + using SvxMSDffManager::ReadObjText; + + PowerPointImportParam& rImportParam; + + SdrEscherImport( PowerPointImportParam&, const OUString& rBaseURL ); + virtual ~SdrEscherImport() override; + virtual bool GetColorFromPalette( sal_uInt16 nNum, Color& rColor ) const override; + virtual bool SeekToShape( SvStream& rSt, SvxMSDffClientData* pClientData, sal_uInt32 nId ) const override; + const PptFontEntityAtom* GetFontEnityAtom( sal_uInt32 nNum ) const; + void RecolorGraphic( SvStream& rSt, sal_uInt32 nRecLen, Graphic& rGraph ); + virtual SdrObject* ReadObjText( PPTTextObj* pTextObj, SdrObject* pObj, SdPageCapsule pPage ) const; + virtual SdrObject* ProcessObj( SvStream& rSt, DffObjData& rData, SvxMSDffClientData& rClientData, tools::Rectangle& rTextRect, SdrObject* pObj ) override; + virtual void ProcessClientAnchor2( SvStream& rSt, DffRecordHeader& rHd, DffObjData& rObj ) override; + void ImportHeaderFooterContainer( DffRecordHeader const & rHeader, HeaderFooterEntry& rEntry ); +}; + + +struct MSFILTER_DLLPUBLIC PPTFieldEntry +{ + sal_uInt16 nPos; + sal_uInt16 nTextRangeEnd; + std::unique_ptr xField1; + std::unique_ptr xField2; + std::optional xString; + + PPTFieldEntry() + : nPos(0) + , nTextRangeEnd(0) + { + } + + ~PPTFieldEntry(); + + void SetDateTime( sal_uInt32 nType ); + + // converting PPT date time format: + static void GetDateTime( + const sal_uInt32 nVal, + SvxDateFormat& eDateFormat, + SvxTimeFormat& eTimeFormat + ); +}; + +struct MSFILTER_DLLPUBLIC HeaderFooterEntry +{ + const PptSlidePersistEntry* pMasterPersist; + OUString pPlaceholder[ 4 ]; + sal_uInt32 nAtom; + + sal_uInt32 IsToDisplay( sal_uInt32 nInstance ); + sal_uInt32 NeedToImportInstance( + const sal_uInt32 nInstance, + const PptSlidePersistEntry& rSlidePersist + ); + + explicit HeaderFooterEntry( const PptSlidePersistEntry* pMaster = nullptr ); +}; + +struct MSFILTER_DLLPUBLIC ProcessData final : public SvxMSDffClientData +{ + PptSlidePersistEntry& rPersistEntry; + SdPageCapsule pPage; + ::std::vector< SdrObject* > aBackgroundColoredObjects; + std::unique_ptr pTableRowProperties; + + ProcessData( PptSlidePersistEntry& rP, SdPageCapsule pP ) : + rPersistEntry ( rP ), + pPage ( pP ) {}; + + virtual void NotifyFreeObj(SdrObject* pObj) override; +}; + + +class SdrTextObj; + +class MSFILTER_DLLPUBLIC SdrPowerPointImport : public SdrEscherImport +{ +protected: + + friend class PPTTextObj; + friend class PPTExtParaProv; + friend struct PPTStyleSheet; + friend class PPTNumberFormatCreator; + + bool m_bOk; + PptUserEditAtom m_aUserEditAtom; + PptColorSchemeAtom m_aPageColors; + ::std::vector< SdHyperlinkEntry > m_aHyperList; + std::unique_ptr + m_pPersistPtr; + sal_uInt32 m_nPersistPtrCnt; + + const PPTStyleSheet* m_pPPTStyleSheet; // this is the current stylesheet; + const PPTStyleSheet* m_pDefaultSheet; // this is a sheet we are using if no masterpage can be found, but that should + // never happen just preventing a crash + std::unique_ptr m_pMasterPages; + std::unique_ptr m_pSlidePages; + std::unique_ptr m_pNotePages; + sal_uInt16 m_nCurrentPageNum; + sal_uLong m_nDocStreamPos; + sal_uInt16 m_nPageColorsNum; + PptPageKind m_ePageColorsKind; + PptPageKind m_eCurrentPageKind; + +protected: + using SdrEscherImport::ReadObjText; + + bool SeekToCurrentPage(DffRecordHeader* pRecHd) const; + bool SeekToDocument(DffRecordHeader* pRecHd) const; + static bool SeekToContentOfProgTag( + sal_Int32 nVersion, + SvStream& rSt, + const DffRecordHeader& rProgTagBinaryDataHd, + DffRecordHeader& rContentHd + ); + virtual SdrObject* ApplyTextObj( + PPTTextObj* pTextObj, + SdrTextObj* pText, + SdPageCapsule pPage, + SfxStyleSheet*, + SfxStyleSheet** ) + const; + virtual SdrObject* ReadObjText( PPTTextObj* pTextObj, SdrObject* pObj, SdPageCapsule pPage ) const override; + // #i32596# - new parameter <_nCalledByGroup>, which + // indicates, if the OLE object is imported inside a group object. + virtual SdrObject* ImportOLE( + sal_uInt32 nOLEId, + const Graphic& rGraf, + const tools::Rectangle& rBoundRect, + const tools::Rectangle& rVisArea, + const int _nCalledByGroup + ) const override; + std::unique_ptr ImportExOleObjStg( sal_uInt32 nPersistPtr, sal_uInt32& nOleId ) const; + rtl::Reference MakeBlankPage(bool bMaster) const; + bool ReadFontCollection(); + PptSlidePersistList* GetPageList(PptPageKind ePageKind) const; + sal_uInt32 GetCurrentPageId(); + sal_uInt32 GetMasterPageId(sal_uInt16 nPageNum, PptPageKind ePageKind) const; + sal_uInt32 GetNotesPageId(sal_uInt16 nPageNum ) const; + static SdrOutliner* GetDrawOutliner( SdrTextObj const * pSdrText ); + void SeekOle( SfxObjectShell* pShell, sal_uInt32 nFilterOptions ); + + void ApplyTextAnchorAttributes( PPTTextObj const & rTextObj, SfxItemSet& rSet ) const; + bool IsVerticalText() const; + +public: + SdrPowerPointImport( PowerPointImportParam&, const OUString& rBaseURL ); + virtual ~SdrPowerPointImport() override; + sal_uInt16 GetPageCount( PptPageKind eKind = PPT_SLIDEPAGE ) const; + void SetPageNum( sal_uInt16 nPageNum, PptPageKind = PPT_SLIDEPAGE ); + Size GetPageSize() const; + SdrObject* ImportPageBackgroundObject( + const SdrPage& rPage, + sal_uInt32& nBgFileOffset + ); + bool IsNoteOrHandout( sal_uInt16 nPageNum ) const; + bool HasMasterPage( + sal_uInt16 nPageNum, + PptPageKind ePageKind = PPT_SLIDEPAGE + ) const; + sal_uInt16 GetMasterPageIndex( + sal_uInt16 nPageNum, + PptPageKind ePageKind = PPT_SLIDEPAGE + ) const; + + void ImportPage( SdrPage* pPage, const PptSlidePersistEntry* pMasterPersist ); + virtual bool GetColorFromPalette(sal_uInt16 nNum, Color& rColor) const override; + virtual bool SeekToShape( SvStream& rSt, SvxMSDffClientData* pClientData, sal_uInt32 nId ) const override; + virtual const PptSlideLayoutAtom* GetSlideLayoutAtom() const override; + SdrObject* CreateTable( + SdrObject* pGroupObject, + const sal_uInt32* pTableArry, + SvxMSDffSolverContainer* pSolverContainer, + std::vector& rBackgroundColoredObjects + ); + virtual bool ReadFormControl( tools::SvRef& rSrc1, css::uno::Reference< css::form::XFormComponent > & rFormComp ) const = 0; +}; + +struct PPTTextParagraphStyleAtomInterpreter +{ + bool bValid; + bool bForbiddenRules; + bool bHangingPunctuation; + bool bLatinTextWrap; + + PPTTextParagraphStyleAtomInterpreter(); + + bool Read( SvStream& rIn, const DffRecordHeader& rRecHd ); +}; + +struct PPTTextSpecInfo +{ + sal_uInt32 nCharIdx; + LanguageType nLanguage[ 3 ]; + sal_uInt16 nDontKnow; + + explicit PPTTextSpecInfo( sal_uInt32 nCharIdx ); +}; + +struct PPTTextSpecInfoAtomInterpreter +{ + bool bValid; + ::std::vector< PPTTextSpecInfo > aList; + + PPTTextSpecInfoAtomInterpreter(); + ~PPTTextSpecInfoAtomInterpreter(); + + bool Read( + SvStream& rIn, + const DffRecordHeader& rRecHd, + sal_uInt16 nRecordType, + const PPTTextSpecInfo* pTextSpecDefault = nullptr + ); + +}; + +#define PPT_STYLESHEETENTRIES 9 + +struct PPTExtParaLevel +{ + sal_uInt32 mnExtParagraphMask; + sal_uInt16 mnBuBlip; + sal_uInt16 mnHasAnm; + sal_uInt32 mnAnmScheme; + sal_uInt32 mpfPP10Ext; + sal_uInt32 mnExtCharacterMask; + sal_uInt32 mcfPP10Ext; + bool mbSet; + + PPTExtParaLevel(); + friend SvStream& ReadPPTExtParaLevel( SvStream& rIn, PPTExtParaLevel& rL ); +}; + +struct PPTExtParaSheet +{ + PPTExtParaLevel aExtParaLevel[nMaxPPTLevels]; +}; + +struct PPTBuGraEntry +{ + sal_uInt32 nInstance; + Graphic aBuGra; + + PPTBuGraEntry( Graphic aGraphic, sal_uInt32 nInstance ); +}; + +class PPTExtParaProv +{ + ::std::vector< std::unique_ptr > aBuGraList; + +public: + bool bStyles; + DffRecordManager aExtendedPresRules; + + o3tl::enumarray aExtParaSheet; + + bool GetGraphic( sal_uInt32 nInstance, Graphic& rGraphic ) const; + + PPTExtParaProv( + SdrPowerPointImport& rManager, + SvStream& rSt, + const DffRecordHeader* pMainMasterHd + ); + ~PPTExtParaProv(); +}; + +struct PPTCharLevel +{ + Color mnFontColorInStyleSheet; + sal_uInt32 mnFontColor; + sal_uInt16 mnFlags; + sal_uInt16 mnFont; + sal_uInt16 mnAsianOrComplexFont; + sal_uInt16 mnFontHeight; + sal_uInt16 mnEscapement; +}; + +struct PPTCharSheet +{ + PPTCharLevel maCharLevel[nMaxPPTLevels]; + + explicit PPTCharSheet( TSS_Type nInstance ); + + void Read( SvStream& rIn, sal_uInt32 nLevel ); +}; + +struct PPTParaLevel +{ + sal_uInt16 mnBuFlags; + sal_uInt16 mnBulletChar; + sal_uInt16 mnBulletFont; + sal_uInt16 mnBulletHeight; + sal_uInt32 mnBulletColor; + + sal_uInt16 mnAdjust; + sal_uInt16 mnLineFeed; + sal_uInt16 mnUpperDist; + sal_uInt16 mnLowerDist; + sal_uInt16 mnTextOfs; + sal_uInt16 mnBulletOfs; + sal_uInt16 mnDefaultTab; + sal_uInt16 mnAsianLineBreak; // bit0: use asian rules for first and last character + // 1: do not wrap latin text in the middle of the word + // 2: allow hanging punctuation + sal_uInt16 mnBiDi; +}; + +struct PPTParaSheet +{ +public: + + PPTParaLevel maParaLevel[nMaxPPTLevels]; + + explicit PPTParaSheet( TSS_Type nInstance ); + + void Read( + SdrPowerPointImport const & rMan, + SvStream& rIn, + sal_uInt32 nLevel, + bool bFirst + ); + void UpdateBulletRelSize( sal_uInt32 nLevel, sal_uInt16 nFontHeight ); +}; + +class PPTParagraphObj; +class PPTNumberFormatCreator +{ + sal_uInt32 nIsBullet; + sal_uInt32 nBulletChar; + sal_uInt32 nBulletFont; + sal_uInt32 nBulletHeight; + sal_uInt32 nBulletColor; + sal_uInt32 nTextOfs; + sal_uInt32 nBulletOfs; + + void ImplGetNumberFormat( + SdrPowerPointImport const & rMan, + SvxNumberFormat& rNumberFormat + ); + bool ImplGetExtNumberFormat( + SdrPowerPointImport const & rMan, + SvxNumberFormat& rNumberFormat, + sal_uInt32 nLevel, + TSS_Type nInstance, + TSS_Type nInstanceInSheet, + std::optional< sal_Int16 >& rStartNumbering, + sal_uInt32 nFontHeight, + PPTParagraphObj const * pPara + ); + +protected: + + PPTNumberFormatCreator( std::unique_ptr ); + ~PPTNumberFormatCreator(); + +public: + + std::unique_ptr pExtParaProv; + + void GetNumberFormat( + SdrPowerPointImport const & rMan, + SvxNumberFormat& rNumberFormat, + sal_uInt32 nLevel, + const PPTParaLevel& rParaLevel, + const PPTCharLevel& rCharLevel, + TSS_Type nInstance + ); + + bool GetNumberFormat( + SdrPowerPointImport const & rMan, + SvxNumberFormat& rNumberFormat, + PPTParagraphObj* pPara, + TSS_Type nInstanceInSheet, + std::optional< sal_Int16 >& rStartNumbering + ); +}; + +class SvxNumBulletItem; +struct PPTStyleSheet : public PPTNumberFormatCreator +{ + PPTTextSpecInfo maTxSI; + o3tl::enumarray> mpCharSheet; + o3tl::enumarray> mpParaSheet; + o3tl::enumarray> mpNumBulletItem; + + PPTStyleSheet( + const DffRecordHeader& rSlideHd, + SvStream& rSt, SdrPowerPointImport&, + const PPTTextParagraphStyleAtomInterpreter&, + const PPTTextSpecInfo& + ); + ~PPTStyleSheet(); +}; + +struct ImplPPTParaPropSet final : public salhelper::SimpleReferenceObject +{ + sal_uInt16 mnDepth; + sal_uInt32 mnAttrSet; + sal_uInt32 mnBulletColor; + sal_uInt16 mpArry[ 22 ]; + + sal_uInt32 mnExtParagraphMask; + sal_uInt32 mnAnmScheme; + sal_uInt16 mnHasAnm; + sal_uInt16 mnBuBlip; + + sal_uInt32 nDontKnow1; + sal_uInt32 nDontKnow2; + sal_uInt16 nDontKnow2bit06; + + ImplPPTParaPropSet() + : mnDepth( 0 ) + , mnAttrSet( 0 ) + , mnBulletColor( 0 ) + , mnExtParagraphMask( 0 ) + , mnAnmScheme( 0 ) + , mnHasAnm( 0 ) + , mnBuBlip( 0 ) + , nDontKnow1( 0 ) + , nDontKnow2( 0 ) + , nDontKnow2bit06( 0 ) + { } +}; + +struct PPTParaPropSet +{ + sal_uInt32 mnOriginalTextPos; + rtl::Reference mxParaSet; + + PPTParaPropSet(); + PPTParaPropSet( PPTParaPropSet const & rParaPropSet ); + ~PPTParaPropSet(); + + PPTParaPropSet& operator=( const PPTParaPropSet& rParaPropSet ); +}; + +struct ImplPPTCharPropSet +{ + sal_uInt32 mnAttrSet; + sal_uInt16 mnFlags; + sal_uInt32 mnColor; + sal_uInt16 mnFont; + sal_uInt16 mnAsianOrComplexFont; + sal_uInt16 mnANSITypeface; + sal_uInt16 mnFontHeight; + sal_uInt16 mnEscapement; + sal_uInt16 mnSymbolFont; + + ImplPPTCharPropSet() + : mnAttrSet( 0 ) + , mnFlags( 0 ) + , mnColor( 0 ) + , mnFont( 0 ) + , mnAsianOrComplexFont( 0 ) + , mnANSITypeface( 0 ) + , mnFontHeight( 0 ) + , mnEscapement( 0 ) + , mnSymbolFont( 0) + { } +}; + +struct PPTCharPropSet +{ + //when the bullet text has more than two color,next the text following with bullet has been set hyperlink. + //now,the bullet color should be set original hyperlink text's color + //so "mbHardHylinkOrigColor" hold the original hyperlink text's color. + sal_uInt32 mnHylinkOrigColor; + //the bullet text whether has a hyperlink. + bool mbIsHyperlink; + //the hyperlink text whether has a custom color. + bool mbHardHylinkOrigColor; + + sal_uInt32 mnOriginalTextPos; + sal_uInt32 mnParagraph; + OUString maString; + std::unique_ptr + mpFieldItem; + LanguageType mnLanguage[ 3 ]; + + void SetFont( sal_uInt16 nFont ); + void SetColor( sal_uInt32 nColor ); + + explicit PPTCharPropSet( sal_uInt32 nParagraph ); + PPTCharPropSet( const PPTCharPropSet& rCharPropSet ); + PPTCharPropSet( const PPTCharPropSet& rCharPropSet, sal_uInt32 nParagraph ); + ~PPTCharPropSet(); + + PPTCharPropSet& operator=( const PPTCharPropSet& rCharPropSet ); + + friend class PPTTextObj; + friend class PPTParagraphObj; + friend class PPTPortionObj; + friend struct PPTStyleTextPropReader; + +private: + o3tl::cow_wrapper< ImplPPTCharPropSet > mpImplPPTCharPropSet; +}; + +struct PPTTabEntry +{ + sal_uInt16 nOffset; + sal_uInt16 nStyle; +}; + +struct PPTRuler final : public salhelper::SimpleReferenceObject +{ + sal_Int32 nFlags; + sal_uInt16 nDefaultTab; + sal_uInt16 nTextOfs[nMaxPPTLevels] = {}; + sal_uInt16 nBulletOfs[nMaxPPTLevels] = {}; + std::unique_ptr + pTab; + sal_uInt16 nTabCount; + + PPTRuler(); + virtual ~PPTRuler() override; +}; + +struct PPTTextRulerInterpreter +{ + rtl::Reference mxImplRuler; + + PPTTextRulerInterpreter(); + PPTTextRulerInterpreter( PPTTextRulerInterpreter const & rRuler ); + PPTTextRulerInterpreter( + sal_uInt32 nFileOfs, + DffRecordHeader const & rHd, + SvStream& rIn + ); + ~PPTTextRulerInterpreter(); + + sal_uInt16 GetTabOffsetByIndex( sal_uInt16 nIndex ) const + { return mxImplRuler->pTab[ nIndex ].nOffset; }; + + sal_uInt16 GetTabStyleByIndex( sal_uInt16 nIndex ) const + { return mxImplRuler->pTab[ nIndex ].nStyle; }; + + sal_uInt16 GetTabCount() const { return mxImplRuler->nTabCount; }; + bool GetDefaultTab( sal_uInt16& nValue ) const; + bool GetTextOfs( sal_uInt32 nLevel, sal_uInt16& nValue ) const; + bool GetBulletOfs( sal_uInt32 nLevel, sal_uInt16& nValue ) const; + + PPTTextRulerInterpreter& operator=( const PPTTextRulerInterpreter& rRuler ); +}; + +#define PPT_SPEC_NEWLINE 0x10000 +#define PPT_SPEC_SYMBOL 0x20000 + +struct StyleTextProp9 +{ + sal_uInt32 mnExtParagraphMask; + sal_uInt16 mnBuBlip; + sal_uInt16 mnHasAnm; + sal_uInt32 mnAnmScheme; + sal_uInt32 mpfPP10Ext; + sal_uInt32 mnExtCharacterMask; + sal_uInt32 mncfPP10Ext; + sal_uInt32 mnSpecialInfoMask; + sal_uInt32 mnPP10Ext; + sal_uInt16 mfBidi; + + StyleTextProp9() + : mnExtParagraphMask( 0 ) + , mnBuBlip( 0 ) + , mnHasAnm( 0 ) + , mnAnmScheme( 0 ) + , mpfPP10Ext( 0 ) + , mnExtCharacterMask( 0 ) + , mncfPP10Ext( 0 ) + , mnSpecialInfoMask( 0 ) + , mnPP10Ext( 0 ) + , mfBidi( 0 ) + { + } + void Read( SvStream& rSt ); +}; + +struct PPTStyleTextPropReader +{ + std::vector< sal_uInt32 > aSpecMarkerList; // hiword -> Flags, loword -> Position + std::vector> aParaPropList; + std::vector> aCharPropList; + + PPTStyleTextPropReader( + SvStream& rIn, + const DffRecordHeader& rClientTextBoxHd, + PPTTextRulerInterpreter const & rInterpreter, + const DffRecordHeader& rExtParaHd, + TSS_Type nTextInstance + ); + ~PPTStyleTextPropReader(); + + void Init( + SvStream& rIn, + const DffRecordHeader& rClientTextBoxHd, + PPTTextRulerInterpreter const & rInterpreter, + const DffRecordHeader& rExtParaHd, + TSS_Type nTextInstance + ); + void ReadParaProps( + SvStream& rIn, + const DffRecordHeader& rTextHeader, + const OUString& aString, + PPTTextRulerInterpreter const & rRuler, + sal_uInt32& nCharCount, + bool& bTextPropAtom + ); + static void ReadCharProps( + SvStream& rIn, + PPTCharPropSet& aCharPropSet, + const OUString& aString, + sal_uInt32& nCharCount, + sal_uInt32 nCharReadCnt, + bool& bTextPropAtom, + sal_uInt32 nExtParaPos, + const std::vector< StyleTextProp9 >& aStyleTextProp9, + sal_uInt32& nExtParaFlags, + sal_uInt16& nBuBlip, + sal_uInt16& nHasAnm, + sal_uInt32& nAnmScheme + ); +}; + +class MSFILTER_DLLPUBLIC PPTPortionObj : public PPTCharPropSet +{ + + friend class PPTParagraphObj; + + const PPTStyleSheet& mrStyleSheet; + TSS_Type mnInstance; + sal_uInt32 mnDepth; + +public: + + bool GetAttrib( sal_uInt32 nAttr, sal_uInt32& nVal, TSS_Type nInstanceInSheet ) const; + SvxFieldItem* GetTextField(); + + PPTPortionObj( const PPTStyleSheet&, TSS_Type nInstance, sal_uInt32 nDepth ); + PPTPortionObj( + const PPTCharPropSet&, + const PPTStyleSheet&, + TSS_Type nInstance, + sal_uInt32 nDepth + ); + PPTPortionObj( const PPTPortionObj& ); + ~PPTPortionObj(); + + // the following function should be removed during next full update + void ApplyTo( + SfxItemSet& rSet, + SdrPowerPointImport& rManager, + TSS_Type nInstanceInSheet + ); + void ApplyTo( + SfxItemSet& rSet, + SdrPowerPointImport& rManager, + TSS_Type nInstanceInSheet, + const PPTTextObj* pTextObj + ); + sal_uInt32 Count() const { return mpFieldItem ? 1 : maString.getLength(); }; +}; + +class MSFILTER_DLLPUBLIC PPTParagraphObj + : public PPTParaPropSet, + public PPTNumberFormatCreator, + public PPTTextRulerInterpreter +{ + friend class PPTTextObj; + friend class PPTNumberFormatCreator; + + const PPTStyleSheet& mrStyleSheet; + TSS_Type mnInstance; + + PPTParagraphObj(PPTParagraphObj const&) = delete; + void operator=(PPTParagraphObj const&) = delete; + +public: + sal_uInt32 mnCurrentObject; + ::std::vector> m_PortionList; + + void UpdateBulletRelSize( sal_uInt32& nBulletRelSize ) const; + bool GetAttrib( sal_uInt32 nAttr, sal_uInt32& nVal, TSS_Type nInstanceInSheet ); + + PPTParagraphObj( + const PPTStyleSheet&, + TSS_Type nInstance, + sal_uInt16 nDepth + ); + PPTParagraphObj( + PPTStyleTextPropReader&, + size_t nCurParaPos, + size_t& rnCurCharPos, + const PPTStyleSheet&, + TSS_Type nInstance, + PPTTextRulerInterpreter const & rRuler + ); + ~PPTParagraphObj(); + + sal_uInt32 GetTextSize(); + PPTPortionObj* First(); + PPTPortionObj* Next(); + + void AppendPortion( PPTPortionObj& rPortion ); + void ApplyTo( + SfxItemSet& rSet, + std::optional< sal_Int16 >& rStartNumbering, + SdrPowerPointImport const & rManager, + TSS_Type nInstanceInSheet + ); +}; + +#define PPT_TEXTOBJ_FLAGS_PARA_ALIGNMENT_USED_LEFT 1 +#define PPT_TEXTOBJ_FLAGS_PARA_ALIGNMENT_USED_CENTER 2 +#define PPT_TEXTOBJ_FLAGS_PARA_ALIGNMENT_USED_RIGHT 4 +#define PPT_TEXTOBJ_FLAGS_PARA_ALIGNMENT_USED_BLOCK 8 +#define PPT_TEXTOBJ_FLAGS_VERTICAL 16 + +struct ImplPPTTextObj final : public salhelper::SimpleReferenceObject +{ + sal_uInt32 mnShapeId; + sal_uInt32 mnShapeMaster; + std::unique_ptr mpPlaceHolderAtom; + TSS_Type mnInstance; + TSS_Type mnDestinationInstance; + MSO_SPT meShapeType; + + sal_uInt32 mnCurrentObject; + sal_uInt32 mnParagraphCount; + std::vector> + maParagraphList; + PptSlidePersistEntry& mrPersistEntry; + + sal_uInt32 mnTextFlags; + + explicit ImplPPTTextObj( PptSlidePersistEntry& rPersistEntry ) + : mnShapeId(0) + , mnShapeMaster(0) + , mnInstance(TSS_Type::PageTitle) + , mnDestinationInstance(TSS_Type::PageTitle) + , meShapeType(mso_sptMin) + , mnCurrentObject(0) + , mnParagraphCount(0) + , mrPersistEntry ( rPersistEntry ) + , mnTextFlags(0) {}; +}; + +class MSFILTER_DLLPUBLIC PPTTextObj +{ + rtl::Reference mxImplTextObj; + +public: + PPTTextObj( + SvStream& rSt, + SdrPowerPointImport&, + PptSlidePersistEntry&, + DffObjData const * + ); + PPTTextObj( PPTTextObj const & rTextObj ); + ~PPTTextObj(); + + sal_uInt32 GetCurrentIndex() const { return mxImplTextObj->mnCurrentObject; }; + sal_uInt32 Count() const { return mxImplTextObj->mnParagraphCount; }; + PPTParagraphObj* First(); + PPTParagraphObj* Next(); + MSO_SPT GetShapeType() const { return mxImplTextObj->meShapeType; }; + TSS_Type GetInstance() const { return mxImplTextObj->mnInstance; }; + void SetInstance( TSS_Type nInstance ) + { mxImplTextObj->mnInstance = nInstance; } + + TSS_Type GetDestinationInstance() const + { return mxImplTextObj->mnDestinationInstance; } + + void SetDestinationInstance( TSS_Type nInstance ) + { mxImplTextObj->mnDestinationInstance = nInstance; } + + PptOEPlaceholderAtom* GetOEPlaceHolderAtom() const { return mxImplTextObj->mpPlaceHolderAtom.get(); } + sal_uInt32 GetTextFlags() const { return mxImplTextObj->mnTextFlags; } + void SetVertical( bool bVertical ) + { + if ( bVertical ) + mxImplTextObj->mnTextFlags |= PPT_TEXTOBJ_FLAGS_VERTICAL; + else + mxImplTextObj->mnTextFlags &= ~PPT_TEXTOBJ_FLAGS_VERTICAL; + } + bool GetVertical() const + { return ( mxImplTextObj->mnTextFlags & PPT_TEXTOBJ_FLAGS_VERTICAL ) != 0; } + + const SfxItemSet* GetBackground() const; + + PPTTextObj& operator=( const PPTTextObj& rTextObj ); +}; + +class PPTConvertOCXControls final : public SvxMSConvertOCXControls +{ + virtual void GetDrawPage() override; + PptPageKind ePageKind; + const SdrPowerPointImport* mpPPTImporter; +public: + + PPTConvertOCXControls( const SdrPowerPointImport* pPPTImporter, const css::uno::Reference< css::frame::XModel >& rxModel, PptPageKind ePKind ) : + SvxMSConvertOCXControls ( rxModel ), + ePageKind ( ePKind ), + mpPPTImporter ( pPPTImporter ) + {}; + bool ReadOCXStream( tools::SvRef& rSrc1, + css::uno::Reference *pShapeRef ); + virtual bool InsertControl( + const css::uno::Reference< css::form::XFormComponent > &rFComp, + const css::awt::Size& rSize, + css::uno::Reference< css::drawing::XShape > *pShape, + bool bFloatingCtrl + ) override; +}; + +// PowerPoint record types +#define PPT_PST_Document 1000 +#define PPT_PST_DocumentAtom 1001 +#define PPT_PST_SlideAtom 1007 +#define PPT_PST_NotesAtom 1009 +#define PPT_PST_Environment 1010 +#define PPT_PST_SlidePersistAtom 1011 +#define PPT_PST_SSSlideInfoAtom 1017 +#define PPT_PST_VBAInfo 1023 +#define PPT_PST_VBAInfoAtom 1024 +#define PPT_PST_SSDocInfoAtom 1025 +#define PPT_PST_ExObjList 1033 +#define PPT_PST_PPDrawingGroup 1035 +#define PPT_PST_PPDrawing 1036 +#define PPT_PST_GridSpacing10Atom 1037 +#define PPT_PST_NamedShows 1040 +#define PPT_PST_NamedShow 1041 +#define PPT_PST_NamedShowSlides 1042 +#define PPT_PST_List 2000 +#define PPT_PST_FontCollection 2005 +#define PPT_PST_SoundCollection 2020 +#define PPT_PST_Sound 2022 +#define PPT_PST_SoundData 2023 +#define PPT_PST_ColorSchemeAtom 2032 + +// these atoms first was seen in ppt2000 in a private Tag atom +#define PPT_PST_ExtendedBuGraContainer 2040 // consist of 4041 +#define PPT_PST_ExtendedBuGraAtom 2041 // the instance of this atom indices the current graphic + +#define PPT_PST_ExObjRefAtom 3009 +#define PPT_PST_OEPlaceholderAtom 3011 +#define PPT_PST_OutlineTextRefAtom 3998 +#define PPT_PST_TextHeaderAtom 3999 +#define PPT_PST_TextCharsAtom 4000 +#define PPT_PST_StyleTextPropAtom 4001 +#define PPT_PST_TxMasterStyleAtom 4003 +#define PPT_PST_TxPFStyleAtom 4005 +#define PPT_PST_TextRulerAtom 4006 +#define PPT_PST_TextBytesAtom 4008 +#define PPT_PST_TxSIStyleAtom 4009 +#define PPT_PST_TextSpecInfoAtom 4010 + +// these atoms first was seen in ppt2000 in a private Tag atom +#define PPT_PST_ExtendedParagraphAtom 4012 +#define PPT_PST_ExtendedParagraphMasterAtom 4013 +#define PPT_PST_ExtendedPresRuleContainer 4014 // consist of 4012, 4015, +#define PPT_PST_ExtendedParagraphHeaderAtom 4015 // the instance of this atom indices the current presobj + // the first sal_uInt32 in this atom indices the current slideId +#define PPT_PST_TextDefaults9Atom 4016 + +#define PPT_PST_FontEntityAtom 4023 +#define PPT_PST_CString 4026 +#define PPT_PST_ExOleObjAtom 4035 +#define PPT_PST_SrKinsoku 4040 +#define PPT_PST_ExEmbed 4044 +#define PPT_PST_ExHyperlinkAtom 4051 +#define PPT_PST_ExHyperlink 4055 +#define PPT_PST_SlideNumberMCAtom 4056 +#define PPT_PST_HeadersFooters 4057 +#define PPT_PST_HeadersFootersAtom 4058 +#define PPT_PST_TxInteractiveInfoAtom 4063 +#define PPT_PST_MasterText 4068 +#define PPT_PST_RecolorInfoAtom 4071 +#define PPT_PST_ExControl 4078 +#define PPT_PST_SlideListWithText 4080 +#define PPT_PST_AnimationInfoAtom 4081 +#define PPT_PST_InteractiveInfo 4082 +#define PPT_PST_InteractiveInfoAtom 4083 +#define PPT_PST_UserEditAtom 4085 +#define PPT_PST_CurrentUserAtom 4086 +#define PPT_PST_DateTimeMCAtom 4087 +#define PPT_PST_GenericDateMCAtom 4088 +#define PPT_PST_HeaderMCAtom 4089 +#define PPT_PST_FooterMCAtom 4090 +#define PPT_PST_ExMediaAtom 4100 +#define PPT_PST_ExVideo 4101 +#define PPT_PST_ExAviMovie 4102 +#define PPT_PST_ExMCIMovie 4103 +#define PPT_PST_AnimationInfo 4116 +#define PPT_PST_RTFDateTimeMCAtom 4117 +#define PPT_PST_ProgTags 5000 +#define PPT_PST_ProgBinaryTag 5002 +#define PPT_PST_BinaryTagData 5003 +#define PPT_PST_PersistPtrIncrementalBlock 6002 + +// these atoms first was seen in ppt2000 in a private Tag atom +#define PPT_PST_PresentationAdvisorFlags9Atom 6010 +#define PPT_PST_HtmlDocInfo9Atom 6011 + + +#define PPT_PST_HashCodeAtom 11008 +#define PPT_PST_BuildList 11010 +#define PPT_PST_Comment10 12000 +#define PPT_PST_CommentAtom10 12001 +#define PPT_PST_CommentIndex10 12004 +#define PPT_PST_SlideFlags10Atom 12010 +#define PPT_PST_SlideTime10Atom 12011 +#define PPT_PST_DocToolbarStates10Atom 14001 + +// attributes for PptTextStyleSheet +#define PPT_ParaAttr_BulletOn 0 //00000001 +#define PPT_ParaAttr_BuHardFont 1 //00000002 +#define PPT_ParaAttr_BuHardColor 2 //00000004 +#define PPT_ParaAttr_BuHardHeight 3 //00000008 +#define PPT_ParaAttr_BulletFont 4 //00000010 +#define PPT_ParaAttr_BulletColor 5 //00000020 +#define PPT_ParaAttr_BulletHeight 6 //00000040 +#define PPT_ParaAttr_BulletChar 7 //00000080 +#define PPT_ParaAttr_Adjust 11 //00000800 0000=Left, 0001=Center, 0002=Right, 0003=Block +#define PPT_ParaAttr_LineFeed 12 //00001000 +#define PPT_ParaAttr_UpperDist 13 //00002000 is set to 0032 for TextFrames by default +#define PPT_ParaAttr_LowerDist 14 //00004000 +#define PPT_ParaAttr_TextOfs 15 //00008000 +#define PPT_ParaAttr_BulletOfs 16 //00010000 +#define PPT_ParaAttr_DefaultTab 17 //00020000 +#define PPT_ParaAttr_AsianLB_1 18 +#define PPT_ParaAttr_AsianLB_2 19 +#define PPT_ParaAttr_AsianLB_3 20 +#define PPT_ParaAttr_BiDi 21 //00200000 + +#define PPT_CharAttr_Bold 0 //00000001 +#define PPT_CharAttr_Italic 1 //00000002 +#define PPT_CharAttr_Underline 2 //00000004 +#define PPT_CharAttr_Shadow 4 //00000010 +#define PPT_CharAttr_Strikeout 8 //00000100 +#define PPT_CharAttr_Embossed 9 //00000200 +#define PPT_CharAttr_Font 16 //00010000 +#define PPT_CharAttr_AsianOrComplexFont 21 //00200000 +#define PPT_CharAttr_ANSITypeface 22 //00400000 +#define PPT_CharAttr_Symbol 23 //00800000 +#define PPT_CharAttr_FontHeight 17 //00020000 +#define PPT_CharAttr_FontColor 18 //00040000 +#define PPT_CharAttr_Escapement 19 //00080000 + +// values for PptSlideLayoutAtom.eLayout +enum class PptSlideLayout +{ + TITLESLIDE = 0, // The slide is a title slide + TITLEANDBODYSLIDE = 1, // Title and body slide + TITLEMASTERSLIDE = 2, // Title master slide + MASTERSLIDE = 3, // Master slide layout + MASTERNOTES = 4, // Master notes layout + NOTESTITLEBODY = 5, // Notes title/body layout + HANDOUTLAYOUT = 6, // Handout layout, therefore it doesn't have placeholders except header, footer, and date + ONLYTITLE = 7, // Only title placeholder + TWOCOLUMNSANDTITLE = 8, // Body of the slide has 2 columns and a title + TWOROWSANDTITLE = 9, // Slide's body has 2 rows and a title + RIGHTCOLUMN2ROWS = 10, // Body contains 2 columns, right column has 2 rows + LEFTCOLUMN2ROWS = 11, // Body contains 2 columns, left column has 2 rows + BOTTOMROW2COLUMNS = 12, // Body contains 2 rows, bottom row has 2 columns + TOPROW2COLUMN = 13, // Body contains 2 rows, top row has 2 columns + FOUROBJECTS = 14, // 4 objects + BIGOBJECT = 15, // Big object + BLANKSLIDE = 16, // Blank slide + TITLERIGHTBODYLEFT = 17, // Vertical title on the right, body on the left + TITLERIGHT2BODIESLEFT = 18 // Vertical title on the right, body on the left split into 2 rows +}; + +// the following table describes the placeholder id's (values from reality followed by values taken from the documentation) +enum class PptPlaceholder : sal_uInt8 +{ + NONE = 0, // 0 None + MASTERTITLE = 1, // 1 Master title + MASTERBODY = 2, // 2 Master body + MASTERCENTEREDTITLE = 3, // 3 Master centered title + MASTERSUBTITLE = 4, // 10 Master subtitle + MASTERNOTESSLIDEIMAGE = 5, // 4 Master notes slide image + MASTERNOTESBODYIMAGE = 6, // 5 Master notes body image + MASTERDATE = 7, // 6 Master date + MASTERSLIDENUMBER = 8, // 7 Master slide number + MASTERFOOTER = 9, // 8 Master footer + MASTERHEADER = 10, // 9 Master header + // 11 Generic text object + TITLE = 13, // 12 Title + BODY = 14, // 13 Body + NOTESBODY = 12, // 14 Notes body + CENTEREDTITLE = 15, // 15 Centered title + SUBTITLE = 16, // 16 Subtitle + VERTICALTEXTTITLE = 17, // 17 Vertical text title + VERTICALTEXTBODY = 18, // 18 Vertical text body + NOTESSLIDEIMAGE = 11, // 19 Notes slide image + OBJECT = 19, // 20 Object (no matter the size) + GRAPH = 20, // 21 Graph + TABLE = 21, // 22 Table + CLIPART = 22, // 23 Clip Art + ORGANISZATIONCHART = 23, // 24 Organization Chart + MEDIACLIP = 24 // 25 Media Clip +}; + +#endif // INCLUDED_FILTER_MSFILTER_SVDFPPT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/svxmsbas.hxx b/include/filter/msfilter/svxmsbas.hxx new file mode 100644 index 000000000..190e289c4 --- /dev/null +++ b/include/filter/msfilter/svxmsbas.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FILTER_MSFILTER_SVXMSBAS_HXX +#define INCLUDED_FILTER_MSFILTER_SVXMSBAS_HXX + +#include +#include +#include +#include +#include + +class SfxObjectShell; + +/* Construct with the root storage of the MS document, with bImportCode + * set the visual basic code will be imported into the stardocument when Import + * is called, with bCopyStorage set, the visual basic storage tree will be + * copied completely into staroffice, so that any future export to a msoffice + * format will retain the vba code, allowing a lossless roundtrip from + * msoffice to staroffice and back. + * + * Setting bAsComment to true in Import will import the visual basic as a + * starbasic comment. Which is currently necessary, as vb is not valid sb. + * + * Setting bStripped will remove the "Attribute" lines from the vb, msoffice + * does this itself when it shows the vb code in the vbeditor, so this is + * probably what the user expects to see when viewing the code + */ + +class MSFILTER_DLLPUBLIC SvxImportMSVBasic +{ +public: + SvxImportMSVBasic(SfxObjectShell& rDocS, SotStorage& rRoot) + : xRoot(&rRoot) + , rDocSh(rDocS) + { + } + // only for the export - copy or delete the saved VBA-macro-storage + // form the ObjectShell + // - returns a warning code if a modified basic exist, in all other + // cases return ERRCODE_NONE. + ErrCode SaveOrDelMSVBAStorage(bool bSaveInto, const OUString& rStorageName); + + // check if the MS-VBA-Storage exist in the RootStorage of the DocShell. + // If it exist, then return the WarningId for losing the information. + static ErrCode GetSaveWarningOfMSVBAStorage(SfxObjectShell& rDocS); + + static OUString GetMSBasicStorageName(); + +private: + tools::SvRef xRoot; + SfxObjectShell& rDocSh; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/util.hxx b/include/filter/msfilter/util.hxx new file mode 100644 index 000000000..3dd7c8884 --- /dev/null +++ b/include/filter/msfilter/util.hxx @@ -0,0 +1,145 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_FILTER_MSFILTER_UTIL_HXX +#define INCLUDED_FILTER_MSFILTER_UTIL_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +class Color; + +namespace com::sun::star { + namespace awt { struct Size; } + namespace lang { struct Locale; } +} + +namespace msfilter::util { + +/// Returns the best-fit default 8bit encoding for a given locale +/// i.e. useful when dealing with legacy formats which use legacy text encodings without recording +/// what the encoding is, but you know or can guess the language +MSFILTER_DLLPUBLIC rtl_TextEncoding getBestTextEncodingFromLocale(const css::lang::Locale &rLocale); + +/// Convert a color in BGR format to RGB. +MSFILTER_DLLPUBLIC ::Color BGRToRGB(sal_uInt32 nColour); + +/** Convert from DTTM to Writer's DateTime + */ +MSFILTER_DLLPUBLIC DateTime DTTM2DateTime( tools::Long lDTTM ); + +/** Convert DateTime to xsd::dateTime string. + +I guess there must be an implementation of this somewhere in LO, but I failed +to find it, unfortunately :-( +*/ + +/// Given a cBullet in encoding r_ioChrSet and fontname r_ioFontName return a +/// suitable new Bullet and change r_ioChrSet and r_ioFontName to form the +/// best-fit replacement in terms of default available MSOffice symbol +/// fonts. +/// +/// Used to map from [Open|Star]Symbol to some Windows font or other. +MSFILTER_DLLPUBLIC sal_Unicode bestFitOpenSymbolToMSFont(sal_Unicode cBullet, + rtl_TextEncoding& r_ioChrSet, OUString& r_ioFontName); + + +/** + * Converts tools Color to HTML color (without leading hashmark). + * + * @param rColor color to convert + */ +MSFILTER_DLLPUBLIC OString ConvertColor( const Color &rColor ); +MSFILTER_DLLPUBLIC OUString ConvertColorOU( const Color &rColor ); + + +/** Paper size in 1/100 millimeters. */ +struct MSFILTER_DLLPUBLIC ApiPaperSize +{ + sal_Int32 mnWidth; + sal_Int32 mnHeight; +}; + +class MSFILTER_DLLPUBLIC PaperSizeConv +{ +public: + static sal_Int32 getMSPaperSizeIndex( const css::awt::Size& rSize ); + static const ApiPaperSize& getApiSizeForMSPaperSizeIndex( sal_Int32 nMSOPaperIndex ); +}; + +/** + * Finds the quoted text in a field instruction text. + * + * Example: SEQ "Figure" \someoption -> "Figure" + */ +MSFILTER_DLLPUBLIC std::u16string_view findQuotedText( std::u16string_view rCommand, const char* cStartQuote, const sal_Unicode uEndQuote ); + +class MSFILTER_DLLPUBLIC WW8ReadFieldParams +{ +private: + const OUString aData; + sal_Int32 nFnd; + sal_Int32 nNext; + sal_Int32 nSavPtr; +public: + WW8ReadFieldParams( OUString aData ); + + bool GoToTokenParam(); + sal_Int32 SkipToNextToken(); + sal_Int32 GetTokenSttPtr() const { return nFnd; } + + sal_Int32 FindNextStringPiece( sal_Int32 _nStart = -1 ); + bool GetTokenSttFromTo(sal_Int32* _pFrom, sal_Int32* _pTo, sal_Int32 _nMax); + + OUString GetResult() const; +}; + +struct MSFILTER_DLLPUBLIC EquationResult +{ + OUString sResult; + OUString sType; +}; + +MSFILTER_DLLPUBLIC EquationResult ParseCombinedChars(const OUString& rStr); + +/// Similar to EnhancedCustomShapeTypeNames::Get(), but it also supports OOXML types and returns a drawingML string. +MSFILTER_DLLPUBLIC OString GetOOXMLPresetGeometry( std::u16string_view rShapeType ); + +/// Similar to EnhancedCustomShapeTypeNames::Get(), but returns an MSO_SPT (binary / VML type). +MSFILTER_DLLPUBLIC MSO_SPT GETVMLShapeType(std::u16string_view aType); + +/** + * The following function checks if a MSO shapetype is allowed to have textboxcontent. + * + * @param nShapeType shape to check + */ +MSFILTER_DLLPUBLIC bool HasTextBoxContent(sal_uInt32 nShapeType); + +/** + * Convert the input color value to an ico value (0..16) + * + * @param[in] rCol input color for conversion + * + * @return ico value [0..16] +**/ +MSFILTER_DLLPUBLIC sal_uInt8 TransColToIco( const Color& rCol ); + +} + + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/filter/msfilter/ww8fields.hxx b/include/filter/msfilter/ww8fields.hxx new file mode 100644 index 000000000..8399fe22e --- /dev/null +++ b/include/filter/msfilter/ww8fields.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +namespace ww +{ +enum eField +{ + eNONE = 0, + eUNKNOWN = 1, + ePOSSIBLEBOOKMARK = 2, + eREF = 3, + eXE = 4, + eFOOTREF = 5, + eSET = 6, + eIF = 7, + eINDEX = 8, + eTC = 9, + eSTYLEREF = 10, + eRD = 11, + eSEQ = 12, + eTOC = 13, + eINFO = 14, + eTITLE = 15, + eSUBJECT = 16, + eAUTHOR = 17, + eKEYWORDS = 18, + eCOMMENTS = 19, + eLASTSAVEDBY = 20, + eCREATEDATE = 21, + eSAVEDATE = 22, + ePRINTDATE = 23, + eREVNUM = 24, + eEDITTIME = 25, + eNUMPAGES = 26, + eNUMWORDS = 27, + eNUMCHARS = 28, + eFILENAME = 29, + eTEMPLATE = 30, + eDATE = 31, + eTIME = 32, + ePAGE = 33, + eEquals = 34, + eQUOTE = 35, + eMERGEINC = 36, + ePAGEREF = 37, + eASK = 38, + eFILLIN = 39, + eMERGEDATA = 40, + eNEXT = 41, + eNEXTIF = 42, + eSKIPIF = 43, + eMERGEREC = 44, + eDDEREF = 45, + eDDEAUTOREF = 46, + eGLOSSREF = 47, + ePRINT = 48, + eEQ = 49, + eGOTOBUTTON = 50, + eMACROBUTTON = 51, + eAUTONUMOUT = 52, + eAUTONUMLGL = 53, + eAUTONUM = 54, + eINCLUDETIFF = 55, + eLINK = 56, + eSYMBOL = 57, + eEMBED = 58, + eMERGEFIELD = 59, + eUSERNAME = 60, + eUSERINITIALS = 61, + eUSERADDRESS = 62, + eBARCODE = 63, + eDOCVARIABLE = 64, + eSECTION = 65, + eSECTIONPAGES = 66, + eINCLUDEPICTURE = 67, + eINCLUDETEXT = 68, + eFILESIZE = 69, + eFORMTEXT = 70, + eFORMCHECKBOX = 71, + eNOTEREF = 72, + eTOA = 73, + eTA = 74, + eMERGESEQ = 75, + eMACRO = 76, + ePRIVATE = 77, + eDATABASE = 78, + eAUTOTEXT = 79, + eCOMPARE = 80, + ePLUGIN = 81, + eSUBSCRIBER = 82, + eFORMDROPDOWN = 83, + eADVANCE = 84, + eDOCPROPERTY = 85, + eUNKNOWN2 = 86, + eCONTROL = 87, + eHYPERLINK = 88, + eAUTOTEXTLIST = 89, + eLISTNUM = 90, + eHTMLCONTROL = 91, + eBIDIOUTLINE = 92, + eADDRESSBLOCK = 93, + eGREETINGLINE = 94, + eSHAPE = 95, + // NOTE: values > 95 / 0x5F do not correspond to documented WW8 fields + // and thus need special handling in WW8Export::OutputField()! + eBIBLIOGRAPHY = 96, + eCITATION = 97, + eFORMDATE = 98, +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/ExternalReferenceHelper.hxx b/include/formula/ExternalReferenceHelper.hxx new file mode 100644 index 000000000..364307f63 --- /dev/null +++ b/include/formula/ExternalReferenceHelper.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_EXTERNALREFERENCEHELPER_HXX +#define INCLUDED_FORMULA_EXTERNALREFERENCEHELPER_HXX + +#include + +#include +#include +#include + +namespace formula +{ + class FORMULA_DLLPUBLIC SAL_NO_VTABLE ExternalReferenceHelper + { + public: + virtual OUString getCacheTableName(sal_uInt16 nFileId, size_t nTabIndex) const = 0; + + protected: + ~ExternalReferenceHelper() {} + }; + +} // formula + +#endif // INCLUDED_FORMULA_EXTERNALREFERENCEHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/FormulaCompiler.hxx b/include/formula/FormulaCompiler.hxx new file mode 100644 index 000000000..08710f561 --- /dev/null +++ b/include/formula/FormulaCompiler.hxx @@ -0,0 +1,506 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FORMULACOMPILER_HXX +#define INCLUDED_FORMULA_FORMULACOMPILER_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define FORMULA_MAXJUMPCOUNT 32 /* maximum number of jumps (ocChoose) */ +#define FORMULA_MAXTOKENS 8192 /* maximum number of tokens in formula */ +#define FORMULA_MAXPARAMS 255 /* maximum number of parameters per function (byte) */ +#define FORMULA_MAXPARAMSII 8 /* maximum number of parameters for functions that have implicit intersection ranges */ + + +namespace com::sun::star { + namespace sheet { + struct FormulaOpCodeMapEntry; + struct FormulaToken; + } +} + +class CharClass; +enum class FormulaError : sal_uInt16; +enum class SvNumFormatType : sal_Int16; + +namespace formula +{ + +struct FormulaArrayStack +{ + FormulaArrayStack* pNext; + FormulaTokenArray* pArr; + FormulaTokenRef mpLastToken; + sal_uInt16 nIndex; + bool bTemp; +}; + +typedef std::unordered_map< OUString, OpCode > OpCodeHashMap; +typedef std::unordered_map< OUString, OUString > ExternalHashMap; + +class FORMULA_DLLPUBLIC FormulaCompiler +{ +private: + FormulaCompiler(const FormulaCompiler&) = delete; + FormulaCompiler& operator=(const FormulaCompiler&) = delete; +public: + FormulaCompiler(bool bComputeII = false, bool bMatrixFlag = false); + FormulaCompiler(FormulaTokenArray& _rArr, bool bComputeII = false, bool bMatrixFlag = false); + virtual ~FormulaCompiler(); + + /** Mappings from strings to OpCodes and vice versa. */ + class FORMULA_DLLPUBLIC OpCodeMap final + { + OpCodeHashMap maHashMap; /// Hash map of symbols, OUString -> OpCode + std::unique_ptr mpTable; /// Array of symbols, OpCode -> OUString, offset==OpCode + ExternalHashMap maExternalHashMap; /// Hash map of ocExternal, Filter String -> AddIn String + ExternalHashMap maReverseExternalHashMap; /// Hash map of ocExternal, AddIn String -> Filter String + FormulaGrammar::Grammar meGrammar; /// Grammar, language and reference convention + sal_uInt16 mnSymbols; /// Count of OpCode symbols + bool mbCore : 1; /// If mapping was setup by core, not filters + bool mbEnglish : 1; /// If English symbols and external names + bool mbEnglishLocale : 1; /// If English locale for numbers + + OpCodeMap( const OpCodeMap& ) = delete; + OpCodeMap& operator=( const OpCodeMap& ) = delete; + + public: + + OpCodeMap(sal_uInt16 nSymbols, bool bCore, FormulaGrammar::Grammar eGrammar ) : + maHashMap(nSymbols), + mpTable( new OUString[ nSymbols ]), + meGrammar( eGrammar), + mnSymbols( nSymbols), + mbCore( bCore), + mbEnglish ( FormulaGrammar::isEnglish(eGrammar) ), + mbEnglishLocale ( mbEnglish ) + { + } + + /** Copy mappings from r into this map, effectively replacing this map. + + Override known legacy bad function names with + correct ones if the conditions can be derived from the + current maps. + */ + void copyFrom( const OpCodeMap& r ); + + /// Get the symbol String -> OpCode hash map for finds. + const OpCodeHashMap& getHashMap() const { return maHashMap; } + + /// Get the symbol String -> AddIn String hash map for finds. + const ExternalHashMap& getExternalHashMap() const { return maExternalHashMap; } + + /// Get the AddIn String -> symbol String hash map for finds. + const ExternalHashMap& getReverseExternalHashMap() const { return maReverseExternalHashMap; } + + /// Get the symbol string matching an OpCode. + const OUString& getSymbol( const OpCode eOp ) const + { + DBG_ASSERT( sal_uInt16(eOp) < mnSymbols, "OpCodeMap::getSymbol: OpCode out of range"); + if (sal_uInt16(eOp) < mnSymbols) + return mpTable[ eOp ]; + static OUString s_sEmpty; + return s_sEmpty; + } + + /// Get the first character of the symbol string matching an OpCode. + sal_Unicode getSymbolChar( const OpCode eOp ) const { return getSymbol(eOp)[0]; }; + + /// Get the grammar. + FormulaGrammar::Grammar getGrammar() const { return meGrammar; } + + /// Get the symbol count. + sal_uInt16 getSymbolCount() const { return mnSymbols; } + + /** Are these English symbols, as opposed to native language (which may + be English as well)? */ + bool isEnglish() const { return mbEnglish; } + + /** Are inline numbers parsed/formatted in en-US locale, as opposed + to default locale? */ + bool isEnglishLocale() const { return mbEnglishLocale; } + + /// Is it an ODF 1.1 compatibility mapping? + bool isPODF() const { return FormulaGrammar::isPODF( meGrammar); } + + /* TODO: add isAPI() once a FormulaLanguage was added. */ + + /// Is it an ODFF / ODF 1.2 mapping? + bool isODFF() const { return FormulaGrammar::isODFF( meGrammar); } + + /// Is it an OOXML mapping? + bool isOOXML() const { return FormulaGrammar::isOOXML( meGrammar); } + + /// Does it have external symbol/name mappings? + bool hasExternals() const { return !maExternalHashMap.empty(); } + + /// Put entry of symbol String and OpCode pair. + void putOpCode( const OUString & rStr, const OpCode eOp, const CharClass* pCharClass ); + + /// Put entry of symbol String and AddIn international String pair. + void putExternal( const OUString & rSymbol, const OUString & rAddIn ); + + /** Put entry of symbol String and AddIn international String pair, + not warning just info as used for AddIn collection and setting up + alias names. */ + void putExternalSoftly( const OUString & rSymbol, const OUString & rAddIn ); + + /// Core implementation of XFormulaOpCodeMapper::getMappings() + css::uno::Sequence< css::sheet::FormulaToken > + createSequenceOfFormulaTokens(const FormulaCompiler& _rCompiler, + const css::uno::Sequence< OUString >& rNames ) const; + + /// Core implementation of XFormulaOpCodeMapper::getAvailableMappings() + css::uno::Sequence< css::sheet::FormulaOpCodeMapEntry > + createSequenceOfAvailableMappings( const FormulaCompiler& _rCompiler,const sal_Int32 nGroup ) const; + + /** The value used in createSequenceOfAvailableMappings() and thus in + XFormulaOpCodeMapper::getMappings() for an unknown symbol. */ + static sal_Int32 getOpCodeUnknown() { return -1; } + + private: + + /** Conditionally put a mapping in copyFrom() context. + + Does NOT check eOp range! + */ + void putCopyOpCode( const OUString& rSymbol, OpCode eOp ); + }; + +public: + typedef std::shared_ptr< const OpCodeMap > OpCodeMapPtr; + typedef std::shared_ptr< OpCodeMap > NonConstOpCodeMapPtr; + +protected: + /** Get finalized OpCodeMap for formula language. + + Creates/returns a singleton instance of an OpCodeMap that contains + external AddIn mappings if the derived class supports them. Do not call + at this base class as it results in a permanent mapping without AddIns + even for derived classes (unless it is for the implementation of the + temporary GetOpCodeMap()). + + @param nLanguage + One of css::sheet::FormulaLanguage constants. + @return Map for nLanguage. If nLanguage is unknown, a NULL map is returned. + */ + OpCodeMapPtr GetFinalOpCodeMap( const sal_Int32 nLanguage ) const; + +public: + /** Get OpCodeMap for formula language. + + Returns either the finalized OpCodeMap (created by GetFinalOpCodeMap() + of a derived class) for nLanguage if there is such, or if not then a + temporary map of which its singleton is reset immediately and the + temporary will get destroyed by the caller's scope. A temporary map + created at this base class does *not* contain AddIn mappings. + + @param nLanguage + One of css::sheet::FormulaLanguage constants. + @return Map for nLanguage. If nLanguage is unknown, a NULL map is returned. + */ + OpCodeMapPtr GetOpCodeMap( const sal_Int32 nLanguage ) const; + + /** Destroy the singleton OpCodeMap for formula language. + + This unconditionally destroys the underlying singleton instance of the + map to be reinitialized again later on the next GetOpCodeMap() call. + Use if the base class FormulaCompiler::GetOpCodeMap() was called and + created the map (i.e. HasOpCodeMap() before returned false) and later a + derived class like ScCompiler shall initialize it including AddIns. + + @param nLanguage + One of css::sheet::FormulaLanguage constants. + */ + void DestroyOpCodeMap( const sal_Int32 nLanguage ); + + /** Whether the singleton OpCodeMap for formula language exists already. + + @param nLanguage + One of css::sheet::FormulaLanguage constants. + */ + bool HasOpCodeMap( const sal_Int32 nLanguage ) const; + + /** Create an internal symbol map from API mapping. + @param bEnglish + Use English number parser / formatter instead of native. + */ + static OpCodeMapPtr CreateOpCodeMap( + const css::uno::Sequence< const css::sheet::FormulaOpCodeMapEntry > & rMapping, + bool bEnglish ); + + /** Get current OpCodeMap in effect. */ + const OpCodeMapPtr& GetCurrentOpCodeMap() const { return mxSymbols; } + + /** Get OpCode for English symbol. + Used in XFunctionAccess to create token array. + @param rName + Symbol to lookup. MUST be upper case. + */ + OpCode GetEnglishOpCode( const OUString& rName ) const; + + FormulaError GetErrorConstant( const OUString& rName ) const; + void AppendErrorConstant( OUStringBuffer& rBuffer, FormulaError nError ) const; + + void EnableJumpCommandReorder( bool bEnable ); + void EnableStopOnError( bool bEnable ); + + static bool IsOpCodeVolatile( OpCode eOp ); + static bool IsOpCodeJumpCommand( OpCode eOp ); + + static bool DeQuote( OUString& rStr ); + + + static const OUString& GetNativeSymbol( OpCode eOp ); + static sal_Unicode GetNativeSymbolChar( OpCode eOp ); + static bool IsMatrixFunction(OpCode _eOpCode); // if a function _always_ returns a Matrix + + SvNumFormatType GetNumFormatType() const { return nNumFmt; } + bool CompileTokenArray(); + + void CreateStringFromTokenArray( OUString& rFormula ); + void CreateStringFromTokenArray( OUStringBuffer& rBuffer ); + const FormulaToken* CreateStringFromToken( OUString& rFormula, const FormulaToken* pToken ); + const FormulaToken* CreateStringFromToken( OUStringBuffer& rBuffer, const FormulaToken* pToken, + bool bAllowArrAdvance = false ); + + void AppendBoolean( OUStringBuffer& rBuffer, bool bVal ) const; + void AppendDouble( OUStringBuffer& rBuffer, double fVal ) const; + static void AppendString( OUStringBuffer& rBuffer, const OUString & rStr ); + + /** Set symbol map corresponding to one of predefined formula::FormulaGrammar::Grammar, + including an address reference convention. */ + FormulaGrammar::Grammar GetGrammar() const { return meGrammar; } + + /** Whether current symbol set and grammar need transformation of Table + structured references to A1 style references when writing / exporting + (creating strings). + */ + bool NeedsTableRefTransformation() const; + + /** If a parameter nParam (0-based) is to be forced to array for OpCode + eOp, i.e. classified as ParamClass::ForceArray or + ParamClass::ReferenceOrForceArray type. */ + virtual formula::ParamClass GetForceArrayParameter( const FormulaToken* pToken, sal_uInt16 nParam ) const; + + static void UpdateSeparatorsNative( const OUString& rSep, const OUString& rArrayColSep, const OUString& rArrayRowSep ); + static void ResetNativeSymbols(); + static void SetNativeSymbols( const OpCodeMapPtr& xMap ); + + /** Sets the implicit intersection compute flag */ + void SetComputeIIFlag(bool bSet) { mbComputeII = bSet; } + + /** Sets the matrix flag for the formula*/ + void SetMatrixFlag(bool bSet) { mbMatrixFlag = bSet; } + + /** Separators mapped when loading opcodes from the resource, values other + than RESOURCE_BASE may override the resource strings. Used by OpCodeList + implementation via loadSymbols(). + */ + enum class SeparatorType + { + RESOURCE_BASE, + SEMICOLON_BASE + }; + +protected: + virtual OUString FindAddInFunction( const OUString& rUpperName, bool bLocalFirst ) const; + virtual void fillFromAddInCollectionUpperName( const NonConstOpCodeMapPtr& xMap ) const; + virtual void fillFromAddInMap( const NonConstOpCodeMapPtr& xMap, FormulaGrammar::Grammar _eGrammar ) const; + virtual void fillFromAddInCollectionEnglishName( const NonConstOpCodeMapPtr& xMap ) const; + virtual void fillAddInToken(::std::vector< css::sheet::FormulaOpCodeMapEntry >& _rVec, bool _bIsEnglish) const; + + virtual void SetError(FormulaError nError); + virtual FormulaTokenRef ExtendRangeReference( FormulaToken & rTok1, FormulaToken & rTok2 ); + virtual bool HandleExternalReference(const FormulaToken& _aToken); + virtual bool HandleRange(); + virtual bool HandleColRowName(); + virtual bool HandleDbData(); + virtual bool HandleTableRef(); + + virtual void CreateStringFromExternal( OUStringBuffer& rBuffer, const FormulaToken* pToken ) const; + virtual void CreateStringFromSingleRef( OUStringBuffer& rBuffer, const FormulaToken* pToken ) const; + virtual void CreateStringFromDoubleRef( OUStringBuffer& rBuffer, const FormulaToken* pToken ) const; + virtual void CreateStringFromMatrix( OUStringBuffer& rBuffer, const FormulaToken* pToken ) const; + virtual void CreateStringFromIndex( OUStringBuffer& rBuffer, const FormulaToken* pToken ) const; + virtual void LocalizeString( OUString& rName ) const; // modify rName - input: exact name + + bool GetToken(); + OpCode NextToken(); + void PutCode( FormulaTokenRef& ); + void Factor(); + void RangeLine(); + void UnionLine(); + void IntersectionLine(); + void UnaryLine(); + void PostOpLine(); + void PowLine(); + void MulDivLine(); + void AddSubLine(); + void ConcatLine(); + void CompareLine(); + OpCode Expression(); + void PopTokenArray(); + void PushTokenArray( FormulaTokenArray*, bool ); + + bool MergeRangeReference( FormulaToken * * const pCode1, FormulaToken * const * const pCode2 ); + + // Returns whether the opcode has implicit intersection ranges as parameters. + // Called for (most) opcodes to possibly handle implicit intersection for the parameters. + virtual void HandleIIOpCode(FormulaToken* /*token*/, + FormulaToken*** /*pppToken*/, sal_uInt8 /*nNumParams*/) {} + + // Called from CompileTokenArray() after RPN code generation is done. + virtual void PostProcessCode() {} + + virtual void AnnotateOperands() {} + + OUString aCorrectedFormula; // autocorrected Formula + OUString aCorrectedSymbol; // autocorrected Symbol + + OpCodeMapPtr mxSymbols; // which symbols are used + + FormulaTokenRef mpToken; // current token + FormulaTokenRef pCurrentFactorToken; // current factor token (of Factor() method) + sal_uInt16 nCurrentFactorParam; // current factor token's parameter, 1-based + FormulaTokenArray* pArr; + FormulaTokenArrayPlainIterator maArrIterator; + FormulaTokenRef mpLastToken; // last token + + FormulaToken** pCode; + FormulaArrayStack* pStack; + + OpCode eLastOp; + short nRecursion; // GetToken() recursions + SvNumFormatType nNumFmt; // set during CompileTokenArray() + sal_uInt16 pc; // program counter + + FormulaGrammar::Grammar meGrammar; // The grammar used, language plus convention. + + bool bAutoCorrect; // whether to apply AutoCorrection + bool bCorrected; // AutoCorrection was applied + bool glSubTotal; // if code contains one or more subtotal functions + bool needsRPNTokenCheck; // whether to make FormulaTokenArray check all tokens at the end + + bool mbJumpCommandReorder; /// Whether or not to reorder RPN for jump commands. + bool mbStopOnError; /// Whether to stop compilation on first encountered error. + + bool mbComputeII; // whether to attempt computing implicit intersection ranges while building the RPN array. + bool mbMatrixFlag; // whether the formula is a matrix formula (needed for II computation) + +public: + enum InitSymbols + { + ASK = 0, + INIT, + DESTROY + }; + +private: + bool InitSymbolsNative( InitSymbols ) const; /// only SymbolsNative, on first document creation + bool InitSymbolsEnglish( InitSymbols ) const; /// only SymbolsEnglish, maybe later + bool InitSymbolsPODF( InitSymbols ) const; /// only SymbolsPODF, on demand + bool InitSymbolsAPI( InitSymbols ) const; /// only SymbolsAPI, on demand + bool InitSymbolsODFF( InitSymbols ) const; /// only SymbolsODFF, on demand + bool InitSymbolsEnglishXL( InitSymbols ) const; /// only SymbolsEnglishXL, on demand + bool InitSymbolsOOXML( InitSymbols ) const; /// only SymbolsOOXML, on demand + + void loadSymbols(const std::pair* pSymbols, FormulaGrammar::Grammar eGrammar, NonConstOpCodeMapPtr& rxMap, + SeparatorType eSepType = SeparatorType::SEMICOLON_BASE) const; + + /** Check pCurrentFactorToken for nParam's (0-based) ForceArray types and + set ForceArray at rCurr if so. Set nParam+1 as 1-based + nCurrentFactorParam for subsequent ForceArrayOperator() calls. + */ + void CheckSetForceArrayParameter( FormulaTokenRef const & rCurr, sal_uInt8 nParam ); + + void ForceArrayOperator( FormulaTokenRef const & rCurr ); + + class CurrentFactor + { + FormulaTokenRef pPrevFac; + sal_uInt16 nPrevParam; + FormulaCompiler* pCompiler; + CurrentFactor( const CurrentFactor& ) = delete; + CurrentFactor& operator=( const CurrentFactor& ) = delete; + public: + explicit CurrentFactor( FormulaCompiler* pComp ) + : pPrevFac( pComp->pCurrentFactorToken ) + , nPrevParam( pComp->nCurrentFactorParam ) + , pCompiler( pComp ) + {} + ~CurrentFactor() + { + pCompiler->pCurrentFactorToken = pPrevFac; + pCompiler->nCurrentFactorParam = nPrevParam; + } + // yes, this operator= may modify the RValue + void operator=( FormulaTokenRef const & r ) + { + pCompiler->ForceArrayOperator( r ); + pCompiler->pCurrentFactorToken = r; + pCompiler->nCurrentFactorParam = 0; + } + void operator=( FormulaToken* p ) + { + FormulaTokenRef xTemp( p ); + *this = xTemp; + } + operator FormulaTokenRef&() + { return pCompiler->pCurrentFactorToken; } + FormulaToken* operator->() + { return pCompiler->pCurrentFactorToken.operator->(); } + operator FormulaToken*() + { return operator->(); } + }; + + + mutable NonConstOpCodeMapPtr mxSymbolsODFF; // ODFF symbols + mutable NonConstOpCodeMapPtr mxSymbolsPODF; // ODF 1.1 symbols + mutable NonConstOpCodeMapPtr mxSymbolsAPI; // XFunctionAccess API symbols + mutable NonConstOpCodeMapPtr mxSymbolsNative; // native symbols + mutable NonConstOpCodeMapPtr mxSymbolsEnglish; // English symbols + mutable NonConstOpCodeMapPtr mxSymbolsEnglishXL; // English Excel symbols (for VBA formula parsing) + mutable NonConstOpCodeMapPtr mxSymbolsOOXML; // Excel OOXML symbols + + static FormulaTokenArray smDummyTokenArray; +}; + +} // formula + + +#endif // INCLUDED_FORMULA_FORMULACOMPILER_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/FormulaOpCodeMapperObj.hxx b/include/formula/FormulaOpCodeMapperObj.hxx new file mode 100644 index 000000000..7e5928a1b --- /dev/null +++ b/include/formula/FormulaOpCodeMapperObj.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FORMULAOPCODEMAPPEROBJ_HXX +#define INCLUDED_FORMULA_FORMULAOPCODEMAPPEROBJ_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace sheet { struct FormulaOpCodeMapEntry; } + namespace sheet { struct FormulaToken; } + namespace uno { class XComponentContext; } + namespace uno { class XInterface; } +} + +namespace formula +{ + +class FormulaCompiler; + +class FORMULA_DLLPUBLIC FormulaOpCodeMapperObj : public cppu::WeakImplHelper< + css::sheet::XFormulaOpCodeMapper, + css::lang::XServiceInfo > +{ + ::std::unique_ptr m_pCompiler; + +public: + FormulaOpCodeMapperObj(::std::unique_ptr && _pCompiler); + virtual ~FormulaOpCodeMapperObj() override; + +private: + // XFormulaOpCodeMapper + // Attributes + virtual ::sal_Int32 SAL_CALL getOpCodeExternal() override; + virtual ::sal_Int32 SAL_CALL getOpCodeUnknown() override; + // Methods + virtual css::uno::Sequence< css::sheet::FormulaToken > SAL_CALL getMappings( + const css::uno::Sequence< OUString >& rNames, + sal_Int32 nLanguage ) override; + virtual css::uno::Sequence< css::sheet::FormulaOpCodeMapEntry > SAL_CALL getAvailableMappings( + sal_Int32 nLanguage, sal_Int32 nGroups ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + +}; + +} // formula + + +#endif // INCLUDED_FORMULA_FORMULAOPCODEMAPPEROBJ_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/IControlReferenceHandler.hxx b/include/formula/IControlReferenceHandler.hxx new file mode 100644 index 000000000..e1096c47a --- /dev/null +++ b/include/formula/IControlReferenceHandler.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_FORMULA_ICONTROLREFERENCEHANDLER_HXX +#define INCLUDED_FORMULA_ICONTROLREFERENCEHANDLER_HXX + +#include +#include +#include + +namespace formula +{ + class RefEdit; + class RefButton; + class FORMULA_DLLPUBLIC SAL_NO_VTABLE IControlReferenceHandler + { + public: + virtual void ShowReference(const OUString& _sRef) = 0; + virtual void HideReference( bool bDoneRefMode = true ) = 0; + virtual void ReleaseFocus( RefEdit* pEdit ) = 0; + virtual void ToggleCollapsed( RefEdit* pEdit, RefButton* pButton ) = 0; + + protected: + ~IControlReferenceHandler() {} + }; +} // formula +#endif // INCLUDED_FORMULA_ICONTROLREFERENCEHANDLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/IFunctionDescription.hxx b/include/formula/IFunctionDescription.hxx new file mode 100644 index 000000000..28f293704 --- /dev/null +++ b/include/formula/IFunctionDescription.hxx @@ -0,0 +1,161 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_IFUNCTIONDESCRIPTION_HXX +#define INCLUDED_FORMULA_IFUNCTIONDESCRIPTION_HXX + +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace sheet { struct FormulaToken; } + namespace sheet { class XFormulaOpCodeMapper; } + namespace sheet { class XFormulaParser; } +} + +namespace com::sun::star::uno { template class Sequence; } + +namespace formula +{ + class IFunctionCategory; + class IFunctionDescription; + class FormEditData; + class FormulaTokenArray; + class FormulaCompiler; + + class SAL_NO_VTABLE IFunctionManager + { + public: + enum EToken + { + eOk, + eClose, + eSep, + eArrayOpen, + eArrayClose + }; + virtual sal_uInt32 getCount() const = 0; + virtual const IFunctionCategory* getCategory(sal_uInt32 nPos) const = 0; + virtual void fillLastRecentlyUsedFunctions(::std::vector< const IFunctionDescription*>& _rLastRUFunctions) const = 0; + + virtual sal_Unicode getSingleToken(const EToken _eToken) const = 0; + + protected: + ~IFunctionManager() {} + }; + + class SAL_NO_VTABLE IFunctionCategory + { + public: + virtual sal_uInt32 getCount() const = 0; + virtual const IFunctionDescription* getFunction(sal_uInt32 _nPos) const = 0; + virtual sal_uInt32 getNumber() const = 0; + virtual OUString getName() const = 0; + + protected: + ~IFunctionCategory() {} + }; + + class SAL_NO_VTABLE IFunctionDescription + { + public: + virtual OUString getFunctionName() const = 0; + virtual const IFunctionCategory* getCategory() const = 0; + virtual OUString getDescription() const = 0; + // GetSuppressedArgCount + virtual sal_Int32 getSuppressedArgumentCount() const = 0; + // GetFormulaString + virtual OUString getFormula(const ::std::vector< OUString >& _aArguments) const = 0; + // GetVisibleArgMapping + virtual void fillVisibleArgumentMapping(::std::vector& _rArguments) const = 0; + virtual void initArgumentInfo() const = 0; + virtual OUString getSignature() const = 0; + virtual OString getHelpId() const = 0; + virtual bool isHidden() const = 0; + + // parameter + virtual sal_uInt32 getParameterCount() const = 0; + virtual sal_uInt32 getVarArgsStart() const = 0; + virtual sal_uInt32 getVarArgsLimit() const = 0; + virtual OUString getParameterName(sal_uInt32 _nPos) const = 0; + virtual OUString getParameterDescription(sal_uInt32 _nPos) const = 0; + virtual bool isParameterOptional(sal_uInt32 _nPos) const = 0; + + protected: + ~IFunctionDescription() {} + }; + + class SAL_NO_VTABLE IFormulaEditorHelper + { + public: + virtual void notifyChange() = 0; + virtual void fill() = 0; + + virtual OUString getCurrentFormula() const = 0; + virtual void setCurrentFormula(const OUString& _sReplacement) = 0; + + virtual void getSelection(sal_Int32& _nStart, sal_Int32& _nEnd) const = 0; + virtual void setSelection(sal_Int32 _nStart, sal_Int32 _nEnd) = 0; + + virtual FormEditData* getFormEditData() const = 0; + virtual bool calculateValue(const OUString& _sExpression, OUString& _rResult, bool bMatrixFormula) = 0; + + /** Obtain a resident FormulaCompiler instance, created without + FormulaTokenArray and reused but being application specific derived. + */ + virtual std::shared_ptr getCompiler() const = 0; + + /** Create an application specific FormulaCompiler instance with + FormulaTokenArray. The FormulaTokenArray had to be created using + convertToTokenArray(). + */ + virtual std::unique_ptr createCompiler( FormulaTokenArray& rArray ) const = 0; + + virtual void switchBack() = 0; + + virtual void clear() = 0; + virtual void deleteFormData() = 0; + + virtual IFunctionManager* getFunctionManager() = 0; + virtual ::std::unique_ptr convertToTokenArray(const css::uno::Sequence< css::sheet::FormulaToken >& _aTokenList) = 0; + + virtual css::uno::Reference< css::sheet::XFormulaParser> getFormulaParser() const = 0; + virtual css::uno::Reference< css::sheet::XFormulaOpCodeMapper> getFormulaOpCodeMapper() const = 0; + virtual css::table::CellAddress getReferencePosition() const = 0; + + virtual void setDispatcherLock( bool bLock ) = 0; + virtual void dispatch(bool _bOK, bool _bMatrixChecked) = 0; + virtual void doClose(bool _bOk) = 0; + virtual void insertEntryToLRUList(const IFunctionDescription* pDesc) = 0; + virtual void showReference(const OUString& _sFormula) = 0; + + protected: + ~IFormulaEditorHelper() {} + }; + +} +#endif // INCLUDED_FORMULA_IFUNCTIONDESCRIPTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/compiler.hxx b/include/formula/compiler.hxx new file mode 100644 index 000000000..fcf7326d3 --- /dev/null +++ b/include/formula/compiler.hxx @@ -0,0 +1,531 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef FORMULA_COMPILER_HXX +#define FORMULA_COMPILER_HXX + +/* Central definition of OpCodes for spreadsheet functions */ + +/*** Special commands ***/ +#define SC_OPCODE_PUSH 0 /* internal commands */ +#define SC_OPCODE_CALL 1 +#define SC_OPCODE_STOP 2 +#define SC_OPCODE_EXTERNAL 3 +#define SC_OPCODE_NAME 4 +#define SC_OPCODE_EXTERNAL_REF 5 +#define SC_OPCODE_IF 6 /* jump commands */ +#define SC_OPCODE_IF_ERROR 7 +#define SC_OPCODE_IF_NA 8 +#define SC_OPCODE_CHOOSE 9 +#define SC_OPCODE_OPEN 10 /* parentheses and separators */ +#define SC_OPCODE_CLOSE 11 +#define SC_OPCODE_SEP 12 +#define SC_OPCODE_MISSING 13 /* special OpCodes */ +#define SC_OPCODE_BAD 14 +#define SC_OPCODE_STRINGXML 15 +#define SC_OPCODE_SPACES 16 +#define SC_OPCODE_WHITESPACE 17 +#define SC_OPCODE_MAT_REF 18 +#define SC_OPCODE_DB_AREA 19 /* additional access operators */ +#define SC_OPCODE_TABLE_REF 20 +#define SC_OPCODE_MACRO 21 +#define SC_OPCODE_COL_ROW_NAME 22 +#define SC_OPCODE_COL_ROW_NAME_AUTO 23 +#define SC_OPCODE_PERCENT_SIGN 24 /* operator _follows_ value */ +#define SC_OPCODE_ARRAY_OPEN 25 +#define SC_OPCODE_ARRAY_CLOSE 26 +#define SC_OPCODE_ARRAY_ROW_SEP 27 +#define SC_OPCODE_ARRAY_COL_SEP 28 /* some convs use sep != col_sep */ +#define SC_OPCODE_TABLE_REF_OPEN 29 +#define SC_OPCODE_TABLE_REF_CLOSE 30 +#define SC_OPCODE_TABLE_REF_ITEM_ALL 31 +#define SC_OPCODE_TABLE_REF_ITEM_HEADERS 32 +#define SC_OPCODE_TABLE_REF_ITEM_DATA 33 +#define SC_OPCODE_TABLE_REF_ITEM_TOTALS 34 +#define SC_OPCODE_TABLE_REF_ITEM_THIS_ROW 35 +#define SC_OPCODE_STOP_DIV 36 +#define SC_OPCODE_SKIP 37 /* used to skip raw tokens during string compilation */ + +/*** error constants #... ***/ +#define SC_OPCODE_START_ERRORS 40 +#define SC_OPCODE_ERROR_NULL 40 +#define SC_OPCODE_ERROR_DIVZERO 41 +#define SC_OPCODE_ERROR_VALUE 42 +#define SC_OPCODE_ERROR_REF 43 +#define SC_OPCODE_ERROR_NAME 44 +#define SC_OPCODE_ERROR_NUM 45 +#define SC_OPCODE_ERROR_NA 46 +#define SC_OPCODE_STOP_ERRORS 47 + +/*** Binary operators ***/ +#define SC_OPCODE_START_BIN_OP 50 +#define SC_OPCODE_ADD 50 +#define SC_OPCODE_SUB 51 +#define SC_OPCODE_MUL 52 +#define SC_OPCODE_DIV 53 +#define SC_OPCODE_AMPERSAND 54 +#define SC_OPCODE_POW 55 +#define SC_OPCODE_EQUAL 56 +#define SC_OPCODE_NOT_EQUAL 57 +#define SC_OPCODE_LESS 58 +#define SC_OPCODE_GREATER 59 +#define SC_OPCODE_LESS_EQUAL 60 +#define SC_OPCODE_GREATER_EQUAL 61 +#define SC_OPCODE_AND 62 +#define SC_OPCODE_OR 63 +#define SC_OPCODE_INTERSECT 64 +#define SC_OPCODE_UNION 65 +#define SC_OPCODE_RANGE 66 +#define SC_OPCODE_STOP_BIN_OP 67 + +/* NOTE: binary and unary operators must be in sequence for compiler! */ + +/*** Unary operators ***/ +#define SC_OPCODE_START_UN_OP 70 +#define SC_OPCODE_NEG_SUB 70 +#define SC_OPCODE_STOP_UN_OP 71 + +#define SC_OPCODE_START_FUNCTION 75 + +/*** Functions without parameters ***/ +#define SC_OPCODE_START_NO_PAR 75 +#define SC_OPCODE_PI 75 +#define SC_OPCODE_RANDOM 76 +#define SC_OPCODE_TRUE 77 +#define SC_OPCODE_FALSE 78 +#define SC_OPCODE_GET_ACT_DATE 79 +#define SC_OPCODE_GET_ACT_TIME 80 +#define SC_OPCODE_NO_VALUE 81 +#define SC_OPCODE_CURRENT 82 +#define SC_OPCODE_RANDOM_NV 83 +#define SC_OPCODE_STOP_NO_PAR 84 + +/*** Functions with one parameter ***/ +#define SC_OPCODE_START_1_PAR 90 +#define SC_OPCODE_DEG 90 /* trigonometric */ +#define SC_OPCODE_RAD 91 +#define SC_OPCODE_SIN 92 +#define SC_OPCODE_COS 93 +#define SC_OPCODE_TAN 94 +#define SC_OPCODE_COT 95 +#define SC_OPCODE_ARC_SIN 96 +#define SC_OPCODE_ARC_COS 97 +#define SC_OPCODE_ARC_TAN 98 +#define SC_OPCODE_ARC_COT 99 +#define SC_OPCODE_SIN_HYP 100 +#define SC_OPCODE_COS_HYP 101 +#define SC_OPCODE_TAN_HYP 102 +#define SC_OPCODE_COT_HYP 103 +#define SC_OPCODE_ARC_SIN_HYP 104 /* transcendent */ +#define SC_OPCODE_ARC_COS_HYP 105 +#define SC_OPCODE_ARC_TAN_HYP 106 +#define SC_OPCODE_ARC_COT_HYP 107 +#define SC_OPCODE_COSECANT 108 +#define SC_OPCODE_SECANT 109 +#define SC_OPCODE_COSECANT_HYP 110 +#define SC_OPCODE_SECANT_HYP 111 +#define SC_OPCODE_EXP 112 +#define SC_OPCODE_LN 113 +#define SC_OPCODE_SQRT 114 +#define SC_OPCODE_FACT 115 +#define SC_OPCODE_GET_YEAR 116 /* date and time */ +#define SC_OPCODE_GET_MONTH 117 +#define SC_OPCODE_GET_DAY 118 +#define SC_OPCODE_GET_HOUR 119 +#define SC_OPCODE_GET_MIN 120 +#define SC_OPCODE_GET_SEC 121 +#define SC_OPCODE_PLUS_MINUS 122 /* miscellaneous */ +#define SC_OPCODE_ABS 123 +#define SC_OPCODE_INT 124 +#define SC_OPCODE_PHI 125 +#define SC_OPCODE_GAUSS 126 +#define SC_OPCODE_IS_EMPTY 127 /* obtain type */ +#define SC_OPCODE_IS_STRING 128 +#define SC_OPCODE_IS_NON_STRING 129 +#define SC_OPCODE_IS_LOGICAL 130 +#define SC_OPCODE_TYPE 131 +#define SC_OPCODE_IS_REF 132 +#define SC_OPCODE_IS_VALUE 133 +#define SC_OPCODE_IS_FORMULA 134 +#define SC_OPCODE_IS_NV 135 +#define SC_OPCODE_IS_ERR 136 +#define SC_OPCODE_IS_ERROR 137 +#define SC_OPCODE_IS_EVEN 138 +#define SC_OPCODE_IS_ODD 139 +#define SC_OPCODE_N 140 +#define SC_OPCODE_GET_DATE_VALUE 141 /* string functions */ +#define SC_OPCODE_GET_TIME_VALUE 142 +#define SC_OPCODE_CODE 143 +#define SC_OPCODE_TRIM 144 +#define SC_OPCODE_UPPER 145 +#define SC_OPCODE_PROPER 146 +#define SC_OPCODE_LOWER 147 +#define SC_OPCODE_LEN 148 +#define SC_OPCODE_T 149 /* miscellaneous, part 21 */ +#define SC_OPCODE_VALUE 150 +#define SC_OPCODE_CLEAN 151 +#define SC_OPCODE_CHAR 152 +#define SC_OPCODE_LOG10 153 +#define SC_OPCODE_EVEN 154 +#define SC_OPCODE_ODD 155 +#define SC_OPCODE_STD_NORM_DIST 156 +#define SC_OPCODE_FISHER 157 +#define SC_OPCODE_FISHER_INV 158 +#define SC_OPCODE_S_NORM_INV 159 +#define SC_OPCODE_GAMMA_LN 160 +#define SC_OPCODE_ERROR_TYPE 161 +#define SC_OPCODE_FORMULA 163 +#define SC_OPCODE_ARABIC 164 +#define SC_OPCODE_INFO 165 +#define SC_OPCODE_BAHTTEXT 166 +#define SC_OPCODE_JIS 167 +#define SC_OPCODE_ASC 168 +#define SC_OPCODE_UNICODE 169 +#define SC_OPCODE_UNICHAR 170 +#define SC_OPCODE_GAMMA 171 +#define SC_OPCODE_GAMMA_LN_MS 172 +#define SC_OPCODE_ERF_MS 173 +#define SC_OPCODE_ERFC_MS 174 +#define SC_OPCODE_ERROR_TYPE_ODF 175 +#define SC_OPCODE_ENCODEURL 176 +#define SC_OPCODE_ISOWEEKNUM 177 +#define SC_OPCODE_NOT 178 +#define SC_OPCODE_NEG 179 +#define SC_OPCODE_STOP_1_PAR 180 + +/*** Functions with more than one parameters ***/ +#define SC_OPCODE_START_2_PAR 201 +#define SC_OPCODE_ARC_TAN_2 201 +#define SC_OPCODE_CEIL 202 +#define SC_OPCODE_FLOOR 203 +#define SC_OPCODE_ROUND 204 +#define SC_OPCODE_ROUND_UP 205 +#define SC_OPCODE_ROUND_DOWN 206 +#define SC_OPCODE_TRUNC 207 +#define SC_OPCODE_LOG 208 +#define SC_OPCODE_POWER 209 +#define SC_OPCODE_GCD 210 +#define SC_OPCODE_LCM 211 +#define SC_OPCODE_MOD 212 +#define SC_OPCODE_SUM_PRODUCT 213 +#define SC_OPCODE_SUM_SQ 214 +#define SC_OPCODE_SUM_X2MY2 215 +#define SC_OPCODE_SUM_X2DY2 216 +#define SC_OPCODE_SUM_XMY2 217 +#define SC_OPCODE_GET_DATE 218 +#define SC_OPCODE_GET_TIME 219 +#define SC_OPCODE_GET_DIFF_DATE 220 +#define SC_OPCODE_GET_DIFF_DATE_360 221 +#define SC_OPCODE_MIN 222 +#define SC_OPCODE_MAX 223 +#define SC_OPCODE_SUM 224 +#define SC_OPCODE_PRODUCT 225 +#define SC_OPCODE_AVERAGE 226 +#define SC_OPCODE_COUNT 227 +#define SC_OPCODE_COUNT_2 228 +#define SC_OPCODE_NPV 229 +#define SC_OPCODE_IRR 230 +#define SC_OPCODE_VAR 231 +#define SC_OPCODE_VAR_P 232 +#define SC_OPCODE_ST_DEV 233 +#define SC_OPCODE_ST_DEV_P 234 +#define SC_OPCODE_B 235 +#define SC_OPCODE_NORM_DIST 236 +#define SC_OPCODE_EXP_DIST 237 +#define SC_OPCODE_BINOM_DIST 238 +#define SC_OPCODE_POISSON_DIST 239 +#define SC_OPCODE_COMBIN 240 +#define SC_OPCODE_COMBIN_A 241 +#define SC_OPCODE_PERMUT 242 +#define SC_OPCODE_PERMUTATION_A 243 +#define SC_OPCODE_PV 244 +#define SC_OPCODE_SYD 245 +#define SC_OPCODE_DDB 246 +#define SC_OPCODE_DB 247 +#define SC_OPCODE_VBD 248 +#define SC_OPCODE_PDURATION 249 +#define SC_OPCODE_SLN 250 +#define SC_OPCODE_PMT 251 +#define SC_OPCODE_COLUMNS 252 +#define SC_OPCODE_ROWS 253 +#define SC_OPCODE_COLUMN 254 +#define SC_OPCODE_ROW 255 +#define SC_OPCODE_RRI 256 +#define SC_OPCODE_FV 257 +#define SC_OPCODE_NPER 258 +#define SC_OPCODE_RATE 259 +#define SC_OPCODE_IPMT 260 +#define SC_OPCODE_PPMT 261 +#define SC_OPCODE_CUM_IPMT 262 +#define SC_OPCODE_CUM_PRINC 263 +#define SC_OPCODE_EFFECT 264 +#define SC_OPCODE_NOMINAL 265 +#define SC_OPCODE_SUB_TOTAL 266 +#define SC_OPCODE_DB_SUM 267 /* database functions */ +#define SC_OPCODE_DB_COUNT 268 +#define SC_OPCODE_DB_COUNT_2 269 +#define SC_OPCODE_DB_AVERAGE 270 +#define SC_OPCODE_DB_GET 271 +#define SC_OPCODE_DB_MAX 272 +#define SC_OPCODE_DB_MIN 273 +#define SC_OPCODE_DB_PRODUCT 274 +#define SC_OPCODE_DB_STD_DEV 275 +#define SC_OPCODE_DB_STD_DEV_P 276 +#define SC_OPCODE_DB_VAR 277 +#define SC_OPCODE_DB_VAR_P 278 +#define SC_OPCODE_INDIRECT 279 /* management functions */ +#define SC_OPCODE_ADDRESS 280 +#define SC_OPCODE_MATCH 281 +#define SC_OPCODE_COUNT_EMPTY_CELLS 282 +#define SC_OPCODE_COUNT_IF 283 +#define SC_OPCODE_SUM_IF 284 +#define SC_OPCODE_LOOKUP 285 +#define SC_OPCODE_V_LOOKUP 286 +#define SC_OPCODE_H_LOOKUP 287 +#define SC_OPCODE_MULTI_AREA 288 +#define SC_OPCODE_OFFSET 289 +#define SC_OPCODE_INDEX 290 +#define SC_OPCODE_AREAS 291 +#define SC_OPCODE_CURRENCY 292 /* string functions */ +#define SC_OPCODE_REPLACE 293 +#define SC_OPCODE_FIXED 294 +#define SC_OPCODE_FIND 295 +#define SC_OPCODE_EXACT 296 +#define SC_OPCODE_LEFT 297 +#define SC_OPCODE_RIGHT 298 +#define SC_OPCODE_SEARCH 299 +#define SC_OPCODE_MID 300 +#define SC_OPCODE_TEXT 301 +#define SC_OPCODE_SUBSTITUTE 302 +#define SC_OPCODE_REPT 303 +#define SC_OPCODE_CONCAT 304 +#define SC_OPCODE_MAT_VALUE 305 /* matrix functions */ +#define SC_OPCODE_MAT_DET 306 +#define SC_OPCODE_MAT_INV 307 +#define SC_OPCODE_MAT_MULT 308 +#define SC_OPCODE_MAT_TRANS 309 +#define SC_OPCODE_MATRIX_UNIT 310 +#define SC_OPCODE_BACK_SOLVER 311 /* BackSolver */ +#define SC_OPCODE_HYP_GEOM_DIST 312 /* statistical functions */ +#define SC_OPCODE_LOG_NORM_DIST 313 +#define SC_OPCODE_T_DIST 314 +#define SC_OPCODE_F_DIST 315 +#define SC_OPCODE_CHI_DIST 316 +#define SC_OPCODE_WEIBULL 317 +#define SC_OPCODE_NEG_BINOM_VERT 318 +#define SC_OPCODE_CRIT_BINOM 319 +#define SC_OPCODE_KURT 320 +#define SC_OPCODE_HAR_MEAN 321 +#define SC_OPCODE_GEO_MEAN 322 +#define SC_OPCODE_STANDARD 323 +#define SC_OPCODE_AVE_DEV 324 +#define SC_OPCODE_SKEW 325 +#define SC_OPCODE_DEV_SQ 326 +#define SC_OPCODE_MEDIAN 327 +#define SC_OPCODE_MODAL_VALUE 328 +#define SC_OPCODE_Z_TEST 329 +#define SC_OPCODE_T_TEST 330 +#define SC_OPCODE_RANK 331 +#define SC_OPCODE_PERCENTILE 332 +#define SC_OPCODE_PERCENT_RANK 333 +#define SC_OPCODE_LARGE 334 +#define SC_OPCODE_SMALL 335 +#define SC_OPCODE_FREQUENCY 336 +#define SC_OPCODE_QUARTILE 337 +#define SC_OPCODE_NORM_INV 338 +#define SC_OPCODE_CONFIDENCE 339 +#define SC_OPCODE_F_TEST 340 +#define SC_OPCODE_TRIM_MEAN 341 +#define SC_OPCODE_PROB 342 +#define SC_OPCODE_CORREL 343 +#define SC_OPCODE_COVAR 344 +#define SC_OPCODE_PEARSON 345 +#define SC_OPCODE_RSQ 346 +#define SC_OPCODE_STEYX 347 +#define SC_OPCODE_SLOPE 348 +#define SC_OPCODE_INTERCEPT 349 +#define SC_OPCODE_TREND 350 +#define SC_OPCODE_GROWTH 351 +#define SC_OPCODE_LINEST 352 +#define SC_OPCODE_LOGEST 353 +#define SC_OPCODE_FORECAST 354 +#define SC_OPCODE_CHI_INV 355 +#define SC_OPCODE_GAMMA_DIST 356 +#define SC_OPCODE_GAMMA_INV 357 +#define SC_OPCODE_T_INV 358 +#define SC_OPCODE_F_INV 359 +#define SC_OPCODE_CHI_TEST 360 +#define SC_OPCODE_LOG_INV 361 +#define SC_OPCODE_TABLE_OP 362 +#define SC_OPCODE_BETA_DIST 363 +#define SC_OPCODE_BETA_INV 364 +#define SC_OPCODE_WEEK 365 /* miscellaneous */ +#define SC_OPCODE_GET_DAY_OF_WEEK 366 +#define SC_OPCODE_NO_NAME 367 +#define SC_OPCODE_STYLE 368 +#define SC_OPCODE_DDE 369 +#define SC_OPCODE_BASE 370 +#define SC_OPCODE_SHEET 371 +#define SC_OPCODE_SHEETS 372 +#define SC_OPCODE_MIN_A 373 +#define SC_OPCODE_MAX_A 374 +#define SC_OPCODE_AVERAGE_A 375 +#define SC_OPCODE_ST_DEV_A 376 +#define SC_OPCODE_ST_DEV_P_A 377 +#define SC_OPCODE_VAR_A 378 +#define SC_OPCODE_VAR_P_A 379 +#define SC_OPCODE_EASTERSUNDAY 380 +#define SC_OPCODE_DECIMAL 381 +#define SC_OPCODE_CONVERT_OOO 382 +#define SC_OPCODE_ROMAN 383 +#define SC_OPCODE_MIRR 384 +#define SC_OPCODE_CELL 385 +#define SC_OPCODE_ISPMT 386 +#define SC_OPCODE_HYPERLINK 387 +// free: 388 +// free: 389 +#define SC_OPCODE_GET_PIVOT_DATA 390 +#define SC_OPCODE_EUROCONVERT 391 +#define SC_OPCODE_NUMBERVALUE 392 +#define SC_OPCODE_CHISQ_DIST 393 +#define SC_OPCODE_CHISQ_INV 394 +#define SC_OPCODE_BITAND 395 +#define SC_OPCODE_BITOR 396 +#define SC_OPCODE_BITXOR 397 +#define SC_OPCODE_BITRSHIFT 398 +#define SC_OPCODE_BITLSHIFT 399 +#define SC_OPCODE_GET_DATEDIF 400 +#define SC_OPCODE_XOR 401 +#define SC_OPCODE_AVERAGE_IF 402 +#define SC_OPCODE_SUM_IFS 403 +#define SC_OPCODE_AVERAGE_IFS 404 +#define SC_OPCODE_COUNT_IFS 405 +#define SC_OPCODE_SKEWP 406 +#define SC_OPCODE_LENB 407 +#define SC_OPCODE_RIGHTB 408 +#define SC_OPCODE_LEFTB 409 +#define SC_OPCODE_MIDB 410 +#define SC_OPCODE_FILTERXML 411 +#define SC_OPCODE_WEBSERVICE 412 +#define SC_OPCODE_COVARIANCE_S 413 +#define SC_OPCODE_COVARIANCE_P 414 +#define SC_OPCODE_ST_DEV_P_MS 415 +#define SC_OPCODE_ST_DEV_S 416 +#define SC_OPCODE_VAR_P_MS 417 +#define SC_OPCODE_VAR_S 418 +#define SC_OPCODE_BETA_DIST_MS 419 +#define SC_OPCODE_BETA_INV_MS 420 +#define SC_OPCODE_BINOM_DIST_MS 421 +#define SC_OPCODE_BINOM_INV 422 +#define SC_OPCODE_CHI_DIST_MS 423 +#define SC_OPCODE_CHI_INV_MS 424 +#define SC_OPCODE_CHI_TEST_MS 425 +#define SC_OPCODE_CHISQ_DIST_MS 426 +#define SC_OPCODE_CHISQ_INV_MS 427 +#define SC_OPCODE_CONFIDENCE_N 428 +#define SC_OPCODE_CONFIDENCE_T 429 +#define SC_OPCODE_F_DIST_LT 430 +#define SC_OPCODE_F_DIST_RT 431 +#define SC_OPCODE_F_INV_LT 432 +#define SC_OPCODE_F_INV_RT 433 +#define SC_OPCODE_F_TEST_MS 434 +#define SC_OPCODE_EXP_DIST_MS 435 +#define SC_OPCODE_HYP_GEOM_DIST_MS 436 +#define SC_OPCODE_POISSON_DIST_MS 437 +#define SC_OPCODE_WEIBULL_MS 438 +#define SC_OPCODE_GAMMA_DIST_MS 439 +#define SC_OPCODE_GAMMA_INV_MS 440 +#define SC_OPCODE_LOG_NORM_DIST_MS 441 +#define SC_OPCODE_LOG_INV_MS 442 +#define SC_OPCODE_NORM_DIST_MS 443 +#define SC_OPCODE_NORM_INV_MS 444 +#define SC_OPCODE_STD_NORM_DIST_MS 445 +#define SC_OPCODE_S_NORM_INV_MS 446 +#define SC_OPCODE_T_DIST_MS 447 +#define SC_OPCODE_T_DIST_RT 448 +#define SC_OPCODE_T_DIST_2T 449 +#define SC_OPCODE_T_INV_2T 450 +#define SC_OPCODE_T_INV_MS 451 +#define SC_OPCODE_T_TEST_MS 452 +#define SC_OPCODE_PERCENTILE_INC 453 +#define SC_OPCODE_PERCENT_RANK_INC 454 +#define SC_OPCODE_QUARTILE_INC 455 +#define SC_OPCODE_RANK_EQ 456 +#define SC_OPCODE_PERCENTILE_EXC 457 +#define SC_OPCODE_PERCENT_RANK_EXC 458 +#define SC_OPCODE_QUARTILE_EXC 459 +#define SC_OPCODE_RANK_AVG 460 +#define SC_OPCODE_MODAL_VALUE_MS 461 +#define SC_OPCODE_MODAL_VALUE_MULTI 462 +#define SC_OPCODE_NEG_BINOM_DIST_MS 463 +#define SC_OPCODE_Z_TEST_MS 464 +#define SC_OPCODE_CEIL_MS 465 +#define SC_OPCODE_CEIL_ISO 466 +#define SC_OPCODE_FLOOR_MS 467 +#define SC_OPCODE_NETWORKDAYS_MS 468 +#define SC_OPCODE_WORKDAY_MS 469 +#define SC_OPCODE_AGGREGATE 470 +#define SC_OPCODE_COLOR 471 +#define SC_OPCODE_CEIL_MATH 472 +#define SC_OPCODE_CEIL_PRECISE 473 +#define SC_OPCODE_NETWORKDAYS 474 +#define SC_OPCODE_FLOOR_MATH 475 +#define SC_OPCODE_FLOOR_PRECISE 476 +#define SC_OPCODE_RAWSUBTRACT 477 +#define SC_OPCODE_WEEKNUM_OOO 478 +#define SC_OPCODE_FORECAST_ETS_ADD 479 +#define SC_OPCODE_FORECAST_ETS_SEA 480 +#define SC_OPCODE_FORECAST_ETS_MUL 481 +#define SC_OPCODE_FORECAST_ETS_PIA 482 +#define SC_OPCODE_FORECAST_ETS_PIM 483 +#define SC_OPCODE_FORECAST_ETS_STA 484 +#define SC_OPCODE_FORECAST_ETS_STM 485 +#define SC_OPCODE_FORECAST_LIN 486 +#define SC_OPCODE_CONCAT_MS 487 +#define SC_OPCODE_TEXTJOIN_MS 488 +#define SC_OPCODE_IFS_MS 489 +#define SC_OPCODE_SWITCH_MS 490 +#define SC_OPCODE_MINIFS_MS 491 +#define SC_OPCODE_MAXIFS_MS 492 +#define SC_OPCODE_ROUNDSIG 493 +#define SC_OPCODE_REPLACEB 494 +#define SC_OPCODE_FINDB 495 +#define SC_OPCODE_SEARCHB 496 +#define SC_OPCODE_REGEX 497 +#define SC_OPCODE_FOURIER 498 +#define SC_OPCODE_RANDBETWEEN_NV 499 +#define SC_OPCODE_STOP_2_PAR 500 /* last function with two or more parameters' OpCode + 1 */ + +#define SC_OPCODE_STOP_FUNCTION SC_OPCODE_STOP_2_PAR /* last function's OpCode + 1 */ +#define SC_OPCODE_LAST_OPCODE_ID (SC_OPCODE_STOP_FUNCTION - 1) /* last OpCode */ + +/*** Internal ***/ +#define SC_OPCODE_INTERNAL_BEGIN 9999 +#define SC_OPCODE_TTT 9999 +#define SC_OPCODE_DEBUG_VAR 10000 +#define SC_OPCODE_INTERNAL_END 10000 + +/*** from here on ExtraData contained ***/ +#define SC_OPCODE_DATA_TOKEN_1 10001 + +#define SC_OPCODE_NONE 0xFFFF + +#endif /* FORMULA_COMPILER_HRC */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/errorcodes.hxx b/include/formula/errorcodes.hxx new file mode 100644 index 000000000..3e929bff4 --- /dev/null +++ b/include/formula/errorcodes.hxx @@ -0,0 +1,190 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_ERRORCODES_HXX +#define INCLUDED_FORMULA_ERRORCODES_HXX + +#include +#include + +#include +#include + +// Store as 16-bits, since error values are stored in tokens and formula results, +// and that can matter +enum class FormulaError : sal_uInt16 +{ + NONE = 0, + + IllegalChar = 501, + IllegalArgument = 502, + IllegalFPOperation = 503, // #NUM! + IllegalParameter = 504, + Pair = 507, + PairExpected = 508, + OperatorExpected = 509, + VariableExpected = 510, + ParameterExpected = 511, + CodeOverflow = 512, + StringOverflow = 513, + StackOverflow = 514, + UnknownState = 515, + UnknownVariable = 516, + UnknownOpCode = 517, + UnknownStackVariable = 518, + NoValue = 519, // #VALUE! + UnknownToken = 520, + NoCode = 521, // #NULL! + CircularReference = 522, + NoConvergence = 523, + NoRef = 524, // #REF! + NoName = 525, // #NAME? +// ScInterpreter internal: no numeric value but numeric queried. If this is +// set as mnStringNoValueError no error is generated but 0 returned. + CellNoValue = 529, +// Interpreter: needed AddIn not found + NoAddin = 530, +// Interpreter: needed Macro not found + NoMacro = 531, +// Interpreter: Division by zero + DivisionByZero = 532, // #DIV/0! +// Compiler: a non-simple (str,err,val) value was put in an array + NestedArray = 533, +// ScInterpreter internal: no numeric value but numeric queried. If this is +// temporarily (!) set as mnStringNoValueError, the error is generated and can +// be used to distinguish that condition from all other (inherited) errors. Do +// not use for anything else! Never push or inherit the error otherwise! + NotNumericString = 534, +// ScInterpreter internal: jump matrix already has a result at this position, +// do not overwrite in case of empty code path. + JumpMatHasResult = 535, +// ScInterpreter internal: (matrix) element is not a numeric value, i.e. +// string or empty, to be distinguished from the general FormulaError::NoValue NAN and not +// to be used as result. + ElementNaN = 536, +// ScInterpreter/ScFormulaCell internal: keep dirty, retry interpreting next +// round. + RetryCircular = 537, +// If matrix could not be allocated. + MatrixSize = 538, +// Bad inline array content, non-value/non-string. + BadArrayContent = 539, +// Interpreter: signal result not available because updating links is not +// allowed (yet) and tell to try hybrid string as result. + LinkFormulaNeedingCheck = 540, + +// Interpreter: NA() not available condition, not a real error + NotAvailable = 0x7fff +}; + +/** Unconditionally construct a double value of NAN where the lower bits + represent an interpreter error code. */ +inline double CreateDoubleError( FormulaError nErr ) +{ + sal_math_Double smVal; + smVal.value = std::numeric_limits::quiet_NaN(); + smVal.nan_parts.fraction_lo = static_cast(nErr); + return smVal.value; +} + +/** Recreate the error code of a coded double error, if any. */ +inline FormulaError GetDoubleErrorValue( double fVal ) +{ + if ( std::isfinite( fVal ) ) + return FormulaError::NONE; + if ( std::isinf( fVal ) ) + return FormulaError::IllegalFPOperation; // normal INF + sal_uInt32 nErr = reinterpret_cast< sal_math_Double * >( &fVal)->nan_parts.fraction_lo; + if ( nErr & 0xffff0000 ) + return FormulaError::NoValue; // just a normal NAN + if (!nErr) + // Another NAN, e.g. -nan(0x8000000000000) from calculating with -inf + return FormulaError::IllegalFPOperation; + // Any other error known to us as error code. + return static_cast(nErr & 0x0000ffff); +} + +/** Error values that are accepted as detailed "#ERRxxx!" constants. + + Used in FormulaCompiler::GetErrorConstant() to prevent users from inventing + arbitrary values that already have or later might get a significant meaning. + */ +inline bool isPublishedFormulaError( FormulaError nErr ) +{ + // Every value has to be handled explicitly, do not add a default case to + // let the compiler complain if a value is missing. + switch (nErr) + { + case FormulaError::NONE: + return false; + + case FormulaError::IllegalChar: + case FormulaError::IllegalArgument: + case FormulaError::IllegalFPOperation: + case FormulaError::IllegalParameter: + case FormulaError::Pair: + case FormulaError::PairExpected: + case FormulaError::OperatorExpected: + case FormulaError::VariableExpected: + case FormulaError::ParameterExpected: + case FormulaError::CodeOverflow: + case FormulaError::StringOverflow: + case FormulaError::StackOverflow: + case FormulaError::UnknownState: + case FormulaError::UnknownVariable: + case FormulaError::UnknownOpCode: + case FormulaError::UnknownStackVariable: + case FormulaError::NoValue: + case FormulaError::UnknownToken: + case FormulaError::NoCode: + case FormulaError::CircularReference: + case FormulaError::NoConvergence: + case FormulaError::NoRef: + case FormulaError::NoName: + return true; + + case FormulaError::CellNoValue: + return false; + + case FormulaError::NoAddin: + case FormulaError::NoMacro: + case FormulaError::DivisionByZero: + case FormulaError::NestedArray: + case FormulaError::BadArrayContent: + return true; + + case FormulaError::NotNumericString: + case FormulaError::JumpMatHasResult: + case FormulaError::ElementNaN: + case FormulaError::RetryCircular: + return false; + + case FormulaError::MatrixSize: + case FormulaError::LinkFormulaNeedingCheck: + return true; + + case FormulaError::NotAvailable: + return false; + } + return false; +} + +#endif // INCLUDED_FORMULA_ERRORCODES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/formdata.hxx b/include/formula/formdata.hxx new file mode 100644 index 000000000..1df42c2e9 --- /dev/null +++ b/include/formula/formdata.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FORMDATA_HXX +#define INCLUDED_FORMULA_FORMDATA_HXX + +#include +#include +#include +#include + +namespace formula +{ +enum class FormulaDlgMode; + +class FORMULA_DLLPUBLIC FormEditData +{ +public: + FormEditData(); + virtual ~FormEditData(); + + virtual void SaveValues(); + + FormulaDlgMode GetMode() const { return nMode; } + sal_Int32 GetFStart() const { return nFStart; } + sal_uInt16 GetOffset() const { return nOffset; } + const OUString& GetUndoStr() const { return aUndoStr; } + bool GetMatrixFlag()const{ return bMatrix;} + const Selection& GetSelection()const { return aSelection;} + + void SetMode( FormulaDlgMode nNew ) { nMode = nNew; } + void SetFStart( sal_Int32 nNew ) { nFStart = nNew; } + void SetOffset( sal_uInt16 nNew ) { nOffset = nNew; } + void SetUndoStr( const OUString& rNew ) { aUndoStr = rNew; } + void SetMatrixFlag(bool bNew) { bMatrix=bNew;} + void SetSelection(const Selection& aSel) { aSelection=aSel;} +protected: + void Reset(); + FormEditData( const FormEditData& ); + FormEditData& operator=( const FormEditData& r ); + +private: + FormulaDlgMode nMode; + sal_Int32 nFStart; + sal_uInt16 nOffset; + OUString aUndoStr; + bool bMatrix; + Selection aSelection; +}; + + +} // formula +#endif // INCLUDED_FORMULA_FORMDATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/formula.hxx b/include/formula/formula.hxx new file mode 100644 index 000000000..aed0e1b0d --- /dev/null +++ b/include/formula/formula.hxx @@ -0,0 +1,125 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FORMULA_HXX +#define INCLUDED_FORMULA_FORMULA_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +class NotifyEvent; +class SfxBindings; +class SfxChildWindow; + +namespace formula +{ + +#define STRUCT_END 1 +#define STRUCT_FOLDER 2 +#define STRUCT_ERROR 3 + +enum class FormulaDlgMode { Formula, Edit }; + + +class FormulaDlg_Impl; +class IControlReferenceHandler; +class FormulaHelper; +class RefEdit; +class RefButton; +class FormEditData; + +class FORMULA_DLLPUBLIC FormulaModalDialog + : public weld::GenericDialogController, public formula::IFormulaEditorHelper +{ + friend class FormulaDlg_Impl; +public: + FormulaModalDialog(weld::Window* pParent, IFunctionManager const * _pFunctionMgr, + IControlReferenceHandler* _pDlg); + virtual ~FormulaModalDialog() override; + +private: + std::unique_ptr> m_pImpl; + +protected: + + ::std::pair RefInputStartBefore( RefEdit* pEdit, RefButton* pButton ); + void RefInputStartAfter(); + void RefInputDoneAfter(); + + void SetMeText(const OUString& _sText); + void Update(); + void CheckMatrix(OUString& aFormula /*IN/OUT*/); + void Update(const OUString& _sExp); + + void StoreFormEditData(FormEditData* pData); +}; + +class FORMULA_DLLPUBLIC FormulaDlg: + public SfxModelessDialogController, public IFormulaEditorHelper +{ + friend class FormulaDlg_Impl; +public: + FormulaDlg(SfxBindings* pB, SfxChildWindow* pCW, + weld::Window* pParent, + IFunctionManager const * _pFunctionMgr, + IControlReferenceHandler* _pDlg); + virtual ~FormulaDlg() override; +private: + std::unique_ptr> m_pImpl; + +protected: + void disableOk(); + +protected: + + ::std::pair RefInputStartBefore( RefEdit* pEdit, RefButton* pButton ); + void RefInputStartAfter(); + void RefInputDoneAfter( bool bForced ); + + void SetMeText(const OUString& _sText); + FormulaDlgMode SetMeText(const OUString& _sText, sal_Int32 PrivStart, sal_Int32 PrivEnd, bool bMatrix, bool _bSelect, bool _bUpdate); + void Update(); + bool CheckMatrix(OUString& aFormula /*IN/OUT*/); + OUString GetMeText() const; + void Update(const OUString& _sExp); + void DoEnter(); + const IFunctionDescription* getCurrentFunctionDescription() const; + bool UpdateParaWin(Selection& _rSelection); + void UpdateParaWin(const Selection& _rSelection, const OUString& _sRefStr); + RefEdit* GetActiveEdit(); + void SetEdSelection(); + + void StoreFormEditData(FormEditData* pData); + + const FormulaHelper& GetFormulaHelper() const; +}; + +} // formula + +#endif // INCLUDED_FORMULA_FORMULA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/formuladllapi.h b/include/formula/formuladllapi.h new file mode 100644 index 000000000..ae408fd42 --- /dev/null +++ b/include/formula/formuladllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FORMULADLLAPI_H +#define INCLUDED_FORMULA_FORMULADLLAPI_H + +#include + +#if defined(FORMULA_DLLIMPLEMENTATION) +#define FORMULA_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define FORMULA_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define FORMULA_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_FORMULA_FORMULADLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/formulahelper.hxx b/include/formula/formulahelper.hxx new file mode 100644 index 000000000..02f757dc3 --- /dev/null +++ b/include/formula/formulahelper.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FORMULAHELPER_HXX +#define INCLUDED_FORMULA_FORMULAHELPER_HXX + +#include +#include + +#include +#include +#include +#include + +class CharClass; + +namespace formula +{ + class IFunctionDescription; + class IFunctionManager; + + class FORMULA_DLLPUBLIC FormulaHelper + { + ::std::unique_ptr m_pSysLocale; + const CharClass* m_pCharClass; + const IFunctionManager* m_pFunctionManager; + const sal_Unicode open; + const sal_Unicode close; + const sal_Unicode sep; + const sal_Unicode arrayOpen; + const sal_Unicode arrayClose; + public: + FormulaHelper(const IFunctionManager* _pFunctionManager); + + const CharClass* GetCharClass() const { return m_pCharClass; } + + sal_Int32 GetCategoryCount() const; + + bool GetNextFunc( const OUString& rFormula, + bool bBack, + sal_Int32& rFStart, // input and output + sal_Int32* pFEnd = nullptr, + const IFunctionDescription** ppFDesc = nullptr, + ::std::vector< OUString>* pArgs = nullptr ) const; + + sal_Int32 GetFunctionStart( const OUString& rFormula, sal_Int32 nStart, + bool bBack, OUString* pFuncName = nullptr ) const; + + sal_Int32 GetFunctionEnd ( const OUString& rFormula, sal_Int32 nStart ) const; + + sal_Int32 GetArgStart ( const OUString& rFormula, sal_Int32 nStart, + sal_uInt16 nArg ) const; + + void GetArgStrings ( ::std::vector< OUString >& _rArgs, + const OUString& rFormula, + sal_Int32 nFuncPos, + sal_uInt16 nArgs ) const; + + void FillArgStrings ( const OUString& rFormula, + sal_Int32 nFuncPos, + sal_uInt16 nArgs, + ::std::vector< OUString >& _rArgs ) const; + }; + +} // formula + + +#endif // INCLUDED_FORMULA_FORMULAHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/funcutl.hxx b/include/formula/funcutl.hxx new file mode 100644 index 000000000..a41f9c09a --- /dev/null +++ b/include/formula/funcutl.hxx @@ -0,0 +1,182 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_FUNCUTL_HXX +#define INCLUDED_FORMULA_FUNCUTL_HXX + +#include +#include +#include +#include +#include + +class KeyEvent; +struct ImplSVEvent; + +namespace formula { + +class IControlReferenceHandler; + +class FORMULA_DLLPUBLIC RefEdit +{ +protected: + std::unique_ptr xEntry; + +private: + Idle aIdle; + IControlReferenceHandler* pAnyRefDlg; // parent dialog + weld::Label* pLabelWidget; + ImplSVEvent* mpFocusInEvent; + ImplSVEvent* mpFocusOutEvent; + + Link maGetFocusHdl; + Link maLoseFocusHdl; + Link maModifyHdl; + Link maActivateHdl; + + DECL_DLLPRIVATE_LINK( UpdateHdl, Timer*, void ); + + DECL_DLLPRIVATE_LINK(KeyInputHdl, const KeyEvent&, bool); + DECL_DLLPRIVATE_LINK(GetFocusHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(LoseFocusHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(AsyncFocusInHdl, void*, void); + DECL_DLLPRIVATE_LINK(AsyncFocusOutHdl, void*, void); + DECL_DLLPRIVATE_LINK(Modify, weld::Entry&, void); + + void GetFocus(); + void LoseFocus(); + +protected: + virtual bool KeyInput(const KeyEvent& rKEvt); + +public: + RefEdit(std::unique_ptr xControl); + weld::Entry* GetWidget() const { return xEntry.get(); } + virtual ~RefEdit(); + + void SetRefString( const OUString& rStr ); + + /** + * Flag reference valid or invalid, which in turn changes the visual + * appearance of the control accordingly. + */ + void SetRefValid(bool bValid); + + void SetText(const OUString& rStr); + OUString GetText() const + { + return xEntry->get_text(); + } + + void StartUpdateData(); + + void SetReferences( IControlReferenceHandler* pDlg, weld::Label *pLabelWidget ); + + void DoModify() + { + Modify(*xEntry); + } + + void GrabFocus() + { + xEntry->grab_focus(); + } + + void SelectAll() + { + xEntry->select_region(0, -1); + } + + void SetSelection(const Selection& rSelection) + { + xEntry->select_region(rSelection.Min(), rSelection.Max()); + } + + void SetCursorAtLast() + { + xEntry->set_position(-1); + } + + Selection GetSelection() const + { + int nStartPos, nEndPos; + xEntry->get_selection_bounds(nStartPos, nEndPos); + return Selection(nStartPos, nEndPos); + } + + weld::Label* GetLabelWidgetForShrinkMode() + { + return pLabelWidget; + } + + void SaveValue() + { + xEntry->save_value(); + } + + bool IsValueChangedFromSaved() const + { + return xEntry->get_value_changed_from_saved(); + } + + void SetGetFocusHdl(const Link& rLink) { maGetFocusHdl = rLink; } + void SetLoseFocusHdl(const Link& rLink) { maLoseFocusHdl = rLink; } + void SetModifyHdl(const Link& rLink) { maModifyHdl = rLink; } + const Link& GetModifyHdl() const { return maModifyHdl; } + void SetActivateHdl(const Link& rLink) { maActivateHdl = rLink; } +}; + +class FORMULA_DLLPUBLIC RefButton +{ +private: + std::unique_ptr xButton; + IControlReferenceHandler* pAnyRefDlg; // parent dialog + RefEdit* pRefEdit; // associated Edit-Control + Link maGetFocusHdl; + Link maLoseFocusHdl; + Link maActivateHdl; + Link maClickHdl; + + DECL_LINK(Click, weld::Button&, void); + DECL_DLLPRIVATE_LINK(KeyInput, const KeyEvent&, bool); + DECL_DLLPRIVATE_LINK(GetFocus, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(LoseFocus, weld::Widget&, void); + +public: + RefButton(std::unique_ptr xControl); + weld::Button* GetWidget() const { return xButton.get(); } + ~RefButton(); + void SetReferences(IControlReferenceHandler* pDlg, RefEdit* pEdit); + void SetStartImage(); + void SetEndImage(); + void DoRef() + { + Click(*xButton); + } + void SetGetFocusHdl(const Link& rLink) { maGetFocusHdl = rLink; } + void SetLoseFocusHdl(const Link& rLink) { maLoseFocusHdl = rLink; } + void SetActivateHdl(const Link& rLink) { maActivateHdl = rLink; } + void SetClickHdl(const Link& rLink) { maClickHdl = rLink; } +}; + +} // formula + +#endif // INCLUDED_FORMULA_FUNCUTL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/funcvarargs.h b/include/formula/funcvarargs.h new file mode 100644 index 000000000..7a1f1e4e7 --- /dev/null +++ b/include/formula/funcvarargs.h @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_FORMULA_FUNCVARARGS_H +#define INCLUDED_FORMULA_FUNCVARARGS_H + +/** Used to indicate a variable number of parameters for the Function Wizard. + + VAR_ARGS if variable number of parameters, or VAR_ARGS+number if number of + fixed parameters and variable arguments following. + + @see formula::ParaWin + @see ScFuncDescCore + + @NOTE: the value can't be easily changed. If changed then + reportdesign/source/ui/misc/FunctionHelper.cxx + FunctionDescription::getVarArgsStart() has to provide some backward + compatibility for implicit API stability. + The new VAR_ARGS value must be significantly greater than the old + PAIRED_VAR_ARGS (2*VAR_ARGS) value, in fact greater than any used number of + fixed parameters followed by optional paired parameters. + + @NOTE: also + reportbuilder/java/org/libreoffice/report/pentaho/StarFunctionDescription.java + uses a hard coded value in StarFunctionDescription::getArguments() for + functionDescription.isInfiniteParameterCount() which though looks like it + could be easily adapted. + */ +#define VAR_ARGS 255 + +/** Used to indicate a variable number of paired parameters for the Function Wizard. + + PAIRED_VAR_ARGS if variable number of paired parameters, or + PAIRED_VAR_ARGS+number if number of fixed parameters and variable paired + arguments following. + + @see VAR_ARGS + */ +#define PAIRED_VAR_ARGS (VAR_ARGS + VAR_ARGS) + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/formula/grammar.hxx b/include/formula/grammar.hxx new file mode 100644 index 000000000..677087d19 --- /dev/null +++ b/include/formula/grammar.hxx @@ -0,0 +1,247 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_GRAMMAR_HXX +#define INCLUDED_FORMULA_GRAMMAR_HXX + +#include +#include +#include + +namespace formula +{ + +/** Grammars digested by ScCompiler. + */ +class FORMULA_DLLPUBLIC FormulaGrammar +{ +public: + enum AddressConvention{ + CONV_UNSPECIFIED = -1, /* useful when we want method to choose, must be first */ + + /* elements must be sequential and changes should be reflected in ScCompiler::pCharTables */ + CONV_OOO = 0, /* 'doc'#sheet.A1:sheet2.B2 */ + CONV_ODF, /* ['doc'#sheet.A1:sheet2.B2] */ + CONV_XL_A1, /* [doc]sheet:sheet2!A1:B2 */ + CONV_XL_R1C1, /* [doc]sheet:sheet2!R1C1:R2C2 */ + CONV_XL_OOX, /* [#]sheet:sheet2!A1:B2 */ + + CONV_LOTUS_A1, /* external? 3d? A1.B2 */ + + CONV_LAST, /* for loops, must always be last */ + + // not a real address convention, a special case for INDIRECT function interpretation + // only -> try using CONV_OOO, failing that CONV_XL_A1 + CONV_A1_XL_A1 + }; + + //! CONV_UNSPECIFIED is a negative value! + static const int kConventionOffset = - CONV_UNSPECIFIED + 1; + // Room for 32k hypothetical languages plus EXTERNAL. + static const int kConventionShift = 16; + // Room for 256 reference conventions. + static const int kEnglishBit = (1 << (kConventionShift + 8)); + // Mask off all non-language bits. + static const int kFlagMask = ~((~unsigned(0)) << kConventionShift); + + /** Values encoding the formula language plus address reference convention + plus English parsing/formatting + */ + //! When adding new values adapt isSupported() below as well. + enum Grammar + { + /// Used only in ScCompiler ctor and in some XML import API context. + GRAM_UNSPECIFIED = -1, + /// ODFF with default ODF A1 bracketed references. + GRAM_ODFF = css::sheet::FormulaLanguage::ODFF | + ((CONV_ODF + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// ODF 1.1 with default ODF A1 bracketed references. + GRAM_PODF = css::sheet::FormulaLanguage::ODF_11 | + ((CONV_ODF + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// English with default A1 reference style. + GRAM_ENGLISH = css::sheet::FormulaLanguage::ENGLISH | + ((CONV_OOO + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// Native with default A1 reference style. + GRAM_NATIVE = css::sheet::FormulaLanguage::NATIVE | + ((CONV_OOO + + kConventionOffset) << kConventionShift), + /// ODFF with reference style as set in UI, may be A1 or R1C1. + GRAM_ODFF_UI = css::sheet::FormulaLanguage::ODFF | + ((CONV_UNSPECIFIED + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// ODFF with A1 reference style, unbracketed. + GRAM_ODFF_A1 = css::sheet::FormulaLanguage::ODFF | + ((CONV_OOO + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// ODF 1.1 with reference style as set in UI, may be A1 or R1C1. + GRAM_PODF_UI = css::sheet::FormulaLanguage::ODF_11 | + ((CONV_UNSPECIFIED + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// ODF 1.1 with A1 reference style, unbracketed. + GRAM_PODF_A1 = css::sheet::FormulaLanguage::ODF_11 | + ((CONV_OOO + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// Native with reference style as set in UI, may be A1 or R1C1. + GRAM_NATIVE_UI = css::sheet::FormulaLanguage::NATIVE | + ((CONV_UNSPECIFIED + + kConventionOffset) << kConventionShift), + /// Native with ODF A1 bracketed references. Not very useful but supported. + GRAM_NATIVE_ODF = css::sheet::FormulaLanguage::NATIVE | + ((CONV_ODF + + kConventionOffset) << kConventionShift), + /// Native with Excel A1 reference style. + GRAM_NATIVE_XL_A1 = css::sheet::FormulaLanguage::NATIVE | + ((CONV_XL_A1 + + kConventionOffset) << kConventionShift), + /// Native with Excel R1C1 reference style. + GRAM_NATIVE_XL_R1C1 = css::sheet::FormulaLanguage::NATIVE | + ((CONV_XL_R1C1 + + kConventionOffset) << kConventionShift), + /// English with Excel A1 reference style. + GRAM_ENGLISH_XL_A1 = css::sheet::FormulaLanguage::XL_ENGLISH | + ((CONV_XL_A1 + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// English with Excel R1C1 reference style. + GRAM_ENGLISH_XL_R1C1 = css::sheet::FormulaLanguage::XL_ENGLISH | + ((CONV_XL_R1C1 + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// English with Excel OOXML reference style. + GRAM_ENGLISH_XL_OOX = css::sheet::FormulaLanguage::XL_ENGLISH | + ((CONV_XL_OOX + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// Excel OOXML with Excel OOXML reference style. + GRAM_OOXML = css::sheet::FormulaLanguage::OOXML | + ((CONV_XL_OOX + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// API English with A1 reference style, unbracketed. + GRAM_API = css::sheet::FormulaLanguage::API | + ((CONV_OOO + + kConventionOffset) << kConventionShift) | + kEnglishBit, + /// Central definition of the default grammar to be used. + GRAM_DEFAULT = GRAM_NATIVE_UI, + + /// Central definition of the default storage grammar to be used. + GRAM_STORAGE_DEFAULT = GRAM_ODFF, + + /** OpCodeMap set by external filter and merged with reference + convention plus English bit on top. Plain value acts as + FormulaLanguage. */ + GRAM_EXTERNAL = (1 << (kConventionShift - 1)) + }; + + /// If English parsing/formatting is associated with a grammar. + static bool isEnglish( const Grammar eGrammar ) + { + return (eGrammar & kEnglishBit) != 0; + } + + /** Compatibility helper for old "bCompileEnglish, bCompileXML" API calls + to obtain the new grammar. */ + static Grammar mapAPItoGrammar( const bool bEnglish, const bool bXML ); + + static bool isSupported( const Grammar eGrammar ); + + static sal_Int32 extractFormulaLanguage( const Grammar eGrammar ) + { + return eGrammar & kFlagMask; + } + + static AddressConvention extractRefConvention( const Grammar eGrammar ) + { + return static_cast( + ((eGrammar & ~kEnglishBit) >> kConventionShift) - + kConventionOffset); + } + + static Grammar setEnglishBit( const Grammar eGrammar, const bool bEnglish ); + + static Grammar mergeToGrammar( const Grammar eGrammar, const AddressConvention eConv ); + + /// If grammar is of ODF 1.1 + static bool isPODF( const Grammar eGrammar ) + { + return extractFormulaLanguage( eGrammar) == + css::sheet::FormulaLanguage::ODF_11; + } + + /// If grammar is of ODFF + static bool isODFF( const Grammar eGrammar ) + { + return extractFormulaLanguage( eGrammar) == + css::sheet::FormulaLanguage::ODFF; + } + + /// If grammar is of OOXML + static bool isOOXML( const Grammar eGrammar ) + { + return extractFormulaLanguage( eGrammar) == + css::sheet::FormulaLanguage::OOXML; + } + + /** If reference convention is OOXML. + + Note this is not equivalent to isOOXML() as it does not have to be + FormulaLanguage::OOXML but can be Grammar::GRAM_EXTERNAL merged with + AddressConvention::CONV_XL_OOX, which is used by various parts of OOXML + import through the API FormulaParser. + */ + static bool isRefConventionOOXML( const Grammar eGrammar ) + { + return extractRefConvention( eGrammar) == + FormulaGrammar::AddressConvention::CONV_XL_OOX; + } + + /// If grammar has an Excel syntax, determined by address convention. + static bool isExcelSyntax( const Grammar eGrammar ) + { + AddressConvention eConv = extractRefConvention( eGrammar ); + switch (eConv) + { + case FormulaGrammar::AddressConvention::CONV_XL_A1: + case FormulaGrammar::AddressConvention::CONV_XL_R1C1: + case FormulaGrammar::AddressConvention::CONV_XL_OOX: + return true; + default: + return false; + } + } + +}; + +} // formula + + +#endif // INCLUDED_FORMULA_GRAMMAR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/opcode.hxx b/include/formula/opcode.hxx new file mode 100644 index 000000000..d92ae0b1d --- /dev/null +++ b/include/formula/opcode.hxx @@ -0,0 +1,995 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_OPCODE_HXX +#define INCLUDED_FORMULA_OPCODE_HXX + +#include + +#include +#include + +enum OpCode : sal_uInt16 +{ + // Special commands + ocPush = SC_OPCODE_PUSH, + ocCall = SC_OPCODE_CALL, + ocStop = SC_OPCODE_STOP, + ocExternal = SC_OPCODE_EXTERNAL, + ocName = SC_OPCODE_NAME, + // Jump commands + ocIf = SC_OPCODE_IF, + ocIfError = SC_OPCODE_IF_ERROR, + ocIfNA = SC_OPCODE_IF_NA, + ocChoose = SC_OPCODE_CHOOSE, + // Parentheses and separators + ocOpen = SC_OPCODE_OPEN, + ocClose = SC_OPCODE_CLOSE, + ocTableRefOpen = SC_OPCODE_TABLE_REF_OPEN, + ocTableRefClose = SC_OPCODE_TABLE_REF_CLOSE, + ocSep = SC_OPCODE_SEP, + ocArrayOpen = SC_OPCODE_ARRAY_OPEN, + ocArrayClose = SC_OPCODE_ARRAY_CLOSE, + ocArrayRowSep = SC_OPCODE_ARRAY_ROW_SEP, + ocArrayColSep = SC_OPCODE_ARRAY_COL_SEP, + // Special OpCodes + ocMissing = SC_OPCODE_MISSING, + ocBad = SC_OPCODE_BAD, + ocStringXML = SC_OPCODE_STRINGXML, + ocSpaces = SC_OPCODE_SPACES, + ocWhitespace = SC_OPCODE_WHITESPACE, + ocMatRef = SC_OPCODE_MAT_REF, + ocTableRefItemAll = SC_OPCODE_TABLE_REF_ITEM_ALL, + ocTableRefItemHeaders = SC_OPCODE_TABLE_REF_ITEM_HEADERS, + ocTableRefItemData = SC_OPCODE_TABLE_REF_ITEM_DATA, + ocTableRefItemTotals = SC_OPCODE_TABLE_REF_ITEM_TOTALS, + ocTableRefItemThisRow = SC_OPCODE_TABLE_REF_ITEM_THIS_ROW, + ocSkip = SC_OPCODE_SKIP, + // Access commands + ocDBArea = SC_OPCODE_DB_AREA, + ocTableRef = SC_OPCODE_TABLE_REF, + ocMacro = SC_OPCODE_MACRO, + ocColRowName = SC_OPCODE_COL_ROW_NAME, + ocColRowNameAuto = SC_OPCODE_COL_ROW_NAME_AUTO, + // Percent operator _follows_ value + ocPercentSign = SC_OPCODE_PERCENT_SIGN, + // Error constants + ocErrNull = SC_OPCODE_ERROR_NULL, + ocErrDivZero = SC_OPCODE_ERROR_DIVZERO, + ocErrValue = SC_OPCODE_ERROR_VALUE, + ocErrRef = SC_OPCODE_ERROR_REF, + ocErrName = SC_OPCODE_ERROR_NAME, + ocErrNum = SC_OPCODE_ERROR_NUM, + ocErrNA = SC_OPCODE_ERROR_NA, + // Binary operators + ocAdd = SC_OPCODE_ADD, + ocSub = SC_OPCODE_SUB, + ocMul = SC_OPCODE_MUL, + ocDiv = SC_OPCODE_DIV, + ocAmpersand = SC_OPCODE_AMPERSAND, + ocPow = SC_OPCODE_POW, + ocEqual = SC_OPCODE_EQUAL, + ocNotEqual = SC_OPCODE_NOT_EQUAL, + ocLess = SC_OPCODE_LESS, + ocGreater = SC_OPCODE_GREATER, + ocLessEqual = SC_OPCODE_LESS_EQUAL, + ocGreaterEqual = SC_OPCODE_GREATER_EQUAL, + ocAnd = SC_OPCODE_AND, + ocOr = SC_OPCODE_OR, + ocXor = SC_OPCODE_XOR, + ocIntersect = SC_OPCODE_INTERSECT, + ocUnion = SC_OPCODE_UNION, + ocRange = SC_OPCODE_RANGE, + // Unary operators + ocNegSub = SC_OPCODE_NEG_SUB, + // Functions with no parameters + ocPi = SC_OPCODE_PI, + ocRandom = SC_OPCODE_RANDOM, + ocTrue = SC_OPCODE_TRUE, + ocFalse = SC_OPCODE_FALSE, + ocGetActDate = SC_OPCODE_GET_ACT_DATE, + ocGetActTime = SC_OPCODE_GET_ACT_TIME, + ocNotAvail = SC_OPCODE_NO_VALUE, + ocCurrent = SC_OPCODE_CURRENT, + ocRandomNV = SC_OPCODE_RANDOM_NV, + // Functions with one parameter + ocNot = SC_OPCODE_NOT, + ocNeg = SC_OPCODE_NEG, + ocDeg = SC_OPCODE_DEG, + ocRad = SC_OPCODE_RAD, + ocSin = SC_OPCODE_SIN, + ocCos = SC_OPCODE_COS, + ocTan = SC_OPCODE_TAN, + ocCot = SC_OPCODE_COT, + ocArcSin = SC_OPCODE_ARC_SIN, + ocArcCos = SC_OPCODE_ARC_COS, + ocArcTan = SC_OPCODE_ARC_TAN, + ocArcCot = SC_OPCODE_ARC_COT, + ocSinHyp = SC_OPCODE_SIN_HYP, + ocCosHyp = SC_OPCODE_COS_HYP, + ocTanHyp = SC_OPCODE_TAN_HYP, + ocCotHyp = SC_OPCODE_COT_HYP, + ocArcSinHyp = SC_OPCODE_ARC_SIN_HYP, + ocArcCosHyp = SC_OPCODE_ARC_COS_HYP, + ocArcTanHyp = SC_OPCODE_ARC_TAN_HYP, + ocArcCotHyp = SC_OPCODE_ARC_COT_HYP, + ocCosecant = SC_OPCODE_COSECANT, + ocSecant = SC_OPCODE_SECANT, + ocCosecantHyp = SC_OPCODE_COSECANT_HYP, + ocSecantHyp = SC_OPCODE_SECANT_HYP, + ocExp = SC_OPCODE_EXP, + ocLn = SC_OPCODE_LN, + ocSqrt = SC_OPCODE_SQRT, + ocFact = SC_OPCODE_FACT, + ocGetYear = SC_OPCODE_GET_YEAR, + ocGetMonth = SC_OPCODE_GET_MONTH, + ocGetDay = SC_OPCODE_GET_DAY, + ocGetHour = SC_OPCODE_GET_HOUR, + ocGetMin = SC_OPCODE_GET_MIN, + ocGetSec = SC_OPCODE_GET_SEC, + ocPlusMinus = SC_OPCODE_PLUS_MINUS, + ocAbs = SC_OPCODE_ABS, + ocInt = SC_OPCODE_INT, + ocPhi = SC_OPCODE_PHI, + ocGauss = SC_OPCODE_GAUSS, + ocIsEmpty = SC_OPCODE_IS_EMPTY, + ocIsString = SC_OPCODE_IS_STRING, + ocIsNonString = SC_OPCODE_IS_NON_STRING, + ocIsLogical = SC_OPCODE_IS_LOGICAL, + ocType = SC_OPCODE_TYPE, + ocCell = SC_OPCODE_CELL, + ocIsRef = SC_OPCODE_IS_REF, + ocIsValue = SC_OPCODE_IS_VALUE, + ocIsFormula = SC_OPCODE_IS_FORMULA, + ocIsNA = SC_OPCODE_IS_NV, + ocIsErr = SC_OPCODE_IS_ERR, + ocIsError = SC_OPCODE_IS_ERROR, + ocIsEven = SC_OPCODE_IS_EVEN, + ocIsOdd = SC_OPCODE_IS_ODD, + ocN = SC_OPCODE_N, + // String functions + ocGetDateValue = SC_OPCODE_GET_DATE_VALUE, + ocGetTimeValue = SC_OPCODE_GET_TIME_VALUE, + ocCode = SC_OPCODE_CODE, + ocTrim = SC_OPCODE_TRIM, + ocUpper = SC_OPCODE_UPPER, + ocProper = SC_OPCODE_PROPER, + ocLower = SC_OPCODE_LOWER, + ocLen = SC_OPCODE_LEN, + ocT = SC_OPCODE_T, + ocValue = SC_OPCODE_VALUE, + ocClean = SC_OPCODE_CLEAN, + ocChar = SC_OPCODE_CHAR, + ocLog10 = SC_OPCODE_LOG10, + ocEven = SC_OPCODE_EVEN, + ocOdd = SC_OPCODE_ODD, + ocStdNormDist = SC_OPCODE_STD_NORM_DIST, + ocStdNormDist_MS = SC_OPCODE_STD_NORM_DIST_MS, + ocFisher = SC_OPCODE_FISHER, + ocFisherInv = SC_OPCODE_FISHER_INV, + ocSNormInv = SC_OPCODE_S_NORM_INV, + ocSNormInv_MS = SC_OPCODE_S_NORM_INV_MS, + ocGammaLn = SC_OPCODE_GAMMA_LN, + ocGammaLn_MS = SC_OPCODE_GAMMA_LN_MS, + ocGamma = SC_OPCODE_GAMMA, + ocErrorType = SC_OPCODE_ERROR_TYPE, + ocErrorType_ODF = SC_OPCODE_ERROR_TYPE_ODF, + ocFormula = SC_OPCODE_FORMULA, + ocArabic = SC_OPCODE_ARABIC, + ocInfo = SC_OPCODE_INFO, + ocBahtText = SC_OPCODE_BAHTTEXT, + ocJis = SC_OPCODE_JIS, + ocAsc = SC_OPCODE_ASC, + ocUnicode = SC_OPCODE_UNICODE, + ocUnichar = SC_OPCODE_UNICHAR, + // Functions with more than one parameters + ocArcTan2 = SC_OPCODE_ARC_TAN_2, + ocCeil = SC_OPCODE_CEIL, + ocCeil_MS = SC_OPCODE_CEIL_MS, + ocCeil_Precise = SC_OPCODE_CEIL_PRECISE, + ocCeil_ISO = SC_OPCODE_CEIL_ISO, + ocCeil_Math = SC_OPCODE_CEIL_MATH, + ocFloor = SC_OPCODE_FLOOR, + ocFloor_MS = SC_OPCODE_FLOOR_MS, + ocFloor_Math = SC_OPCODE_FLOOR_MATH, + ocFloor_Precise = SC_OPCODE_FLOOR_PRECISE, + ocRound = SC_OPCODE_ROUND, + ocRoundUp = SC_OPCODE_ROUND_UP, + ocRoundDown = SC_OPCODE_ROUND_DOWN, + ocTrunc = SC_OPCODE_TRUNC, + ocLog = SC_OPCODE_LOG, + ocPower = SC_OPCODE_POWER, + ocGCD = SC_OPCODE_GCD, + ocLCM = SC_OPCODE_LCM, + ocMod = SC_OPCODE_MOD, + ocSumProduct = SC_OPCODE_SUM_PRODUCT, + ocSumSQ = SC_OPCODE_SUM_SQ, + ocSumX2MY2 = SC_OPCODE_SUM_X2MY2, + ocSumX2DY2 = SC_OPCODE_SUM_X2DY2, + ocSumXMY2 = SC_OPCODE_SUM_XMY2, + ocGetDate = SC_OPCODE_GET_DATE, + ocGetTime = SC_OPCODE_GET_TIME, + ocGetDiffDate = SC_OPCODE_GET_DIFF_DATE, + ocGetDiffDate360 = SC_OPCODE_GET_DIFF_DATE_360, + ocGetDateDif = SC_OPCODE_GET_DATEDIF, + ocMin = SC_OPCODE_MIN, + ocMax = SC_OPCODE_MAX, + ocSum = SC_OPCODE_SUM, + ocProduct = SC_OPCODE_PRODUCT, + ocAverage = SC_OPCODE_AVERAGE, + ocCount = SC_OPCODE_COUNT, + ocCount2 = SC_OPCODE_COUNT_2, + ocNPV = SC_OPCODE_NPV, + ocIRR = SC_OPCODE_IRR, + ocMIRR = SC_OPCODE_MIRR, + ocISPMT = SC_OPCODE_ISPMT, + ocVar = SC_OPCODE_VAR, + ocVarP = SC_OPCODE_VAR_P, + ocVarP_MS = SC_OPCODE_VAR_P_MS, + ocVarS = SC_OPCODE_VAR_S, + ocStDev = SC_OPCODE_ST_DEV, + ocStDevP = SC_OPCODE_ST_DEV_P, + ocStDevP_MS = SC_OPCODE_ST_DEV_P_MS, + ocStDevS = SC_OPCODE_ST_DEV_S, + ocB = SC_OPCODE_B, + ocNormDist = SC_OPCODE_NORM_DIST, + ocNormDist_MS = SC_OPCODE_NORM_DIST_MS, + ocExpDist = SC_OPCODE_EXP_DIST, + ocExpDist_MS = SC_OPCODE_EXP_DIST_MS, + ocBinomDist = SC_OPCODE_BINOM_DIST, + ocBinomDist_MS = SC_OPCODE_BINOM_DIST_MS, + ocBinomInv = SC_OPCODE_BINOM_INV, + ocPoissonDist = SC_OPCODE_POISSON_DIST, + ocPoissonDist_MS = SC_OPCODE_POISSON_DIST_MS, + ocCombin = SC_OPCODE_COMBIN, + ocCombinA = SC_OPCODE_COMBIN_A, + ocPermut = SC_OPCODE_PERMUT, + ocPermutationA = SC_OPCODE_PERMUTATION_A, + ocPV = SC_OPCODE_PV, + ocSYD = SC_OPCODE_SYD, + ocDDB = SC_OPCODE_DDB, + ocDB = SC_OPCODE_DB, + ocVBD = SC_OPCODE_VBD, + ocPDuration = SC_OPCODE_PDURATION, + ocSLN = SC_OPCODE_SLN, + ocPMT = SC_OPCODE_PMT, + ocColumns = SC_OPCODE_COLUMNS, + ocRows = SC_OPCODE_ROWS, + ocColumn = SC_OPCODE_COLUMN, + ocRow = SC_OPCODE_ROW, + ocRRI = SC_OPCODE_RRI, + ocFV = SC_OPCODE_FV, + ocNper = SC_OPCODE_NPER, + ocRate = SC_OPCODE_RATE, + ocIpmt = SC_OPCODE_IPMT, + ocPpmt = SC_OPCODE_PPMT, + ocCumIpmt = SC_OPCODE_CUM_IPMT, + ocCumPrinc = SC_OPCODE_CUM_PRINC, + ocEffect = SC_OPCODE_EFFECT, + ocNominal = SC_OPCODE_NOMINAL, + ocSubTotal = SC_OPCODE_SUB_TOTAL, + ocRawSubtract = SC_OPCODE_RAWSUBTRACT, + ocIfs_MS = SC_OPCODE_IFS_MS, + ocSwitch_MS = SC_OPCODE_SWITCH_MS, + ocMinIfs_MS = SC_OPCODE_MINIFS_MS, + ocMaxIfs_MS = SC_OPCODE_MAXIFS_MS, + ocRoundSig = SC_OPCODE_ROUNDSIG, + // Database functions + ocDBSum = SC_OPCODE_DB_SUM, + ocDBCount = SC_OPCODE_DB_COUNT, + ocDBCount2 = SC_OPCODE_DB_COUNT_2, + ocDBAverage = SC_OPCODE_DB_AVERAGE, + ocDBGet = SC_OPCODE_DB_GET, + ocDBMax = SC_OPCODE_DB_MAX, + ocDBMin = SC_OPCODE_DB_MIN, + ocDBProduct = SC_OPCODE_DB_PRODUCT, + ocDBStdDev = SC_OPCODE_DB_STD_DEV, + ocDBStdDevP = SC_OPCODE_DB_STD_DEV_P, + ocDBVar = SC_OPCODE_DB_VAR, + ocDBVarP = SC_OPCODE_DB_VAR_P, + // Management functions + ocIndirect = SC_OPCODE_INDIRECT, + ocAddress = SC_OPCODE_ADDRESS, + ocMatch = SC_OPCODE_MATCH, + ocCountEmptyCells = SC_OPCODE_COUNT_EMPTY_CELLS, + ocCountIf = SC_OPCODE_COUNT_IF, + ocSumIf = SC_OPCODE_SUM_IF, + ocAverageIf = SC_OPCODE_AVERAGE_IF, + ocSumIfs = SC_OPCODE_SUM_IFS, + ocAverageIfs = SC_OPCODE_AVERAGE_IFS, + ocCountIfs = SC_OPCODE_COUNT_IFS, + ocLookup = SC_OPCODE_LOOKUP, + ocVLookup = SC_OPCODE_V_LOOKUP, + ocHLookup = SC_OPCODE_H_LOOKUP, + ocMultiArea = SC_OPCODE_MULTI_AREA, + ocOffset = SC_OPCODE_OFFSET, + ocIndex = SC_OPCODE_INDEX, + ocAreas = SC_OPCODE_AREAS, + // String functions + ocCurrency = SC_OPCODE_CURRENCY, + ocReplace = SC_OPCODE_REPLACE, + ocFixed = SC_OPCODE_FIXED, + ocFind = SC_OPCODE_FIND, + ocExact = SC_OPCODE_EXACT, + ocLeft = SC_OPCODE_LEFT, + ocRight = SC_OPCODE_RIGHT, + ocSearch = SC_OPCODE_SEARCH, + ocMid = SC_OPCODE_MID, + ocText = SC_OPCODE_TEXT, + ocSubstitute = SC_OPCODE_SUBSTITUTE, + ocRept = SC_OPCODE_REPT, + ocConcat = SC_OPCODE_CONCAT, + ocConcat_MS = SC_OPCODE_CONCAT_MS, + ocTextJoin_MS = SC_OPCODE_TEXTJOIN_MS, + ocLenB = SC_OPCODE_LENB, + ocRightB = SC_OPCODE_RIGHTB, + ocLeftB = SC_OPCODE_LEFTB, + ocMidB = SC_OPCODE_MIDB, + ocReplaceB = SC_OPCODE_REPLACEB, + ocFindB = SC_OPCODE_FINDB, + ocSearchB = SC_OPCODE_SEARCHB, + ocNumberValue = SC_OPCODE_NUMBERVALUE, + ocRegex = SC_OPCODE_REGEX, + // Matrix functions + ocMatValue = SC_OPCODE_MAT_VALUE, + ocMatDet = SC_OPCODE_MAT_DET, + ocMatInv = SC_OPCODE_MAT_INV, + ocMatMult = SC_OPCODE_MAT_MULT, + ocMatTrans = SC_OPCODE_MAT_TRANS, + ocMatrixUnit = SC_OPCODE_MATRIX_UNIT, + // BackSolver + ocBackSolver = SC_OPCODE_BACK_SOLVER, + // Statistical functions + ocHypGeomDist = SC_OPCODE_HYP_GEOM_DIST, + ocHypGeomDist_MS = SC_OPCODE_HYP_GEOM_DIST_MS, + ocLogNormDist = SC_OPCODE_LOG_NORM_DIST, + ocLogNormDist_MS = SC_OPCODE_LOG_NORM_DIST_MS, + ocTDist = SC_OPCODE_T_DIST, + ocTDist_MS = SC_OPCODE_T_DIST_MS, + ocTDist_RT = SC_OPCODE_T_DIST_RT, + ocTDist_2T = SC_OPCODE_T_DIST_2T, + ocFDist = SC_OPCODE_F_DIST, + ocFDist_LT = SC_OPCODE_F_DIST_LT, + ocFDist_RT = SC_OPCODE_F_DIST_RT, + ocChiDist = SC_OPCODE_CHI_DIST, + ocChiDist_MS = SC_OPCODE_CHI_DIST_MS, + ocChiSqDist = SC_OPCODE_CHISQ_DIST, + ocChiSqDist_MS = SC_OPCODE_CHISQ_DIST_MS, + ocChiSqInv = SC_OPCODE_CHISQ_INV, + ocChiSqInv_MS = SC_OPCODE_CHISQ_INV_MS, + ocWeibull = SC_OPCODE_WEIBULL, + ocWeibull_MS = SC_OPCODE_WEIBULL_MS, + ocNegBinomVert = SC_OPCODE_NEG_BINOM_VERT, + ocNegBinomDist_MS = SC_OPCODE_NEG_BINOM_DIST_MS, + ocCritBinom = SC_OPCODE_CRIT_BINOM, + ocKurt = SC_OPCODE_KURT, + ocHarMean = SC_OPCODE_HAR_MEAN, + ocGeoMean = SC_OPCODE_GEO_MEAN, + ocStandard = SC_OPCODE_STANDARD, + ocAveDev = SC_OPCODE_AVE_DEV, + ocSkew = SC_OPCODE_SKEW, + ocSkewp = SC_OPCODE_SKEWP, + ocDevSq = SC_OPCODE_DEV_SQ, + ocMedian = SC_OPCODE_MEDIAN, + ocModalValue = SC_OPCODE_MODAL_VALUE, + ocModalValue_MS = SC_OPCODE_MODAL_VALUE_MS, + ocModalValue_Multi = SC_OPCODE_MODAL_VALUE_MULTI, + ocZTest = SC_OPCODE_Z_TEST, + ocZTest_MS = SC_OPCODE_Z_TEST_MS, + ocAggregate = SC_OPCODE_AGGREGATE, + ocTTest = SC_OPCODE_T_TEST, + ocTTest_MS = SC_OPCODE_T_TEST_MS, + ocRank = SC_OPCODE_RANK, + ocPercentile = SC_OPCODE_PERCENTILE, + ocPercentrank = SC_OPCODE_PERCENT_RANK, + ocPercentile_Inc = SC_OPCODE_PERCENTILE_INC, + ocPercentrank_Inc = SC_OPCODE_PERCENT_RANK_INC, + ocQuartile_Inc = SC_OPCODE_QUARTILE_INC, + ocRank_Eq = SC_OPCODE_RANK_EQ, + ocPercentile_Exc = SC_OPCODE_PERCENTILE_EXC, + ocPercentrank_Exc = SC_OPCODE_PERCENT_RANK_EXC, + ocQuartile_Exc = SC_OPCODE_QUARTILE_EXC, + ocRank_Avg = SC_OPCODE_RANK_AVG, + ocLarge = SC_OPCODE_LARGE, + ocSmall = SC_OPCODE_SMALL, + ocFrequency = SC_OPCODE_FREQUENCY, + ocQuartile = SC_OPCODE_QUARTILE, + ocNormInv = SC_OPCODE_NORM_INV, + ocNormInv_MS = SC_OPCODE_NORM_INV_MS, + ocConfidence = SC_OPCODE_CONFIDENCE, + ocConfidence_N = SC_OPCODE_CONFIDENCE_N, + ocConfidence_T = SC_OPCODE_CONFIDENCE_T, + ocFTest = SC_OPCODE_F_TEST, + ocFTest_MS = SC_OPCODE_F_TEST_MS, + ocTrimMean = SC_OPCODE_TRIM_MEAN, + ocProb = SC_OPCODE_PROB, + ocCorrel = SC_OPCODE_CORREL, + ocCovar = SC_OPCODE_COVAR, + ocCovarianceP = SC_OPCODE_COVARIANCE_P, + ocCovarianceS = SC_OPCODE_COVARIANCE_S, + ocPearson = SC_OPCODE_PEARSON, + ocRSQ = SC_OPCODE_RSQ, + ocSTEYX = SC_OPCODE_STEYX, + ocSlope = SC_OPCODE_SLOPE, + ocIntercept = SC_OPCODE_INTERCEPT, + ocTrend = SC_OPCODE_TREND, + ocGrowth = SC_OPCODE_GROWTH, + ocLinest = SC_OPCODE_LINEST, + ocLogest = SC_OPCODE_LOGEST, + ocForecast = SC_OPCODE_FORECAST, + ocForecast_ETS_ADD = SC_OPCODE_FORECAST_ETS_ADD, + ocForecast_ETS_SEA = SC_OPCODE_FORECAST_ETS_SEA, + ocForecast_ETS_MUL = SC_OPCODE_FORECAST_ETS_MUL, + ocForecast_ETS_PIA = SC_OPCODE_FORECAST_ETS_PIA, + ocForecast_ETS_PIM = SC_OPCODE_FORECAST_ETS_PIM, + ocForecast_ETS_STA = SC_OPCODE_FORECAST_ETS_STA, + ocForecast_ETS_STM = SC_OPCODE_FORECAST_ETS_STM, + ocForecast_LIN = SC_OPCODE_FORECAST_LIN, + ocChiInv = SC_OPCODE_CHI_INV, + ocChiInv_MS = SC_OPCODE_CHI_INV_MS, + ocGammaDist = SC_OPCODE_GAMMA_DIST, + ocGammaDist_MS = SC_OPCODE_GAMMA_DIST_MS, + ocGammaInv = SC_OPCODE_GAMMA_INV, + ocGammaInv_MS = SC_OPCODE_GAMMA_INV_MS, + ocTInv = SC_OPCODE_T_INV, + ocTInv_2T = SC_OPCODE_T_INV_2T, + ocTInv_MS = SC_OPCODE_T_INV_MS, + ocFInv = SC_OPCODE_F_INV, + ocFInv_LT = SC_OPCODE_F_INV_LT, + ocFInv_RT = SC_OPCODE_F_INV_RT, + ocChiTest = SC_OPCODE_CHI_TEST, + ocChiTest_MS = SC_OPCODE_CHI_TEST_MS, + ocLogInv = SC_OPCODE_LOG_INV, + ocLogInv_MS = SC_OPCODE_LOG_INV_MS, + ocTableOp = SC_OPCODE_TABLE_OP, + ocBetaDist = SC_OPCODE_BETA_DIST, + ocBetaInv = SC_OPCODE_BETA_INV, + ocBetaDist_MS = SC_OPCODE_BETA_DIST_MS, + ocBetaInv_MS = SC_OPCODE_BETA_INV_MS, + // Bit functions + ocBitAnd = SC_OPCODE_BITAND, + ocBitOr = SC_OPCODE_BITOR, + ocBitXor = SC_OPCODE_BITXOR, + ocBitRshift = SC_OPCODE_BITRSHIFT, + ocBitLshift = SC_OPCODE_BITLSHIFT, + // miscellaneous + ocWeek = SC_OPCODE_WEEK, + ocIsoWeeknum = SC_OPCODE_ISOWEEKNUM, + ocWeeknumOOo = SC_OPCODE_WEEKNUM_OOO, + ocGetDayOfWeek = SC_OPCODE_GET_DAY_OF_WEEK, + ocNetWorkdays = SC_OPCODE_NETWORKDAYS, + ocNetWorkdays_MS = SC_OPCODE_NETWORKDAYS_MS, + ocWorkday_MS = SC_OPCODE_WORKDAY_MS, + ocNoName = SC_OPCODE_NO_NAME, + ocStyle = SC_OPCODE_STYLE, + ocDde = SC_OPCODE_DDE, + ocBase = SC_OPCODE_BASE, + ocSheet = SC_OPCODE_SHEET, + ocSheets = SC_OPCODE_SHEETS, + ocMinA = SC_OPCODE_MIN_A, + ocMaxA = SC_OPCODE_MAX_A, + ocAverageA = SC_OPCODE_AVERAGE_A, + ocStDevA = SC_OPCODE_ST_DEV_A, + ocStDevPA = SC_OPCODE_ST_DEV_P_A, + ocVarA = SC_OPCODE_VAR_A, + ocVarPA = SC_OPCODE_VAR_P_A, + ocEasterSunday = SC_OPCODE_EASTERSUNDAY, + ocDecimal = SC_OPCODE_DECIMAL, + ocConvertOOo = SC_OPCODE_CONVERT_OOO, + ocRoman = SC_OPCODE_ROMAN, + ocHyperLink = SC_OPCODE_HYPERLINK, + ocGetPivotData = SC_OPCODE_GET_PIVOT_DATA, + ocEuroConvert = SC_OPCODE_EUROCONVERT, + ocFilterXML = SC_OPCODE_FILTERXML, + ocWebservice = SC_OPCODE_WEBSERVICE, + ocColor = SC_OPCODE_COLOR, + ocErf_MS = SC_OPCODE_ERF_MS, + ocErfc_MS = SC_OPCODE_ERFC_MS, + ocEncodeURL = SC_OPCODE_ENCODEURL, + ocFourier = SC_OPCODE_FOURIER, + ocRandbetweenNV = SC_OPCODE_RANDBETWEEN_NV, + // internal stuff + ocInternalBegin = SC_OPCODE_INTERNAL_BEGIN, + ocTTT = SC_OPCODE_TTT, + ocDebugVar = SC_OPCODE_DEBUG_VAR, + ocInternalEnd = SC_OPCODE_INTERNAL_END, + // from here on ExtraData + ocDataToken1 = SC_OPCODE_DATA_TOKEN_1, + // no OpCode + ocNone = SC_OPCODE_NONE +}; + +// Only to be used for debugging output. No guarantee of stability of the +// return value. + +// Turn this into an operator<< when OpCode becomes a scoped enum + +inline std::string OpCodeEnumToString(OpCode eCode) +{ + switch (eCode) + { + case ocPush: return "Push"; + case ocCall: return "Call"; + case ocStop: return "Stop"; + case ocExternal: return "External"; + case ocName: return "Name"; + case ocIf: return "If"; + case ocIfError: return "IfError"; + case ocIfNA: return "IfNA"; + case ocChoose: return "Choose"; + case ocOpen: return "Open"; + case ocClose: return "Close"; + case ocTableRefOpen: return "TableRefOpen"; + case ocTableRefClose: return "TableRefClose"; + case ocSep: return "Sep"; + case ocArrayOpen: return "ArrayOpen"; + case ocArrayClose: return "ArrayClose"; + case ocArrayRowSep: return "ArrayRowSep"; + case ocArrayColSep: return "ArrayColSep"; + case ocMissing: return "Missing"; + case ocBad: return "Bad"; + case ocStringXML: return "StringXML"; + case ocSpaces: return "Spaces"; + case ocWhitespace: return "Whitespace"; + case ocMatRef: return "MatRef"; + case ocTableRefItemAll: return "TableRefItemAll"; + case ocTableRefItemHeaders: return "TableRefItemHeaders"; + case ocTableRefItemData: return "TableRefItemData"; + case ocTableRefItemTotals: return "TableRefItemTotals"; + case ocTableRefItemThisRow: return "TableRefItemThisRow"; + case ocSkip: return "Skip"; + case ocDBArea: return "DBArea"; + case ocTableRef: return "TableRef"; + case ocMacro: return "Macro"; + case ocColRowName: return "ColRowName"; + case ocColRowNameAuto: return "ColRowNameAuto"; + case ocPercentSign: return "PercentSign"; + case ocErrNull: return "ErrNull"; + case ocErrDivZero: return "ErrDivZero"; + case ocErrValue: return "ErrValue"; + case ocErrRef: return "ErrRef"; + case ocErrName: return "ErrName"; + case ocErrNum: return "ErrNum"; + case ocErrNA: return "ErrNA"; + case ocAdd: return "Add"; + case ocSub: return "Sub"; + case ocMul: return "Mul"; + case ocDiv: return "Div"; + case ocAmpersand: return "Ampersand"; + case ocPow: return "Pow"; + case ocEqual: return "Equal"; + case ocNotEqual: return "NotEqual"; + case ocLess: return "Less"; + case ocGreater: return "Greater"; + case ocLessEqual: return "LessEqual"; + case ocGreaterEqual: return "GreaterEqual"; + case ocAnd: return "And"; + case ocOr: return "Or"; + case ocXor: return "Xor"; + case ocIntersect: return "Intersect"; + case ocUnion: return "Union"; + case ocRange: return "Range"; + case ocNot: return "Not"; + case ocNeg: return "Neg"; + case ocNegSub: return "NegSub"; + case ocPi: return "Pi"; + case ocRandom: return "Random"; + case ocRandomNV: return "RandomNV"; + case ocTrue: return "True"; + case ocFalse: return "False"; + case ocGetActDate: return "GetActDate"; + case ocGetActTime: return "GetActTime"; + case ocNotAvail: return "NotAvail"; + case ocCurrent: return "Current"; + case ocDeg: return "Deg"; + case ocRad: return "Rad"; + case ocSin: return "Sin"; + case ocCos: return "Cos"; + case ocTan: return "Tan"; + case ocCot: return "Cot"; + case ocArcSin: return "ArcSin"; + case ocArcCos: return "ArcCos"; + case ocArcTan: return "ArcTan"; + case ocArcCot: return "ArcCot"; + case ocSinHyp: return "SinHyp"; + case ocCosHyp: return "CosHyp"; + case ocTanHyp: return "TanHyp"; + case ocCotHyp: return "CotHyp"; + case ocArcSinHyp: return "ArcSinHyp"; + case ocArcCosHyp: return "ArcCosHyp"; + case ocArcTanHyp: return "ArcTanHyp"; + case ocArcCotHyp: return "ArcCotHyp"; + case ocCosecant: return "Cosecant"; + case ocSecant: return "Secant"; + case ocCosecantHyp: return "CosecantHyp"; + case ocSecantHyp: return "SecantHyp"; + case ocExp: return "Exp"; + case ocLn: return "Ln"; + case ocSqrt: return "Sqrt"; + case ocFact: return "Fact"; + case ocGetYear: return "GetYear"; + case ocGetMonth: return "GetMonth"; + case ocGetDay: return "GetDay"; + case ocGetHour: return "GetHour"; + case ocGetMin: return "GetMin"; + case ocGetSec: return "GetSec"; + case ocPlusMinus: return "PlusMinus"; + case ocAbs: return "Abs"; + case ocInt: return "Int"; + case ocPhi: return "Phi"; + case ocGauss: return "Gauss"; + case ocIsEmpty: return "IsEmpty"; + case ocIsString: return "IsString"; + case ocIsNonString: return "IsNonString"; + case ocIsLogical: return "IsLogical"; + case ocType: return "Type"; + case ocCell: return "Cell"; + case ocIsRef: return "IsRef"; + case ocIsValue: return "IsValue"; + case ocIsFormula: return "IsFormula"; + case ocIsNA: return "IsNA"; + case ocIsErr: return "IsErr"; + case ocIsError: return "IsError"; + case ocIsEven: return "IsEven"; + case ocIsOdd: return "IsOdd"; + case ocN: return "N"; + case ocGetDateValue: return "GetDateValue"; + case ocGetTimeValue: return "GetTimeValue"; + case ocCode: return "Code"; + case ocTrim: return "Trim"; + case ocUpper: return "Upper"; + case ocProper: return "Proper"; + case ocLower: return "Lower"; + case ocLen: return "Len"; + case ocT: return "T"; + case ocValue: return "Value"; + case ocClean: return "Clean"; + case ocChar: return "Char"; + case ocLog10: return "Log10"; + case ocEven: return "Even"; + case ocOdd: return "Odd"; + case ocStdNormDist: return "StdNormDist"; + case ocStdNormDist_MS: return "StdNormDist_MS"; + case ocFisher: return "Fisher"; + case ocFisherInv: return "FisherInv"; + case ocSNormInv: return "SNormInv"; + case ocSNormInv_MS: return "SNormInv_MS"; + case ocGammaLn: return "GammaLn"; + case ocGammaLn_MS: return "GammaLn_MS"; + case ocGamma: return "Gamma"; + case ocErrorType: return "ErrorType"; + case ocErrorType_ODF: return "ErrorType_ODF"; + case ocFormula: return "Formula"; + case ocArabic: return "Arabic"; + case ocInfo: return "Info"; + case ocBahtText: return "BahtText"; + case ocJis: return "Jis"; + case ocAsc: return "Asc"; + case ocUnicode: return "Unicode"; + case ocUnichar: return "Unichar"; + case ocArcTan2: return "ArcTan2"; + case ocCeil: return "Ceil"; + case ocCeil_MS: return "Ceil_MS"; + case ocCeil_Precise: return "Ceil_Precise"; + case ocCeil_ISO: return "Ceil_ISO"; + case ocCeil_Math: return "Ceil_Math"; + case ocFloor: return "Floor"; + case ocFloor_MS: return "Floor_MS"; + case ocFloor_Math: return "Floor_Math"; + case ocFloor_Precise: return "Floor_Precise"; + case ocRound: return "Round"; + case ocRoundUp: return "RoundUp"; + case ocRoundDown: return "RoundDown"; + case ocTrunc: return "Trunc"; + case ocLog: return "Log"; + case ocPower: return "Power"; + case ocGCD: return "GCD"; + case ocLCM: return "LCM"; + case ocMod: return "Mod"; + case ocSumProduct: return "SumProduct"; + case ocSumSQ: return "SumSQ"; + case ocSumX2MY2: return "SumX2MY2"; + case ocSumX2DY2: return "SumX2DY2"; + case ocSumXMY2: return "SumXMY2"; + case ocGetDate: return "GetDate"; + case ocGetTime: return "GetTime"; + case ocGetDiffDate: return "GetDiffDate"; + case ocGetDiffDate360: return "GetDiffDate360"; + case ocGetDateDif: return "GetDateDif"; + case ocMin: return "Min"; + case ocMax: return "Max"; + case ocSum: return "Sum"; + case ocProduct: return "Product"; + case ocAverage: return "Average"; + case ocCount: return "Count"; + case ocCount2: return "Count2"; + case ocNPV: return "NPV"; + case ocIRR: return "IRR"; + case ocMIRR: return "MIRR"; + case ocISPMT: return "ISPMT"; + case ocVar: return "Var"; + case ocVarP: return "VarP"; + case ocVarP_MS: return "VarP_MS"; + case ocVarS: return "VarS"; + case ocStDev: return "StDev"; + case ocStDevP: return "StDevP"; + case ocStDevP_MS: return "StDevP_MS"; + case ocStDevS: return "StDevS"; + case ocB: return "B"; + case ocNormDist: return "NormDist"; + case ocNormDist_MS: return "NormDist_MS"; + case ocExpDist: return "ExpDist"; + case ocExpDist_MS: return "ExpDist_MS"; + case ocBinomDist: return "BinomDist"; + case ocBinomDist_MS: return "BinomDist_MS"; + case ocBinomInv: return "BinomInv"; + case ocPoissonDist: return "PoissonDist"; + case ocPoissonDist_MS: return "PoissonDist_MS"; + case ocCombin: return "Combin"; + case ocCombinA: return "CombinA"; + case ocPermut: return "Permut"; + case ocPermutationA: return "PermutationA"; + case ocPV: return "PV"; + case ocSYD: return "SYD"; + case ocDDB: return "DDB"; + case ocDB: return "DB"; + case ocVBD: return "VBD"; + case ocPDuration: return "PDuration"; + case ocSLN: return "SLN"; + case ocPMT: return "PMT"; + case ocColumns: return "Columns"; + case ocRows: return "Rows"; + case ocColumn: return "Column"; + case ocRow: return "Row"; + case ocRRI: return "RRI"; + case ocFV: return "FV"; + case ocNper: return "Nper"; + case ocRate: return "Rate"; + case ocIpmt: return "Ipmt"; + case ocPpmt: return "Ppmt"; + case ocCumIpmt: return "CumIpmt"; + case ocCumPrinc: return "CumPrinc"; + case ocEffect: return "Effect"; + case ocNominal: return "Nominal"; + case ocSubTotal: return "SubTotal"; + case ocRawSubtract: return "RawSubtract"; + case ocIfs_MS: return "Ifs_MS"; + case ocSwitch_MS: return "Switch_MS"; + case ocMinIfs_MS: return "MinIfs_MS"; + case ocMaxIfs_MS: return "MaxIfs_MS"; + case ocRoundSig: return "RoundSig"; + case ocDBSum: return "DBSum"; + case ocDBCount: return "DBCount"; + case ocDBCount2: return "DBCount2"; + case ocDBAverage: return "DBAverage"; + case ocDBGet: return "DBGet"; + case ocDBMax: return "DBMax"; + case ocDBMin: return "DBMin"; + case ocDBProduct: return "DBProduct"; + case ocDBStdDev: return "DBStdDev"; + case ocDBStdDevP: return "DBStdDevP"; + case ocDBVar: return "DBVar"; + case ocDBVarP: return "DBVarP"; + case ocIndirect: return "Indirect"; + case ocAddress: return "Address"; + case ocMatch: return "Match"; + case ocCountEmptyCells: return "CountEmptyCells"; + case ocCountIf: return "CountIf"; + case ocSumIf: return "SumIf"; + case ocAverageIf: return "AverageIf"; + case ocSumIfs: return "SumIfs"; + case ocAverageIfs: return "AverageIfs"; + case ocCountIfs: return "CountIfs"; + case ocLookup: return "Lookup"; + case ocVLookup: return "VLookup"; + case ocHLookup: return "HLookup"; + case ocMultiArea: return "MultiArea"; + case ocOffset: return "Offset"; + case ocIndex: return "Index"; + case ocAreas: return "Areas"; + case ocCurrency: return "Currency"; + case ocReplace: return "Replace"; + case ocFixed: return "Fixed"; + case ocFind: return "Find"; + case ocExact: return "Exact"; + case ocLeft: return "Left"; + case ocRight: return "Right"; + case ocSearch: return "Search"; + case ocMid: return "Mid"; + case ocText: return "Text"; + case ocSubstitute: return "Substitute"; + case ocRept: return "Rept"; + case ocRegex: return "Regex"; + case ocConcat: return "Concat"; + case ocConcat_MS: return "Concat_MS"; + case ocTextJoin_MS: return "TextJoin_MS"; + case ocLenB: return "LenB"; + case ocRightB: return "RightB"; + case ocLeftB: return "LeftB"; + case ocMidB: return "MidB"; + case ocReplaceB: return "ReplaceB"; + case ocFindB: return "FindB"; + case ocSearchB: return "SearchB"; + case ocNumberValue: return "NumberValue"; + case ocMatValue: return "MatValue"; + case ocMatDet: return "MatDet"; + case ocMatInv: return "MatInv"; + case ocMatMult: return "MatMult"; + case ocMatTrans: return "MatTrans"; + case ocMatrixUnit: return "MatrixUnit"; + case ocBackSolver: return "BackSolver"; + case ocHypGeomDist: return "HypGeomDist"; + case ocHypGeomDist_MS: return "HypGeomDist_MS"; + case ocLogNormDist: return "LogNormDist"; + case ocLogNormDist_MS: return "LogNormDist_MS"; + case ocTDist: return "TDist"; + case ocTDist_MS: return "TDist_MS"; + case ocTDist_RT: return "TDist_RT"; + case ocTDist_2T: return "TDist_2T"; + case ocFDist: return "FDist"; + case ocFDist_LT: return "FDist_LT"; + case ocFDist_RT: return "FDist_RT"; + case ocChiDist: return "ChiDist"; + case ocChiDist_MS: return "ChiDist_MS"; + case ocChiSqDist: return "ChiSqDist"; + case ocChiSqDist_MS: return "ChiSqDist_MS"; + case ocChiSqInv: return "ChiSqInv"; + case ocChiSqInv_MS: return "ChiSqInv_MS"; + case ocWeibull: return "Weibull"; + case ocWeibull_MS: return "Weibull_MS"; + case ocNegBinomVert: return "NegBinomVert"; + case ocNegBinomDist_MS: return "NegBinomDist_MS"; + case ocCritBinom: return "CritBinom"; + case ocKurt: return "Kurt"; + case ocHarMean: return "HarMean"; + case ocGeoMean: return "GeoMean"; + case ocStandard: return "Standard"; + case ocAveDev: return "AveDev"; + case ocSkew: return "Skew"; + case ocSkewp: return "Skewp"; + case ocDevSq: return "DevSq"; + case ocMedian: return "Median"; + case ocModalValue: return "ModalValue"; + case ocModalValue_MS: return "ModalValue_MS"; + case ocModalValue_Multi: return "ModalValue_Multi"; + case ocZTest: return "ZTest"; + case ocZTest_MS: return "ZTest_MS"; + case ocAggregate: return "Aggregate"; + case ocTTest: return "TTest"; + case ocTTest_MS: return "TTest_MS"; + case ocRank: return "Rank"; + case ocPercentile: return "Percentile"; + case ocPercentrank: return "Percentrank"; + case ocPercentile_Inc: return "Percentile_Inc"; + case ocPercentrank_Inc: return "Percentrank_Inc"; + case ocQuartile_Inc: return "Quartile_Inc"; + case ocRank_Eq: return "Rank_Eq"; + case ocPercentile_Exc: return "Percentile_Exc"; + case ocPercentrank_Exc: return "Percentrank_Exc"; + case ocQuartile_Exc: return "Quartile_Exc"; + case ocRank_Avg: return "Rank_Avg"; + case ocLarge: return "Large"; + case ocSmall: return "Small"; + case ocFrequency: return "Frequency"; + case ocQuartile: return "Quartile"; + case ocNormInv: return "NormInv"; + case ocNormInv_MS: return "NormInv_MS"; + case ocConfidence: return "Confidence"; + case ocConfidence_N: return "Confidence_N"; + case ocConfidence_T: return "Confidence_T"; + case ocFTest: return "FTest"; + case ocFTest_MS: return "FTest_MS"; + case ocTrimMean: return "TrimMean"; + case ocProb: return "Prob"; + case ocCorrel: return "Correl"; + case ocCovar: return "Covar"; + case ocCovarianceP: return "CovarianceP"; + case ocCovarianceS: return "CovarianceS"; + case ocPearson: return "Pearson"; + case ocRSQ: return "RSQ"; + case ocSTEYX: return "STEYX"; + case ocSlope: return "Slope"; + case ocIntercept: return "Intercept"; + case ocTrend: return "Trend"; + case ocGrowth: return "Growth"; + case ocLinest: return "Linest"; + case ocLogest: return "Logest"; + case ocForecast: return "Forecast"; + case ocForecast_ETS_ADD: return "Forecast_ETS_ADD"; + case ocForecast_ETS_SEA: return "Forecast_ETS_SEA"; + case ocForecast_ETS_MUL: return "Forecast_ETS_MUL"; + case ocForecast_ETS_PIA: return "Forecast_ETS_PIA"; + case ocForecast_ETS_PIM: return "Forecast_ETS_PIM"; + case ocForecast_ETS_STA: return "Forecast_ETS_STA"; + case ocForecast_ETS_STM: return "Forecast_ETS_STM"; + case ocForecast_LIN: return "Forecast_LIN"; + case ocChiInv: return "ChiInv"; + case ocChiInv_MS: return "ChiInv_MS"; + case ocGammaDist: return "GammaDist"; + case ocGammaDist_MS: return "GammaDist_MS"; + case ocGammaInv: return "GammaInv"; + case ocGammaInv_MS: return "GammaInv_MS"; + case ocTInv: return "TInv"; + case ocTInv_2T: return "TInv_2T"; + case ocTInv_MS: return "TInv_MS"; + case ocFInv: return "FInv"; + case ocFInv_LT: return "FInv_LT"; + case ocFInv_RT: return "FInv_RT"; + case ocChiTest: return "ChiTest"; + case ocChiTest_MS: return "ChiTest_MS"; + case ocLogInv: return "LogInv"; + case ocLogInv_MS: return "LogInv_MS"; + case ocTableOp: return "TableOp"; + case ocBetaDist: return "BetaDist"; + case ocBetaInv: return "BetaInv"; + case ocBetaDist_MS: return "BetaDist_MS"; + case ocBetaInv_MS: return "BetaInv_MS"; + case ocBitAnd: return "BitAnd"; + case ocBitOr: return "BitOr"; + case ocBitXor: return "BitXor"; + case ocBitRshift: return "BitRshift"; + case ocBitLshift: return "BitLshift"; + case ocWeek: return "Week"; + case ocIsoWeeknum: return "IsoWeeknum"; + case ocWeeknumOOo: return "WeeknumOOo"; + case ocGetDayOfWeek: return "GetDayOfWeek"; + case ocNetWorkdays: return "NetWorkdays"; + case ocNetWorkdays_MS: return "NetWorkdays_MS"; + case ocWorkday_MS: return "Workday_MS"; + case ocNoName: return "NoName"; + case ocStyle: return "Style"; + case ocDde: return "Dde"; + case ocBase: return "Base"; + case ocSheet: return "Sheet"; + case ocSheets: return "Sheets"; + case ocMinA: return "MinA"; + case ocMaxA: return "MaxA"; + case ocAverageA: return "AverageA"; + case ocStDevA: return "StDevA"; + case ocStDevPA: return "StDevPA"; + case ocVarA: return "VarA"; + case ocVarPA: return "VarPA"; + case ocEasterSunday: return "EasterSunday"; + case ocDecimal: return "Decimal"; + case ocConvertOOo: return "ConvertOOo"; + case ocRoman: return "Roman"; + case ocHyperLink: return "HyperLink"; + case ocGetPivotData: return "GetPivotData"; + case ocEuroConvert: return "EuroConvert"; + case ocFilterXML: return "FilterXML"; + case ocWebservice: return "Webservice"; + case ocColor: return "Color"; + case ocErf_MS: return "Erf_MS"; + case ocErfc_MS: return "Erfc_MS"; + case ocEncodeURL: return "EncodeURL"; + case ocFourier: return "Fourier"; + case ocRandbetweenNV: return "RandbetweenNV"; + case ocTTT: return "TTT"; + case ocDebugVar: return "DebugVar"; + case ocDataToken1: return "DataToken1"; + case ocNone: return "None"; + } + std::ostringstream os; + os << static_cast(eCode); + return os.str(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/paramclass.hxx b/include/formula/paramclass.hxx new file mode 100644 index 000000000..30773c35e --- /dev/null +++ b/include/formula/paramclass.hxx @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_FORMULA_PARAMCLASS_HXX +#define INCLUDED_FORMULA_PARAMCLASS_HXX + +#include +#include + +namespace formula +{ + enum ParamClass : sal_uInt8 + { + Unknown = 0, // MUST be zero for initialization mechanism! + + /** Out of bounds, function doesn't expect that many parameters. + However, not necessarily returned if a module specific definition + for example returns type Value for an unlisted function. */ + Bounds, + + /** In array formula: single value to be passed. Results in JumpMatrix + being created and multiple calls to function. Functions handling a + formula::svDoubleRef by means of DoubleRefToPosSingleRef() or + PopDoubleRefOrSingleRef() or GetDouble() or GetString() should have + this. */ + Value, + + /** In array formula: area reference must stay reference. Otherwise + don't care. Functions handling a formula::svDoubleRef by means of + PopDoubleRefOrSingleRef() should not have this. */ + Reference, + + /** Like Reference but the function accepts also a list of references + (ocUnion svRefList) as one argument AND handles the special case of + an array of references in array mode. Then the resulting argument + for a parameter in JumpMatrix context may be an array of references + which then is to be preferred over a result matrix. This final + behaviour is the opposite of SuppressedReferenceOrForceArray. */ + ReferenceOrRefArray, + + /** In array formula: convert area reference to array. Function will be + called only once if no Value type is involved. Functions able to + handle a svMatrix parameter but not a formula::svDoubleRef parameter as area + should have this. */ + Array, + + /** Area reference must be converted to array in any case, and must + also be propagated to subsequent operators and functions being part + of a parameter of this function. */ + ForceArray, + + /** Area reference is not converted to array, but ForceArray must be + propagated to subsequent operators and functions being part of a + parameter of this function. Used with functions that treat + references separately from arrays, but need the forced array + calculation of parameters that are not references. */ + ReferenceOrForceArray, + + /** Same as ReferenceOrForceArray but suppressed / not inherited in the + compiler's ForceArray context to indicate that a result of + Reference in JumpMatrix context should use the result matrix + instead of the array of references. Never used as initial parameter + classification. */ + SuppressedReferenceOrForceArray, + + /** A function return forces the caller into array mode for this one + call, making it behave like it had ForceArray but not propagated to + any further operators in the same parameter. */ + ForceArrayReturn + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/formula/token.hxx b/include/formula/token.hxx new file mode 100644 index 000000000..ebb08e6d7 --- /dev/null +++ b/include/formula/token.hxx @@ -0,0 +1,482 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_TOKEN_HXX +#define INCLUDED_FORMULA_TOKEN_HXX + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +class ScJumpMatrix; +class ScMatrix; +struct ScComplexRefData; +struct ScSingleRefData; +enum class FormulaError : sal_uInt16; + +namespace formula +{ + +enum StackVar : sal_uInt8 +{ + svByte, + svDouble, + svString, + svSingleRef, + svDoubleRef, + svMatrix, + svIndex, + svJump, + svExternal, // Byte + String + svFAP, // FormulaAutoPilot only, ever exported + svJumpMatrix, + svRefList, // ocUnion result + svEmptyCell, // Result is an empty cell, e.g. in LOOKUP() + + svMatrixCell, // Result is a matrix with bells and + // whistles as needed for _the_ matrix + // formula result. + + svHybridCell, // A temporary condition of a formula + // cell during import, having a double + // and/or string result and a formula + // string to be compiled. + + svExternalSingleRef, + svExternalDoubleRef, + svExternalName, + svSingleVectorRef, + svDoubleVectorRef, + svError, // error token + svMissing, // 0 or "" + svSep, // separator, ocSep, ocOpen, ocClose + svUnknown // unknown StackType +}; + +// Only to be used for debugging output. No guarantee of stability of the +// return value. + +// Turn this into an operator<< when StackVar becomes a scoped enum + +inline std::string StackVarEnumToString(StackVar const e) +{ + switch (e) + { + case svByte: return "Byte"; + case svDouble: return "Double"; + case svString: return "String"; + case svSingleRef: return "SingleRef"; + case svDoubleRef: return "DoubleRef"; + case svMatrix: return "Matrix"; + case svIndex: return "Index"; + case svJump: return "Jump"; + case svExternal: return "External"; + case svFAP: return "FAP"; + case svJumpMatrix: return "JumpMatrix"; + case svRefList: return "RefList"; + case svEmptyCell: return "EmptyCell"; + case svMatrixCell: return "MatrixCell"; + case svHybridCell: return "HybridCell"; + case svExternalSingleRef: return "ExternalSingleRef"; + case svExternalDoubleRef: return "ExternalDoubleRef"; + case svExternalName: return "ExternalName"; + case svSingleVectorRef: return "SingleVectorRef"; + case svDoubleVectorRef: return "DoubleVectorRef"; + case svError: return "Error"; + case svMissing: return "Missing"; + case svSep: return "Sep"; + case svUnknown: return "Unknown"; + } + std::ostringstream os; + os << static_cast(e); + return os.str(); +} + +class FORMULA_DLLPUBLIC FormulaToken +{ + OpCode eOp; + const StackVar eType; // type of data + mutable oslInterlockedCount mnRefCnt; // reference count + + FormulaToken& operator=( const FormulaToken& ) = delete; +public: + FormulaToken( StackVar eTypeP,OpCode e = ocPush ); + FormulaToken( const FormulaToken& r ); + + virtual ~FormulaToken(); + + void Delete() { delete this; } + void DeleteIfZeroRef() { if (mnRefCnt == 0) delete this; } + StackVar GetType() const { return eType; } + bool IsFunction() const; // pure functions, no operators + + bool IsExternalRef() const; + bool IsRef() const; + + sal_uInt8 GetParamCount() const; + + void IncRef() const + { + osl_atomic_increment(&mnRefCnt); + } + + void DecRef() const + { + if (!osl_atomic_decrement(&mnRefCnt)) + const_cast(this)->Delete(); + } + + oslInterlockedCount GetRef() const { return mnRefCnt; } + OpCode GetOpCode() const { return eOp; } + + bool IsInForceArray() const; + + /** + Dummy methods to avoid switches and casts where possible, + the real token classes have to override the appropriate method[s]. + The only methods valid anytime if not overridden are: + + - GetByte() since this represents the count of parameters to a function + which of course is 0 on non-functions. FormulaByteToken and ScExternal do + override it. + + - GetInForceArray() since also this is only used for operators and + functions and is ParamClass::Unknown for other tokens. + + Any other non-overridden method pops up an assertion. + */ + + virtual sal_uInt8 GetByte() const; + virtual void SetByte( sal_uInt8 n ); + virtual ParamClass GetInForceArray() const; + virtual void SetInForceArray( ParamClass c ); + virtual double GetDouble() const; + virtual double& GetDoubleAsReference(); + virtual sal_Int16 GetDoubleType() const; + virtual void SetDoubleType( sal_Int16 nType ); + virtual const svl::SharedString & GetString() const; + virtual void SetString( const svl::SharedString& rStr ); + virtual sal_uInt16 GetIndex() const; + virtual void SetIndex( sal_uInt16 n ); + virtual sal_Int16 GetSheet() const; + virtual void SetSheet( sal_Int16 n ); + virtual sal_Unicode GetChar() const; + virtual short* GetJump() const; + virtual const OUString& GetExternal() const; + virtual FormulaToken* GetFAPOrigToken() const; + virtual FormulaError GetError() const; + virtual void SetError( FormulaError ); + + virtual const ScSingleRefData* GetSingleRef() const; + virtual ScSingleRefData* GetSingleRef(); + virtual const ScComplexRefData* GetDoubleRef() const; + virtual ScComplexRefData* GetDoubleRef(); + virtual const ScSingleRefData* GetSingleRef2() const; + virtual ScSingleRefData* GetSingleRef2(); + virtual const ScMatrix* GetMatrix() const; + virtual ScMatrix* GetMatrix(); + virtual ScJumpMatrix* GetJumpMatrix() const; + virtual const std::vector* GetRefList() const; + virtual std::vector* GetRefList(); + + virtual FormulaToken* Clone() const { return new FormulaToken(*this); } + + virtual bool TextEqual( const formula::FormulaToken& rToken ) const; + virtual bool operator==( const FormulaToken& rToken ) const; + + /** This is dirty and only the compiler should use it! */ + struct PrivateAccess { friend class FormulaCompiler; private: PrivateAccess() { } }; + void NewOpCode( OpCode e, const PrivateAccess& ) { eOp = e; } +}; + +inline void intrusive_ptr_add_ref(const FormulaToken* p) +{ + p->IncRef(); +} + +inline void intrusive_ptr_release(const FormulaToken* p) +{ + p->DecRef(); +} + +class FORMULA_DLLPUBLIC FormulaSpaceToken final : public FormulaToken +{ +private: + sal_uInt8 nByte; + sal_Unicode cChar; +public: + FormulaSpaceToken( sal_uInt8 n, sal_Unicode c ) : + FormulaToken( svByte, ocWhitespace ), + nByte( n ), cChar( c ) {} + FormulaSpaceToken( const FormulaSpaceToken& r ) : + FormulaToken( r ), + nByte( r.nByte ), cChar( r.cChar ) {} + + virtual FormulaToken* Clone() const override { return new FormulaSpaceToken(*this); } + virtual sal_uInt8 GetByte() const override; + virtual sal_Unicode GetChar() const override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + +class FORMULA_DLLPUBLIC FormulaByteToken : public FormulaToken +{ +private: + sal_uInt8 nByte; + ParamClass eInForceArray; +protected: + FormulaByteToken( OpCode e, sal_uInt8 n, StackVar v, ParamClass c ) : + FormulaToken( v,e ), nByte( n ), + eInForceArray( c ) {} +public: + FormulaByteToken( OpCode e, sal_uInt8 n, ParamClass c ) : + FormulaToken( svByte,e ), nByte( n ), + eInForceArray( c ) {} + FormulaByteToken( OpCode e, sal_uInt8 n ) : + FormulaToken( svByte,e ), nByte( n ), + eInForceArray( ParamClass::Unknown ) {} + FormulaByteToken( OpCode e ) : + FormulaToken( svByte,e ), nByte( 0 ), + eInForceArray( ParamClass::Unknown ) {} + FormulaByteToken( const FormulaByteToken& r ) : + FormulaToken( r ), nByte( r.nByte ), + eInForceArray( r.eInForceArray ) {} + + virtual FormulaToken* Clone() const override { return new FormulaByteToken(*this); } + virtual sal_uInt8 GetByte() const override; + virtual void SetByte( sal_uInt8 n ) override; + virtual ParamClass GetInForceArray() const override; + virtual void SetInForceArray( ParamClass c ) override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +// A special token for the FormulaAutoPilot only. Keeps a reference pointer of +// the token of which it was created for comparison. +class FORMULA_DLLPUBLIC FormulaFAPToken final : public FormulaByteToken +{ +private: + FormulaTokenRef pOrigToken; +public: + FormulaFAPToken( OpCode e, sal_uInt8 n, FormulaToken* p ) : + FormulaByteToken( e, n, svFAP, ParamClass::Unknown ), + pOrigToken( p ) {} + FormulaFAPToken( const FormulaFAPToken& r ) : + FormulaByteToken( r ), pOrigToken( r.pOrigToken ) {} + + virtual FormulaToken* Clone() const override { return new FormulaFAPToken(*this); } + virtual FormulaToken* GetFAPOrigToken() const override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + +class FORMULA_DLLPUBLIC FormulaDoubleToken : public FormulaToken +{ +private: + double fDouble; +public: + FormulaDoubleToken( double f ) : + FormulaToken( svDouble ), fDouble( f ) {} + FormulaDoubleToken( const FormulaDoubleToken& r ) : + FormulaToken( r ), fDouble( r.fDouble ) {} + + virtual FormulaToken* Clone() const override { return new FormulaDoubleToken(*this); } + virtual double GetDouble() const override; + virtual double& GetDoubleAsReference() override; + virtual sal_Int16 GetDoubleType() const override; ///< always returns 0 for "not typed" + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + +class FORMULA_DLLPUBLIC FormulaTypedDoubleToken final : public FormulaDoubleToken +{ +private: + sal_Int16 mnType; /**< Can hold, for example, a value + of SvNumFormatType, or by + contract any other + classification. */ +public: + FormulaTypedDoubleToken( double f, sal_Int16 nType ) : + FormulaDoubleToken( f ), mnType( nType ) {} + FormulaTypedDoubleToken( const FormulaTypedDoubleToken& r ) : + FormulaDoubleToken( r ), mnType( r.mnType ) {} + + virtual FormulaToken* Clone() const override { return new FormulaTypedDoubleToken(*this); } + virtual sal_Int16 GetDoubleType() const override; + virtual void SetDoubleType( sal_Int16 nType ) override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +class FORMULA_DLLPUBLIC FormulaStringToken final : public FormulaToken +{ + svl::SharedString maString; +public: + FormulaStringToken( const svl::SharedString& r ); + FormulaStringToken( const FormulaStringToken& r ); + + virtual FormulaToken* Clone() const override; + virtual const svl::SharedString & GetString() const override; + virtual void SetString( const svl::SharedString& rStr ) override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +/** Identical to FormulaStringToken, but with explicit OpCode instead of implicit + ocPush, and an optional sal_uInt8 for ocBad tokens. */ +class FORMULA_DLLPUBLIC FormulaStringOpToken final : public FormulaByteToken +{ + svl::SharedString maString; +public: + FormulaStringOpToken( OpCode e, const svl::SharedString& r ); + FormulaStringOpToken( const FormulaStringOpToken& r ); + + virtual FormulaToken* Clone() const override; + virtual const svl::SharedString & GetString() const override; + virtual void SetString( const svl::SharedString& rStr ) override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + +class FORMULA_DLLPUBLIC FormulaIndexToken final : public FormulaToken +{ +private: + sal_uInt16 nIndex; + sal_Int16 mnSheet; +public: + FormulaIndexToken( OpCode e, sal_uInt16 n, sal_Int16 nSheet = -1 ) : + FormulaToken( svIndex, e ), nIndex( n ), mnSheet( nSheet ) {} + FormulaIndexToken( const FormulaIndexToken& r ) : + FormulaToken( r ), nIndex( r.nIndex ), mnSheet( r.mnSheet ) {} + + virtual FormulaToken* Clone() const override { return new FormulaIndexToken(*this); } + virtual sal_uInt16 GetIndex() const override; + virtual void SetIndex( sal_uInt16 n ) override; + virtual sal_Int16 GetSheet() const override; + virtual void SetSheet( sal_Int16 n ) override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +class FORMULA_DLLPUBLIC FormulaExternalToken final : public FormulaByteToken +{ +private: + OUString aExternal; +public: + FormulaExternalToken( OpCode e, sal_uInt8 n, const OUString& r ) : + FormulaByteToken( e, n, svExternal, ParamClass::Unknown ), + aExternal( r ) {} + FormulaExternalToken( OpCode e, const OUString& r ) : + FormulaByteToken( e, 0, svExternal, ParamClass::Unknown ), + aExternal( r ) {} + FormulaExternalToken( const FormulaExternalToken& r ) : + FormulaByteToken( r ), aExternal( r.aExternal ) {} + + virtual FormulaToken* Clone() const override { return new FormulaExternalToken(*this); } + virtual const OUString& GetExternal() const override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +class FORMULA_DLLPUBLIC FormulaMissingToken final : public FormulaToken +{ +public: + FormulaMissingToken() : + FormulaToken( svMissing,ocMissing ) {} + FormulaMissingToken( const FormulaMissingToken& r ) : + FormulaToken( r ) {} + + virtual FormulaToken* Clone() const override { return new FormulaMissingToken(*this); } + virtual double GetDouble() const override; + virtual const svl::SharedString & GetString() const override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + +class FORMULA_DLLPUBLIC FormulaJumpToken final : public FormulaToken +{ +private: + std::unique_ptr + pJump; + ParamClass eInForceArray; +public: + FormulaJumpToken( OpCode e, short const * p ) : + FormulaToken( formula::svJump , e), + eInForceArray( ParamClass::Unknown) + { + pJump.reset( new short[ p[0] + 1 ] ); + memcpy( pJump.get(), p, (p[0] + 1) * sizeof(short) ); + } + FormulaJumpToken( const FormulaJumpToken& r ) : + FormulaToken( r ), + eInForceArray( r.eInForceArray) + { + pJump.reset( new short[ r.pJump[0] + 1 ] ); + memcpy( pJump.get(), r.pJump.get(), (r.pJump[0] + 1) * sizeof(short) ); + } + virtual ~FormulaJumpToken() override; + virtual short* GetJump() const override; + virtual bool operator==( const formula::FormulaToken& rToken ) const override; + virtual FormulaToken* Clone() const override { return new FormulaJumpToken(*this); } + virtual ParamClass GetInForceArray() const override; + virtual void SetInForceArray( ParamClass c ) override; +}; + + +class FORMULA_DLLPUBLIC FormulaUnknownToken final : public FormulaToken +{ +public: + FormulaUnknownToken( OpCode e ) : + FormulaToken( svUnknown, e ) {} + FormulaUnknownToken( const FormulaUnknownToken& r ) : + FormulaToken( r ) {} + + virtual FormulaToken* Clone() const override { return new FormulaUnknownToken(*this); } + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +class FORMULA_DLLPUBLIC FormulaErrorToken final : public FormulaToken +{ + FormulaError nError; +public: + FormulaErrorToken( FormulaError nErr ) : + FormulaToken( svError ), nError( nErr) {} + FormulaErrorToken( const FormulaErrorToken& r ) : + FormulaToken( r ), nError( r.nError) {} + + virtual FormulaToken* Clone() const override { return new FormulaErrorToken(*this); } + virtual FormulaError GetError() const override; + virtual void SetError( FormulaError nErr ) override; + virtual bool operator==( const FormulaToken& rToken ) const override; +}; + + +} // formula + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/tokenarray.hxx b/include/formula/tokenarray.hxx new file mode 100644 index 000000000..cbff6a3e4 --- /dev/null +++ b/include/formula/tokenarray.hxx @@ -0,0 +1,669 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_TOKENARRAY_HXX +#define INCLUDED_FORMULA_TOKENARRAY_HXX + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace sheet { struct FormulaToken; } +} + +namespace com::sun::star::uno { template class Sequence; } +namespace formula { class FormulaTokenArray; } + +namespace svl { + +class SharedString; +class SharedStringPool; + +} + +// RecalcMode access only via TokenArray SetExclusiveRecalcMode...() / +// IsRecalcMode...() + +// Only one of the exclusive bits can be set and one must be set, +// handled by TokenArray SetExclusiveRecalcMode...() methods. +// Exclusive bits are ordered by priority, AddRecalcMode() relies on that. +enum class ScRecalcMode : sal_uInt8 +{ + ALWAYS = 0x01, // exclusive, always + ONLOAD_MUST = 0x02, // exclusive, always after load + ONLOAD_ONCE = 0x04, // exclusive, once after load, import filter + ONLOAD_LENIENT = 0x08, // exclusive, lenient after load (eg. macros not always, aliens, ...) + NORMAL = 0x10, // exclusive + FORCED = 0x20, // combined, also if cell isn't visible, for macros with side effects + ONREFMOVE = 0x40, // combined, if reference was moved + EMask = ALWAYS | ONLOAD_MUST | ONLOAD_LENIENT | ONLOAD_ONCE | NORMAL // mask of exclusive bits +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace formula +{ + +class FORMULA_DLLPUBLIC MissingConvention +{ +public: + enum Convention + { + FORMULA_MISSING_CONVENTION_PODF, + FORMULA_MISSING_CONVENTION_ODFF, + FORMULA_MISSING_CONVENTION_OOXML + }; + explicit MissingConvention( Convention eConvention ) : meConvention(eConvention) {} + bool isPODF() const { return meConvention == FORMULA_MISSING_CONVENTION_PODF; } + bool isODFF() const { return meConvention == FORMULA_MISSING_CONVENTION_ODFF; } + bool isOOXML() const { return meConvention == FORMULA_MISSING_CONVENTION_OOXML; } + Convention getConvention() const { return meConvention; } +private: + Convention meConvention; +}; + +class FORMULA_DLLPUBLIC MissingConventionODF : public MissingConvention +{ +public: + explicit MissingConventionODF( bool bODFF ) : + MissingConvention( bODFF ? + MissingConvention::FORMULA_MISSING_CONVENTION_ODFF : + MissingConvention::FORMULA_MISSING_CONVENTION_PODF) + { + } + // Implementation and usage only in token.cxx + inline bool isRewriteNeeded( OpCode eOp ) const; +}; + +class FORMULA_DLLPUBLIC MissingConventionOOXML : public MissingConvention +{ +public: + explicit MissingConventionOOXML() : MissingConvention( MissingConvention::FORMULA_MISSING_CONVENTION_OOXML) {} + // Implementation and usage only in token.cxx + static inline bool isRewriteNeeded( OpCode eOp ); +}; + +typedef std::unordered_set::type> > unordered_opcode_set; + +class FORMULA_DLLPUBLIC FormulaTokenArrayStandardRange +{ +private: + FormulaToken** mpBegin; + FormulaToken** mpEnd; + +public: + FormulaTokenArrayStandardRange(FormulaToken** pBegin, sal_uInt16 nSize) : + mpBegin(pBegin), + mpEnd(pBegin + nSize) + { + } + + FormulaToken** begin() const + { + return mpBegin; + } + + FormulaToken** end() const + { + return mpEnd; + } +}; + +class FORMULA_DLLPUBLIC FormulaTokenArrayReferencesIterator +{ +private: + FormulaToken** maIter; + FormulaToken** maEnd; + + void nextReference() + { + while (maIter != maEnd) + { + switch ((*maIter)->GetType()) + { + case svSingleRef: + case svDoubleRef: + case svExternalSingleRef: + case svExternalDoubleRef: + return; + default: + ++maIter; + } + } + } + + enum class Dummy { Flag }; + + FormulaTokenArrayReferencesIterator(const FormulaTokenArrayStandardRange& rRange, Dummy) : + maIter(rRange.end()), + maEnd(rRange.end()) + { + } + +public: + FormulaTokenArrayReferencesIterator(const FormulaTokenArrayStandardRange& rRange) : + maIter(rRange.begin()), + maEnd(rRange.end()) + { + nextReference(); + } + + FormulaTokenArrayReferencesIterator operator++(int) + { + FormulaTokenArrayReferencesIterator result(*this); + operator++(); + return result; + } + + FormulaTokenArrayReferencesIterator const & operator++() + { + assert(maIter != maEnd); + ++maIter; + nextReference(); + return *this; + } + + FormulaToken* operator*() const + { + return *maIter; + } + + bool operator==(const FormulaTokenArrayReferencesIterator& rhs) const + { + return maIter == rhs.maIter; + } + + bool operator!=(const FormulaTokenArrayReferencesIterator& rhs) const + { + return !operator==(rhs); + } + + static FormulaTokenArrayReferencesIterator endOf(const FormulaTokenArrayStandardRange& rRange) + { + return FormulaTokenArrayReferencesIterator(rRange, Dummy::Flag); + } +}; + +class FORMULA_DLLPUBLIC FormulaTokenArrayReferencesRange +{ +private: + const FormulaTokenArray& mrFTA; + +public: + FormulaTokenArrayReferencesRange(const FormulaTokenArray& rFTA) : + mrFTA(rFTA) + { + } + + FormulaTokenArrayReferencesIterator begin(); + + FormulaTokenArrayReferencesIterator end(); +}; + +class FORMULA_DLLPUBLIC FormulaTokenArray +{ +protected: + std::unique_ptr pCode; // Token code array + FormulaToken** pRPN; // RPN array + sal_uInt16 nLen; // Length of token array + sal_uInt16 nRPN; // Length of RPN array + FormulaError nError; // Error code + ScRecalcMode nMode; // Flags to indicate when to recalc this code + bool bHyperLink :1; // If HYPERLINK() occurs in the formula. + bool mbFromRangeName :1; // If this array originates from a named expression + bool mbShareable :1; // Whether or not it can be shared with adjacent cells. + bool mbFinalized :1; // Whether code arrays have their final used size and no more tokens can be added. + +protected: + void Assign( const FormulaTokenArray& ); + void Assign( sal_uInt16 nCode, FormulaToken **pTokens ); + void Move( FormulaTokenArray&& ); + + /// Also used by the compiler. The token MUST had been allocated with new! + FormulaToken* Add( FormulaToken* ); + +public: + enum ReplaceMode + { + CODE_ONLY, ///< replacement only in pCode + CODE_AND_RPN ///< replacement in pCode and pRPN + }; + + /** Also used by the compiler. The token MUST had been allocated with new! + @param nOffset + Absolute offset in pCode of the token to be replaced. + @param eMode + If CODE_ONLY only the token in pCode at nOffset is replaced. + If CODE_AND_RPN the token in pCode at nOffset is replaced; + if the original token was also referenced in the pRPN array + then that reference is replaced with a reference to the new + token as well. + */ + FormulaToken* ReplaceToken( sal_uInt16 nOffset, FormulaToken*, ReplaceMode eMode ); + + /** Remove a sequence of tokens from pCode array, and pRPN array if the + tokens are referenced there. + + nLen and nRPN are adapted. + + @param nOffset + Start offset into pCode. + @param nCount + Count of tokens to remove. + + @return Count of tokens removed. + */ + sal_uInt16 RemoveToken( sal_uInt16 nOffset, sal_uInt16 nCount ); + + FormulaTokenArray(); + /** Assignment with incrementing references of FormulaToken entries + (not copied!) */ + FormulaTokenArray( const FormulaTokenArray& ); + FormulaTokenArray( FormulaTokenArray&& ); + virtual ~FormulaTokenArray(); + + virtual void Clear(); + + /** + * The array has its final used size and no more token can be added. + */ + void Finalize(); + + void SetFromRangeName( bool b ) { mbFromRangeName = b; } + bool IsFromRangeName() const { return mbFromRangeName; } + + void SetShareable( bool b ) { mbShareable = b; } + + /** + * Check if this token array is shareable between multiple adjacent + * formula cells. Certain tokens may not function correctly when shared. + * + * @return true if the token array is shareable, false otherwise. + */ + bool IsShareable() const { return mbShareable; } + + void DelRPN(); + FormulaToken* FirstToken() const; + + /// Return pCode[nIdx], or nullptr if nIdx is out of bounds + FormulaToken* TokenAt( sal_uInt16 nIdx) const + { + if (nIdx >= nLen) + return nullptr; + return pCode[nIdx]; + } + + /// Peek at nIdx-1 if not out of bounds, decrements nIdx if successful. Returns NULL if not. + FormulaToken* PeekPrev( sal_uInt16 & nIdx ) const; + + /// Return the opcode at pCode[nIdx-1], ocNone if nIdx-1 is out of bounds + OpCode OpCodeBefore( sal_uInt16 nIdx) const + { + if (nIdx == 0 || nIdx > nLen) + return ocNone; + + return pCode[nIdx-1]->GetOpCode(); + } + + FormulaToken* FirstRPNToken() const; + FormulaToken* LastRPNToken() const; + + bool HasReferences() const; + + bool HasExternalRef() const; + bool HasOpCode( OpCode ) const; + bool HasOpCodeRPN( OpCode ) const; + /// Token of type svIndex or opcode ocColRowName + bool HasNameOrColRowName() const; + + /** + * Check if the token array contains any of specified opcode tokens. + * + * @param rOpCodes collection of opcodes to check against. + * + * @return true if the token array contains at least one of the specified + * opcode tokens, false otherwise. + */ + bool HasOpCodes( const unordered_opcode_set& rOpCodes ) const; + + /// Assign pRPN to point to a newly created array filled with the data from pData + void CreateNewRPNArrayFromData( FormulaToken** pData, sal_uInt16 nSize ) + { + pRPN = new FormulaToken*[ nSize ]; + nRPN = nSize; + memcpy( pRPN, pData, nSize * sizeof( FormulaToken* ) ); + } + + FormulaToken** GetArray() const { return pCode.get(); } + + FormulaTokenArrayStandardRange Tokens() const + { + return FormulaTokenArrayStandardRange(pCode.get(), nLen); + } + + FormulaToken** GetCode() const { return pRPN; } + + FormulaTokenArrayStandardRange RPNTokens() const + { + return FormulaTokenArrayStandardRange(pRPN, nRPN); + } + + FormulaTokenArrayReferencesRange References() const + { + return FormulaTokenArrayReferencesRange(*this); + } + + sal_uInt16 GetLen() const { return nLen; } + sal_uInt16 GetCodeLen() const { return nRPN; } + FormulaError GetCodeError() const { return nError; } + void SetCodeError( FormulaError n ) { nError = n; } + void SetHyperLink( bool bVal ) { bHyperLink = bVal; } + bool IsHyperLink() const { return bHyperLink; } + + ScRecalcMode GetRecalcMode() const { return nMode; } + + void SetCombinedBitsRecalcMode( ScRecalcMode nBits ) + { nMode |= nBits & ~ScRecalcMode::EMask; } + ScRecalcMode GetCombinedBitsRecalcMode() const + { return nMode & ~ScRecalcMode::EMask; } + + /** Exclusive bits already set in nMode are zero'ed, nBits + may contain combined bits, but only one exclusive bit + may be set! */ + void SetMaskedRecalcMode( ScRecalcMode nBits ) + { nMode = GetCombinedBitsRecalcMode() | nBits; } + + /** Bits aren't set directly but validated and handled + according to priority if more than one exclusive bit + was set. */ + void AddRecalcMode( ScRecalcMode nBits ); + + void ClearRecalcMode() { nMode = ScRecalcMode::NORMAL; } + void SetExclusiveRecalcModeNormal() + { SetMaskedRecalcMode( ScRecalcMode::NORMAL ); } + void SetExclusiveRecalcModeAlways() + { SetMaskedRecalcMode( ScRecalcMode::ALWAYS ); } + void SetRecalcModeForced() + { nMode |= ScRecalcMode::FORCED; } + void SetRecalcModeOnRefMove() + { nMode |= ScRecalcMode::ONREFMOVE; } + bool IsRecalcModeNormal() const + { return bool(nMode & ScRecalcMode::NORMAL); } + bool IsRecalcModeAlways() const + { return bool(nMode & ScRecalcMode::ALWAYS); } + bool IsRecalcModeForced() const + { return bool(nMode & ScRecalcMode::FORCED); } + bool IsRecalcModeOnRefMove() const + { return bool(nMode & ScRecalcMode::ONREFMOVE); } + /** Whether recalculation must happen after import, for + example OOXML. */ + bool IsRecalcModeMustAfterImport() const + { return (nMode & ScRecalcMode::EMask) <= ScRecalcMode::ONLOAD_ONCE; } + + /** Get OpCode of the most outer function */ + inline OpCode GetOuterFuncOpCode() const; + + /** Operators +,-,*,/,^,&,=,<>,<,>,<=,>= + with DoubleRef in Formula? */ + bool HasMatrixDoubleRefOps() const; + + virtual FormulaToken* AddOpCode(OpCode e); + + /** Adds the single token to array. + Derived classes must override it when they want to support derived classes from FormulaToken. + @return true when an error occurs + */ + virtual bool AddFormulaToken( + const css::sheet::FormulaToken& rToken, svl::SharedStringPool& rSPool, + ExternalReferenceHelper* pExtRef ); + + /** fill the array with the tokens from the sequence. + It calls AddFormulaToken for each token in the list. + @param _aSequence the token to add + @return true when an error occurs + */ + bool Fill( + const css::uno::Sequence& rSequence, + svl::SharedStringPool& rSPool, ExternalReferenceHelper* pExtRef ); + + /** + * Do some checking based on the individual tokens. For now, we use this + * only to check whether we can vectorize the token array. + */ + virtual void CheckToken( const FormulaToken& t ); + + /** + * Call CheckToken() for all RPN tokens. + */ + void CheckAllRPNTokens(); + + /** Clones the token and then adds the clone to the pCode array. + For just new'ed tokens use Add() instead of cloning it again. + Use this AddToken() when adding a token from another origin. + */ + FormulaToken* AddToken( const FormulaToken& ); + + FormulaToken* AddString( const svl::SharedString& rStr ); + FormulaToken* AddDouble( double fVal ); + void AddExternal( const sal_Unicode* pStr ); + /** Xcl import may play dirty tricks with OpCode!=ocExternal. + Others don't use! */ + FormulaToken* AddExternal( const OUString& rStr, OpCode eOp = ocExternal ); + FormulaToken* AddBad( const OUString& rStr ); /// ocBad with OUString + FormulaToken* AddStringXML( const OUString& rStr ); /// ocStringXML with OUString, temporary during import + + virtual FormulaToken* MergeArray( ); + + /** Assignment with incrementing references of FormulaToken entries + (not copied!) */ + FormulaTokenArray& operator=( const FormulaTokenArray& ); + FormulaTokenArray& operator=( FormulaTokenArray&& ); + + /** Determines if this formula needs any changes to convert it to something + previous versions of OOo could consume (Plain Old Formula, pre-ODFF, or + also ODFF) */ + bool NeedsPodfRewrite( const MissingConventionODF & rConv ); + + /** Determines if this formula needs any changes to convert it to OOXML. */ + bool NeedsOoxmlRewrite(); + + /** Rewrites to Plain Old Formula or OOXML, substituting missing parameters. The + FormulaTokenArray* returned is new'ed. */ + FormulaTokenArray* RewriteMissing( const MissingConvention & rConv ); + + /** Determines if this formula may be followed by a reference. */ + bool MayReferenceFollow(); + + /** Re-intern SharedString in case the SharedStringPool differs. */ + void ReinternStrings( svl::SharedStringPool& rPool ); +}; + +inline OpCode FormulaTokenArray::GetOuterFuncOpCode() const +{ + if ( pRPN && nRPN ) + return pRPN[nRPN-1]->GetOpCode(); + return ocNone; +} + +inline FormulaTokenArrayReferencesIterator FormulaTokenArrayReferencesRange::begin() +{ + return FormulaTokenArrayReferencesIterator(mrFTA.Tokens()); +} + +inline FormulaTokenArrayReferencesIterator FormulaTokenArrayReferencesRange::end() +{ + return FormulaTokenArrayReferencesIterator::endOf(mrFTA.Tokens()); +} + +class FORMULA_DLLPUBLIC FormulaTokenIterator +{ + struct Item + { + public: + const FormulaTokenArray* pArr; + short nPC; + short nStop; + + Item(const FormulaTokenArray* arr, short pc, short stop); + }; + + std::vector maStack; + +public: + FormulaTokenIterator( const FormulaTokenArray& ); + ~FormulaTokenIterator(); + void Reset(); + const FormulaToken* Next(); + const FormulaToken* PeekNextOperator(); + bool IsEndOfPath() const; /// if a jump or subroutine path is done + bool HasStacked() const { return maStack.size() > 1; } + short GetPC() const { return maStack.back().nPC; } + + /** Jump or subroutine call. + Program counter values will be incremented before code is executed => + positions are to be passed with -1 offset. + @param nStart + Start on code at position nStart+1 (yes, pass with offset -1) + @param nNext + After subroutine continue with instruction at position nNext+1 + @param nStop + Stop before reaching code at position nStop. If not specified the + default is to either run the entire code, or to stop if an ocSep or + ocClose is encountered, which are only present in ocIf or ocChoose + jumps. + */ + void Jump( short nStart, short nNext, short nStop = SHRT_MAX ); + void Push( const FormulaTokenArray* ); + void Pop(); + + /** Reconstruct the iterator afresh from a token array + */ + void ReInit( const FormulaTokenArray& ); + +private: + const FormulaToken* GetNonEndOfPathToken( short nIdx ) const; +}; + +// For use in SAL_INFO, SAL_WARN etc + +template +inline std::basic_ostream & operator <<(std::basic_ostream & stream, const FormulaTokenArray& point) +{ + stream << + static_cast(&point) << + ":{nLen=" << point.GetLen() << + ",nRPN=" << point.GetCodeLen() << + ",pCode=" << static_cast(point.GetArray()) << + ",pRPN=" << static_cast(point.GetCode()) << + "}"; + + return stream; +} + +class FORMULA_DLLPUBLIC FormulaTokenArrayPlainIterator +{ +private: + const FormulaTokenArray* mpFTA; + sal_uInt16 mnIndex; // Current step index + +public: + FormulaTokenArrayPlainIterator( const FormulaTokenArray& rFTA ) : + mpFTA( &rFTA ), + mnIndex( 0 ) + { + } + + void Reset() + { + mnIndex = 0; + } + + sal_uInt16 GetIndex() const + { + return mnIndex; + } + + FormulaToken* First() + { + mnIndex = 0; + return Next(); + } + + void Jump(sal_uInt16 nIndex) + { + mnIndex = nIndex; + } + + void StepBack() + { + assert(mnIndex > 0); + mnIndex--; + } + + FormulaToken* Next(); + FormulaToken* NextNoSpaces(); + FormulaToken* GetNextName(); + FormulaToken* GetNextReference(); + FormulaToken* GetNextReferenceRPN(); + FormulaToken* GetNextReferenceOrName(); + FormulaToken* GetNextColRowName(); + FormulaToken* PeekNext(); + FormulaToken* PeekPrevNoSpaces() const; /// Only after Reset/First/Next/Last/Prev! + FormulaToken* PeekNextNoSpaces() const; /// Only after Reset/First/Next/Last/Prev! + + FormulaToken* FirstRPN() + { + mnIndex = 0; + return NextRPN(); + } + + FormulaToken* NextRPN(); + + FormulaToken* LastRPN() + { + mnIndex = mpFTA->GetCodeLen(); + return PrevRPN(); + } + + FormulaToken* PrevRPN(); + + void AfterRemoveToken( sal_uInt16 nOffset, sal_uInt16 nCount ); +}; + + +} // formula + +#endif // INCLUDED_FORMULA_TOKENARRAY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/types.hxx b/include/formula/types.hxx new file mode 100644 index 000000000..c0c8b64c2 --- /dev/null +++ b/include/formula/types.hxx @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FORMULA_TYPES_HXX +#define INCLUDED_FORMULA_TYPES_HXX + +#include + +namespace formula +{ +class FormulaToken; +typedef ::boost::intrusive_ptr FormulaTokenRef; +typedef ::boost::intrusive_ptr FormulaConstTokenRef; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/formula/vectortoken.hxx b/include/formula/vectortoken.hxx new file mode 100644 index 000000000..046d71faf --- /dev/null +++ b/include/formula/vectortoken.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_FORMULA_VECTORTOKEN_HXX +#define INCLUDED_FORMULA_VECTORTOKEN_HXX + +#include +#include + +#include +#include +#include + +namespace formula { + +/** + * Single unit of vector reference consists of two physical arrays. + * + *

    If the whole data array consists of only numeric values, mpStringArray + * will be NULL, and NaN values in the numeric array represent empty + * cells.

    + * + *

    If the whole data array consists of only string values, mpNumericArray + * will be NULL, and NULL values in the string array represent empty + * cells.

    + * + *

    If the data array consists of numeric and string values, then both + * mpNumericArray and mpStringArray will be non-NULL, and a string cell will + * be represented by a non-NULL pointer value in the string array. If the + * string value is NULL, check the corresponding value in the numeric array. + * If the value in the numeric array is NaN, it's an empty cell, otherwise + * it's a numeric cell.

    + */ +struct FORMULA_DLLPUBLIC VectorRefArray +{ + enum InitInvalid { Invalid }; + + const double* mpNumericArray; + rtl_uString** mpStringArray; + + bool mbValid; + + VectorRefArray(); + VectorRefArray( InitInvalid ); + VectorRefArray( const double* pArray ); + VectorRefArray( rtl_uString** pArray ); + VectorRefArray( const double* pNumArray, rtl_uString** pStrArray ); + + bool isValid() const; +}; + +/** + * This token represents a single cell reference in a vectorized formula + * calculation context. + */ +class FORMULA_DLLPUBLIC SingleVectorRefToken final : public FormulaToken +{ + VectorRefArray maArray; + size_t mnArrayLength; + +public: + SingleVectorRefToken( const VectorRefArray& rArray, size_t nArrayLength ); + + virtual FormulaToken* Clone() const override; + + const VectorRefArray& GetArray() const; + size_t GetArrayLength() const; +}; + +/** + * This token represents a range reference in a vectorized formula + * calculation context. + */ +class FORMULA_DLLPUBLIC DoubleVectorRefToken final : public FormulaToken +{ + std::vector maArrays; + + size_t mnArrayLength; /// length of all arrays which does not include trailing empty region. + size_t mnRefRowSize; /// original reference row size. The row size may + /// change as it goes down the array if either the + /// start or end position is fixed. + + bool mbStartFixed:1; /// whether or not the start row position is absolute. + bool mbEndFixed:1; /// whether or not the end row position is absolute. + +public: + DoubleVectorRefToken( + std::vector&& rArrays, size_t nArrayLength, + size_t nRefRowSize, bool bStartFixed, bool bEndFixed ); + + virtual FormulaToken* Clone() const override; + + const std::vector& GetArrays() const; + size_t GetArrayLength() const; + size_t GetRefRowSize() const; + bool IsStartFixed() const; + bool IsEndFixed() const; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/fpicker/fpsofficeResMgr.hxx b/include/fpicker/fpsofficeResMgr.hxx new file mode 100644 index 000000000..a86a91509 --- /dev/null +++ b/include/fpicker/fpsofficeResMgr.hxx @@ -0,0 +1,15 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#pragma once + +#include + +inline OUString FpsResId(TranslateId aId) { return Translate::get(aId, Translate::Create("fps")); }; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/fpicker/strings.hrc b/include/fpicker/strings.hrc new file mode 100644 index 000000000..efce3a69f --- /dev/null +++ b/include/fpicker/strings.hrc @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_FPICKER_FPICKER_HRC +#define INCLUDED_FPICKER_FPICKER_HRC + +#define NC_(Context, String) TranslateId(Context, reinterpret_cast(u8##String)) + +#define STR_SVT_FILEPICKER_AUTO_EXTENSION NC_("STR_SVT_FILEPICKER_AUTO_EXTENSION", "~Automatic file name extension") +#define STR_SVT_FILEPICKER_PASSWORD NC_("STR_SVT_FILEPICKER_PASSWORD", "Save with pass~word") +//dear loplugins, please don't remove this constant, it will be used in follow-up commits +#define STR_SVT_FILEPICKER_GPGENCRYPT NC_("STR_SVT_FILEPICKER_GPGENCRYPT", "Encrypt with ~GPG key") +#define STR_SVT_FILEPICKER_FILTER_OPTIONS NC_("STR_SVT_FILEPICKER_FILTER_OPTIONS", "~Edit filter settings") +#define STR_SVT_FILEPICKER_READONLY NC_("STR_SVT_FILEPICKER_READONLY", "~Read-only") +#define STR_SVT_FILEPICKER_INSERT_AS_LINK NC_("STR_SVT_FILEPICKER_INSERT_AS_LINK", "~Link") +#define STR_SVT_FILEPICKER_SHOW_PREVIEW NC_("STR_SVT_FILEPICKER_SHOW_PREVIEW", "Pr~eview") +#define STR_SVT_FILEPICKER_PLAY NC_("STR_SVT_FILEPICKER_PLAY", "~Play") +#define STR_SVT_FILEPICKER_VERSION NC_("STR_SVT_FILEPICKER_VERSION", "~Version:") +#define STR_SVT_FILEPICKER_TEMPLATES NC_("STR_SVT_FILEPICKER_TEMPLATES", "S~tyles:") +#define STR_SVT_FILEPICKER_IMAGE_TEMPLATE NC_("STR_SVT_FILEPICKER_IMAGE_TEMPLATE", "Style:") +#define STR_SVT_FILEPICKER_IMAGE_ANCHOR NC_("STR_SVT_FILEPICKER_IMAGE_ANCHOR", "A~nchor:") +#define STR_SVT_FILEPICKER_SELECTION NC_("STR_SVT_FILEPICKER_SELECTION", "~Selection") +#define STR_SVT_FILEPICKER_FILTER_TITLE NC_("STR_SVT_FILEPICKER_FILTER_TITLE", "File ~type:") +#define STR_SVT_FOLDERPICKER_DEFAULT_TITLE NC_("STR_SVT_FOLDERPICKER_DEFAULT_TITLE", "Select Path") +#define STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION NC_("STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION", "Please select a folder.") +#define STR_SVT_ALREADYEXISTOVERWRITE NC_("STR_SVT_ALREADYEXISTOVERWRITE", "A file named \"$filename$\" already exists.\n\nDo you want to replace it?") +#define STR_SVT_ALREADYEXISTOVERWRITE_SECONDARY NC_("STR_SVT_ALREADYEXISTOVERWRITE_SECONDARY", "The file already exists in \"$dirname$\". Replacing it will overwrite its contents.") +#define STR_SVT_ALLFORMATS NC_("STR_SVT_ALLFORMATS", "All Formats") +#define STR_SVT_DELETESERVICE NC_("STR_SVT_DELETESERVICE", "Are you sure you want to delete the service?\n\"$servicename$\"") +#define STR_SVT_ROOTLABEL NC_("STR_SVT_ROOTLABEL", "Root") +#define STR_FILTERNAME_ALL NC_("STR_FILTERNAME_ALL", "All files") +#define STR_FILEDLG_OPEN NC_("STR_FILEDLG_OPEN", "Open") +#define STR_FILEDLG_TYPE NC_("STR_FILEDLG_TYPE", "File ~type") +#define STR_FILEDLG_SAVE NC_("STR_FILEDLG_SAVE", "Save") + +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/ContextChangeEventMultiplexerTunnel.hxx b/include/framework/ContextChangeEventMultiplexerTunnel.hxx new file mode 100644 index 000000000..d2ff18bbe --- /dev/null +++ b/include/framework/ContextChangeEventMultiplexerTunnel.hxx @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include +#include + +#include + +namespace com::sun::star::ui { class XContextChangeEventListener; } +namespace com::sun::star::uno { class XInterface; } +namespace com::sun::star::uno { class XComponentContext; } + +namespace framework { + +// this is pretty horrible, don't use it! +FWK_DLLPUBLIC css::uno::Reference +GetFirstListenerWith( + css::uno::Reference const & xComponentContext, + css::uno::Reference const& xEventFocus, + std::function const&)> const& rPredicate); + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/actiontriggerhelper.hxx b/include/framework/actiontriggerhelper.hxx new file mode 100644 index 000000000..d0efa7a3a --- /dev/null +++ b/include/framework/actiontriggerhelper.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace com::sun::star::awt { class XPopupMenu; } +namespace com::sun::star::container { class XIndexContainer; } + +namespace framework +{ + class FWK_DLLPUBLIC ActionTriggerHelper + { + public: + // Fills the submitted menu with the structure contained in the second + // parameter rActionTriggerContainer + // @param pNewMenu = must be a valid and empty menu + // @param rActionTriggerContainer = must be an instance of service "com.sun.star.ui.ActionTriggerContainer" + static void + CreateMenuFromActionTriggerContainer( + const css::uno::Reference& rNewMenu, + const css::uno::Reference& rActionTriggerContainer); + + // Creates a "css::ui::ActionTriggerContainer" with the structure of the menu + // provided as a parameter. The implementation class stores the menu pointer + // to optimize the time of creation of a menu from an actiontrigger structure. + // IMPORTANT: The caller must ensure that the menu pointer is valid through the + // life time of the XIndexContainer object!!! + // @param rMenu = Must be a valid menu. Please be aware that this implementation is based on + // the above mentioned restriction!!! + + static css::uno::Reference< css::container::XIndexContainer > CreateActionTriggerContainerFromMenu( + const css::uno::Reference& rMenu, const OUString* pMenuIdentifier ); + + // Fills the submitted rActionTriggerContainer with the structure of the menu + // provided as the second parameter + // @param rActionTriggerContainer = must be an instance of service "com.sun.star.ui.ActionTriggerContainer" + // @param rMenu = must be a valid menu + static void + FillActionTriggerContainerFromMenu( + css::uno::Reference< css::container::XIndexContainer > const & rActionTriggerContainer, + const css::uno::Reference& rMenu); + + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/addonsoptions.hxx b/include/framework/addonsoptions.hxx new file mode 100644 index 000000000..0e97f7a24 --- /dev/null +++ b/include/framework/addonsoptions.hxx @@ -0,0 +1,264 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_FRAMEWORK_ADDONSOPTIONS_HXX +#define INCLUDED_FRAMEWORK_ADDONSOPTIONS_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace osl { class Mutex; } + +/*-************************************************************************************************************ + @descr The method GetAddonsMenu() returns a list of property values. + Use follow defines to separate values by names. +*//*-*************************************************************************************************************/ +inline constexpr OUStringLiteral ADDONSMENUITEM_STRING_URL = u"URL"; +inline constexpr OUStringLiteral ADDONSMENUITEM_STRING_TITLE = u"Title"; +inline constexpr OUStringLiteral ADDONSMENUITEM_STRING_TARGET = u"Target"; +inline constexpr OUStringLiteral ADDONSMENUITEM_STRING_IMAGEIDENTIFIER = u"ImageIdentifier"; +inline constexpr OUStringLiteral ADDONSMENUITEM_STRING_CONTEXT = u"Context"; +inline constexpr OUStringLiteral ADDONSMENUITEM_STRING_SUBMENU = u"Submenu"; + +inline constexpr OUStringLiteral ADDONSPOPUPMENU_URL_PREFIX_STR = u"private:menu/Addon"; + +namespace framework +{ + +struct FWK_DLLPUBLIC MergeMenuInstruction +{ + OUString aMergePoint; + OUString aMergeCommand; + OUString aMergeCommandParameter; + OUString aMergeFallback; + OUString aMergeContext; + css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aMergeMenu; +}; +typedef ::std::vector< MergeMenuInstruction > MergeMenuInstructionContainer; + +struct FWK_DLLPUBLIC MergeToolbarInstruction +{ + OUString aMergeToolbar; + OUString aMergePoint; + OUString aMergeCommand; + OUString aMergeCommandParameter; + OUString aMergeFallback; + OUString aMergeContext; + css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aMergeToolbarItems; +}; + +typedef ::std::vector< MergeToolbarInstruction > MergeToolbarInstructionContainer; + +struct FWK_DLLPUBLIC MergeNotebookBarInstruction +{ + OUString aMergeNotebookBar; + OUString aMergePoint; + OUString aMergeCommand; + OUString aMergeCommandParameter; + OUString aMergeFallback; + OUString aMergeContext; + css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aMergeNotebookBarItems; +}; + +typedef ::std::vector< MergeNotebookBarInstruction > MergeNotebookBarInstructionContainer; + +struct FWK_DLLPUBLIC MergeStatusbarInstruction +{ + OUString aMergePoint; + OUString aMergeCommand; + OUString aMergeCommandParameter; + OUString aMergeContext; + css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aMergeStatusbarItems; +}; + +typedef ::std::vector< MergeStatusbarInstruction > MergeStatusbarInstructionContainer; + +/*-************************************************************************************************************ + @short forward declaration to our private date container implementation + @descr We use these class as internal member to support small memory requirements. + You can create the container if it is necessary. The class which use these mechanism + is faster and smaller then a complete implementation! +*//*-*************************************************************************************************************/ + +class AddonsOptions_Impl; + +/*-************************************************************************************************************ + @short collect information about menu features + @devstatus ready to use +*//*-*************************************************************************************************************/ + +class UNLESS_MERGELIBS(FWK_DLLPUBLIC) AddonsOptions +{ + public: + AddonsOptions(); + ~AddonsOptions(); + + /*-**************************************************************************************************** + @short returns if an addons menu is available + @descr Call to retrieve if an addons menu is available + + @return true if there is a menu otherwise false + *//*-*****************************************************************************************************/ + + bool HasAddonsMenu() const; + + /*-**************************************************************************************************** + @short returns number of addons toolbars + @descr Call to retrieve the number of addons toolbars + + @return number of addons toolbars + *//*-*****************************************************************************************************/ + sal_Int32 GetAddonsToolBarCount() const ; + + /*-**************************************************************************************************** + @short returns number of addons notebookbar + @descr Call to retrieve the number of addons notebookbar + + @return number of addons notebookar + *//*-*****************************************************************************************************/ + sal_Int32 GetAddonsNotebookBarCount() const ; + + /*-**************************************************************************************************** + @short returns the complete addons menu + @descr Call it to get all entries of the addon menu. + We return a list of all nodes with its names and properties. + @return A list of menu items is returned. + + @onerror We return an empty list. + *//*-*****************************************************************************************************/ + + const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& GetAddonsMenu() const; + + /*-**************************************************************************************************** + @short Gets the menu bar part of all addon components registered + @return A complete + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + + const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& GetAddonsMenuBarPart() const; + + /*-**************************************************************************************************** + @short Gets a toolbar part of a single addon + @return A complete + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + + const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& GetAddonsToolBarPart( sal_uInt32 nIndex ) const; + + /*-**************************************************************************************************** + @short Gets a unique toolbar resource name of a single addon + @return A complete + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + + OUString GetAddonsToolbarResourceName( sal_uInt32 nIndex ) const; + + /*-**************************************************************************************************** + @short Gets a NotebookBar part of a single addon + @return A complete + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + + const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& GetAddonsNotebookBarPart( sal_uInt32 nIndex ) const; + + /*-**************************************************************************************************** + @short Gets a unique NotebookBar resource name of a single addon + @return A complete + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + + OUString GetAddonsNotebookBarResourceName( sal_uInt32 ) const; + + /*-**************************************************************************************************** + @short Retrieves all available merge instructions for the Office menu bar + @return The filled MergeMenuDefinitionContainer + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + + const MergeMenuInstructionContainer& GetMergeMenuInstructions() const; + + /*-**************************************************************************************************** + @short Retrieves all available merge instructions for a single toolbar + @return The filled + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + bool GetMergeToolbarInstructions( const OUString& rToolbarName, MergeToolbarInstructionContainer& rToolbar ) const; + + /*-**************************************************************************************************** + @short Retrieves all available merge instructions for Notebookbar + @return The filled + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + bool GetMergeNotebookBarInstructions( const OUString& rNotebookBarName, MergeNotebookBarInstructionContainer& rNotebookBar ) const; + + /*-**************************************************************************************************** + @short Gets the Add-On help menu part of all addon components registered + @return A complete + + @onerror We return sal_False + *//*-*****************************************************************************************************/ + const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& GetAddonsHelpMenu() const; + + const MergeStatusbarInstructionContainer& GetMergeStatusbarInstructions() const; + + /*-**************************************************************************************************** + @short Retrieve an image for a command URL which is defined inside the addon menu configuration + @descr Call it to retrieve an image for a command URL which is defined inside the addon menu configuration + @return An image which was defined in the configuration for the menu item. The image can be empty + no bitmap was defined for the request image properties. + + @onerror An empty image + *//*-*****************************************************************************************************/ + + BitmapEx GetImageFromURL( const OUString& aURL, bool bBig, bool bNoScale ) const; + BitmapEx GetImageFromURL( const OUString& aURL, bool bBig ) const; + + // private methods + + /*-**************************************************************************************************** + @short return a reference to a static mutex + @descr These class is partially threadsafe (for de-/initialization only). + All access methods aren't safe! + We create a static mutex only for one ime and use at different times. + @return A reference to a static mutex member. + *//*-*****************************************************************************************************/ + + static ::osl::Mutex& GetOwnStaticMutex(); + + private: + std::shared_ptr m_pImpl; +}; + +} + +#endif // INCLUDED_FRAMEWORK_ADDONSOPTIONS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/configimporter.hxx b/include/framework/configimporter.hxx new file mode 100644 index 000000000..eca312719 --- /dev/null +++ b/include/framework/configimporter.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_CONFIGIMPORTER_HXX +#define INCLUDED_FRAMEWORK_CONFIGIMPORTER_HXX + +#include +#include +#include + +namespace com::sun::star::container { class XIndexContainer; } +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::ui { class XUIConfigurationManager2; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { template class Reference; } + +namespace framework +{ + class UNLESS_MERGELIBS(FWK_DLLPUBLIC) UIConfigurationImporterOOo1x + { + public: + static bool ImportCustomToolbars( + const css::uno::Reference< css::ui::XUIConfigurationManager2 >& rContainerFactory, + std::vector< css::uno::Reference< css::container::XIndexContainer > >& rSeqContainer, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::embed::XStorage >& rToolbarStorage ); + }; + +} // namespace framework + +#endif // INCLUDED_FRAMEWORK_CONFIGIMPORTER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/desktop.hxx b/include/framework/desktop.hxx new file mode 100644 index 000000000..3d525eb54 --- /dev/null +++ b/include/framework/desktop.hxx @@ -0,0 +1,455 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +#include "framecontainer.hxx" +#include "fwkdllapi.h" +#include "transactionmanager.hxx" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace framework{ + +enum ELoadState +{ + E_NOTSET , + E_SUCCESSFUL , + E_FAILED , + E_INTERACTION +}; + +/*-************************************************************************************************************ + @short implement the topframe of frame tree + @descr This is the root of the frame tree. The desktop has no window, is not visible but he is the logical + "masternode" to build the hierarchy. + + @implements XInterface + XTypeProvider + XServiceInfo + XDesktop + XComponentLoader + XTasksSupplier + XDispatchProvider + XFramesSupplier + XFrame + XComponent + XPropertySet + XFastPropertySet + XMultiPropertySet + XDispatchResultListener + XEventListener + XInteractionHandler + + @devstatus ready to use + @threadsafe yes +*//*-*************************************************************************************************************/ +typedef cppu::WeakComponentImplHelper< + css::lang::XServiceInfo , + css::frame::XDesktop2 , + css::frame::XTasksSupplier , + css::frame::XDispatchResultListener , // => XEventListener + css::task::XInteractionHandler , + css::frame::XUntitledNumbers > Desktop_BASE; + +class FWK_DLLPUBLIC Desktop final : private cppu::BaseMutex, + public Desktop_BASE, + public cppu::OPropertySetHelper +{ + // internal used types, const etcpp. + private: + + /** used temporary to know which listener was already called or not. */ + typedef ::std::vector< css::uno::Reference< css::frame::XTerminateListener > > TTerminateListenerList; + + // public methods + public: + + // constructor / destructor + Desktop( css::uno::Reference< css::uno::XComponentContext > xContext ); + virtual ~Desktop( ) override; + + void constructorInit(); + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + + virtual sal_Bool SAL_CALL supportsService(OUString const & ServiceName) override; + + virtual css::uno::Sequence SAL_CALL getSupportedServiceNames() override; + + // XInterface + virtual void SAL_CALL acquire() noexcept override + { OWeakObject::acquire(); } + virtual void SAL_CALL release() noexcept override + { OWeakObject::release(); } + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& type) override; + + // XTypeProvider + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; + + /** + @interface XDesktop + + @short try to shutdown these desktop environment. + + @descr Will try to close all frames. If at least one frame could + not be closed successfully termination will be stopped. + + Registered termination listener will be taken into account + also. As special feature some of our registered listener + are well known by its UNO implementation name. They are handled + different to all other listener. + + Btw: Desktop.terminate() was designed in the past to be used + within an UI based environment. So it's allowed e.g. to + call XController.suspend() here. If UI isn't an option ... please + use XCloseable.close() at these desktop implementation. + ... if it will be supported in the future .-)) + + @seealso XTerminateListener + @seealso XTerminateListener2 + + @return true if all open frames could be closed and no listener threw + a veto exception; false otherwise. + + @onerror False will be returned. + @threadsafe yes + */ + virtual sal_Bool SAL_CALL terminate() override; + + /** + @interface XDesktop + + @short add a listener for termination events + + @descr Additional to adding normal listener these method was implemented special. + Every listener will be asked for its uno implementation name. + Some of them are well known... and the corresponding listener won't be added + to the container of "normal listener". Those listener will be set as special + member. + see e.g. member m_xSfxTerminator + + @seealso terminate() + + @param xListener + the listener for registration. + + @threadsafe yes + */ + virtual void SAL_CALL addTerminateListener( const css::uno::Reference< css::frame::XTerminateListener >& xListener ) override; + + /** + @interface XDesktop + + @short remove a listener from this container. + + @descr Additional to removing normal listener these method was implemented special. + Every listener will be asked for its uno implementation name. + Some of them are well known... and the corresponding listener was set as special member. + Now those special member will be reset also. + see e.g. member m_xSfxTerminator + + @seealso terminate() + + @param xListener + the listener for deregistration. + + @threadsafe yes + */ + virtual void SAL_CALL removeTerminateListener( const css::uno::Reference< css::frame::XTerminateListener >& xListener ) override; + + virtual css::uno::Reference< css::container::XEnumerationAccess > SAL_CALL getComponents ( ) override; + virtual css::uno::Reference< css::lang::XComponent > SAL_CALL getCurrentComponent ( ) override; + virtual css::uno::Reference< css::frame::XFrame > SAL_CALL getCurrentFrame ( ) override; + + // XComponentLoader + virtual css::uno::Reference< css::lang::XComponent > SAL_CALL loadComponentFromURL ( const OUString& sURL , + const OUString& sTargetFrameName , + sal_Int32 nSearchFlags , + const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) override; + + // XTasksSupplier + virtual css::uno::Reference< css::container::XEnumerationAccess > SAL_CALL getTasks ( ) override; + virtual css::uno::Reference< css::frame::XTask > SAL_CALL getActiveTask ( ) override; + + // XDispatchProvider + virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL queryDispatch ( const css::util::URL& aURL , + const OUString& sTargetFrameName , + sal_Int32 nSearchFlags ) override; + virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches ( const css::uno::Sequence< css::frame::DispatchDescriptor >& lQueries ) override; + + // XDispatchProviderInterception + virtual void SAL_CALL registerDispatchProviderInterceptor( const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor) override; + virtual void SAL_CALL releaseDispatchProviderInterceptor ( const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor) override; + + // XFramesSupplier + virtual css::uno::Reference< css::frame::XFrames > SAL_CALL getFrames ( ) override; + virtual css::uno::Reference< css::frame::XFrame > SAL_CALL getActiveFrame ( ) override; + virtual void SAL_CALL setActiveFrame ( const css::uno::Reference< css::frame::XFrame >& xFrame ) override; + + // XFrame + // Attention: findFrame() is implemented only! Other methods make no sense for our desktop! + virtual css::uno::Reference< css::frame::XFrame > SAL_CALL findFrame ( const OUString& sTargetFrameName , + sal_Int32 nSearchFlags ) override; + virtual void SAL_CALL initialize ( const css::uno::Reference< css::awt::XWindow >& xWindow ) override; + virtual css::uno::Reference< css::awt::XWindow > SAL_CALL getContainerWindow ( ) override; + virtual void SAL_CALL setCreator ( const css::uno::Reference< css::frame::XFramesSupplier >& xCreator ) override; + virtual css::uno::Reference< css::frame::XFramesSupplier > SAL_CALL getCreator ( ) override; + virtual OUString SAL_CALL getName ( ) override; + virtual void SAL_CALL setName ( const OUString& sName ) override; + virtual sal_Bool SAL_CALL isTop ( ) override; + virtual void SAL_CALL activate ( ) override; + virtual void SAL_CALL deactivate ( ) override; + virtual sal_Bool SAL_CALL isActive ( ) override; + virtual sal_Bool SAL_CALL setComponent ( const css::uno::Reference< css::awt::XWindow >& xComponentWindow , + const css::uno::Reference< css::frame::XController >& xController ) override; + virtual css::uno::Reference< css::awt::XWindow > SAL_CALL getComponentWindow ( ) override; + virtual css::uno::Reference< css::frame::XController > SAL_CALL getController ( ) override; + virtual void SAL_CALL contextChanged ( ) override; + virtual void SAL_CALL addFrameActionListener ( const css::uno::Reference< css::frame::XFrameActionListener >& xListener ) override; + virtual void SAL_CALL removeFrameActionListener ( const css::uno::Reference< css::frame::XFrameActionListener >& xListener ) override; + + // XComponent + virtual void SAL_CALL disposing() override; + virtual void SAL_CALL addEventListener ( const css::uno::Reference< css::lang::XEventListener >& xListener ) override; + virtual void SAL_CALL removeEventListener ( const css::uno::Reference< css::lang::XEventListener >& xListener ) override; + + // XDispatchResultListener + virtual void SAL_CALL dispatchFinished ( const css::frame::DispatchResultEvent& aEvent ) override; + + // XEventListener + virtual void SAL_CALL disposing ( const css::lang::EventObject& aSource ) override; + + // XInteractionHandler + virtual void SAL_CALL handle ( const css::uno::Reference< css::task::XInteractionRequest >& xRequest ) override; + + // css.frame.XUntitledNumbers + virtual ::sal_Int32 SAL_CALL leaseNumber( const css::uno::Reference< css::uno::XInterface >& xComponent ) override; + + // css.frame.XUntitledNumbers + virtual void SAL_CALL releaseNumber( ::sal_Int32 nNumber ) override; + + // css.frame.XUntitledNumbers + virtual void SAL_CALL releaseNumberForComponent( const css::uno::Reference< css::uno::XInterface >& xComponent ) override; + + // css.frame.XUntitledNumbers + virtual OUString SAL_CALL getUntitledPrefix() override; + + // we need this wrapped terminate()-call to terminate even the QuickStarter + // non-virtual and non-UNO for now + /// @throws css::uno::RuntimeException + bool terminateQuickstarterToo(); + + void shutdown(); + + private: + // OPropertySetHelper + virtual sal_Bool SAL_CALL convertFastPropertyValue ( css::uno::Any& aConvertedValue , + css::uno::Any& aOldValue , + sal_Int32 nHandle , + const css::uno::Any& aValue ) override; + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle , + const css::uno::Any& aValue ) override; + using cppu::OPropertySetHelper::getFastPropertyValue; + virtual void SAL_CALL getFastPropertyValue ( css::uno::Any& aValue , + sal_Int32 nHandle ) const override; + virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper ( ) override; + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo ( ) override; + + css::uno::Reference< css::lang::XComponent > impl_getFrameComponent ( const css::uno::Reference< css::frame::XFrame >& xFrame ) const; + + /** calls queryTermination() on every registered termination listener. + * + * Note: Only normal termination listener (registered in list m_aListenerContainer + * will be recognized here. Special listener like quick starter, pipe or others + * has to be handled explicitly ! + * + * @param [out] lCalledListener + * every called listener will be returned here. + * Those list will be used to inform all called listener + * about cancel this termination request. + * + * @return true if no one vetoed the termination. + * + * @see impl_sendCancelTerminationEvent() + */ + bool impl_sendQueryTerminationEvent(TTerminateListenerList& lCalledListener); + + /** calls cancelTermination() on every termination listener + * where queryTermination() was called before. + * + * Note: Only normal termination listener (registered in list m_aListenerContainer + * will be recognized here. Special listener like quick starter, pipe or others + * has to be handled explicitly ! + * + * @param [in] lCalledListener + * every listener in this list was called within its method + * queryTermination() before. + * + * @see impl_sendQueryTerminationEvent() + */ + void impl_sendCancelTerminationEvent(const TTerminateListenerList& lCalledListener); + + /** calls notifyTermination() on the clipboard listener + * + * The system clipboard may decide that it wants copies + * in several formats of the clipboard content requiring + * nearly all the services + * + */ + void impl_sendTerminateToClipboard(); + + /** calls notifyTermination() on every registered termination listener. + * + * Note: Only normal termination listener (registered in list m_aListenerContainer + * will be recognized here. Special listener like quick starter, pipe or others + * has to be handled explicitly ! + */ + void impl_sendNotifyTerminationEvent(); + + /** try to close all open frames. + * + * Iterates over all child frames and try to close them. + * Given parameter bAllowUI enable/disable showing any UI + * (which mostly occur on calling XController->suspend()). + * + * This method doesn't stop if one frame could not be closed. + * It will ignore such frames and try all other ones. + * But it returns false in such case - true otherwise. + * + * @param bAllowUI + * enable/disable showing of UI. + * + * @return true if all frames could be closed; false otherwise. + */ + bool impl_closeFrames(bool bAllowUI); + + private: + + mutable TransactionManager m_aTransactionManager; + + /** check flag to protect against multiple terminate runs + */ + bool m_bIsTerminated; + + /** check flag to protect us against dispose before terminate! + * see dispose() for further information! + */ + bool m_bIsShutdown; + + /** when true, the call came from session manager + * the method is Desktop::terminateQuickstarterToo() + * this the only one place where set this to true + * In this case, when one frame break, not make + * question for other, the break of shutdown or logout + * can be only once. + * In Desktop::impl_closeFrames would be test and break + * the loop and reset to false + */ + bool m_bSession; + + css::uno::Reference< css::uno::XComponentContext > m_xContext; /// reference to factory, which has create this instance + FrameContainer m_aChildTaskContainer; /// array of child tasks (children of desktop are tasks; and tasks are also frames - But pure frames are not accepted!) + comphelper::OMultiTypeInterfaceContainerHelper2 m_aListenerContainer; /// container for ALL Listener + css::uno::Reference< css::frame::XFrames > m_xFramesHelper; /// helper for XFrames, XIndexAccess, XElementAccess and implementation of a childcontainer! + css::uno::Reference< css::frame::XDispatchProvider > m_xDispatchHelper; /// helper to dispatch something for new tasks, created by "_blank"! + ELoadState m_eLoadState; /// hold information about state of asynchron loading of component for loadComponentFromURL()! + bool m_bSuspendQuickstartVeto; /// don't ask quickstart for a veto + std::unique_ptr m_xCommandOptions; /// ref counted class to support disabling commands defined by configuration file + OUString m_sName; + OUString m_sTitle; + css::uno::Reference< css::frame::XDispatchRecorderSupplier > m_xDispatchRecorderSupplier; + + /** special terminate listener to close pipe and block external requests + * during/after termination process is/was running + */ + css::uno::Reference< css::frame::XTerminateListener > m_xPipeTerminator; + + /** special terminate listener shown inside system tray (quick starter) + * Will hinder the office on shutdown ... but wish to allow closing + * of open documents. And because that's different to a normal terminate listener + * it has to be handled special .-) + */ + css::uno::Reference< css::frame::XTerminateListener > m_xQuickLauncher; + + /** special terminate listener which loads images asynchronous for current open documents. + * Because internally it uses blocking system APIs... it can't be guaranteed that + * running jobs can be cancelled successfully if the corresponding document will be closed... + * it will not hinder those documents on closing. Instead it let all jobs running... + * but at least on terminate we have to wait for all those blocked requests. + * So these implementation must be a special terminate listener too .-( + */ + css::uno::Reference< css::frame::XTerminateListener > m_xSWThreadManager; + + /** special terminate listener shutting down the SfxApplication. + * Because these desktop instance closes documents and informs listener + * only... it does not really shutdown the whole application. + * + * Btw: that wouldn't be possible by design... because Desktop.terminate() + * has to return a boolean value about success... it can't really shutdown the + * process .-) + * + * So we uses a trick: a special listener (exactly these one here) listen for notifyTermination() + * and shutdown the process asynchronous. But desktop has to make this special + * notification as really last one ... Otherwise it can happen that asynchronous + * shutdown will be faster then all other code around Desktop.terminate() .-)) + */ + css::uno::Reference< css::frame::XTerminateListener > m_xSfxTerminator; + + css::uno::Reference< css::frame::XUntitledNumbers > m_xTitleNumberGenerator; + + std::vector> m_xComponentDllListeners; + +}; // class Desktop + +FWK_DLLPUBLIC const rtl::Reference & getDesktop( + css::uno::Reference const & context); + +} // namespace framework + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/dispatchhelper.hxx b/include/framework/dispatchhelper.hxx new file mode 100644 index 000000000..399d3f0ec --- /dev/null +++ b/include/framework/dispatchhelper.hxx @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_INC_SERVICES_DISPATCHHELPER_HXX +#define INCLUDED_FRAMEWORK_INC_SERVICES_DISPATCHHELPER_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace com::sun::star::lang +{ +class XMultiServiceFactory; +} +namespace com::sun::star::lang +{ +class XSingleServiceFactory; +} +namespace com::sun::star::uno +{ +class XComponentContext; +} + +namespace framework +{ +/** + @short implements an easy way for dispatches + @descr Dispatches are split into different parts: + - parsing of the URL + - searching for a dispatch object + - dispatching of the URL + All these steps are done inside one method call here. +*/ +class UNLESS_MERGELIBS(FWK_DLLPUBLIC) DispatchHelper final + : public ::cppu::WeakImplHelper +{ + std::mutex m_mutex; + + /** global uno service manager. + Can be used to create own needed services. */ + css::uno::Reference m_xContext; + + /** used to wait for asynchronous listener callbacks. */ + std::condition_variable m_aBlock; + bool m_aBlockFlag; + + css::uno::Any m_aResult; + + css::uno::Reference m_xBroadcaster; + + // interface + +public: + // ctor/dtor + + DispatchHelper(css::uno::Reference xContext); + virtual ~DispatchHelper() override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService(const OUString& sServiceName) override; + virtual css::uno::Sequence SAL_CALL getSupportedServiceNames() override; + + // XDispatchHelper + virtual css::uno::Any SAL_CALL + executeDispatch(const css::uno::Reference& xDispatchProvider, + const OUString& sURL, const OUString& sTargetFrameName, sal_Int32 nSearchFlags, + const css::uno::Sequence& lArguments) override; + + // not a public XDispatchHelper-method, need in sfx2/source/control/statcach.cxx for extensions + /// @throws css::uno::RuntimeException + const css::uno::Any& + executeDispatch(const css::uno::Reference& xDispatch, + const css::util::URL& aURL, bool SyncronFlag, + const css::uno::Sequence& lArguments); + + // XDispatchResultListener + virtual void SAL_CALL dispatchFinished(const css::frame::DispatchResultEvent& aResult) override; + + // XEventListener + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) override; +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/documentundoguard.hxx b/include/framework/documentundoguard.hxx new file mode 100644 index 000000000..ec1a5951b --- /dev/null +++ b/include/framework/documentundoguard.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_DOCUMENTUNDOGUARD_HXX +#define INCLUDED_FRAMEWORK_DOCUMENTUNDOGUARD_HXX + +#include + +#include + +#include + +namespace com::sun::star::uno { class XInterface; } + +namespace framework +{ + //= DocumentUndoGuard + + struct DocumentUndoGuard_Data; + /** a helper class guarding the Undo manager of a document + + This class guards, within a given scope, the Undo Manager of a document (or another component supporting + the XUndoManagerSupplier interface). When entering the scope (i.e. when the DocumentUndoGuard + instances is constructed), the current state of the undo contexts of the undo manager is examined. + Upon leaving the scope (i.e. when the DocumentUndoGuard is destructed), the guard will execute + as many calls to XUndoManager::leaveUndoContext as are + necessary to restore the manager's initial state. + */ + class FWK_DLLPUBLIC DocumentUndoGuard + { + public: + DocumentUndoGuard( const css::uno::Reference< css::uno::XInterface >& i_undoSupplierComponent ); + ~DocumentUndoGuard(); + + private: + std::unique_ptr< DocumentUndoGuard_Data > m_xData; + }; + + +} // namespace framework + + +#endif // INCLUDED_FRAMEWORK_DOCUMENTUNDOGUARD_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/framecontainer.hxx b/include/framework/framecontainer.hxx new file mode 100644 index 000000000..1678a8670 --- /dev/null +++ b/include/framework/framecontainer.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + +#include +#include + +#include + +namespace framework{ + +typedef ::std::vector< css::uno::Reference< css::frame::XFrame > > TFrameContainer; + +/*-************************************************************************************************************ + @short implement a container to hold children of frame, task or desktop + @descr Every object of frame, task or desktop hold reference to its children. These container is used as helper + to do this. Some helper-classes like OFrames or OTasksAccess use it to. They hold a pointer to an instance + of this class, which is a member of a frame, task or desktop! You can append and remove frames. + It's possible to set one of these frames as active or deactivate. You could have full index-access to + container-items. + + @devstatus ready to use + @threadsafe yes +*//*-*************************************************************************************************************/ +class FrameContainer final +{ + + // member + + private: + + /// list to hold all frames + TFrameContainer m_aContainer; + /// one container item can be the current active frame. It's necessary for Desktop or Frame implementation. + css::uno::Reference< css::frame::XFrame > m_xActiveFrame; + + // interface + + public: + + /// constructor / destructor + FrameContainer(); + ~FrameContainer(); + + /// add/remove/mark container items + void append ( const css::uno::Reference< css::frame::XFrame >& xFrame ); + void remove ( const css::uno::Reference< css::frame::XFrame >& xFrame ); + void setActive ( const css::uno::Reference< css::frame::XFrame >& xFrame ); + css::uno::Reference< css::frame::XFrame > getActive ( ) const; + + /// checks and free memory + bool exist ( const css::uno::Reference< css::frame::XFrame >& xFrame ) const; + void clear ( ); + + /// deprecated IndexAccess! + sal_uInt32 getCount ( ) const; + css::uno::Reference< css::frame::XFrame > operator[]( sal_uInt32 nIndex ) const; + + /// replacement for deprecated index access + css::uno::Sequence< css::uno::Reference< css::frame::XFrame > > getAllElements() const; + + /// special helper for Frame::findFrame() + css::uno::Reference< css::frame::XFrame > searchOnAllChildrens ( const OUString& sName ) const; + css::uno::Reference< css::frame::XFrame > searchOnDirectChildrens( std::u16string_view sName ) const; + +}; // class FrameContainer + +} // namespace framework + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/framelistanalyzer.hxx b/include/framework/framelistanalyzer.hxx new file mode 100644 index 000000000..df47f90b2 --- /dev/null +++ b/include/framework/framelistanalyzer.hxx @@ -0,0 +1,204 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_FRAMELISTANALYZER_HXX +#define INCLUDED_FRAMEWORK_FRAMELISTANALYZER_HXX + +#include +#include +#include +#include + +#include + +namespace com::sun::star::frame { class XFrame; } +namespace com::sun::star::frame { class XFramesSupplier; } + +/** These enums can be combined as flags to enable/disable + special search algorithm during analyze phase. + see impl_analyze() for further information. + But note: To be usable as flags, these enums + must be values of range [2^n]! */ +enum class FrameAnalyzerFlags +{ + Model = 1, + Help = 2, + BackingComponent = 4, + Hidden = 8, + All = 15, + Zombie = 32768 // use it for special test scenarios only!!! +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + + +namespace framework{ + +/** analyze and split the current available frame list of a given frames supplier + into different parts. + + These analyzed information can be used e.g. to decide if it's necessary + to switch into the backing mode, close the current active frame only or + exit the whole application explicitly or implicitly. + */ +class UNLESS_MERGELIBS(FWK_DLLPUBLIC) FrameListAnalyzer final +{ + + // types + + public: + + // member + + public: + + /** provides access to the frame container, which should be analyzed. */ + const css::uno::Reference< css::frame::XFramesSupplier >& m_xSupplier; + + /** hold the reference frame, which is used e.g. to detect other frames with the same model. */ + const css::uno::Reference< css::frame::XFrame >& m_xReferenceFrame; + + /** enable/disable some special analyzing steps. + see impl_analyze() for further information. */ + FrameAnalyzerFlags m_eDetectMode; + + /** contains all frames, which uses the same model like the reference frame. + Will be filled only if m_eDetectMode has set the flag FrameAnalyzerFlags::Model. + The reference frame is never part of this list! */ + std::vector< css::uno::Reference< css::frame::XFrame > > m_lModelFrames; + + /** contains all frames, which does not contain the same model like the reference frame. + Filling of it can't be suppressed by m_eDetectMode. + The reference frame is never part of this list! + All frames inside this list are visible ones. */ + std::vector< css::uno::Reference< css::frame::XFrame > > m_lOtherVisibleFrames; + + /** contains all frames, which does not contain the same model like the reference frame. + Filling of it can't be suppressed by m_eDetectMode. + The reference frame is never part of this list! + All frames inside this list are hidden ones. */ + std::vector< css::uno::Reference< css::frame::XFrame > > m_lOtherHiddenFrames; + + /** points to the help frame. + Will be set only, if any other frame (means different from the reference frame) + contains the help component. If the reference frame itself includes the help module + it's not set ... but another member m_bIsHelp is used to safe this information. + See following example code: + + + if (m_xReferenceFrame == help) + { + m_xHelp = NULL; + m_bIsHelp = sal_True; + } + else + if (xOtherFrame == help) + { + m_xHelp = xOtherFrame; + m_bIsHelp = sal_False; + } + + + Analyzing of the help frame ignores the visible state of any frame. + But note: a hidden help frame indicates a wrong state! + */ + css::uno::Reference< css::frame::XFrame > m_xHelp; + + /** points to the frame, which contains the backing component. + Will be set only, if any other frame (means different from the reference frame) + contains the backing component. If the reference frame itself includes the + backing component it's not set ... but another member m_bIsBackingComponent + will used to safe this information. + See following example code: + + + if (m_xReferenceFrame == backing) + { + m_xBackingComponent = NULL; + m_bIsBackingComponent = sal_True; + } + else + if (xOtherFrame == backing) + { + m_xBackingComponent = xOtherFrame; + m_bIsBackingComponent = sal_False ; + } + + + Analyzing of the help frame ignores the visible state of any frame. + But note: a hidden backing mode frame indicates a wrong state! + */ + css::uno::Reference< css::frame::XFrame > m_xBackingComponent; + + /** is set to true only, if the reference frame is a hidden one. + This value is undefined if m_eDetectMode doesn't have set the flag FrameAnalyzerFlags::Hidden! */ + bool m_bReferenceIsHidden; + + /** is set to true only, if the reference frame contains the help component. + In this case the member m_xHelp is set to NULL every time. + This value is undefined if m_eDetectMode doesn't have set the flag FrameAnalyzerFlags::Help! */ + bool m_bReferenceIsHelp; + + /** is set to true only, if the reference frame contains the backing component. + In this case the member m_xBackingComponent is set to NULL every time. + This value is undefined if m_eDetectMode doesn't have set the flag FrameAnalyzerFlags::BackingComponent! */ + bool m_bReferenceIsBacking; + + + // interface + + public: + + /** starts analyze phase and fill all members with valid information. + + @param xSupplier + Must be a valid reference to a frames supplier, which provides + access to the frame list for analyzing. + + @param xReferenceFrame + This frame must(!) exist inside the analyzed frame list and + is used for some comparing functions. Further some member states + depends from the current state of this frame. + + @param eDetectMode + It represent a flag field, which can enable/disable special + analyze steps. Note: Some member values will be undefined, if + an analyze step will be disabled. + */ + FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , + const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , + FrameAnalyzerFlags eDetectMode ); + ~FrameListAnalyzer(); + + + // helper + + private: + + void impl_analyze(); + + +}; // class FrameListAnalyzer + +} // namespace framework + +#endif // INCLUDED_FRAMEWORK_FRAMELISTANALYZER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/fwkdllapi.h b/include/framework/fwkdllapi.h new file mode 100644 index 000000000..dc580c1bb --- /dev/null +++ b/include/framework/fwkdllapi.h @@ -0,0 +1,22 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include + +#if defined FWK_DLLIMPLEMENTATION +#define FWK_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define FWK_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/framework/gate.hxx b/include/framework/gate.hxx new file mode 100644 index 000000000..ab9f81c24 --- /dev/null +++ b/include/framework/gate.hxx @@ -0,0 +1,146 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +namespace framework{ + +/*-************************************************************************************************************ + @short implement a gate to block multiple threads at the same time or unblock all + @descr A gate can be used as a negative-condition! You can open a "door" - wait() will not block ... + or you can close it - wait() blocks till open() is called again. + Then all currently waiting threads are running immediately - but new ones are blocked! + + @attention To prevent us against wrong using, the default ctor, copy ctor and the =operator are marked private! + + @devstatus ready to use +*//*-*************************************************************************************************************/ +class Gate +{ + + // public methods + + public: + + /*-**************************************************************************************************** + @short ctor + @descr These initialize the object right as an open gate. + *//*-*****************************************************************************************************/ + Gate() + : m_bClosed ( false ) + { + open(); + } + + /*-**************************************************************************************************** + @short dtor + @descr Is user forget it - we open the gate ... + blocked threads can running ... but I don't know + if it's right - we are destroyed yet!? + *//*-*****************************************************************************************************/ + ~Gate() + { + open(); + } + /*-**************************************************************************************************** + @short copy-ctor + @descr Forbid copy construction + *//*-*****************************************************************************************************/ + Gate(const Gate&) = delete; + /*-**************************************************************************************************** + @short copy-assignment + @descr Forbid copy assigning + *//*-*****************************************************************************************************/ + Gate& operator=(const Gate&) = delete; + + /*-**************************************************************************************************** + @short open the gate + @descr A wait() call will not block then. + + @seealso method close() + *//*-*****************************************************************************************************/ + void open() + { + // We must safe access to our internal member! + std::unique_lock aLock( m_aAccessLock ); + // Set condition -> wait don't block any longer -> gate is open + m_aPassage.set(); + // Check if operation was successful! + // Check returns false if condition isn't set => m_bClosed will be true then => we must return false; opening failed + m_bClosed = !m_aPassage.check(); + } + + /*-**************************************************************************************************** + @short close the gate + @descr A wait() call will block then. + + @seealso method open() + *//*-*****************************************************************************************************/ + void close() + { + // We must safe access to our internal member! + std::unique_lock aLock( m_aAccessLock ); + // Reset condition -> wait blocks now -> gate is closed + m_aPassage.reset(); + // Check if operation was successful! + // Check returns false if condition was reset => m_bClosed will be true then => we can return true; closing ok + m_bClosed = !m_aPassage.check(); + } + + /*-**************************************************************************************************** + @short must be called to pass the gate + @descr If gate "open" => wait() will not block. + If gate "closed" => wait() will block till somewhere open it again. + + @seealso method wait() + @seealso method open() + + *//*-*****************************************************************************************************/ + void wait() + { + // We must safe access to our internal member! + std::unique_lock aLock( m_aAccessLock ); + // If gate not closed - caller can pass it. + if( m_bClosed ) + { + // Then we must release used access lock - + // because next call will block... + // and if we hold the access lock nobody else can use this object without a deadlock! + aLock.unlock(); + // Wait for opening gate... + m_aPassage.wait(); + } + } + + // private member + + private: + + std::mutex m_aAccessLock; + ::osl::Condition m_aPassage; + bool m_bClosed; + +}; // class Gate + +} // namespace framework + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/generictoolbarcontroller.hxx b/include/framework/generictoolbarcontroller.hxx new file mode 100644 index 000000000..e177ea5f0 --- /dev/null +++ b/include/framework/generictoolbarcontroller.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +class ToolBox; + +namespace framework +{ + +class FWK_DLLPUBLIC GenericToolbarController final : public svt::ToolboxController +{ + public: + GenericToolbarController( const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XFrame >& rFrame, + ToolBox* pToolBar, + ToolBoxItemId nID, + const OUString& aCommand ); + GenericToolbarController( const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XFrame >& rFrame, + weld::Toolbar& rToolBar, + const OUString& aCommand ); + virtual ~GenericToolbarController() override; + + // XComponent + virtual void SAL_CALL dispose() override; + + // XToolbarController + virtual void SAL_CALL execute( sal_Int16 KeyModifier ) override; + + // XStatusListener + virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& Event ) override; + + DECL_DLLPRIVATE_STATIC_LINK( GenericToolbarController, ExecuteHdl_Impl, void*, void ); + + struct ExecuteInfo + { + css::uno::Reference< css::frame::XDispatch > xDispatch; + css::util::URL aTargetURL; + css::uno::Sequence< css::beans::PropertyValue > aArgs; + }; + + private: + VclPtr m_xToolbar; + ToolBoxItemId m_nID; + bool m_bEnumCommand : 1, + m_bMadeInvisible : 1; + OUString m_aEnumCommand; +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/imutex.hxx b/include/framework/imutex.hxx new file mode 100644 index 000000000..4b4668f8e --- /dev/null +++ b/include/framework/imutex.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_IMUTEX_HXX +#define INCLUDED_FRAMEWORK_IMUTEX_HXX + +#include + +namespace framework{ + +/// Interface to support different mutex implementations in a generic way. +class SAL_NO_VTABLE IMutex +{ + public: + /// try to register thread + virtual void acquire() = 0; + /// unregister thread + virtual void release() = 0; + + protected: + ~IMutex() {} +}; +} + +#endif // INCLUDED_FRAMEWORK_IMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/interaction.hxx b/include/framework/interaction.hxx new file mode 100644 index 000000000..4700d1920 --- /dev/null +++ b/include/framework/interaction.hxx @@ -0,0 +1,105 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_INTERACTION_HXX +#define INCLUDED_FRAMEWORK_INTERACTION_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::task +{ +class XInteractionContinuation; +} +namespace com::sun::star::task +{ +class XInteractionRequest; +} +namespace com::sun::star::uno +{ +template class Sequence; +} + +namespace framework +{ +/*-************************************************************************************************************ + @short special request for interaction to ask user for right filter + @descr These helper can be used to ask user for right filter, if filter detection failed. + It capsulate communication with any interaction handler and supports an easy + access on interaction results for user of these class. + Use it and forget complex mechanism of interaction ... + + @example RequestFilterSelect* pRequest = new RequestFilterSelect; + Reference< XInteractionRequest > xRequest ( pRequest ); + xInteractionHandler->handle( xRequest ); + if( ! pRequest.isAbort() ) + { + OUString sFilter = pRequest->getFilter(); + } + + @implements XInteractionRequest + + @devstatus ready to use + @threadsafe no (used on once position only!) +*/ /*-*************************************************************************************************************/ +class RequestFilterSelect_Impl; +class UNLESS_MERGELIBS(FWK_DLLPUBLIC) RequestFilterSelect +{ + rtl::Reference mxImpl; + +public: + RequestFilterSelect(const OUString& sURL); + ~RequestFilterSelect(); + + RequestFilterSelect& operator=(RequestFilterSelect const&) = delete; // MSVC2019 workaround + RequestFilterSelect(RequestFilterSelect const&) = delete; // MSVC2019 workaround + + bool isAbort() const; + OUString getFilter() const; + css::uno::Reference GetRequest() const; +}; + +/*-************************************************************************************************************ + @short special request for interaction + @descr User must decide between a preselected and another detected filter. + It capsulate communication with any interaction handler and supports an easy + access on interaction results for user of these class. + + @implements XInteractionRequest + + @devstatus ready to use + @threadsafe no (used on once position only!) +*/ /*-*************************************************************************************************************/ +class FWK_DLLPUBLIC InteractionRequest +{ +public: + static css::uno::Reference CreateRequest( + const css::uno::Any& aRequest, + const css::uno::Sequence>& + lContinuations); +}; + +} // namespace framework + +#endif // #define INCLUDED_FRAMEWORK_INTERACTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/sfxhelperfunctions.hxx b/include/framework/sfxhelperfunctions.hxx new file mode 100644 index 000000000..36de22f54 --- /dev/null +++ b/include/framework/sfxhelperfunctions.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace com::sun::star::frame { class XFrame; class XToolbarController; } +namespace com::sun::star::uno { template class Reference; } +namespace svt { class StatusbarController; } +namespace svt { class ToolboxController; } + +class StatusBar; +class ToolBox; +namespace weld { + class Toolbar; + class Builder; +}; + +typedef rtl::Reference ( *pfunc_setToolBoxControllerCreator)( + const css::uno::Reference< css::frame::XFrame >& rFrame, + ToolBox* pToolbox, + ToolBoxItemId nID, + const OUString& aCommandURL ); + +typedef css::uno::Reference ( *pfunc_setWeldToolBoxControllerCreator)( + const css::uno::Reference< css::frame::XFrame >& rFrame, + weld::Toolbar* pToolbar, + weld::Builder* pBuilder, + const OUString& aCommandURL ); + +typedef rtl::Reference ( *pfunc_setStatusBarControllerCreator)( + const css::uno::Reference< css::frame::XFrame >& rFrame, + StatusBar* pStatusBar, + unsigned short nID, + const OUString& aCommandURL ); + +typedef void ( *pfunc_getRefreshToolbars)( + css::uno::Reference< css::frame::XFrame > const & rFrame ); + +typedef void ( *pfunc_createDockingWindow)( + const css::uno::Reference< css::frame::XFrame >& rFrame, + std::u16string_view rResourceURL ); + +typedef bool ( *pfunc_isDockingWindowVisible)( + const css::uno::Reference< css::frame::XFrame >& rFrame, + std::u16string_view rResourceURL ); + + +namespace framework +{ +FWK_DLLPUBLIC pfunc_setToolBoxControllerCreator SetToolBoxControllerCreator( pfunc_setToolBoxControllerCreator pSetToolBoxControllerCreator ); +FWK_DLLPUBLIC rtl::Reference CreateToolBoxController( + const css::uno::Reference< css::frame::XFrame >& rFrame, + ToolBox* pToolbox, + ToolBoxItemId nID, + const OUString& aCommandURL ); + +FWK_DLLPUBLIC pfunc_setWeldToolBoxControllerCreator SetWeldToolBoxControllerCreator( pfunc_setWeldToolBoxControllerCreator pSetToolBoxControllerCreator ); +FWK_DLLPUBLIC css::uno::Reference CreateWeldToolBoxController( + const css::uno::Reference< css::frame::XFrame >& rFrame, + weld::Toolbar* pToolbar, + weld::Builder* pBuilder, + const OUString& aCommandURL ); + +FWK_DLLPUBLIC pfunc_setStatusBarControllerCreator SetStatusBarControllerCreator( pfunc_setStatusBarControllerCreator pSetStatusBarControllerCreator ); +FWK_DLLPUBLIC rtl::Reference CreateStatusBarController( + const css::uno::Reference< css::frame::XFrame >& rFrame, + StatusBar* pStatusBar, + unsigned short nID, + const OUString& aCommandURL ); + +FWK_DLLPUBLIC pfunc_getRefreshToolbars SetRefreshToolbars( pfunc_getRefreshToolbars pRefreshToolbarsFunc ); +FWK_DLLPUBLIC void RefreshToolbars( + css::uno::Reference< css::frame::XFrame > const & rFrame ); + +FWK_DLLPUBLIC pfunc_createDockingWindow SetDockingWindowCreator( pfunc_createDockingWindow pCreateDockingWindow ); +FWK_DLLPUBLIC void CreateDockingWindow( + const css::uno::Reference< css::frame::XFrame >& rFrame, + std::u16string_view rResourceURL ); + +FWK_DLLPUBLIC pfunc_isDockingWindowVisible SetIsDockingWindowVisible( pfunc_isDockingWindowVisible pIsDockingWindowVisible ); +FWK_DLLPUBLIC bool IsDockingWindowVisible( + const css::uno::Reference< css::frame::XFrame >& rFrame, + std::u16string_view rResourceURL ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/titlehelper.hxx b/include/framework/titlehelper.hxx new file mode 100644 index 000000000..2b6e251d3 --- /dev/null +++ b/include/framework/titlehelper.hxx @@ -0,0 +1,181 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_TITLEHELPER_HXX +#define INCLUDED_FRAMEWORK_TITLEHELPER_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include + +namespace com::sun::star::frame { class XController; } +namespace com::sun::star::frame { class XFrame; } +namespace com::sun::star::frame { class XModel3; } +namespace com::sun::star::frame { class XUntitledNumbers; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { class XInterface; } + + +namespace framework{ + + +/** @short can be used as implementation helper of interface css.frame.XTitle + + @threadsafe + */ +class FWK_DLLPUBLIC TitleHelper final : private ::cppu::BaseMutex + , public ::cppu::WeakImplHelper< css::frame::XTitle , + css::frame::XTitleChangeBroadcaster, + css::frame::XTitleChangeListener , + css::frame::XFrameActionListener , + css::document::XDocumentEventListener > +{ + + // interface + public: + + + /** set an outside component which uses this container and must be set + as source of all broadcasted messages, exceptions. + + It's holded weak only so we do not need any complex dispose sessions. + + Note: Passing NULL as parameter will be allowed. It will reset the internal + member reference only. + + @param xOwner + the new owner of this collection. + @param xNumbers + provides the right string and number for an untitled component. + */ + TitleHelper(css::uno::Reference< css::uno::XComponentContext > xContext, + const css::uno::Reference< css::uno::XInterface >& xOwner, + const css::uno::Reference< css::frame::XUntitledNumbers >& xNumbers); + + /** @short free all internally used resources. + */ + virtual ~TitleHelper() override; + + + /** @see XTitle */ + virtual OUString SAL_CALL getTitle() override; + + + /** @see XTitle */ + virtual void SAL_CALL setTitle(const OUString& sTitle) override; + + + /** @see XTitleChangeBroadcaster */ + virtual void SAL_CALL addTitleChangeListener(const css::uno::Reference< css::frame::XTitleChangeListener >& xListener) override; + + + /** @see XTitleChangeBroadcaster */ + virtual void SAL_CALL removeTitleChangeListener(const css::uno::Reference< css::frame::XTitleChangeListener >& xListener) override; + + + /** @see XTitleChangeListener */ + virtual void SAL_CALL titleChanged(const css::frame::TitleChangedEvent& aEvent) override; + + + /** @see css.document.XDocumentEventListener */ + virtual void SAL_CALL documentEventOccured(const css::document::DocumentEvent& aEvent) override; + + + /** @see css.lang.XEventListener */ + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) override; + + + /** @see css.frame.XFrameActionListener */ + virtual void SAL_CALL frameAction(const css::frame::FrameActionEvent& aEvent) override; + + + // internal + private: + + void impl_sendTitleChangedEvent (); + + void impl_updateTitle (bool init = false); + void impl_updateTitleForModel (const css::uno::Reference< css::frame::XModel3 >& xModel, bool init); + void impl_updateTitleForController (const css::uno::Reference< css::frame::XController >& xController, bool init); + void impl_updateTitleForFrame (const css::uno::Reference< css::frame::XFrame >& xFrame, bool init); + + void impl_startListeningForModel (const css::uno::Reference< css::frame::XModel >& xModel); + void impl_startListeningForController (const css::uno::Reference< css::frame::XController >& xController); + void impl_startListeningForFrame (const css::uno::Reference< css::frame::XFrame >& xFrame); + void impl_updateListeningForFrame (const css::uno::Reference< css::frame::XFrame >& xFrame); + + void impl_appendComponentTitle ( OUStringBuffer& sTitle , + const css::uno::Reference< css::uno::XInterface >& xComponent); + void impl_appendProductName (OUStringBuffer& sTitle); + void impl_appendModuleName (OUStringBuffer& sTitle); + void impl_appendDebugVersion (OUStringBuffer& sTitle); + void impl_appendSafeMode (OUStringBuffer& sTitle); + + void impl_setSubTitle (const css::uno::Reference< css::frame::XTitle >& xSubTitle); + + OUString impl_convertURL2Title(std::u16string_view sURL); + + + // member + private: + + /** points to the global uno service manager. */ + css::uno::Reference< css::uno::XComponentContext> m_xContext; + + /** reference to the outside UNO class using this helper. */ + css::uno::WeakReference< css::uno::XInterface > m_xOwner; + + /** used to know how an "Untitled X" string can be created right :-) */ + css::uno::WeakReference< css::frame::XUntitledNumbers > m_xUntitledNumbers; + + /** provides parts of our own title and we listen there for changes too. */ + css::uno::WeakReference< css::frame::XTitle > m_xSubTitle; + + /** if it's set to sal_True the member m_sTitle has not to be changed internally. + It was set from outside and so outside code has to make sure it will be + updated. + */ + bool m_bExternalTitle; + + /** the actual title value */ + OUString m_sTitle; + + /** knows the leased number which must be used for untitled components. */ + ::sal_Int32 m_nLeasedNumber; + + /** contains all title change listener */ + comphelper::OMultiTypeInterfaceContainerHelper2 m_aListener; +}; + +} // namespace framework + +#endif // INCLUDED_FRAMEWORK_TITLEHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/transactionmanager.hxx b/include/framework/transactionmanager.hxx new file mode 100644 index 000000000..fe011968c --- /dev/null +++ b/include/framework/transactionmanager.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include "gate.hxx" + +namespace framework{ + +/*-************************************************************************************************************ + @descr Describe different states of a feature of following implementation. + During lifetime of an object different working states occur: + initialization - working - closing - closed + If you wish to implement thread safe classes you should use this feature to protect + your code against calls at wrong time. e.g. you are not full initialized but somewhere + call an interface method (initialize phase means startup time from creating object till + calling specified first method e.g. XInitialization::initialize()!) then you should refuse + this call. The same for closing/disposing the object! +*//*-*************************************************************************************************************/ +enum EWorkingMode +{ + E_INIT , // We stand in an init method -> some calls are accepted - some ones are rejected + E_WORK , // Object is ready for working -> all calls are accepted + E_BEFORECLOSE, // We stand in a close method -> some calls are accepted - some ones are rejected + E_CLOSE // Object is dead! -> all calls are rejected! +}; + +/*-************************************************************************************************************ + @descr A transaction object should support throwing exceptions if user used it at wrong working mode. + e.g. We can throw a DisposedException if user try to work and our mode is E_CLOSE! + But sometimes he doesn't need this feature - will handle it by himself. + Then we must differ between some exception-modi: + E_HARDEXCEPTIONS We throw exceptions for all working modes different from E_WORK! + E_SOFTEXCEPTIONS We throw exceptions for all working modes different from E_WORK AND E_INCLOSE! + This mode is useful for impl-methods which should be callable from dispose() method! + + e.g. void dispose() + { + m_aTransactionManager.setWorkingMode( E_BEFORECLOSE ); + ... + impl_setA( 0 ); + ... + m_aTransactionManager.setWorkingMode( E_CLOSE ); + } + + void impl_setA( int nA ) + { + ERejectReason EReason; + TransactionGuard aTransactionGuard( m_aTransactionManager, E_SOFTEXCEPTIONS, eReason ); + + m_nA = nA; + } + + Normally (if E_HARDEXCEPTIONS was used!) creation of guard + will throw an exception ... but using of E_SOFTEXCEPTIONS suppress it + and member "A" can be set. +*//*-*************************************************************************************************************/ +enum EExceptionMode +{ + E_HARDEXCEPTIONS, + E_SOFTEXCEPTIONS +}; + +/*-************************************************************************************************************ + @short implement a transaction manager to support non breakable interface methods + @descr Use it to support non breakable interface methods without using any thread + synchronization like e.g. mutex, rw-lock! + That protect your code against wrong calls at wrong time ... e.g. calls after disposing an object! + Use combination of EExceptionMode and ERejectReason to detect rejected requests + and react for it. You can enable automatically throwing of exceptions too. + + @devstatus draft +*//*-*************************************************************************************************************/ +class TransactionManager +{ + + // public methods + + public: + + TransactionManager ( ); + ~TransactionManager ( ); + TransactionManager(const TransactionManager&) = delete; + TransactionManager& operator=(const TransactionManager&) = delete; + void setWorkingMode ( EWorkingMode eMode ); + EWorkingMode getWorkingMode ( ) const; + /// @throws css::uno::RuntimeException + /// @throws css::lang::DisposedException + void registerTransaction ( EExceptionMode eMode ); + /// @throws css::uno::RuntimeException + /// @throws css::lang::DisposedException + void unregisterTransaction ( ); + + private: + + mutable std::mutex m_aAccessLock; /// regulate access on internal member of this instance + Gate m_aBarrier; /// used to block transactions requests during change or work mode + EWorkingMode m_eWorkingMode; /// current working mode of object which use this manager (used to reject calls at wrong time) + sal_Int32 m_nTransactionCount; /// every transaction request is registered by this counter + +}; // class TransactionManager + +} // namespace framework + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/framework/undomanagerhelper.hxx b/include/framework/undomanagerhelper.hxx new file mode 100644 index 000000000..eb9986919 --- /dev/null +++ b/include/framework/undomanagerhelper.hxx @@ -0,0 +1,162 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_FRAMEWORK_UNDOMANAGERHELPER_HXX +#define INCLUDED_FRAMEWORK_UNDOMANAGERHELPER_HXX + +#include +#include +#include + +#include + +namespace com::sun::star::document { class XUndoAction; } +namespace com::sun::star::document { class XUndoManager; } +namespace com::sun::star::document { class XUndoManagerListener; } +namespace com::sun::star::util { class XModifyListener; } +namespace framework { class IMutex; } + +class SfxUndoManager; + + +namespace framework +{ + + + //= IMutexGuard + + class SAL_NO_VTABLE IMutexGuard + { + public: + /** clears the lock. If the guard does not currently hold the lock, nothing happens. + */ + virtual void clear() = 0; + + /** returns the mutex guarded by the instance. + + Even if the guard currently has not a lock on the mutex, this method must succeed. + */ + virtual IMutex& getGuardedMutex() = 0; + + protected: + ~IMutexGuard() {} + }; + + + //= IUndoManagerImplementation + + class SAL_NO_VTABLE IUndoManagerImplementation + { + public: + /** returns the SfxUndoManager interface to the actual Undo stack + + @throws css::lang::DisposedException + when the instance is already disposed, and no SfxUndoManager can be provided + + @throws css::lang::NotInitializedException + when the instance is not initialized, yet, and no SfxUndoManager can be provided + */ + virtual SfxUndoManager& getImplUndoManager() = 0; + + /** provides access to a UNO interface for the XUndoManager implementation. Used when throwing exceptions. + */ + virtual css::uno::Reference< css::document::XUndoManager > + getThis() = 0; + + protected: + ~IUndoManagerImplementation() {} + }; + + + //= UndoManagerHelper + + class UndoManagerHelper_Impl; + /** helper class for implementing an XUndoManager + + Several of the methods of the class take an IMutexGuard instance. It is assumed that this guard has a lock on + its mutex at the moment the method is entered. The lock will be released before any notifications to the + registered XUndoManagerListeners happen. + + The following locking strategy is used for this mutex: +
    • Any notifications to the registered XUndoManagerListeners are after the guard has been cleared. i.e. + without the mutex being locked.

      +
    • Any calls into the SfxUndoManager implementation is made without the mutex being locked. + Note that this implies that the SfxUndoManager implementation must be thread-safe in itself + (which is true for the default implementation, SfxUndoManager).
    • +
    • An exception to the previous item are the SfxUndoManager::Undo and + SfxUndoManager::Redo methods: They're called with the given external mutex being + locked.
    • +
    + + The reason for the exception for SfxUndoManager::Undo and SfxUndoManager::Redo is that those are expected to + modify the actual document which the UndoManager works for. And as long as our documents are not thread-safe, + and as long as we do not re-fit all existing SfxUndoImplementations to not expect + the dreaded SolarMutex being locked when they're called, the above behavior is a compromise between "how it should + be" and "how it can realistically be". + */ + class FWK_DLLPUBLIC UndoManagerHelper + { + public: + UndoManagerHelper( IUndoManagerImplementation& i_undoManagerImpl ); + ~UndoManagerHelper(); + + // life time control + void disposing(); + + // XUndoManager equivalents + void enterUndoContext( const OUString& i_title, IMutexGuard& i_instanceLock ); + void enterHiddenUndoContext( IMutexGuard& i_instanceLock ); + void leaveUndoContext( IMutexGuard& i_instanceLock ); + void addUndoAction( const css::uno::Reference< css::document::XUndoAction >& i_action, IMutexGuard& i_instanceLock ); + void undo( IMutexGuard& i_instanceLock ); + void redo( IMutexGuard& i_instanceLock ); + bool isUndoPossible() const; + bool isRedoPossible() const; + OUString getCurrentUndoActionTitle() const; + OUString getCurrentRedoActionTitle() const; + css::uno::Sequence< OUString > + getAllUndoActionTitles() const; + css::uno::Sequence< OUString > + getAllRedoActionTitles() const; + void clear( IMutexGuard& i_instanceLock ); + void clearRedo( IMutexGuard& i_instanceLock ); + void reset( IMutexGuard& i_instanceLock ); + void addUndoManagerListener( const css::uno::Reference< css::document::XUndoManagerListener >& i_listener ); + void removeUndoManagerListener( const css::uno::Reference< css::document::XUndoManagerListener >& i_listener ); + + // XLockable, base of XUndoManager, equivalents + void lock(); + void unlock(); + bool isLocked(); + + // XModifyBroadcaster equivalents + void addModifyListener( const css::uno::Reference< css::util::XModifyListener >& i_listener ); + void removeModifyListener( const css::uno::Reference< css::util::XModifyListener >& i_listener ); + + private: + std::unique_ptr< UndoManagerHelper_Impl > m_xImpl; + }; + + +} // namespace framework + + +#endif // INCLUDED_FRAMEWORK_UNDOMANAGERHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/helpcompiler/HelpIndexer.hxx b/include/helpcompiler/HelpIndexer.hxx new file mode 100644 index 000000000..2f8e7f322 --- /dev/null +++ b/include/helpcompiler/HelpIndexer.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_HELPCOMPILER_HELPINDEXER_HXX +#define INCLUDED_HELPCOMPILER_HELPINDEXER_HXX + +#include + +#include +#include +#include + +// I assume that TCHAR is defined as wchar_t throughout + +namespace lucene +{ +namespace document +{ +class Document; +} +namespace util +{ +class Reader; +} +} + +class L10N_DLLPUBLIC HelpIndexer { + private: + OUString d_lang; + OUString d_module; + OUString d_captionDir; + OUString d_contentDir; + OUString d_indexDir; + OUString d_error; + std::set d_files; + + public: + + /** + * @param lang Help files language. + * @param module The module of the helpfiles. + * @param srcDir The help directory to index + * @param outDir The directory to write the "module".idxl directory to + */ + HelpIndexer(OUString const &lang, OUString const &module, + std::u16string_view srcDir, std::u16string_view outDir); + + /** + * Run the indexer. + * @return true if index successfully generated. + */ + bool indexDocuments(); + + /** + * Get the error string (empty if no error occurred). + */ + OUString const & getErrorMessage() const { return d_error;} + + private: + + /** + * Scan the caption & contents directories for help files. + */ + bool scanForFiles(); + + /** + * Scan for files in the given directory. + */ + bool scanForFiles(OUString const &path); + + /** + * Fill the Document with information on the given help file. + */ + void helpDocument(OUString const & fileName, lucene::document::Document *doc) const; + + /** + * Create a reader for the given file, and create an "empty" reader in case the file doesn't exist. + */ + static lucene::util::Reader *helpFileReader(OUString const & path); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/helpcompiler/HelpSearch.hxx b/include/helpcompiler/HelpSearch.hxx new file mode 100644 index 000000000..074373c43 --- /dev/null +++ b/include/helpcompiler/HelpSearch.hxx @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_HELPCOMPILER_HELPSEARCH_HXX +#define INCLUDED_HELPCOMPILER_HELPSEARCH_HXX + +#include + +#include +#include + +class L10N_DLLPUBLIC HelpSearch{ + private: + OString d_indexDir; + + public: + + /** + * @param indexDir The directory where the index files are stored. + */ + HelpSearch(OUString const &indexDir); + + /** + * Query the index for a certain query string. + * @param queryStr The query. + * @param captionOnly Set to true to search in the caption, not the content. + * @param rDocuments Vector to write the paths of the found documents. + * @param rScores Vector to write the scores to. + */ + void query(OUString const &queryStr, bool captionOnly, + std::vector &rDocuments, std::vector &rScores); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/helpcompiler/compilehelp.hxx b/include/helpcompiler/compilehelp.hxx new file mode 100644 index 000000000..8944257bd --- /dev/null +++ b/include/helpcompiler/compilehelp.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_HELPCOMPILER_COMPILEHELP_HXX +#define INCLUDED_HELPCOMPILER_COMPILEHELP_HXX + +#include + +#include + +#include + +#if defined(HELPLINKER_DLLIMPLEMENTATION) +#define HELPLINKER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define HELPLINKER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define HELPLINKER_DLLPRIVATE SAL_DLLPRIVATE + +#include + +enum class HelpProcessingErrorClass +{ + NONE, + General, // Missing files, options etc. + XmlParsing // Errors thrown by libxml +}; + +struct HelpProcessingErrorInfo +{ + HelpProcessingErrorClass m_eErrorClass; + OUString m_aErrorMsg; + OUString m_aXMLParsingFile; + sal_Int32 m_nXMLParsingLine; + + HelpProcessingErrorInfo() + : m_eErrorClass( HelpProcessingErrorClass::NONE ) + , 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 OUString& aOfficeHelpPath, + std::u16string_view aExtensionName, + std::u16string_view aExtensionLanguageRoot, + sal_Int32 nXhpFileCount, const OUString* pXhpFiles, + std::u16string_view aDestination, + HelpProcessingErrorInfo& o_rHelpProcessingErrorInfo +); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/helpcompiler/dllapi.h b/include/helpcompiler/dllapi.h new file mode 100644 index 000000000..e0a115d05 --- /dev/null +++ b/include/helpcompiler/dllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_HELPCOMPILER_DLLAPI_H +#define INCLUDED_HELPCOMPILER_DLLAPI_H + +#include +#include + +#if defined L10N_DLLIMPLEMENTATION +#define L10N_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define L10N_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nlangtag/applelangid.hxx b/include/i18nlangtag/applelangid.hxx new file mode 100644 index 000000000..0733d9207 --- /dev/null +++ b/include/i18nlangtag/applelangid.hxx @@ -0,0 +1,145 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +//as seen at http://www.microsoft.com/typography/otspec/name.htm + +#ifndef INCLUDED_I18NLANGTAG_APPLELANGID_H +#define INCLUDED_I18NLANGTAG_APPLELANGID_H + +#include + +enum class AppleLanguageId : unsigned short +{ + ENGLISH =0, + FRENCH =1, + GERMAN =2, + ITALIAN =3, + DUTCH =4, + SWEDISH =5, + SPANISH =6, + DANISH =7, + PORTUGUESE =8, + NORWEGIAN =9, + HEBREW =10, + JAPANESE =11, + ARABIC =12, + FINNISH =13, + GREEK =14, + ICELANDIC =15, + MALTESE =16, + TURKISH =17, + CROATIAN =18, + CHINESE_TRADITIONAL =19, + URDU =20, + HINDI =21, + THAI =22, + KOREAN =23, + LITHUANIAN =24, + POLISH =25, + HUNGARIAN =26, + ESTONIAN =27, + LATVIAN =28, + SAMI =29, + FAROESE =30, + FARSI =31, + RUSSIAN =32, + CHINESE_SIMPLIFIED =33, + FLEMISH =34, + IRISH_GAELIC =35, + ALBANIAN =36, + ROMANIAN =37, + CZECH =38, + SLOVAK =39, + SLOVENIAN =40, + YIDDISH =41, + SERBIAN =42, + MACEDONIAN =43, + BULGARIAN =44, + UKRAINIAN =45, + BYELORUSSIAN =46, + UZBEK =47, + KAZAKH =48, + AZERI_CYRILLIC =49, + AZERI_ARABIC =50, + ARMENIAN =51, + GEORGIAN =52, + MOLDAVIAN =53, + KIRGHIZ =54, + TAJIKI =55, + TURKMEN =56, + MONGOLIAN_MONGOLIAN =57, + MONGOLIAN_CYRILLIC =58, + PASHTO =59, + KURDISH =60, + KASHMIRI =61, + SINDHI =62, + TIBETAN =63, + NEPALI =64, + SANSKRIT =65, + MARATHI =66, + BENGALI =67, + ASSAMESE =68, + GUJARATI =69, + PUNJABI =70, + ORIYA =71, + MALAYALAM =72, + KANNADA =73, + TAMIL =74, + TELUGU =75, + SINHALESE =76, + BURMESE =77, + KHMER =78, + LAO =79, + VIETNAMESE =80, + INDONESIAN =81, + TAGALONG =82, + MALAY_LATIN =83, + MALAY_ARABIC =84, + AMHARIC =85, + TIGRINYA =86, + GALLA =87, + SOMALI =88, + SWAHILI =89, + KINYARWANDA =90, + RUNDI =91, + NYANJA =92, + MALAGASY =93, + ESPERANTO =94, + WELSH =128, + BASQUE =129, + CATALAN =130, + LATIN =131, + QUENCHUA =132, + GUARANI =133, + AYMARA =134, + TATAR =135, + UIGHUR =136, + DZONGKHA =137, + JAVANESE_LATIN =138, + SUNDANESE_LATIN =139, + GALICIAN =140, + AFRIKAANS =141, + BRETON =142, + INUKTITUT =143, + SCOTTISH_GAELIC =144, + MANX_GAELIC =145, + IRISH_GAELIC_WITH_DOT_ABOVE =146, + TONGAN =147, + GREEK_POLYTONIC =148, + GREENLANDIC =149, + AZERI_LATIN =150, +}; + +/** Init LanguageTag with Apple LanguageId */ +I18NLANGTAG_DLLPUBLIC LanguageTag makeLanguageTagFromAppleLanguageId(AppleLanguageId nLanguage); + + +#endif /* INCLUDED_I18NLANGTAG_APPLELANGID_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nlangtag/i18nlangtagdllapi.h b/include/i18nlangtag/i18nlangtagdllapi.h new file mode 100644 index 000000000..4222c0e95 --- /dev/null +++ b/include/i18nlangtag/i18nlangtagdllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_I18NLANGTAG_I18NLANGTAGDLLAPI_H +#define INCLUDED_I18NLANGTAG_I18NLANGTAGDLLAPI_H + +#include + +#if defined(I18NLANGTAG_DLLIMPLEMENTATION) +#define I18NLANGTAG_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define I18NLANGTAG_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define I18NLANGTAG_DLLPRIVATE SAL_DLLPRIVATE + +#endif /* INCLUDED_I18NLANGTAG_I18NLANGTAGDLLAPI_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nlangtag/lang.h b/include/i18nlangtag/lang.h new file mode 100644 index 000000000..0e4c6d23a --- /dev/null +++ b/include/i18nlangtag/lang.h @@ -0,0 +1,803 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_I18NLANGTAG_LANG_H +#define INCLUDED_I18NLANGTAG_LANG_H + +/** + These are MS LANGIDs, the lower 10 bits (mask 0x03ff, values below 0x0400 + aren't real locale IDs) represent the primary language ID, the upper 6 bits + represent the sublanguage ID, which in most cases together with the primary + language simply designates a country. A LANGID is constructed by + UINT16 nLangID = ((((UINT16)(SubLangId)) << 10) | (UINT16)(PriLangId)); + + A user-defined primary language ID is a value in the range 0x0200 to 0x03ff. + All other values are reserved for Windows system use. + + A user-defined sublanguage identifier is a value in the range 0x20 to 0x3f. + All other values are reserved for Windows system use. + If there is no sublanguage ID for a primary language ID, use SUBLANG_DEFAULT + (0x01, which shifted to the left by 10 bits results in the frequently seen + 0x0400). OR'ed with a 0x0200 primary results in 0x0600. + + Values added as of 2006-04-18, a helper script: ../../source/isolang/lcid.awk + Utility to compare MS-LANGID definitions with those defined in this file. + + For further information about MS-LANGIDs please see include/winnt.h of a + recent MSDEV version and the following web pages. + + + The once complete list, not necessarily supported by Windows: + List of Locale ID (LCID) Values as Assigned by Microsoft + http://www.microsoft.com/globaldev/reference/lcid-all.mspx + + As a complete list is never complete, some more that came with WinXP SP2: + Windows XP/Server 2003 - List of Locale IDs, Input Locale, and Language Collection + http://www.microsoft.com/globaldev/reference/winxp/xp-lcid.mspx + + And of course 2 lists aren't enough, so Windows Vista needs an extra one. + Which at least seems to include values of other versions of Windows. + Language Identifier Constants and Strings + http://msdn.microsoft.com/en-us/library/ms776294.aspx + + ! Hey, yet another list, maybe this one will not move around? It seems to be + ! quite complete... + ! Language Identifier Constants and Strings (Windows) + ! http://msdn.microsoft.com/en-us/library/dd318693.aspx + ! + ! Use THAT ^^^ as of 2013-09-17 it includes also Windows 8 + + ! BUT, you can download a PDF document from + ! http://msdn.microsoft.com/library/cc233965.aspx + ! that has YET MORE definitions, sigh... didn't cross-check if any are missing + ! from that... however, it also contains a few MS-reserved definitions that use + ! ISO 639-3 codes reserved for local use, such as 'qps-ploc' and 'qps-ploca' + ! (sic!), or strange things like 'ar-Ploc-SA' and 'ja-Ploc-JP' ('Ploc'??). + ! + ! Use THAT ^^^ as the ultimate reference source (haha?) as of 2013-10-17 it + ! includes also Windows 8.1 (Release: Monday, July 22, 2013; well, its table + ! says 08/08/2013 Revision 6.0, but hey, who cares...) + + For completeness, you can never have enough lists: + List of supported locale identifiers in Word + Applies to Microsoft Word 2000 and 2002 + http://support.microsoft.com/default.aspx?scid=KB;en-us;q221435 + */ + +#include +#include +#include + +typedef o3tl::strong_int LanguageType; +inline std::ostream& operator<<(std::ostream& os, LanguageType const & lt) { os << sal_uInt16(lt); return os; } +constexpr LanguageType primary(LanguageType lt) { return LanguageType(sal_uInt16(lt) & 0x03ff); } + +namespace o3tl +{ + // delete "sal_Int16" constructor via specialization: values > 0x7FFF are + // actually used, and unfortunately passed around in the API as signed + // "short", so use this to find all places where casts must be inserted + template<> template<> constexpr strong_int::strong_int(short, std::enable_if::value, int>::type) = delete; +} + +#define LANGUAGE_MASK_PRIMARY 0x03ff + +#define LANGUAGE_DONTKNOW LanguageType(0x03FF) /* yes, the mask */ +#define LANGUAGE_NONE LanguageType(0x00FF) +#define LANGUAGE_HID_HUMAN_INTERFACE_DEVICE LanguageType(0x04FF) +#define LANGUAGE_SYSTEM LanguageType(0x0000) /* OOo/SO definition */ + +/* The Invariant Locale (Locale ID = 0x007f) is a locale that can be used by + * applications when a consistent and locale-independent result is required. + * The invariant locale can be used, for example, when comparing character + * strings using the CompareString() API and a consistent result regardless of + * the User Locale is expected. + * The settings of the Invariant Locale are similar to US-English international + * standards, but should not be used to display formatted data. */ +/* NOTE: this is taken from the MS documentation! Not supported by OOo/SO! */ +#define LANGUAGE_INVARIANT LanguageType(0x007F) + +/* Naming conventions: + * * ..._LSO suffix indicates a Language-Script-Only mapping, i.e. no country + * assignment in i18nlangtag/source/isolang/isolang.cxx. + * Used for backward compatibility or where MS assigned such values and they + * should be explicitly handled. + * * LANGUAGE_USER_... for our user-defined IDs. + * * LANGUAGE_OBSOLETE_USER_... for a user-defined ID that has been replaced by + * a value defined by MS. + */ + +#define LANGUAGE_AFRIKAANS LanguageType(0x0436) +#define LANGUAGE_ALBANIAN LanguageType(0x041C) +#define LANGUAGE_ALSATIAN_FRANCE LanguageType(0x0484) +#define LANGUAGE_AMHARIC_ETHIOPIA LanguageType(0x045E) +#define LANGUAGE_ARABIC_ALGERIA LanguageType(0x1401) +#define LANGUAGE_ARABIC_BAHRAIN LanguageType(0x3C01) +#define LANGUAGE_ARABIC_EGYPT LanguageType(0x0C01) +#define LANGUAGE_ARABIC_IRAQ LanguageType(0x0801) +#define LANGUAGE_ARABIC_JORDAN LanguageType(0x2C01) +#define LANGUAGE_ARABIC_KUWAIT LanguageType(0x3401) +#define LANGUAGE_ARABIC_LEBANON LanguageType(0x3001) +#define LANGUAGE_ARABIC_LIBYA LanguageType(0x1001) +#define LANGUAGE_ARABIC_MOROCCO LanguageType(0x1801) +#define LANGUAGE_ARABIC_OMAN LanguageType(0x2001) +#define LANGUAGE_ARABIC_PRIMARY_ONLY LanguageType(0x0001) /* primary only, not a locale! */ +#define LANGUAGE_ARABIC_QATAR LanguageType(0x4001) +#define LANGUAGE_ARABIC_SAUDI_ARABIA LanguageType(0x0401) +#define LANGUAGE_ARABIC_SYRIA LanguageType(0x2801) +#define LANGUAGE_ARABIC_TUNISIA LanguageType(0x1C01) +#define LANGUAGE_ARABIC_UAE LanguageType(0x3801) +#define LANGUAGE_ARABIC_YEMEN LanguageType(0x2401) +#define LANGUAGE_ARMENIAN LanguageType(0x042B) /* Eastern Armenian */ +#define LANGUAGE_ASSAMESE LanguageType(0x044D) +#define LANGUAGE_AZERI_CYRILLIC LanguageType(0x082C) +#define LANGUAGE_AZERI_CYRILLIC_LSO LanguageType(0x742C) +#define LANGUAGE_AZERI_LATIN LanguageType(0x042C) +#define LANGUAGE_AZERI_LATIN_LSO LanguageType(0x782C) +#define LANGUAGE_BASHKIR_RUSSIA LanguageType(0x046D) +#define LANGUAGE_BASQUE LanguageType(0x042D) +#define LANGUAGE_BELARUSIAN LanguageType(0x0423) +#define LANGUAGE_BENGALI LanguageType(0x0445) /* in India */ +#define LANGUAGE_BENGALI_BANGLADESH LanguageType(0x0845) +#define LANGUAGE_BOSNIAN_CYRILLIC_LSO LanguageType(0x641A) +#define LANGUAGE_BOSNIAN_CYRILLIC_BOSNIA_HERZEGOVINA LanguageType(0x201A) +#define LANGUAGE_BOSNIAN_LATIN_LSO LanguageType(0x681A) +#define LANGUAGE_BOSNIAN_LSO LanguageType(0x781A) +#define LANGUAGE_BOSNIAN_LATIN_BOSNIA_HERZEGOVINA LanguageType(0x141A) +#define LANGUAGE_BOSNIAN_BOSNIA_HERZEGOVINA LANGUAGE_BOSNIAN_LATIN_BOSNIA_HERZEGOVINA /* TODO: remove, only for langtab.src & localize.sdf compatibility */ +#define LANGUAGE_BRETON_FRANCE LanguageType(0x047E) /* obsoletes LANGUAGE_USER_BRETON 0x0629 */ +#define LANGUAGE_BULGARIAN LanguageType(0x0402) +#define LANGUAGE_BURMESE LanguageType(0x0455) +#define LANGUAGE_CATALAN LanguageType(0x0403) +#define LANGUAGE_CATALAN_VALENCIAN LanguageType(0x0803) /* obsoletes LANGUAGE_USER_CATALAN_VALENCIAN 0x8003 */ +#define LANGUAGE_CHEROKEE_UNITED_STATES LanguageType(0x045C) +#define LANGUAGE_CHEROKEE_CHEROKEE_LSO LanguageType(0x7C5C) +#define LANGUAGE_CHINESE_HONGKONG LanguageType(0x0C04) +#define LANGUAGE_CHINESE_LSO LanguageType(0x7804) +#define LANGUAGE_CHINESE_MACAU LanguageType(0x1404) +#define LANGUAGE_CHINESE_SIMPLIFIED LanguageType(0x0804) +#define LANGUAGE_CHINESE_SINGAPORE LanguageType(0x1004) +#define LANGUAGE_CHINESE_TRADITIONAL LanguageType(0x0404) +#define LANGUAGE_CHINESE_SIMPLIFIED_LEGACY LanguageType(0x0004) /* MS-.NET 'zh-CHS', primary only! but maps to 'zh-CN' */ +#define LANGUAGE_CHINESE_TRADITIONAL_LSO LanguageType(0x7C04) /* MS-.NET 'zh-CHT' but maps to 'zh-Hant' */ +#define LANGUAGE_CHINESE LANGUAGE_CHINESE_SIMPLIFIED /* most code uses LANGUAGE_CHINESE */ +#define LANGUAGE_CORSICAN_FRANCE LanguageType(0x0483) +#define LANGUAGE_CROATIAN LanguageType(0x041A) +#define LANGUAGE_CROATIAN_BOSNIA_HERZEGOVINA LanguageType(0x101A) +#define LANGUAGE_CZECH LanguageType(0x0405) +#define LANGUAGE_DANISH LanguageType(0x0406) +#define LANGUAGE_DARI_AFGHANISTAN LanguageType(0x048C) /* AKA Zoroastrian Dari */ +#define LANGUAGE_DHIVEHI LanguageType(0x0465) /* AKA Divehi */ +#define LANGUAGE_DUTCH LanguageType(0x0413) +#define LANGUAGE_DUTCH_BELGIAN LanguageType(0x0813) +#define LANGUAGE_EDO LanguageType(0x0466) +#define LANGUAGE_ENGLISH LanguageType(0x0009) /* primary only, not a locale! */ +#define LANGUAGE_ENGLISH_ARAB_EMIRATES LanguageType(0x4C09) +#define LANGUAGE_ENGLISH_AUS LanguageType(0x0C09) +#define LANGUAGE_ENGLISH_BAHRAIN LanguageType(0x5009) +#define LANGUAGE_ENGLISH_BELIZE LanguageType(0x2809) +#define LANGUAGE_ENGLISH_CAN LanguageType(0x1009) +#define LANGUAGE_ENGLISH_CARIBBEAN LanguageType(0x2409) /* MS reserved since rev.15, "en-029" */ +#define LANGUAGE_ENGLISH_EGYPT LanguageType(0x5409) +#define LANGUAGE_ENGLISH_EIRE LanguageType(0x1809) +#define LANGUAGE_ENGLISH_HONG_KONG_SAR LanguageType(0x3C09) +#define LANGUAGE_ENGLISH_INDIA LanguageType(0x4009) +#define LANGUAGE_ENGLISH_INDONESIA LanguageType(0x3809) +#define LANGUAGE_ENGLISH_JAMAICA LanguageType(0x2009) +#define LANGUAGE_ENGLISH_JORDAN LanguageType(0x5809) +#define LANGUAGE_ENGLISH_KUWAIT LanguageType(0x5C09) +#define LANGUAGE_ENGLISH_MALAYSIA LanguageType(0x4409) +#define LANGUAGE_ENGLISH_NZ LanguageType(0x1409) +#define LANGUAGE_ENGLISH_PHILIPPINES LanguageType(0x3409) +#define LANGUAGE_ENGLISH_SAFRICA LanguageType(0x1C09) +#define LANGUAGE_ENGLISH_SINGAPORE LanguageType(0x4809) +#define LANGUAGE_ENGLISH_TRINIDAD LanguageType(0x2C09) +#define LANGUAGE_ENGLISH_TURKEY LanguageType(0x6009) +#define LANGUAGE_ENGLISH_UK LanguageType(0x0809) +#define LANGUAGE_ENGLISH_US LanguageType(0x0409) +#define LANGUAGE_ENGLISH_YEMEN LanguageType(0x6409) +#define LANGUAGE_ENGLISH_ZIMBABWE LanguageType(0x3009) +#define LANGUAGE_ESTONIAN LanguageType(0x0425) +#define LANGUAGE_FAEROESE LanguageType(0x0438) +#define LANGUAGE_FARSI LanguageType(0x0429) +#define LANGUAGE_FILIPINO LanguageType(0x0464) +#define LANGUAGE_FINNISH LanguageType(0x040B) +#define LANGUAGE_FRENCH LanguageType(0x040C) +#define LANGUAGE_FRENCH_BELGIAN LanguageType(0x080C) +#define LANGUAGE_FRENCH_CAMEROON LanguageType(0x2C0C) +#define LANGUAGE_FRENCH_CANADIAN LanguageType(0x0C0C) +#define LANGUAGE_FRENCH_COTE_D_IVOIRE LanguageType(0x300C) + +#define LANGUAGE_FRENCH_HAITI LanguageType(0x3C0C) +#define LANGUAGE_FRENCH_LUXEMBOURG LanguageType(0x140C) +#define LANGUAGE_FRENCH_MALI LanguageType(0x340C) +#define LANGUAGE_FRENCH_MONACO LanguageType(0x180C) +#define LANGUAGE_FRENCH_MOROCCO LanguageType(0x380C) +#define LANGUAGE_FRENCH_NORTH_AFRICA LanguageType(0xE40C) /* MS reserved, "fr-015", "015"="Northern Africa" */ +#define LANGUAGE_FRENCH_REUNION LanguageType(0x200C) +#define LANGUAGE_FRENCH_SENEGAL LanguageType(0x280C) +#define LANGUAGE_FRENCH_SWISS LanguageType(0x100C) +#define LANGUAGE_FRENCH_WEST_INDIES LanguageType(0x1C0C) /* MS-LCID.pdf in between said "Neither defined nor reserved" but since rev.15 it's "fr-029" */ +#define LANGUAGE_FRENCH_ZAIRE LanguageType(0x240C) +#define LANGUAGE_FRISIAN_NETHERLANDS LanguageType(0x0462) +#define LANGUAGE_FULFULDE_LATIN_LSO LanguageType(0x7C67) +#define LANGUAGE_FULFULDE_NIGERIA LanguageType(0x0467) +#define LANGUAGE_FULFULDE_SENEGAL LanguageType(0x0867) +#define LANGUAGE_GAELIC_IRELAND LanguageType(0x083C) +#define LANGUAGE_GAELIC_SCOTLAND LanguageType(0x0491) /* apparently it occurred to MS that those are different languages */ +#define LANGUAGE_GAELIC_SCOTLAND_LEGACY LanguageType(0x043C) +#define LANGUAGE_GALICIAN LanguageType(0x0456) +#define LANGUAGE_GEORGIAN LanguageType(0x0437) +#define LANGUAGE_GERMAN LanguageType(0x0407) +#define LANGUAGE_GERMAN_AUSTRIAN LanguageType(0x0C07) +#define LANGUAGE_GERMAN_LIECHTENSTEIN LanguageType(0x1407) +#define LANGUAGE_GERMAN_LUXEMBOURG LanguageType(0x1007) +#define LANGUAGE_GERMAN_SWISS LanguageType(0x0807) +#define LANGUAGE_GREEK LanguageType(0x0408) +#define LANGUAGE_GUARANI_PARAGUAY LanguageType(0x0474) +#define LANGUAGE_GUJARATI LanguageType(0x0447) +#define LANGUAGE_HAUSA_LATIN_LSO LanguageType(0x7C68) +#define LANGUAGE_HAUSA_NIGERIA LanguageType(0x0468) +#define LANGUAGE_HAWAIIAN_UNITED_STATES LanguageType(0x0475) +#define LANGUAGE_HEBREW LanguageType(0x040D) +#define LANGUAGE_HINDI LanguageType(0x0439) +#define LANGUAGE_HUNGARIAN LanguageType(0x040E) +#define LANGUAGE_IBIBIO_NIGERIA LanguageType(0x0469) +#define LANGUAGE_ICELANDIC LanguageType(0x040F) +#define LANGUAGE_IGBO_NIGERIA LanguageType(0x0470) +#define LANGUAGE_INDONESIAN LanguageType(0x0421) +#define LANGUAGE_INUKTITUT_SYLLABICS_CANADA LanguageType(0x045D) +#define LANGUAGE_INUKTITUT_SYLLABICS_LSO LanguageType(0x785D) +#define LANGUAGE_INUKTITUT_LATIN_CANADA LanguageType(0x085D) +#define LANGUAGE_INUKTITUT_LATIN_LSO LanguageType(0x7C5D) +#define LANGUAGE_ITALIAN LanguageType(0x0410) +#define LANGUAGE_ITALIAN_SWISS LanguageType(0x0810) +#define LANGUAGE_JAPANESE LanguageType(0x0411) +#define LANGUAGE_KALAALLISUT_GREENLAND LanguageType(0x046F) /* obsoletes LANGUAGE_USER_KALAALLISUT 0x062A */ +#define LANGUAGE_KANNADA LanguageType(0x044B) +#define LANGUAGE_KANURI_NIGERIA LanguageType(0x0471) +#define LANGUAGE_KASHMIRI LanguageType(0x0460) +#define LANGUAGE_KASHMIRI_INDIA LanguageType(0x0860) +#define LANGUAGE_KAZAKH LanguageType(0x043F) +#define LANGUAGE_KAZAKH_LATIN LanguageType(0x083F) +#define LANGUAGE_KAZAKH_CYRILLIC_LSO LanguageType(0x783F) +#define LANGUAGE_KAZAKH_LATIN_LSO LanguageType(0x7C3F) +#define LANGUAGE_KHMER LanguageType(0x0453) +#define LANGUAGE_KICHE_GUATEMALA LanguageType(0x0486) /* AKA K'iche', West Central Quiche */ +#define LANGUAGE_KINYARWANDA_RWANDA LanguageType(0x0487) /* obsoletes LANGUAGE_USER_KINYARWANDA 0x0621 */ +#define LANGUAGE_KIRGHIZ LanguageType(0x0440) /* AKA Kyrgyz */ +#define LANGUAGE_KONKANI LanguageType(0x0457) +#define LANGUAGE_KOREAN LanguageType(0x0412) +#define LANGUAGE_KOREAN_JOHAB LanguageType(0x0812) /* not mentioned in MS-LCID.pdf, oh joy */ +#define LANGUAGE_KURDISH_ARABIC_IRAQ LanguageType(0x0492) /* obsoletes LANGUAGE_USER_KURDISH_IRAQ 0x0E26 */ +#define LANGUAGE_KURDISH_ARABIC_LSO LanguageType(0x7C92) +#define LANGUAGE_LAO LanguageType(0x0454) +#define LANGUAGE_LATIN LanguageType(0x0476) /* obsoletes LANGUAGE_USER_LATIN 0x0610 and LANGUAGE_USER_LATIN_VATICAN 0x8076 */ +#define LANGUAGE_LATVIAN LanguageType(0x0426) +#define LANGUAGE_LITHUANIAN LanguageType(0x0427) +#define LANGUAGE_LITHUANIAN_CLASSIC LanguageType(0x0827) /* MS in its MS-LCID.pdf now says "Neither defined nor reserved" */ +#define LANGUAGE_LU_CHINA LanguageType(0x0490) +#define LANGUAGE_LUXEMBOURGISH_LUXEMBOURG LanguageType(0x046E) /* obsoletes LANGUAGE_USER_LUXEMBOURGISH 0x0630 */ +#define LANGUAGE_MACEDONIAN LanguageType(0x042F) +#define LANGUAGE_MALAGASY_PLATEAU LanguageType(0x048D) /* obsoletes LANGUAGE_OBSOLETE_USER_MALAGASY_PLATEAU */ +#define LANGUAGE_MALAYALAM LanguageType(0x044C) /* in India */ +#define LANGUAGE_MALAY_BRUNEI_DARUSSALAM LanguageType(0x083E) +#define LANGUAGE_MALAY_MALAYSIA LanguageType(0x043E) +#define LANGUAGE_MALTESE LanguageType(0x043A) +#define LANGUAGE_MANIPURI LanguageType(0x0458) +#define LANGUAGE_MAORI_NEW_ZEALAND LanguageType(0x0481) /* obsoletes LANGUAGE_USER_MAORI 0x0620 */ +#define LANGUAGE_MAPUDUNGUN_CHILE LanguageType(0x047A) /* AKA Araucanian */ +#define LANGUAGE_MARATHI LanguageType(0x044E) +#define LANGUAGE_MOHAWK_CANADA LanguageType(0x047C) +#define LANGUAGE_MONGOLIAN_CYRILLIC_MONGOLIA LanguageType(0x0450) +#define LANGUAGE_MONGOLIAN_CYRILLIC_LSO LanguageType(0x7850) +#define LANGUAGE_MONGOLIAN_MONGOLIAN_MONGOLIA LanguageType(0x0C50) +#define LANGUAGE_MONGOLIAN_MONGOLIAN_CHINA LanguageType(0x0850) +#define LANGUAGE_MONGOLIAN_MONGOLIAN_LSO LanguageType(0x7C50) +#define LANGUAGE_NEPALI LanguageType(0x0461) +#define LANGUAGE_NEPALI_INDIA LanguageType(0x0861) +#define LANGUAGE_NORWEGIAN LanguageType(0x0014) /* primary only, not a locale! */ +#define LANGUAGE_NORWEGIAN_BOKMAL LanguageType(0x0414) +#define LANGUAGE_NORWEGIAN_BOKMAL_LSO LanguageType(0x7C14) +#define LANGUAGE_NORWEGIAN_NYNORSK LanguageType(0x0814) +#define LANGUAGE_NORWEGIAN_NYNORSK_LSO LanguageType(0x7814) +#define LANGUAGE_OCCITAN_FRANCE LanguageType(0x0482) /* obsoletes LANGUAGE_USER_OCCITAN 0x0625 */ +#define LANGUAGE_ODIA LanguageType(0x0448) +#define LANGUAGE_OROMO LanguageType(0x0472) +#define LANGUAGE_PAPIAMENTU LanguageType(0x0479) +#define LANGUAGE_PASHTO LanguageType(0x0463) +#define LANGUAGE_POLISH LanguageType(0x0415) +#define LANGUAGE_PORTUGUESE LanguageType(0x0816) +#define LANGUAGE_PORTUGUESE_BRAZILIAN LanguageType(0x0416) +#define LANGUAGE_PUNJABI LanguageType(0x0446) +#define LANGUAGE_PUNJABI_ARABIC_LSO LanguageType(0x7C46) +#define LANGUAGE_PUNJABI_PAKISTAN LanguageType(0x0846) +#define LANGUAGE_QUECHUA_BOLIVIA LanguageType(0x046B) +#define LANGUAGE_QUECHUA_COLOMBIA LanguageType(0x0493) /* different primary ID */ +#define LANGUAGE_QUECHUA_ECUADOR LanguageType(0x086B) +#define LANGUAGE_QUECHUA_PERU LanguageType(0x0C6B) +#define LANGUAGE_RHAETO_ROMAN LanguageType(0x0417) +#define LANGUAGE_ROMANIAN LanguageType(0x0418) +#define LANGUAGE_ROMANIAN_MOLDOVA LanguageType(0x0818) +#define LANGUAGE_RUSSIAN LanguageType(0x0419) +#define LANGUAGE_RUSSIAN_MOLDOVA LanguageType(0x0819) +#define LANGUAGE_SAMI_NORTHERN_NORWAY LanguageType(0x043B) +#define LANGUAGE_SAMI_LAPPISH LANGUAGE_SAMI_NORTHERN_NORWAY /* the old MS definition */ +#define LANGUAGE_SAMI_INARI LanguageType(0x243B) +#define LANGUAGE_SAMI_INARI_LSO LanguageType(0x703B) +#define LANGUAGE_SAMI_LULE_LSO LanguageType(0x7C3B) +#define LANGUAGE_SAMI_LULE_NORWAY LanguageType(0x103B) +#define LANGUAGE_SAMI_LULE_SWEDEN LanguageType(0x143B) +#define LANGUAGE_SAMI_NORTHERN_FINLAND LanguageType(0x0C3B) +#define LANGUAGE_SAMI_NORTHERN_SWEDEN LanguageType(0x083B) +#define LANGUAGE_SAMI_SKOLT LanguageType(0x203B) +#define LANGUAGE_SAMI_SKOLT_LSO LanguageType(0x743B) +#define LANGUAGE_SAMI_SOUTHERN_LSO LanguageType(0x783B) +#define LANGUAGE_SAMI_SOUTHERN_NORWAY LanguageType(0x183B) +#define LANGUAGE_SAMI_SOUTHERN_SWEDEN LanguageType(0x1C3B) +#define LANGUAGE_SANSKRIT LanguageType(0x044F) +#define LANGUAGE_SEPEDI LanguageType(0x046C) +#define LANGUAGE_NORTHERNSOTHO LANGUAGE_SEPEDI /* just an alias for the already existing localization */ +#define LANGUAGE_SERBIAN_CYRILLIC_LSO LanguageType(0x6C1A) +#define LANGUAGE_SERBIAN_CYRILLIC_SAM LanguageType(0x0C1A) /* Serbia and Montenegro (former) */ +#define LANGUAGE_SERBIAN_CYRILLIC_BOSNIA_HERZEGOVINA LanguageType(0x1C1A) +#define LANGUAGE_SERBIAN_CYRILLIC_MONTENEGRO LanguageType(0x301A) +#define LANGUAGE_SERBIAN_CYRILLIC_SERBIA LanguageType(0x281A) +#define LANGUAGE_SERBIAN_LATIN_LSO LanguageType(0x701A) +#define LANGUAGE_SERBIAN_LATIN_SAM LanguageType(0x081A) +#define LANGUAGE_SERBIAN_LATIN_BOSNIA_HERZEGOVINA LanguageType(0x181A) +#define LANGUAGE_SERBIAN_LATIN_MONTENEGRO LanguageType(0x2C1A) +#define LANGUAGE_SERBIAN_LATIN_NEUTRAL LanguageType(0x7C1A) +#define LANGUAGE_SERBIAN_LATIN_SERBIA LanguageType(0x241A) +#define LANGUAGE_SESOTHO LanguageType(0x0430) /* also called Sutu now by MS */ +#define LANGUAGE_SINDHI LanguageType(0x0459) +#define LANGUAGE_SINDHI_ARABIC_LSO LanguageType(0x7C59) +#define LANGUAGE_SINDHI_PAKISTAN LanguageType(0x0859) +#define LANGUAGE_SINHALESE_SRI_LANKA LanguageType(0x045B) +#define LANGUAGE_SLOVAK LanguageType(0x041B) +#define LANGUAGE_SLOVENIAN LanguageType(0x0424) +#define LANGUAGE_SOMALI LanguageType(0x0477) +#define LANGUAGE_UPPER_SORBIAN_GERMANY LanguageType(0x042E) /* obsoletes LANGUAGE_USER_UPPER_SORBIAN 0x0623 */ +#define LANGUAGE_LOWER_SORBIAN_GERMANY LanguageType(0x082E) /* obsoletes LANGUAGE_USER_LOWER_SORBIAN 0x0624. NOTE: the primary ID is identical to Upper Sorbian, which is not quite correct because they're distinct languages */ +#define LANGUAGE_LOWER_SORBIAN_LSO LanguageType(0x7C2E) +#define LANGUAGE_SORBIAN LANGUAGE_USER_UPPER_SORBIAN /* a strange MS definition */ +#define LANGUAGE_SPANISH_DATED LanguageType(0x040A) /* old collation, not supported, see #i94435# */ +#define LANGUAGE_SPANISH_ARGENTINA LanguageType(0x2C0A) +#define LANGUAGE_SPANISH_BOLIVIA LanguageType(0x400A) +#define LANGUAGE_SPANISH_CHILE LanguageType(0x340A) +#define LANGUAGE_SPANISH_COLOMBIA LanguageType(0x240A) +#define LANGUAGE_SPANISH_COSTARICA LanguageType(0x140A) +#define LANGUAGE_SPANISH_CUBA LanguageType(0x5C0A) +#define LANGUAGE_SPANISH_DOMINICAN_REPUBLIC LanguageType(0x1C0A) +#define LANGUAGE_SPANISH_ECUADOR LanguageType(0x300A) +#define LANGUAGE_SPANISH_EL_SALVADOR LanguageType(0x440A) +#define LANGUAGE_SPANISH_GUATEMALA LanguageType(0x100A) +#define LANGUAGE_SPANISH_HONDURAS LanguageType(0x480A) +#define LANGUAGE_SPANISH_LATIN_AMERICA LanguageType(0xE40A) /* no locale possible */ +#define LANGUAGE_SPANISH_MEXICAN LanguageType(0x080A) +#define LANGUAGE_SPANISH_MODERN LanguageType(0x0C0A) +#define LANGUAGE_SPANISH_NICARAGUA LanguageType(0x4C0A) +#define LANGUAGE_SPANISH_PANAMA LanguageType(0x180A) +#define LANGUAGE_SPANISH_PARAGUAY LanguageType(0x3C0A) +#define LANGUAGE_SPANISH_PERU LanguageType(0x280A) +#define LANGUAGE_SPANISH_PUERTO_RICO LanguageType(0x500A) +#define LANGUAGE_SPANISH_UNITED_STATES LanguageType(0x540A) +#define LANGUAGE_SPANISH_URUGUAY LanguageType(0x380A) +#define LANGUAGE_SPANISH_VENEZUELA LanguageType(0x200A) +#define LANGUAGE_SPANISH LANGUAGE_SPANISH_MODERN /* modern collation, see #i94435# */ +#define LANGUAGE_SWAHILI LanguageType(0x0441) /* Kenya */ +#define LANGUAGE_SWEDISH LanguageType(0x041D) +#define LANGUAGE_SWEDISH_FINLAND LanguageType(0x081D) +#define LANGUAGE_SYRIAC LanguageType(0x045A) +#define LANGUAGE_TAI_NUA_CHINA LanguageType(0x048F) +#define LANGUAGE_TAJIK LanguageType(0x0428) +#define LANGUAGE_TAJIK_LSO LanguageType(0x7C28) +#define LANGUAGE_TAMAZIGHT_ARABIC_MOROCCO LanguageType(0x045F) +#define LANGUAGE_TAMAZIGHT_LATIN_ALGERIA LanguageType(0x085F) +#define LANGUAGE_TAMAZIGHT_LATIN_LSO LanguageType(0x7C5F) +#define LANGUAGE_TAMAZIGHT_MOROCCO LanguageType(0x0C5F) +#define LANGUAGE_TAMAZIGHT_TIFINAGH_MOROCCO LanguageType(0x105F) +#define LANGUAGE_TAMAZIGHT_TIFINAGH_LSO LanguageType(0x785F) +#define LANGUAGE_TAMIL LanguageType(0x0449) +#define LANGUAGE_TAMIL_SRI_LANKA LanguageType(0x0849) +#define LANGUAGE_TATAR LanguageType(0x0444) +#define LANGUAGE_TELUGU LanguageType(0x044A) +#define LANGUAGE_THAI LanguageType(0x041E) +#define LANGUAGE_TIBETAN LanguageType(0x0451) +#define LANGUAGE_TIBETAN_BHUTAN LanguageType(0x0851) /* was used as Dzongkha, a MS error, see #i53497# */ +#define LANGUAGE_DZONGKHA_BHUTAN LanguageType(0x0C51) /* they finally got it ... ([MS-LCID] rev. 7.0 2015-06-30) */ +#define LANGUAGE_TIGRIGNA_ERITREA LanguageType(0x0873) +#define LANGUAGE_TIGRIGNA_ETHIOPIA LanguageType(0x0473) +#define LANGUAGE_TSONGA LanguageType(0x0431) +#define LANGUAGE_TSWANA LanguageType(0x0432) /* AKA Setsuana, for South Africa */ +#define LANGUAGE_TSWANA_BOTSWANA LanguageType(0x0832) /* obsoletes LANGUAGE_USER_TSWANA_BOTSWANA 0x8032 */ +#define LANGUAGE_TURKISH LanguageType(0x041F) +#define LANGUAGE_TURKMEN LanguageType(0x0442) +#define LANGUAGE_UIGHUR_CHINA LanguageType(0x0480) +#define LANGUAGE_UKRAINIAN LanguageType(0x0422) +#define LANGUAGE_URDU_INDIA LanguageType(0x0820) +#define LANGUAGE_URDU_PAKISTAN LanguageType(0x0420) +#define LANGUAGE_UZBEK_CYRILLIC LanguageType(0x0843) +#define LANGUAGE_UZBEK_CYRILLIC_LSO LanguageType(0x7843) +#define LANGUAGE_UZBEK_LATIN LanguageType(0x0443) +#define LANGUAGE_UZBEK_LATIN_LSO LanguageType(0x7C43) +#define LANGUAGE_VENDA LanguageType(0x0433) +#define LANGUAGE_VIETNAMESE LanguageType(0x042A) +#define LANGUAGE_WELSH LanguageType(0x0452) +#define LANGUAGE_WOLOF_SENEGAL LanguageType(0x0488) +#define LANGUAGE_XHOSA LanguageType(0x0434) /* AKA isiZhosa */ +#define LANGUAGE_YAKUT_RUSSIA LanguageType(0x0485) +#define LANGUAGE_YI LanguageType(0x0478) /* Sichuan Yi */ +#define LANGUAGE_YIDDISH LanguageType(0x043D) +#define LANGUAGE_YORUBA LanguageType(0x046A) +#define LANGUAGE_YUE_CHINESE_HONGKONG LanguageType(0x048E) +#define LANGUAGE_ZULU LanguageType(0x0435) + +#define LANGUAGE_qps_ploc LanguageType(0x0501) /* 'qps-ploc', qps is a reserved for local use code */ +#define LANGUAGE_qps_ploca LanguageType(0x05FE) /* 'qps-ploca', qps is a reserved for local use code */ +#define LANGUAGE_qps_plocm LanguageType(0x09FF) /* 'qps-plocm', qps is a reserved for local use code */ + +#define LANGUAGE_ar_Ploc_SA_reserved LanguageType(0x4401) /* 'ar-Ploc-SA', 'Ploc'?? */ +#define LANGUAGE_ja_Ploc_JP_reserved LanguageType(0x0811) /* 'ja-Ploc-JP', 'Ploc'?? */ +#define LANGUAGE_pap_029_reserved LanguageType(0x0479) /* "pap-029", "029"="Caribbean" */ +#define LANGUAGE_ar_145_reserved LanguageType(0x4801) /* "ar-145", "145"="Western Asia" */ +#define LANGUAGE_es_419_reserved LanguageType(0x580A) /* MS reserved since rev.15, "es-419", "419"="Latin America and the Caribbean" */ + +/* Seems these values were used or reserved at one point of time ... */ +#define LANGUAGE_Neither_defined_nor_reserved_0x007B LanguageType(0x007B) +#define LANGUAGE_Neither_defined_nor_reserved_0x007D LanguageType(0x007D) +#define LANGUAGE_Neither_defined_nor_reserved_0x0089 LanguageType(0x0089) +#define LANGUAGE_Neither_defined_nor_reserved_0x008A LanguageType(0x008A) +#define LANGUAGE_Neither_defined_nor_reserved_0x008B LanguageType(0x008B) +#define LANGUAGE_Neither_defined_nor_reserved_0x008D LanguageType(0x008D) +#define LANGUAGE_Neither_defined_nor_reserved_0x008E LanguageType(0x008E) +#define LANGUAGE_Neither_defined_nor_reserved_0x008F LanguageType(0x008F) +#define LANGUAGE_Neither_defined_nor_reserved_0x0090 LanguageType(0x0090) +#define LANGUAGE_Neither_defined_nor_reserved_0x0827 LanguageType(0x0827) +#define LANGUAGE_Neither_defined_nor_reserved_0x1C0C LanguageType(0x1C0C) +#define LANGUAGE_Neither_defined_nor_reserved_0x2008 LanguageType(0x2008) + +/* MS defines these as reserved, whatever that might imply... */ +#define LANGUAGE_reserved_0xEEEE LanguageType(0xEEEE) /* primary 0x2ee, sub 0x3b */ +#define LANGUAGE_reserved_0xF2EE LanguageType(0xF2EE) /* primary 0x2ee, sub 0x3c */ + +/*! use only for import/export of MS documents, number formatter maps it to + *! LANGUAGE_SYSTEM and then to effective system language */ +#define LANGUAGE_SYSTEM_DEFAULT LanguageType(0x0800) + +/*! use only for import/export of MS documents, number formatter maps it to + *! LANGUAGE_SYSTEM and then to effective system language */ +#define LANGUAGE_PROCESS_OR_USER_DEFAULT LanguageType(0x0400) + +/* Number format code modifier attribute for system time. + * Primary language 0x000, sublanguage 0x3D. */ +#define LANGUAGE_NF_SYSTEM_TIME LanguageType(0xF400) + +/* Number format code modifier attribute for system date. + * Primary language 0x000, sublanguage 0x3E. */ +#define LANGUAGE_NF_SYSTEM_DATE LanguageType(0xF800) + + +/* And now the extensions we define, + * with primary language IDs from 0x200 to 0x3FF valid in blocks from + * + * 0x0610 to 0x07FF with sublanguage ID 0x01 (default) + * 0x0A00 to 0x0BFF with sublanguage ID 0x02 + * ... + * 0x8200 to 0x83FF with sublanguage ID 0x20 + * 0x8600 to 0x87FF with sublanguage ID 0x21 + * ... + * 0xFA00 to 0xFBFF with sublanguage ID 0x3E + * 0xFE00 to 0xFFFF with sublanguage ID 0x3F + * + * Of which we define reserved blocks: + * All primary language IDs 0x3E0 to 0x3FE with any sublanguage ID, not to be + * assigned as user-defined IDs: + * + * 0x07E0 to 0x07FE with sublanguage ID 0x01, first on-the-fly block + * 0x0BE0 to 0x0BFE with sublanguage ID 0x02, second on-the-fly block + * ... + * 0x83E0 to 0x83FE with sublanguage ID 0x20 + * 0x87E0 to 0x87FE with sublanguage ID 0x21 + * ... + * 0xFBE0 to 0xFBFE with sublanguage ID 0x3E, last on-the-fly block + * 0xFFE0 to 0xFFFE with sublanguage ID 0x3F, 32 privateuse and specials + * + * This leaves room for 479 user-defined primary language IDs (instead of 512) + * with primary bitmask comparability, and 1922 on-the-fly IDs (instead of 0) + * with arbitrary assignment ((0x3E - 0x01 + 1) * (0x3FE - 0x3E0 + 1)). + * + * The primary ID 0x3FF is reserved and unassigned as it is the same as the + * LANGUAGE_MASK_PRIMARY and LANGUAGE_DONTKNOW value, so to not be mistaken as + * such. + * + * Obsolete OOo user defines now have other values assigned by MS, and + * different name. Mapping an obsolete value to ISO code should work provided + * that such a mapping exists in i18nlangtag/source/isolang/isolang.cxx, but + * mapping ISO back to LANGID will return the new value. + */ +#define LANGUAGE_OBSOLETE_USER_LATIN LanguageType(0x0610) +#define LANGUAGE_USER_LATIN LANGUAGE_LATIN +#define LANGUAGE_OBSOLETE_USER_LATIN_VATICAN LanguageType(0x8076) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_LATIN)) */ +#define LANGUAGE_USER_LATIN_VATICAN LANGUAGE_LATIN +#define LANGUAGE_USER_ESPERANTO LanguageType(0x0611) /* no locale possible */ +#define LANGUAGE_USER_INTERLINGUA LanguageType(0x0612) /* no locale, but conventions */ +#define LANGUAGE_OBSOLETE_USER_MAORI LanguageType(0x0620) +#define LANGUAGE_USER_MAORI LANGUAGE_MAORI_NEW_ZEALAND +#define LANGUAGE_OBSOLETE_USER_KINYARWANDA LanguageType(0x0621) +#define LANGUAGE_USER_KINYARWANDA LANGUAGE_KINYARWANDA_RWANDA +/* was reserved for Northern Sotho but never used: 0x0622 */ /* obsoleted by LANGUAGE_SEPEDI */ +#define LANGUAGE_OBSOLETE_USER_UPPER_SORBIAN LanguageType(0x0623) +#define LANGUAGE_USER_UPPER_SORBIAN LANGUAGE_UPPER_SORBIAN_GERMANY +#define LANGUAGE_OBSOLETE_USER_LOWER_SORBIAN LanguageType(0x0624) +#define LANGUAGE_USER_LOWER_SORBIAN LANGUAGE_LOWER_SORBIAN_GERMANY +#define LANGUAGE_OBSOLETE_USER_OCCITAN LanguageType(0x0625) +#define LANGUAGE_USER_OCCITAN LANGUAGE_OCCITAN_FRANCE /* reserved to languedocian */ + +#define LANGUAGE_USER_KOREAN_NORTH LanguageType(0x8012) /* North Korean as opposed to South Korean, makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_KOREAN)) */ +#define LANGUAGE_USER_KURDISH_TURKEY LanguageType(0x0626) /* sublang 0x01, Latin script */ +#define LANGUAGE_USER_KURDISH_SYRIA LanguageType(0x0A26) /* sublang 0x02, Latin script */ +#define LANGUAGE_OBSOLETE_USER_KURDISH_IRAQ LanguageType(0x0E26) /* sublang 0x03, Arabic script */ +#define LANGUAGE_USER_KURDISH_IRAQ LANGUAGE_KURDISH_ARABIC_IRAQ +#define LANGUAGE_USER_KURDISH_IRAN LanguageType(0x1226) /* sublang 0x04, Arabic script */ +#define LANGUAGE_USER_KURDISH_SOUTHERN_IRAQ LanguageType(0x8092) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_KURDISH_ARABIC_LSO)) */ +#define LANGUAGE_USER_KURDISH_SOUTHERN_IRAN LanguageType(0x8492) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_KURDISH_ARABIC_LSO)) */ +#define LANGUAGE_USER_SARDINIAN LanguageType(0x0627) +/* was reserved for Dzongkha but turned down with #i53497#: 0x0628 */ /* obsoleted by LANGUAGE_DZONGKHA_BHUTAN */ +#define LANGUAGE_USER_DZONGKHA_MAP_LONLY LanguageType(0xF851) /* to map "dz" only, because of the MS error, and preserve CTL information, sub 0x3e */ +#define LANGUAGE_USER_SWAHILI_TANZANIA LanguageType(0x8041) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_SWAHILI)) */ +#define LANGUAGE_OBSOLETE_USER_BRETON LanguageType(0x0629) +#define LANGUAGE_USER_BRETON LANGUAGE_BRETON_FRANCE +#define LANGUAGE_OBSOLETE_USER_KALAALLISUT LanguageType(0x062A) +#define LANGUAGE_USER_KALAALLISUT LANGUAGE_KALAALLISUT_GREENLAND +#define LANGUAGE_USER_SWAZI LanguageType(0x062B) +#define LANGUAGE_USER_NDEBELE_SOUTH LanguageType(0x062C) +#define LANGUAGE_OBSOLETE_USER_TSWANA_BOTSWANA LanguageType(0x8032) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_TSWANA)) */ +#define LANGUAGE_USER_TSWANA_BOTSWANA LANGUAGE_TSWANA_BOTSWANA +#define LANGUAGE_USER_MOORE LanguageType(0x062D) +#define LANGUAGE_USER_BAMBARA LanguageType(0x062E) +#define LANGUAGE_USER_AKAN LanguageType(0x062F) +#define LANGUAGE_OBSOLETE_USER_LUXEMBOURGISH LanguageType(0x0630) +#define LANGUAGE_USER_LUXEMBOURGISH LANGUAGE_LUXEMBOURGISH_LUXEMBOURG +#define LANGUAGE_USER_FRIULIAN LanguageType(0x0631) +#define LANGUAGE_USER_FIJIAN LanguageType(0x0632) +#define LANGUAGE_USER_AFRIKAANS_NAMIBIA LanguageType(0x8036) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_AFRIKAANS)) */ +#define LANGUAGE_USER_ENGLISH_NAMIBIA LanguageType(0x8009) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_ENGLISH_US)) */ +#define LANGUAGE_USER_WALLOON LanguageType(0x0633) +#define LANGUAGE_USER_COPTIC LanguageType(0x0634) +#define LANGUAGE_USER_CHUVASH LanguageType(0x0635) +#define LANGUAGE_USER_GASCON LanguageType(0x0636) /* Gascon France */ +#define LANGUAGE_USER_GERMAN_BELGIUM LanguageType(0x8007) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_GERMAN)) */ +#define LANGUAGE_OBSOLETE_USER_CATALAN_VALENCIAN LanguageType(0x8003) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_CATALAN)) */ +#define LANGUAGE_USER_CATALAN_VALENCIAN LANGUAGE_CATALAN_VALENCIAN +#define LANGUAGE_USER_HAUSA_GHANA LanguageType(0x8068) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_HAUSA_NIGERIA)) */ +#define LANGUAGE_USER_EWE_GHANA LanguageType(0x0637) +#define LANGUAGE_USER_ENGLISH_GHANA LanguageType(0x8409) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_ENGLISH_US)) */ +#define LANGUAGE_USER_TAGALOG LanguageType(0x0638) +#define LANGUAGE_USER_LINGALA_DRCONGO LanguageType(0x0639) +#define LANGUAGE_USER_SANGO LanguageType(0x063A) +#define LANGUAGE_USER_GANDA LanguageType(0x063B) +#define LANGUAGE_USER_LOW_GERMAN LanguageType(0x063C) +#define LANGUAGE_USER_HILIGAYNON LanguageType(0x063D) +#define LANGUAGE_USER_NYANJA LanguageType(0x063E) +#define LANGUAGE_USER_KASHUBIAN LanguageType(0x063F) +#define LANGUAGE_OBSOLETE_USER_SPANISH_CUBA LanguageType(0x800A) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_SPANISH)) */ +#define LANGUAGE_USER_SPANISH_CUBA LANGUAGE_SPANISH_CUBA +#define LANGUAGE_USER_TETUN LanguageType(0x0640) +#define LANGUAGE_USER_QUECHUA_NORTH_BOLIVIA LanguageType(0x0641) +#define LANGUAGE_USER_QUECHUA_SOUTH_BOLIVIA LanguageType(0x0642) +#define LANGUAGE_OBSOLETE_USER_SERBIAN_CYRILLIC_SERBIA LanguageType(0x8C1A) /* makeLangID( 0x20+0x03, getPrimaryLanguage( LANGUAGE_SERBIAN_CYRILLIC_LSO)) */ +#define LANGUAGE_USER_SERBIAN_CYRILLIC_SERBIA LANGUAGE_SERBIAN_CYRILLIC_SERBIA +#define LANGUAGE_OBSOLETE_USER_SERBIAN_LATIN_SERBIA LanguageType(0x881A) /* makeLangID( 0x20+0x02, getPrimaryLanguage( LANGUAGE_SERBIAN_LATIN_LSO)) */ +#define LANGUAGE_USER_SERBIAN_LATIN_SERBIA LANGUAGE_SERBIAN_LATIN_SERBIA +#define LANGUAGE_OBSOLETE_USER_SERBIAN_CYRILLIC_MONTENEGRO LanguageType(0xCC1A) /* makeLangID( 0x20+0x13, getPrimaryLanguage( LANGUAGE_SERBIAN_CYRILLIC_LSO)) */ +#define LANGUAGE_USER_SERBIAN_CYRILLIC_MONTENEGRO LANGUAGE_SERBIAN_CYRILLIC_MONTENEGRO +#define LANGUAGE_OBSOLETE_USER_SERBIAN_LATIN_MONTENEGRO LanguageType(0xC81A) /* makeLangID( 0x20+0x12, getPrimaryLanguage( LANGUAGE_SERBIAN_LATIN_LSO)) */ +#define LANGUAGE_USER_SERBIAN_LATIN_MONTENEGRO LANGUAGE_SERBIAN_LATIN_MONTENEGRO +#define LANGUAGE_USER_SAMI_KILDIN_RUSSIA LanguageType(0x803B) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_SAMI_NORTHERN_NORWAY)) */ +#define LANGUAGE_USER_BODO_INDIA LanguageType(0x0643) +#define LANGUAGE_USER_DOGRI_INDIA LanguageType(0x0644) +#define LANGUAGE_USER_MAITHILI_INDIA LanguageType(0x0645) +#define LANGUAGE_USER_SANTALI_INDIA LanguageType(0x0646) +#define LANGUAGE_USER_TETUN_TIMOR_LESTE LanguageType(0x0A40) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_TETUN)) */ +#define LANGUAGE_USER_TOK_PISIN LanguageType(0x0647) +#define LANGUAGE_USER_SHUSWAP LanguageType(0x0648) +#define LANGUAGE_USER_ARABIC_CHAD LanguageType(0x8001) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_COMOROS LanguageType(0x8401) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_DJIBOUTI LanguageType(0x8801) /* makeLangID( 0x22, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_ERITREA LanguageType(0x8C01) /* makeLangID( 0x23, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_ISRAEL LanguageType(0x9001) /* makeLangID( 0x24, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_MAURITANIA LanguageType(0x9401) /* makeLangID( 0x25, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_PALESTINE LanguageType(0x9801) /* makeLangID( 0x26, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_SOMALIA LanguageType(0x9C01) /* makeLangID( 0x27, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ARABIC_SUDAN LanguageType(0xA001) /* makeLangID( 0x28, getPrimaryLanguage( LANGUAGE_ARABIC_SAUDI_ARABIA)) */ +#define LANGUAGE_USER_ANCIENT_GREEK LanguageType(0x0649) +#define LANGUAGE_USER_ASTURIAN LanguageType(0x064A) +#define LANGUAGE_USER_LATGALIAN LanguageType(0x064B) +#define LANGUAGE_USER_MAORE LanguageType(0x064C) +#define LANGUAGE_USER_BUSHI LanguageType(0x064D) +#define LANGUAGE_USER_TAHITIAN LanguageType(0x064E) +#define LANGUAGE_OBSOLETE_USER_MALAGASY_PLATEAU LanguageType(0x064F) +#define LANGUAGE_USER_PAPIAMENTU_ARUBA LanguageType(0x8079) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_PAPIAMENTU)) */ +#define LANGUAGE_USER_SARDINIAN_CAMPIDANESE LanguageType(0x0650) +#define LANGUAGE_USER_SARDINIAN_GALLURESE LanguageType(0x0651) +#define LANGUAGE_USER_SARDINIAN_LOGUDORESE LanguageType(0x0652) +#define LANGUAGE_USER_SARDINIAN_SASSARESE LanguageType(0x0653) +#define LANGUAGE_USER_BAFIA LanguageType(0x0654) +#define LANGUAGE_USER_GIKUYU LanguageType(0x0655) +#define LANGUAGE_USER_RUSYN_UKRAINE LanguageType(0x0656) +#define LANGUAGE_USER_RUSYN_SLOVAKIA LanguageType(0x8256) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_RUSYN_UKRAINE)) */ +#define LANGUAGE_USER_YIDDISH_US LanguageType(0x803D) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_YIDDISH)) */ +#define LANGUAGE_USER_LIMBU LanguageType(0x0657) +#define LANGUAGE_USER_LOJBAN LanguageType(0x0658) /* no locale */ +#define LANGUAGE_OBSOLETE_USER_KABYLE LanguageType(0x0659) +#define LANGUAGE_USER_KABYLE LANGUAGE_TAMAZIGHT_LATIN_ALGERIA +#define LANGUAGE_USER_HAITIAN LanguageType(0x065A) +#define LANGUAGE_USER_BEEMBE LanguageType(0x065B) +#define LANGUAGE_USER_BEKWEL LanguageType(0x065C) +#define LANGUAGE_USER_KITUBA LanguageType(0x065D) +#define LANGUAGE_USER_LARI LanguageType(0x065E) +#define LANGUAGE_USER_MBOCHI LanguageType(0x065F) +#define LANGUAGE_USER_TEKE_IBALI LanguageType(0x0660) +#define LANGUAGE_USER_TEKE_TYEE LanguageType(0x0661) +#define LANGUAGE_USER_VILI LanguageType(0x0662) +#define LANGUAGE_USER_PORTUGUESE_ANGOLA LanguageType(0x8016) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_PORTUGUESE)) */ +#define LANGUAGE_USER_MANX LanguageType(0x0663) +#define LANGUAGE_USER_TEKE_EBOO LanguageType(0x0664) +#define LANGUAGE_USER_ARAGONESE LanguageType(0x0665) +#define LANGUAGE_USER_KEYID LanguageType(0x0666) /* key id pseudolanguage */ +#define LANGUAGE_USER_PALI_LATIN LanguageType(0x0667) +#define LANGUAGE_USER_KYRGYZ_CHINA LanguageType(0x0668) /* not derived from LANGUAGE_KIRGHIZ as these may be different scripts, see http://www.omniglot.com/writing/kirghiz.htm */ +#define LANGUAGE_USER_KOMI_ZYRIAN LanguageType(0x0669) +#define LANGUAGE_USER_KOMI_PERMYAK LanguageType(0x066A) +#define LANGUAGE_USER_PITJANTJATJARA LanguageType(0x066B) +#define LANGUAGE_USER_ENGLISH_MALAWI LanguageType(0x8809) /* makeLangID( 0x22, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_ERZYA LanguageType(0x066C) +#define LANGUAGE_USER_MARI_MEADOW LanguageType(0x066D) +#define LANGUAGE_USER_KHANTY LanguageType(0x066E) +#define LANGUAGE_USER_LIVONIAN LanguageType(0x066F) +#define LANGUAGE_USER_MOKSHA LanguageType(0x0670) +#define LANGUAGE_USER_MARI_HILL LanguageType(0x0671) +#define LANGUAGE_USER_NGANASAN LanguageType(0x0672) +#define LANGUAGE_USER_OLONETS LanguageType(0x0673) +#define LANGUAGE_USER_VEPS LanguageType(0x0674) +#define LANGUAGE_USER_VORO LanguageType(0x0675) +#define LANGUAGE_USER_NENETS LanguageType(0x0676) +#define LANGUAGE_USER_PAPIAMENTU_CURACAO LanguageType(0x8479) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_PAPIAMENTU)) */ +#define LANGUAGE_USER_PAPIAMENTU_BONAIRE LanguageType(0x8879) /* makeLangID( 0x22, getPrimaryLanguage( LANGUAGE_PAPIAMENTU)) */ +#define LANGUAGE_USER_AKA LanguageType(0x0677) +#define LANGUAGE_USER_AKA_CONGO LanguageType(0x8277) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_AKA)) */ +#define LANGUAGE_USER_DIBOLE LanguageType(0x0678) +#define LANGUAGE_USER_DOONDO LanguageType(0x0679) +#define LANGUAGE_USER_KAAMBA LanguageType(0x067A) +#define LANGUAGE_USER_KOONGO LanguageType(0x067B) +#define LANGUAGE_USER_KOONGO_CONGO LanguageType(0x827B) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_KOONGO)) */ +#define LANGUAGE_USER_KUNYI LanguageType(0x067C) +#define LANGUAGE_USER_NGUNGWEL LanguageType(0x067D) +#define LANGUAGE_USER_NJYEM LanguageType(0x067E) +#define LANGUAGE_USER_NJYEM_CONGO LanguageType(0x827E) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_NJYEM)) */ +#define LANGUAGE_USER_PUNU LanguageType(0x067F) +#define LANGUAGE_USER_PUNU_CONGO LanguageType(0x827F) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_PUNU)) */ +#define LANGUAGE_USER_SUUNDI LanguageType(0x0680) +#define LANGUAGE_USER_TEKE_KUKUYA LanguageType(0x0681) +#define LANGUAGE_USER_TSAANGI LanguageType(0x0682) +#define LANGUAGE_USER_YAKA LanguageType(0x0683) +#define LANGUAGE_USER_YOMBE LanguageType(0x0684) +#define LANGUAGE_USER_YOMBE_CONGO LanguageType(0x8284) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_YOMBE)) */ +#define LANGUAGE_USER_SIDAMA LanguageType(0x0685) +#define LANGUAGE_USER_NKO LanguageType(0x0686) +#define LANGUAGE_USER_UDMURT LanguageType(0x0687) +#define LANGUAGE_USER_TIBETAN_INDIA LanguageType(0x8051) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_TIBETAN)) */ +#define LANGUAGE_USER_CORNISH LanguageType(0x0688) +#define LANGUAGE_USER_SAMI_PITE_SWEDEN LanguageType(0x843B) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_SAMI_NORTHERN_NORWAY)) */ +#define LANGUAGE_USER_NGAEBERE LanguageType(0x0689) +#define LANGUAGE_USER_ENGLISH_UK_OED LanguageType(0x8C09) /* makeLangID( 0x23, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_KUMYK LanguageType(0x068A) +#define LANGUAGE_USER_NOGAI LanguageType(0x068B) +#define LANGUAGE_USER_KARAKALPAK_LATIN LanguageType(0x068C) +#define LANGUAGE_USER_LADIN LanguageType(0x068D) +#define LANGUAGE_USER_TIBETAN_BHUTAN LanguageType(0x8451) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_TIBETAN)) */ +#define LANGUAGE_USER_FRENCH_BURKINA_FASO LanguageType(0x800C) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_FRENCH)) */ +#define LANGUAGE_USER_PUINAVE LanguageType(0x068E) +#define LANGUAGE_USER_MANINKAKAN_EASTERN_LATIN LanguageType(0x068F) +#define LANGUAGE_USER_AVAR LanguageType(0x0690) +#define LANGUAGE_USER_CREE_PLAINS_LATIN LanguageType(0x0691) +#define LANGUAGE_USER_CREE_PLAINS_SYLLABICS LanguageType(0x8291) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_USER_CREE_PLAINS_LATIN)) */ +#define LANGUAGE_USER_LENGO LanguageType(0x0692) +#define LANGUAGE_USER_FRENCH_BENIN LanguageType(0x840C) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_FRENCH)) */ +#define LANGUAGE_USER_FRENCH_NIGER LanguageType(0x880C) /* makeLangID( 0x22, getPrimaryLanguage( LANGUAGE_FRENCH)) */ +#define LANGUAGE_USER_FRENCH_TOGO LanguageType(0x8C0C) /* makeLangID( 0x23, getPrimaryLanguage( LANGUAGE_FRENCH)) */ +#define LANGUAGE_USER_KVEN_FINNISH LanguageType(0x0693) +#define LANGUAGE_USER_CHURCH_SLAVIC LanguageType(0x0694) +#define LANGUAGE_USER_VENETIAN LanguageType(0x0695) +#define LANGUAGE_USER_ENGLISH_GAMBIA LanguageType(0x9009) /* makeLangID( 0x24, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_OCCITAN_ARANESE LanguageType(0x8082) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_OCCITAN_FRANCE)) */ +#define LANGUAGE_USER_ENGLISH_UK_OXENDICT LanguageType(0x9409) /* makeLangID( 0x25, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_ARPITAN_FRANCE LanguageType(0x0696) +#define LANGUAGE_USER_ARPITAN_ITALY LanguageType(0x0A96) /* makeLangID( 0x02, getPrimaryLanguage( LANGUAGE_USER_ARPITAN_FRANCE)) */ +#define LANGUAGE_USER_ARPITAN_SWITZERLAND LanguageType(0x0E96) /* makeLangID( 0x03, getPrimaryLanguage( LANGUAGE_USER_ARPITAN_FRANCE)) */ +#define LANGUAGE_USER_ENGLISH_BOTSWANA LanguageType(0x9809) /* makeLangID( 0x26, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_INTERLINGUE LanguageType(0x0697) /* no locale */ +#define LANGUAGE_USER_APATANI LanguageType(0x0698) +#define LANGUAGE_USER_ENGLISH_MAURITIUS LanguageType(0x9C09) /* makeLangID( 0x27, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_FRENCH_MAURITIUS LanguageType(0x900C) /* makeLangID( 0x24, getPrimaryLanguage( LANGUAGE_FRENCH)) */ +#define LANGUAGE_USER_SILESIAN LanguageType(0x0699) +#define LANGUAGE_USER_HUNGARIAN_ROVAS LanguageType(0x800E) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_HUNGARIAN)) */ +#define LANGUAGE_USER_MANCHU LanguageType(0x069A) +#define LANGUAGE_USER_XIBE LanguageType(0x069B) +#define LANGUAGE_USER_KITUBA_DRCONGO LanguageType(0x069C) +#define LANGUAGE_USER_FON LanguageType(0x069D) +#define LANGUAGE_USER_PLAUTDIETSCH LanguageType(0x069E) +#define LANGUAGE_USER_ARMENIAN_RUSSIA LanguageType(0x802B) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_ARMENIAN)) */ +#define LANGUAGE_USER_ARMENIAN_IRAN LanguageType(0x842B) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_ARMENIAN)) */ +#define LANGUAGE_USER_ARMENIAN_WESTERN LanguageType(0x069F) +#define LANGUAGE_USER_ARMENIAN_CLASSICAL LanguageType(0x06A0) +#define LANGUAGE_USER_MALAY_ARABIC_MALAYSIA LanguageType(0x803E) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_MALAY_MALAYSIA)) */ +#define LANGUAGE_USER_MALAY_ARABIC_BRUNEI LanguageType(0x843E) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_MALAY_BRUNEI_DARUSSALAM)) */ +#define LANGUAGE_USER_JUHOAN LanguageType(0x06A1) +#define LANGUAGE_USER_NARO LanguageType(0x06A2) +#define LANGUAGE_USER_ILOKO LanguageType(0x06A3) +#define LANGUAGE_USER_ENGLISH_ZAMBIA LanguageType(0xA009) /* makeLangID( 0x28, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_ENGLISH_SRI_LANKA LanguageType(0xA409) /* makeLangID( 0x29, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_ENGLISH_NIGERIA LanguageType(0xA809) /* makeLangID( 0x2A, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_KABARDIAN LanguageType(0x06A4) +#define LANGUAGE_USER_GUADELOUPEAN_CREOLE_FRENCH LanguageType(0x06A5) +#define LANGUAGE_USER_LIGURIAN LanguageType(0x06A6) +#define LANGUAGE_USER_MINANGKABAU LanguageType(0x06A7) +#define LANGUAGE_USER_SUNDANESE LanguageType(0x06A8) +#define LANGUAGE_USER_YAKA_DRCONGO LanguageType(0x06A9) +#define LANGUAGE_USER_ENGLISH_KENYA LanguageType(0xAC09) /* makeLangID( 0x2B, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_PALI_THAI LanguageType(0x0A67) /* makeLangID( 0x02, getPrimaryLanguage( LANGUAGE_USER_PALI_LATIN)) */ +#define LANGUAGE_USER_CABECAR LanguageType(0x06AA) +#define LANGUAGE_USER_BRIBRI LanguageType(0x06AB) +#define LANGUAGE_USER_ENGLISH_DENMARK LanguageType(0xB009) /* makeLangID( 0x2C, getPrimaryLanguage( LANGUAGE_ENGLISH_UK)) */ +#define LANGUAGE_USER_SESOTHO_LESOTHO LanguageType(0x8030) /* makeLangID( 0x20, getPrimaryLanguage( LANGUAGE_SESOTHO)) */ +#define LANGUAGE_USER_YIDDISH_ISRAEL LanguageType(0x843D) /* makeLangID( 0x21, getPrimaryLanguage( LANGUAGE_YIDDISH)) */ +#define LANGUAGE_USER_KLINGON LanguageType(0x06AC) +#define LANGUAGE_USER_ENGLISH_ISRAEL LanguageType(0xB409) /* makeLangID( 0x2D, getPrimaryLanguage( LANGUAGE_ENGLISH_US)) */ +#define LANGUAGE_USER_INTERSLAVIC_LATIN LanguageType(0x06AD) +#define LANGUAGE_USER_INTERSLAVIC_CYRILLIC LanguageType(0x06AE) +#define LANGUAGE_USER_PENNSYLVANIA_DUTCH LanguageType(0x06AF) + + +/* XXX Add new user defined LCIDs ^^^ there. + * Note that we run out of IDs with sublanguage ID 0x01 after 0x07DF ... */ + + +/* Primary language ID range for on-the-fly assignment. */ +#define LANGUAGE_ON_THE_FLY_START LanguageType(0x03E0) +#define LANGUAGE_ON_THE_FLY_END LanguageType(0x03FE) +/* Sublanguage ID range for on-the-fly assignment. */ +#define LANGUAGE_ON_THE_FLY_SUB_START LanguageType(0x01) +#define LANGUAGE_ON_THE_FLY_SUB_END LanguageType(0x3E) + +/* 0xFFE0 to 0xFFFF reserved for privateuse and specials. */ +#define LANGUAGE_USER_PRIV_NONE LanguageType(0xFFEA) /* privateuse "x-none", MS ill-escaped into the wild, primary 0x3ea, sub 0x3f */ +#define LANGUAGE_USER_PRIV_JOKER LanguageType(0xFFEB) /* privateuse "*" (sic! bad! nasty!), primary 0x3eb, sub 0x3f */ +#define LANGUAGE_USER_PRIV_COMMENT LanguageType(0xFFEC) /* privateuse "x-comment", primary 0x3ec, sub 0x3f */ +#define LANGUAGE_USER_PRIV_DEFAULT LanguageType(0xFFED) /* privateuse "x-default", primary 0x3ed, sub 0x3f */ +#define LANGUAGE_USER_PRIV_NOTRANSLATE LanguageType(0xFFEE) /* privateuse "x-no-translate" (sic!), primary 0x3ee, sub 0x3f */ +#define LANGUAGE_MULTIPLE LanguageType(0xFFEF) /* multiple languages, primary 0x3ef, sub 0x3f */ +#define LANGUAGE_UNDETERMINED LanguageType(0xFFF0) /* undetermined language, primary 0x3f0, sub 0x3f */ +#define LANGUAGE_USER_SYSTEM_CONFIG LanguageType(0xFFFE) /* not a locale, to be used only in configuration context to obtain system default, primary 0x3fe, sub 0x3f */ + + +#endif /* INCLUDED_I18NLANGTAG_LANG_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nlangtag/languagetag.hxx b/include/i18nlangtag/languagetag.hxx new file mode 100644 index 000000000..3b5fb3d6d --- /dev/null +++ b/include/i18nlangtag/languagetag.hxx @@ -0,0 +1,592 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_I18NLANGTAG_LANGUAGETAG_HXX +#define INCLUDED_I18NLANGTAG_LANGUAGETAG_HXX + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/** The ISO 639-2 code reserved for local use used to indicate that a + css::Locale contains a BCP 47 string in its Variant field. The + Locale's Language field then will contain this language code. + + @see LanguageTag::getLocale() + + Avoid use, only needed internally or if conversion from Locale to + LanguageTag is not wanted, i.e. during ODF import. To check whether a + LanguageTag contains a plain language/country combination or a more + detailed BCP 47 language tag use LanguageTag::isIsoLocale() instead. + */ +#define I18NLANGTAG_QLT_ASCII "qlt" +inline constexpr OUStringLiteral I18NLANGTAG_QLT = u"qlt"; + + +class LanguageTagImpl; + + +/** Wrapper for liblangtag BCP 47 language tags, MS-LangIDs, locales and + conversions in between. + + Note that member variables are mutable and may change their values even in + const methods. Getter methods return either the original value or matching + converted values. + + For standalone conversions if no LanguageTag instance is at hand, static + convertTo...() methods exist. + */ +class SAL_WARN_UNUSED I18NLANGTAG_DLLPUBLIC LanguageTag +{ + friend class LanguageTagImpl; + +public: + + /** ScriptType for a language. + + Used only in onTheFly languages as a way of marking key script behaviours + for the script of the language without having to store and analyse the + script each time. Used primarily from msLangId. + + These need to correspond to the ExtraLanguages.ScriptType template + property in officecfg/registry/schema/org/openoffice/VCL.xcs + */ + enum class ScriptType + { + UNKNOWN = 0, + WESTERN = 1, // Copies css::i18n::ScriptType for strong types + CJK = 2, + CTL = 3, + RTL = 4 // implies CTL + }; + + /** Init LanguageTag with existing BCP 47 language tag string. + + @param bCanonicalize + If TRUE, canonicalize tag and reparse, the resulting tag string may + be different. + IF FALSE, the tag is simply stored and can be retrieved with + getBcp47(). + + Note that conversions to ISO codes, locales or LanguageType or + obtaining language or script will canonicalize the tag string anyway, + so specifying bCanonicalize=false is not a guarantee that the tag will + stay identical to what was passed. + */ + explicit LanguageTag( const OUString & rBcp47LanguageTag, bool bCanonicalize = false ); + + /** Init LanguageTag with Locale. */ + explicit LanguageTag( const css::lang::Locale & rLocale ); + + /** Init LanguageTag with LanguageType MS-LangID. */ + explicit LanguageTag( LanguageType nLanguage ); + + /** Init LanguageTag with either BCP 47 language tag (precedence if not + empty), or a combination of language, script and country. + + This is a convenience ctor to be used in ODF import where these are + distinct attributes. + */ + explicit LanguageTag( const OUString& rBcp47, const OUString& rLanguage, + std::u16string_view rScript, const OUString& rCountry ); + + /** Init LanguageTag with rtl_Locale. + + This is a convenience ctor. + */ + explicit LanguageTag( const rtl_Locale & rLocale ); + + ~LanguageTag(); + + LanguageTag(LanguageTag const &) = default; + LanguageTag(LanguageTag &&) = default; + LanguageTag & operator =(LanguageTag const &) = default; + LanguageTag & operator =(LanguageTag &&) = default; + + /** Obtain BCP 47 language tag. + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return an empty OUString for such a tag. + */ + const OUString & getBcp47( bool bResolveSystem = true ) const; + + /** Obtain BCP 47 language tag, but with MS malformed exceptions. + + To be used *only* in OOXML filter context. + For example, es-ES-u-co-trad is stored as es-ES_tradnl which is not a + valid BCP 47 language tag. + */ + OUString getBcp47MS() const; + + /** Obtain language tag as Locale. + + As a convention, language tags that can not be expressed as "pure" + css::lang::Locale content using Language and Country fields + store "qlt" (ISO 639 reserved for local use) in the Language field and + the entire BCP 47 language tag in the Variant field. The Country field + contains the corresponding ISO 3166 country code _if_ there is one, or + otherwise is empty. + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return an empty Locale for such a tag. + */ + const css::lang::Locale & getLocale( bool bResolveSystem = true ) const; + + /** Obtain mapping to MS-LangID. + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return LANGUAGE_SYSTEM for such a tag. + */ + LanguageType getLanguageType( bool bResolveSystem = true ) const; + + /** Obtain ISO strings for language, script and country. + + This is a convenience method for ODF export places only. Avoid use in + other code. + + ATTENTION! May return empty strings if the language tag is not + expressible in valid ISO codes! + + @see isIsoODF() + + Always resolves an empty tag to the system locale. + */ + void getIsoLanguageScriptCountry( OUString& rLanguage, + OUString& rScript, OUString& rCountry ) const; + + /** Get ISO 639 language code, or BCP 47 language. + + Always resolves an empty tag to the system locale. + */ + OUString getLanguage() const; + + /** Get ISO 15924 script code, if not the default script according to + BCP 47. For default script an empty string is returned. + + @see hasScript() + + Always resolves an empty tag to the system locale. + */ + OUString getScript() const; + + /** Get combined language and script code, separated by '-' if + non-default script, if default script only language. + + @see hasScript() + + Always resolves an empty tag to the system locale. + */ + OUString getLanguageAndScript() const; + + /** Get ISO 3166 country alpha code. Empty if the BCP 47 tags denote a + region not expressible as 2 character country code. + + Always resolves an empty tag to the system locale. + */ + OUString getCountry() const; + + /** Get BCP 47 variant subtags, of the IANA Language Subtag Registry. + + If there are multiple variant subtags they are separated by '-'. + + This is NOT related to Locale.Variant! + + Always resolves an empty tag to the system locale. + */ + OUString getVariants() const; + + /** Get a GLIBC locale string. + + Always resolves an empty tag to the system locale. + + @param rEncoding + An encoding to be appended to language_country, for example + ".UTF-8" including the dot. + + @return The resulting GLIBC locale string if it could be constructed, + if not an empty string is returned. + */ + OUString getGlibcLocaleString( std::u16string_view rEncoding ) const; + + /** If language tag has a non-default script specified. + */ + bool hasScript() const; + + /** If language tag is a locale that can be expressed using only ISO 639 + language codes and ISO 3166 country codes, thus is convertible to a + conforming Locale struct without using extension mechanisms. + + Note that an empty language tag or empty Locale::Language field or + LanguageType LANGUAGE_SYSTEM could be treated as a valid ISO locale in + some context, but here is not. If you want that ask for + aTag.isSystemLocale() || aTag.isIsoLocale() + + Always resolves an empty tag to the system locale. + */ + bool isIsoLocale() const; + + /** If language tag is a locale that can be expressed using only ISO 639 + language codes and ISO 15924 script codes and ISO 3166 country codes, + thus can be stored in an ODF document using only fo:language, fo:script + and fo:country attributes. If this is FALSE, the locale must be stored + as a <*:rfc-language-tag> element. + + Always resolves an empty tag to the system locale. + */ + bool isIsoODF() const; + + /** If this is a valid BCP 47 language tag. + + Always resolves an empty tag to the system locale. + + @seealso static bool isValidBcp47(const OUString&) + */ + bool isValidBcp47() const; + + /** If this tag was constructed as an empty tag denoting the system locale. + */ + bool isSystemLocale() const { return mbSystemLocale;} + + /** Returns the script type for this language, UNKNOWN if not set */ + ScriptType getScriptType() const; + + /** Sets the script type for this language */ + void setScriptType(ScriptType st); + + /** Reset with existing BCP 47 language tag string. See ctor. */ + LanguageTag & reset( const OUString & rBcp47LanguageTag ); + + /** Reset with Locale. */ + LanguageTag & reset( const css::lang::Locale & rLocale ); + + /** Reset with LanguageType MS-LangID. */ + LanguageTag & reset( LanguageType nLanguage ); + + + /** Fall back to a known locale. + + If the current tag does not represent a known (by us) locale, fall back + to the most likely locale possible known. + If the current tag is known, no change occurs. + */ + LanguageTag & makeFallback(); + + /** Return a vector of fall-back strings. + + In order: + full BCP 47 tag, same as getBcp47() + lll-Ssss-CC + lll-Ssss + lll-CC + lll + + If the tag includes variants the order is: + full BCP 47 tag, same as getBcp47() + lll-Ssss-CC-vvvvvvvv + lll-Ssss-vvvvvvvv + lll-Ssss-CC + lll-Ssss + lll-CC-vvvvvvvv + lll-vvvvvvvv + lll-CC + lll + + Only strings that differ from a higher order are included, for example + if there is no script the elements will be bcp47, lll-CC, lll; if the + bcp47 string is identical to lll-CC then only lll-CC, lll. + + Note that lll is only ISO 639-1/2 alpha code and CC is only ISO 3166 + alpha code. If the region can not be expressed as ISO 3166 then no -CC + tags are included. + + @param bIncludeFullBcp47 + If TRUE, the full BCP 47 tag is included as first element. + If FALSE, the full tag is not included; used if the caller + obtains the fallbacks only if the full tag did not lead to a + match, so subsequent tries need not to include it again. + */ + ::std::vector< OUString > getFallbackStrings( bool bIncludeFullBcp47 ) const; + + + /** @short Search for an equal or at least for a similar locale in a list + of possible ones. + + @descr First search for a locale that is equal to the reference + locale. (means: same BCP47 string) + + If the reference locale could not be located, check for + "similar" locales, in the same order as obtained by + getFallbackStrings(). + + If no similar locale could be located, we search for a locale + "en-US" inside the given locale list. + + If "en-US" could not be located, we search for a locale "en" + inside the given list. + + If no "same" nor any "similar" locale could be found, we try + "x-default" and "x-no-translate" explicitly. Sometimes + variables don't use real localization. For example, in case the + localized value is a fix product name. + + If no locale matched until then, we use any other locale that + exists inside the set of given ones, namely the first + encountered! + + @param rList + the vector of possible locales as BCP47 strings. + + @param rReference + the reference locale, BCP47 string. + + @return An iterator that points to the found element inside the given + locale list. If no matching locale could be found it points to + the beginning of the list. + */ + static ::std::vector< OUString >::const_iterator getFallback( const ::std::vector< OUString > & rList, + const OUString & rReference ); + + + /** @short Search for an equal or for a similar locale in a list + of possible ones where at least the language matches. + + @descr First search for a locale that is equal to the reference + locale. + + If the reference locale could not be located, check for + "similar" locales, in the same order as obtained by + getFallbackStrings(). + + If no locale matches, rList.end() is returned. + + @param rList + the vector of possible locales. + + @param rReference + the reference locale. + + @return An iterator that points to the found element inside the given + locale list. If no matching locale could be found it points to + the end of the list. + */ + static ::std::vector< css::lang::Locale >::const_iterator getMatchingFallback( + const ::std::vector< css::lang::Locale > & rList, + const css::lang::Locale & rReference ); + + + /** Test equality of two LanguageTag, possibly resolving system locale. + + Resolve empty language tags denoting the system + locale to the real locale used before comparing. + */ + bool equals( const LanguageTag & rLanguageTag ) const; + + /** Test equality of two LanguageTag. + + Does NOT resolve system, i.e. if the system locale is en-US + LanguageTag("")==LanguageTag("en-US") returns false! Use + equals(...) instead if system locales shall be resolved. + */ + bool operator==( const LanguageTag & rLanguageTag ) const; + + /** Test inequality of two LanguageTag. + + Does NOT resolve system, i.e. if the system locale is en-US + LanguageTag("")!=LanguageTag("en-US") returns true! Use + !equals(,..) instead if system locales shall be resolved. + */ + bool operator!=( const LanguageTag & rLanguageTag ) const; + + /** Test this LanguageTag less than that LanguageTag. + + For sorted containers. Does NOT resolve system. + */ + bool operator<( const LanguageTag & rLanguageTag ) const; + + /** Convert MS-LangID to Locale. + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return an empty Locale for such a tag. + */ + static css::lang::Locale convertToLocale( LanguageType nLangID, bool bResolveSystem = true ); + + /** Convert Locale to MS-LangID. + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return LANGUAGE_SYSTEM for such a tag. + */ + static LanguageType convertToLanguageType( const css::lang::Locale& rLocale, bool bResolveSystem = true ); + + /** Convert MS-LangID to BCP 47 string. + + Resolve an empty language tag denoting the system + locale to the real locale used. + */ + static OUString convertToBcp47( LanguageType nLangID ); + + /** Convert Locale to BCP 47 string. + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return an empty OUString for such a tag. + */ + static OUString convertToBcp47( const css::lang::Locale& rLocale, bool bResolveSystem = true ); + + /** Convert BCP 47 string to Locale, convenience method. + + NOTE: exists only for consistency with the other convertTo...() + methods, internally uses a temporary LanguageTag instance for + conversion so does not save anything compared to + LanguageTag(rBcp47).getLocale(bResolveSystem). + + @param bResolveSystem + If TRUE, resolve an empty language tag denoting the system + locale to the real locale used. + If FALSE, return an empty Locale for such a tag. + */ + static css::lang::Locale convertToLocale( const OUString& rBcp47, bool bResolveSystem = true ); + + /** Convert BCP 47 string to MS-LangID, convenience method. + + NOTE: exists only for consistency with the other convertTo...() + methods, internally uses a temporary LanguageTag instance for + conversion so does not save anything compared to + LanguageTag(rBcp47).getLanguageType(bResolveSystem). + + Resolve an empty language tag denoting the system + locale to the real locale used. + */ + static LanguageType convertToLanguageType( const OUString& rBcp47 ); + + /** Convert BCP 47 string to MS-LangID with fallback, convenience method. + + NOTE: exists only for consistency with the other convertTo...() + methods, internally uses a temporary LanguageTag instance for + conversion so does not save anything compared to + LanguageTag(rBcp47).makeFallback().getLanguageType(bResolveSystem). + + @see makeFallback() + + Always resolves an empty tag to the system locale. + */ + static LanguageType convertToLanguageTypeWithFallback( const OUString& rBcp47 ); + + /** Convert BCP 47 string to Locale with fallback, convenience method. + + NOTE: exists only for consistency with the other convertTo...() + methods, internally uses a temporary LanguageTag instance for + conversion so does not save anything compared to + LanguageTag(rBcp47).makeFallback().getLocale(bResolveSystem). + + @see makeFallback() + + Always resolves an empty tag to the system locale. + */ + static css::lang::Locale convertToLocaleWithFallback( const OUString& rBcp47 ); + + /** Convert Locale to MS-LangID with fallback. + + Resolves an empty language tag denoting the system + locale to LANGUAGE_SYSTEM and does not fallback. + */ + static LanguageType convertToLanguageTypeWithFallback( const css::lang::Locale& rLocale ); + + /** If rString represents a valid BCP 47 language tag. + + Never resolves an empty tag to the system locale, in fact an empty + string is invalid here. Does not create an instance to be registered + with a conversion to Locale or LanguageType. + + @param o_pCanonicalized + If given and rString is a valid BCP 47 language tag, the + canonicalized form is assigned, which may differ from the + original string even if that was a valid tag. If rString is not + a valid tag, nothing is assigned. + + @param bDisallowPrivate + If TRUE, valid tags according to BCP 47 but reserved for + private use, like 'x-...', are not allowed and FALSE is + returned in this case. + */ + static bool isValidBcp47( const OUString& rString, OUString* o_pCanonicalized, + bool bDisallowPrivate = false ); + + /** If nLang is a generated on-the-fly LangID */ + static bool isOnTheFlyID( LanguageType nLang ); + static ScriptType getOnTheFlyScriptType( LanguageType nLang ); + + /** @ATTENTION: _ONLY_ to be called by the application's configuration! */ + static void setConfiguredSystemLanguage( LanguageType nLang ); + + /** @ATTENTION: _ONLY_ to be called by fuzzing setup */ + static void disable_lt_tag_parse(); + + typedef std::shared_ptr< LanguageTagImpl > ImplPtr; + +private: + + mutable css::lang::Locale maLocale; + mutable OUString maBcp47; + mutable LanguageType mnLangID; + mutable ImplPtr mpImpl; + bool mbSystemLocale : 1; + mutable bool mbInitializedBcp47 : 1; + mutable bool mbInitializedLocale : 1; + mutable bool mbInitializedLangID : 1; + bool mbIsFallback : 1; + + LanguageTagImpl* getImpl(); + LanguageTagImpl const* getImpl() const; + ImplPtr registerImpl() const; + void syncFromImpl(); + void syncVarsFromRawImpl() const; + void syncVarsFromImpl() const; + + void convertLocaleToLang(); + void convertBcp47ToLocale(); + void convertBcp47ToLang(); + void convertLangToLocale(); + + void convertFromRtlLocale(); + + /** Canonicalize if not yet done and synchronize initialized conversions. + + @return whether BCP 47 language tag string was changed. + */ + bool synCanonicalize(); + + void resetVars(); + + static bool isIsoLanguage( const OUString& rLanguage ); + static bool isIsoScript( const OUString& rScript ); + static bool isIsoCountry( const OUString& rRegion ); + +}; + +#endif // INCLUDED_I18NLANGTAG_LANGUAGETAG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nlangtag/languagetagicu.hxx b/include/i18nlangtag/languagetagicu.hxx new file mode 100644 index 000000000..430c483f3 --- /dev/null +++ b/include/i18nlangtag/languagetagicu.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_I18NLANGTAG_LANGUAGETAGICU_HXX +#define INCLUDED_I18NLANGTAG_LANGUAGETAGICU_HXX + +#include + +#include + +#include +#include +#include + +class LanguageTag; + + +/** Interface LanguageTag to ICU's icu::Locale + + Separated from LanguageTag to not pollute the entire code base (and thus + makefiles) with ICU header file inclusion, only the few code actually using + this needs to know about ICU, which it did anyway. +*/ +class SAL_WARN_UNUSED I18NLANGTAG_DLLPUBLIC LanguageTagIcu +{ +public: + + /** Obtain language tag as ICU icu::Locale. + + If the language tag is a "pure" ISO locale (see + LanguageTag::getLocale()) that is directly constructed, otherwise it is + converted using the available ICU mechanisms. + + Always resolves an empty tag to the system locale. + */ + static icu::Locale getIcuLocale( const LanguageTag & rLanguageTag ); + + /** Obtain language tag as ICU icu::Locale, adding variant data. + + From the LanguageTag only language and country are used to construct + the icu:Locale, the variant field is copied from rVariant. + The 4th arg of icu::Locale "keywords" (eg: for collation) + + Always resolves an empty tag to the system locale. + */ + static icu::Locale getIcuLocale( const LanguageTag & rLanguageTag, std::u16string_view rVariant, std::u16string_view rKeywords); + + /** Obtain the display name for a language tag. + + Gets a localized name from icu::Locale::getDisplayName(). Meant to be + used only with language tags that do not have a language list entry in + svtools/inc/langtab.hrc STR_ARR_SVT_LANGUAGE_TABLE, thus used by + SvtLanguageTable::GetLanguageString() + + @param rLanguageTag + The language tag for which the name is to be displayed. + + @param rDisplayLanguage + The language in which the name is to be displayed. + Usually Application::GetSettings().GetUILanguageTag(). + */ + static OUString getDisplayName( const LanguageTag & rLanguageTag, const LanguageTag & rDisplayLanguage ); +}; + +#endif // INCLUDED_I18NLANGTAG_LANGUAGETAGICU_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nlangtag/mslangid.hxx b/include/i18nlangtag/mslangid.hxx new file mode 100644 index 000000000..1d2f5cc8c --- /dev/null +++ b/include/i18nlangtag/mslangid.hxx @@ -0,0 +1,338 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_I18NLANGTAG_MSLANGID_HXX +#define INCLUDED_I18NLANGTAG_MSLANGID_HXX + +#include + +#include +#include +#include + +#include +#include +#include + +struct IsoLanguageCountryEntry; +struct IsoLanguageScriptCountryEntry; +struct Bcp47CountryEntry; + +/** Methods related to Microsoft language IDs. For details about MS-LANGIDs + please see lang.h */ +class SAL_WARN_UNUSED I18NLANGTAG_DLLPUBLIC MsLangId +{ +public: + + /// Create a LangID from a primary and a sublanguage. + static LanguageType makeLangID( LanguageType nSubLangId, LanguageType nPriLangId) + { + return LanguageType((sal_uInt16(nSubLangId) << 10) | sal_uInt16(nPriLangId)); + } + + /// Get the primary language of a LangID. + static LanguageType getPrimaryLanguage( LanguageType nLangID) + { + return LanguageType(sal_uInt16(nLangID) & LANGUAGE_MASK_PRIMARY); + } + + /// Get the sublanguage of a LangID. + static LanguageType getSubLanguage( LanguageType nLangID) + { + return LanguageType((sal_uInt16(nLangID) & ~LANGUAGE_MASK_PRIMARY) >> 10); + } + + /** Get the configured system language/locale. + If not set yet then getSystemLanguage(). + + Prefer this over getSystemLanguage() unless you exactly know why you + would not. */ + static LanguageType getConfiguredSystemLanguage(); + + /** Get the configured system UI language/locale. + If not set yet then getSystemUILanguage(). + + Prefer this over getSystemUILanguage() unless you exactly know why you + would not. */ + static LanguageType getConfiguredSystemUILanguage(); + + + /** Language/locale of category LC_CTYPE (on Unix, else the system + language). + Evaluation order: LC_ALL, LC_CTYPE, LANG + Note this may return an unknown unsupported locale. */ + static LanguageType getSystemLanguage(); + + /** Language/locale of category LC_MESSAGES (on Unix, else same as + getSystemLanguage()). + Evaluation order: LANGUAGE, LC_ALL, LC_MESSAGES, LANG + Note this may return an unknown unsupported locale. */ + static LanguageType getSystemUILanguage(); + + + /** @short: A proper language/locale if the nLang parameter designates some + special value. + + @descr: NOTE: The "system" values may be overridden by the + application's configuration. + + @returns + case LANGUAGE_PROCESS_OR_USER_DEFAULT : configured or system language + case LANGUAGE_SYSTEM_DEFAULT : configured or system language + case LANGUAGE_SYSTEM : configured or system language + case LANGUAGE_HID_HUMAN_INTERFACE_DEVICE : configured or system UI language + case LANGUAGE_DONTKNOW : LANGUAGE_ENGLISH_US + else: nLang + + In case the configured language is LANGUAGE_SYSTEM, which is also + the initial default, the system language is obtained. In case the + configured or resulting system language is LANGUAGE_DONTKNOW, + LANGUAGE_ENGLISH_US is returned instead. + */ + static LanguageType getRealLanguage( LanguageType nLang ); + + + // TODO: refactor to LanguageTag? Used only in + // i18npool/source/localedata/localedata.cxx + + /** Get fall-back Locale for Locale with handling of an empty language name + designating the SYSTEM language. Returns the same Locale if an exact + match was found. + */ + static css::lang::Locale getFallbackLocale( const css::lang::Locale & rLocale ); + + + // TODO: refactor to LanguageTag, used only in + // i18npool/source/isolang/inunx.cxx to convert Unix locale string + + static LanguageType convertUnxByteStringToLanguage( std::string_view rString ); + + + static LanguageType resolveSystemLanguageByScriptType( LanguageType nLang, sal_Int16 nType ); + + + /** Whether the language uses hyphenation. */ + static bool usesHyphenation( LanguageType nLang ); + + /** Whether locale has a Right-To-Left orientation for text. */ + static bool isRightToLeft( LanguageType nLang ); + + /** Whether locale has a Right-To-Left orientation for math. */ + static bool isRightToLeftMath( LanguageType nLang ); + + /** Whether locale is a CJK locale */ + static bool isCJK( LanguageType nLang ); + + /** Whether locale is a chinese locale */ + static bool isChinese( LanguageType nLang ); + + /** Whether locale is a simplified chinese locale */ + static bool isSimplifiedChinese( LanguageType nLang ); + + /** Whether locale is a traditional chinese locale */ + static bool isTraditionalChinese( LanguageType nLang ); + + /** Whether locale is a korean locale */ + static bool isKorean( LanguageType nLang ); + + /** Whether locale is a simplified chinese locale */ + static bool isSimplifiedChinese( const css::lang::Locale & rLocale ); + + /** Whether locale is a traditional chinese locale */ + static bool isTraditionalChinese( const css::lang::Locale & rLocale ); + + /** Whether locale is one where family name comes first, e.g. Japan, Hungary, Samoa */ + static bool isFamilyNameFirst( LanguageType nLang ); + + /** Whether there are "forbidden characters at start or end of line" in + this locale. CJK locales. + + @see offapi/com/sun/star/i18n/ForbiddenCharacters.idl + */ + static bool hasForbiddenCharacters( LanguageType nLang ); + + + /** Whether locale needs input sequence checking. CTL locales. */ + static bool needsSequenceChecking( LanguageType nLang ); + + + /** Get css::i18n::ScriptType of locale. */ + static sal_Int16 getScriptType( LanguageType nLang ); + + /** Whether locale is "Western" but not Latin script, e.g. Cyrillic or Greek. */ + static bool isNonLatinWestern( LanguageType nLang ); + + + /** Map an obsolete user defined LANGID (see lang.h + LANGUAGE_OBSOLETE_USER_...) to the new value defined by MS in the + meantime. + + Also used to map UI localizations using reserved ISO codes to something + "official" but not identical in order to not pollute documents with + invalid ISO codes. + */ + static LanguageType getReplacementForObsoleteLanguage( LanguageType nLang ); + + /** Whether locale is legacy, i.e. country or confederation doesn't exist anymore. */ + static bool isLegacy( LanguageType nLang ); + + + /** @ATTENTION: these are _ONLY_ to be called by the application's + configuration! */ + static void setConfiguredSystemUILanguage( LanguageType nLang ); + static void setConfiguredWesternFallback( LanguageType nLang ); + static void setConfiguredComplexFallback( LanguageType nLang ); + static void setConfiguredAsianFallback( LanguageType nLang ); + + + /** Encapsulated methods that shall only be accessed through + class LanguageTag. + */ + class LanguageTagAccess + { + private: + + friend class LanguageTag; + + /** Configured system locale needs always be synchronized with + LanguageTag's system locale. + */ + I18NLANGTAG_DLLPRIVATE static void setConfiguredSystemLanguage( LanguageType nLang ); + }; + + + struct LanguagetagMapping + { + OUString maBcp47; + LanguageType mnLang; + + LanguagetagMapping( OUString aBcp47, LanguageType nLang ) : maBcp47(std::move(aBcp47)), mnLang(nLang) {} + }; + + /** @internal - Obtain a list of known locales (i.e. those that have a + defined mapping between MS-LangID and ISO codes or tags) as BCP 47 + language tag strings. + */ + static ::std::vector< LanguagetagMapping > getDefinedLanguagetags(); + + + /** Encapsulated conversion methods used by LanguageTag and conversions, + not to be used by anything else. + */ + class Conversion + { + private: + + friend class LanguageTag; + friend class LanguageTagImpl; + + friend css::lang::Locale MsLangId::getFallbackLocale( + const css::lang::Locale & rLocale ); + + friend LanguageType MsLangId::convertUnxByteStringToLanguage( + std::string_view rString ); + + + /** Convert a Locale to a LanguageType with handling of an empty + language name designating LANGUAGE_SYSTEM. + */ + I18NLANGTAG_DLLPRIVATE static LanguageType convertLocaleToLanguage( + const css::lang::Locale & rLocale ); + + /** Used by convertLocaleToLanguage(Locale) */ + I18NLANGTAG_DLLPRIVATE static LanguageType convertLocaleToLanguageImpl( + const css::lang::Locale & rLocale ); + + /** Convert x-... privateuse, used by convertLocaleToLanguageImpl(Locale) */ + I18NLANGTAG_DLLPRIVATE static LanguageType convertPrivateUseToLanguage( + const OUString& rPriv ); + + /** Used by LanguageTag::canonicalize() */ + I18NLANGTAG_DLLPRIVATE static css::lang::Locale getOverride( + const css::lang::Locale & rLocale ); + + /** Used by convertLocaleToLanguageImpl(Locale) and LanguageTagImpl::convertLocaleToLang() */ + I18NLANGTAG_DLLPRIVATE static LanguageType convertIsoNamesToLanguage( + const OUString& rLang, const OUString& rCountry, bool bSkipIsoTable ); + + + /** Used by convertUnxByteStringToLanguage(OString) */ + I18NLANGTAG_DLLPRIVATE static LanguageType convertIsoNamesToLanguage( + std::string_view rLang, std::string_view rCountry ); + + + /** Used by lookupFallbackLocale(Locale) */ + I18NLANGTAG_DLLPRIVATE static css::lang::Locale getLocale( + const IsoLanguageCountryEntry * pEntry ); + + /** Used by lookupFallbackLocale(Locale) */ + I18NLANGTAG_DLLPRIVATE static css::lang::Locale getLocale( + const IsoLanguageScriptCountryEntry * pEntry ); + + /** Used by lookupFallbackLocale(Locale) */ + I18NLANGTAG_DLLPRIVATE static css::lang::Locale getLocale( + const Bcp47CountryEntry * pEntry ); + + + /** Convert a LanguageType to a Locale. */ + I18NLANGTAG_DLLPRIVATE static css::lang::Locale convertLanguageToLocale( + LanguageType nLang ); + + /** Used by convertLanguageToLocale(LanguageType,bool) and + getLocale(IsoLanguageCountryEntry*) and + getLocale(IsoLanguageScriptCountryEntry) + + @param bIgnoreOverride + If bIgnoreOverride==true, a matching entry is used even if + mnOverride is set, for conversion to an even outdated tag. + If bIgnoreOverride==false, a matching entry is skipped if + mnOverride is set and instead the override is followed. + + @return rLocale set to mapped values, unchanged if no mapping was + found. E.g. pass empty Locale to obtain empty SYSTEM locale + for that case. + */ + I18NLANGTAG_DLLPRIVATE static void convertLanguageToLocaleImpl( + LanguageType nLang, css::lang::Locale & rLocale, bool bIgnoreOverride ); + + + I18NLANGTAG_DLLPRIVATE static css::lang::Locale lookupFallbackLocale( + const css::lang::Locale & rLocale ); + }; + +private: + + static LanguageType nConfiguredSystemLanguage; + static LanguageType nConfiguredSystemUILanguage; + + static LanguageType nConfiguredWesternFallback; + static LanguageType nConfiguredAsianFallback; + static LanguageType nConfiguredComplexFallback; + + static LanguageType getPlatformSystemLanguage(); + static LanguageType getPlatformSystemUILanguage(); + + // Substitute LANGUAGE_SYSTEM for LANGUAGE_SYSTEM_DEFAULT and + // LANGUAGE_PROCESS_OR_USER_DEFAULT, other values aren't touched. + I18NLANGTAG_DLLPRIVATE static inline LanguageType simplifySystemLanguages( LanguageType nLang ); +}; + +#endif // INCLUDED_I18NLANGTAG_MSLANGID_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18npool/reservedconstants.hxx b/include/i18npool/reservedconstants.hxx new file mode 100644 index 000000000..6f707f83a --- /dev/null +++ b/include/i18npool/reservedconstants.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include + +/** Constant values shared between i18npool and, for example, the number formatter. */ +namespace i18npool +{ +/** The number of predefined format code indices that must be defined by + locale data, except BOOLEAN and TEXT, exclusive. + This later in the build is static asserted to be equal to + NfIndexTableOffset::NF_INDEX_TABLE_RESERVED_START. */ +constexpr sal_Int16 nStopPredefinedFormatIndex = 51; + +/** The number of reserved (with defined meaning) built-in format code indices, + additional locale data format codes can be defined starting at this index + value. + This later in the build is static asserted to be greater or equal to + NfIndexTableOffset::NF_INDEX_TABLE_ENTRIES */ +constexpr sal_Int16 nFirstFreeFormatIndex = 66; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/i18nutil/calendar.hxx b/include/i18nutil/calendar.hxx new file mode 100644 index 000000000..86a5beacd --- /dev/null +++ b/include/i18nutil/calendar.hxx @@ -0,0 +1,23 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +namespace i18nutil +{ +/** This number shows month days without Jan and Feb. + * According to the article, it is calculated as (365-31-28)/10 = 30.6, but because + * of a floating point bug, it was used as 30.6001 as a workaround. + * + * "30.6001, 25 year old hack?" + * https://www.hpmuseum.org/cgi-sys/cgiwrap/hpmuseum/archv011.cgi?read=31650 */ +constexpr double monthDaysWithoutJanFeb = (365 - 31 - 28) / 10.0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/i18nutil/casefolding.hxx b/include/i18nutil/casefolding.hxx new file mode 100644 index 000000000..b15a51ae8 --- /dev/null +++ b/include/i18nutil/casefolding.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_CASEFOLDING_HXX +#define INCLUDED_I18NUTIL_CASEFOLDING_HXX + +#include +#include +#include +#include + +namespace com::sun::star::lang { struct Locale; } + +enum class TransliterationFlags; + +enum class MappingType { + NONE = 0x00, + LowerToUpper = 0x01, // Upper to Lower mapping + UpperToLower = 0x02, // Lower to Upper mapping + ToUpper = 0x04, // to Upper mapping + ToLower = 0x08, // to Lower mapping + ToTitle = 0x10, // to Title mapping + SimpleFolding = 0x20, // Simple Case Folding + FullFolding = 0x40, // Full Case Folding + // for final sigma (where the case-mapping is different for the last letter of a word) + CasedLetterMask = LowerToUpper | UpperToLower | ToUpper | ToLower | ToTitle | SimpleFolding | FullFolding, + NotValue = 0x80, // Value field is an address +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +namespace i18nutil { + +struct Value +{ + sal_uInt8 type; + sal_uInt16 value; // value or address, depend on the type +}; + +struct Mapping +{ + sal_uInt8 type; + sal_Int8 nmap; +#define NMAPPINGMAX 3 + sal_Unicode map[NMAPPINGMAX]; +}; // for Unconditional mapping + +struct MappingElement +{ + MappingElement() + : current(0) + { + element.type = element.nmap = 0; + } + Mapping element; + sal_Int8 current; +}; + +class UNLESS_MERGELIBS(I18NUTIL_DLLPUBLIC) casefolding +{ +public: + /// @throws css::uno::RuntimeException + static Mapping getValue(const sal_Unicode* str, sal_Int32 pos, sal_Int32 len, css::lang::Locale const & aLocale, MappingType nMappingType); + /// @throws css::uno::RuntimeException + static const Mapping& getConditionalValue(const sal_Unicode* str, sal_Int32 pos, sal_Int32 len, css::lang::Locale const & aLocale, MappingType nMappingType); + /// @throws css::uno::RuntimeException + static sal_Unicode getNextChar(const sal_Unicode *str, sal_Int32& idx, sal_Int32 len, MappingElement& e, css::lang::Locale const & aLocale, MappingType nMappingtype, TransliterationFlags moduleLoaded); + +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/i18nutildllapi.h b/include/i18nutil/i18nutildllapi.h new file mode 100644 index 000000000..9797e87a3 --- /dev/null +++ b/include/i18nutil/i18nutildllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_I18NUTIL_I18NUTILDLLAPI_H +#define INCLUDED_I18NUTIL_I18NUTILDLLAPI_H + +#include + +#if defined(I18NUTIL_DLLIMPLEMENTATION) +#define I18NUTIL_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define I18NUTIL_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define I18NUTIL_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_I18NUTIL_I18NUTILDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/oneToOneMapping.hxx b/include/i18nutil/oneToOneMapping.hxx new file mode 100644 index 000000000..bc659b30a --- /dev/null +++ b/include/i18nutil/oneToOneMapping.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_ONETOONEMAPPING_HXX +#define INCLUDED_I18NUTIL_ONETOONEMAPPING_HXX + +#include +#include +#include + +namespace i18nutil { + +struct OneToOneMappingTable_t +{ + sal_Unicode first; + sal_Unicode second; +}; + +typedef sal_Int8 UnicodePairFlag; +struct UnicodePairWithFlag +{ + sal_Unicode first; + sal_Unicode second; + UnicodePairFlag flag; +}; + +class UNLESS_MERGELIBS(I18NUTIL_DLLPUBLIC) oneToOneMapping +{ +private: + oneToOneMapping(const oneToOneMapping&) = delete; + oneToOneMapping& operator=(const oneToOneMapping&) = delete; +public: + oneToOneMapping( OneToOneMappingTable_t const *rpTable, const size_t rnSize, const size_t rnUnitSize = sizeof(OneToOneMappingTable_t) ); + virtual ~oneToOneMapping(); + + // binary search + virtual sal_Unicode find( const sal_Unicode nKey ) const; + + // translator + sal_Unicode operator[] ( const sal_Unicode nKey ) const { return find( nKey ); }; + +protected: + OneToOneMappingTable_t const *mpTable; + size_t mnSize; +}; + +class oneToOneMappingWithFlag final : public oneToOneMapping +{ +private: + oneToOneMappingWithFlag(const oneToOneMappingWithFlag&) = delete; + oneToOneMappingWithFlag& operator=(const oneToOneMappingWithFlag&) = delete; + + friend class widthfolding; + +public: + oneToOneMappingWithFlag( UnicodePairWithFlag const *rpTableWF, const size_t rnSize, const UnicodePairFlag rnFlag ); + virtual ~oneToOneMappingWithFlag() override; + + // make index for fast search + void makeIndex(); + + // index search + virtual sal_Unicode find( const sal_Unicode nKey ) const override; +private: + UnicodePairWithFlag const *mpTableWF; + UnicodePairFlag mnFlag; + std::unique_ptr mpIndex[256]; + bool mbHasIndex; +}; + +} + +#endif // _I18N_TRANSLITERATION_ONETOONEMAPPING_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/paper.hxx b/include/i18nutil/paper.hxx new file mode 100644 index 000000000..b84d7b3af --- /dev/null +++ b/include/i18nutil/paper.hxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_I18NUTIL_PAPER_HXX +#define INCLUDED_I18NUTIL_PAPER_HXX + +#include +#include +#include + +namespace com::sun::star::lang +{ +struct Locale; +} + +//!! The values of the following enumerators must correspond to the array position +//!! of the respective paper size in the file i18nutil/source/utility/paper.cxx +//!! Thus don't reorder the enum values here without changing the code there as well. + +//!! Also the RID_STR_PAPERNAMES array in vcl/inc/print.hrc and the +//!! PaperIndex array in Printer::GetPaperName() in +//!! vcl/source/gdi/print.cxx are parallel to this enum. +enum Paper : unsigned +{ + PAPER_A0, + PAPER_A1, + PAPER_A2, + PAPER_A3, + PAPER_A4, + PAPER_A5, + PAPER_B4_ISO, + PAPER_B5_ISO, + PAPER_LETTER, + PAPER_LEGAL, + PAPER_TABLOID, + PAPER_USER, + PAPER_B6_ISO, + PAPER_ENV_C4, + PAPER_ENV_C5, + PAPER_ENV_C6, + PAPER_ENV_C65, + PAPER_ENV_DL, + PAPER_SLIDE_DIA, + PAPER_SCREEN_4_3, + PAPER_C, + PAPER_D, + PAPER_E, + PAPER_EXECUTIVE, + PAPER_FANFOLD_LEGAL_DE, + PAPER_ENV_MONARCH, + PAPER_ENV_PERSONAL, + PAPER_ENV_9, + PAPER_ENV_10, + PAPER_ENV_11, + PAPER_ENV_12, + PAPER_KAI16, + PAPER_KAI32, + PAPER_KAI32BIG, + PAPER_B4_JIS, + PAPER_B5_JIS, + PAPER_B6_JIS, + PAPER_LEDGER, + PAPER_STATEMENT, + PAPER_QUARTO, + PAPER_10x14, + PAPER_ENV_14, + PAPER_ENV_C3, + PAPER_ENV_ITALY, + PAPER_FANFOLD_US, + PAPER_FANFOLD_DE, + PAPER_POSTCARD_JP, + PAPER_9x11, + PAPER_10x11, + PAPER_15x11, + PAPER_ENV_INVITE, + PAPER_A_PLUS, + PAPER_B_PLUS, + PAPER_LETTER_PLUS, + PAPER_A4_PLUS, + PAPER_DOUBLEPOSTCARD_JP, + PAPER_A6, + PAPER_12x11, + PAPER_A7, + PAPER_A8, + PAPER_A9, + PAPER_A10, + PAPER_B0_ISO, + PAPER_B1_ISO, + PAPER_B2_ISO, + PAPER_B3_ISO, + PAPER_B7_ISO, + PAPER_B8_ISO, + PAPER_B9_ISO, + PAPER_B10_ISO, + PAPER_ENV_C2, + PAPER_ENV_C7, + PAPER_ENV_C8, + PAPER_ARCHA, + PAPER_ARCHB, + PAPER_ARCHC, + PAPER_ARCHD, + PAPER_ARCHE, + PAPER_SCREEN_16_9, + PAPER_SCREEN_16_10, + PAPER_16K_195x270, + PAPER_16K_197x273, + PAPER_WIDESCREEN, //PowerPoint Widescreen + PAPER_ONSCREENSHOW_4_3, //PowerPoint On-screen Show (4:3) + PAPER_ONSCREENSHOW_16_9, //PowerPoint On-screen Show (16:9) + PAPER_ONSCREENSHOW_16_10 //PowerPoint On-screen Show (16:10) +}; + +// defined for 'equal size' test with the implementation array +#define NUM_PAPER_ENTRIES (PAPER_ONSCREENSHOW_16_10 - PAPER_A0 + 1) + +class I18NUTIL_DLLPUBLIC PaperInfo +{ + Paper m_eType; + tools::Long m_nPaperWidth; // width in 100thMM + tools::Long m_nPaperHeight; // height in 100thMM +public: + PaperInfo(Paper eType); + PaperInfo(tools::Long nPaperWidth, tools::Long nPaperHeight); + + Paper getPaper() const { return m_eType; } + tools::Long getWidth() const { return m_nPaperWidth; } + tools::Long getHeight() const { return m_nPaperHeight; } + bool sloppyEqual(const PaperInfo& rOther) const; + void doSloppyFit(bool bAlsoTryRotated = false); + + static PaperInfo getSystemDefaultPaper(); + static PaperInfo getDefaultPaperForLocale(const css::lang::Locale& rLocale); + + static Paper fromPSName(const OString& rName); + static OString toPSName(Paper eType); + + static tools::Long sloppyFitPageDimension(tools::Long nDimension); +}; + +#endif // INCLUDED_I18NUTIL_PAPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/scripttypedetector.hxx b/include/i18nutil/scripttypedetector.hxx new file mode 100644 index 000000000..a3d4d8ed2 --- /dev/null +++ b/include/i18nutil/scripttypedetector.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_SCRIPTTYPEDETECTOR_HXX +#define INCLUDED_I18NUTIL_SCRIPTTYPEDETECTOR_HXX + +#include +#include + +class I18NUTIL_DLLPUBLIC ScriptTypeDetector +{ +public: + static sal_Int32 beginOfScriptDirection( std::u16string_view Text, sal_Int32 nPos, sal_Int16 scriptDirection ); + static sal_Int32 endOfScriptDirection( std::u16string_view Text, sal_Int32 nPos, sal_Int16 scriptDirection ); + static sal_Int16 getScriptDirection( std::u16string_view Text, sal_Int32 nPos, sal_Int16 defaultScriptDirection ); + static sal_Int32 beginOfCTLScriptType( std::u16string_view Text, sal_Int32 nPos ); + static sal_Int32 endOfCTLScriptType( std::u16string_view Text, sal_Int32 nPos ); + static sal_Int16 getCTLScriptType(std::u16string_view Text, sal_Int32 nPos ); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/searchopt.hxx b/include/i18nutil/searchopt.hxx new file mode 100644 index 000000000..c215da0d2 --- /dev/null +++ b/include/i18nutil/searchopt.hxx @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_SEARCHOPT_HXX +#define INCLUDED_I18NUTIL_SEARCHOPT_HXX + +#include +#include +#include +#include +#include +#include + +namespace i18nutil +{ + +/** + * This is a wrapper around com::sun::star::util::SearchOptions + * but using the more type-safe TransliterationFlags enum. + */ +struct SAL_WARN_UNUSED SearchOptions { + css::util::SearchAlgorithms algorithmType; + sal_Int32 searchFlag; + OUString searchString; + OUString replaceString; + css::lang::Locale Locale; + sal_Int32 changedChars; + sal_Int32 deletedChars; + sal_Int32 insertedChars; + TransliterationFlags transliterateFlags; + + SearchOptions& operator=(css::util::SearchOptions const & other) + { + algorithmType = other.algorithmType; + searchFlag = other.searchFlag; + searchString = other.searchString; + replaceString = other.replaceString; + Locale = other.Locale; + changedChars = other.changedChars; + deletedChars = other.deletedChars; + insertedChars = other.insertedChars; + transliterateFlags = static_cast(other.transliterateFlags); + return *this; + } + + SearchOptions() + : algorithmType(::css::util::SearchAlgorithms_ABSOLUTE) + , searchFlag(0) + , changedChars(0) + , deletedChars(0) + , insertedChars(0) + , transliterateFlags(TransliterationFlags::NONE) + { + } + + SearchOptions(const css::util::SearchAlgorithms& algorithmType_, const sal_Int32 searchFlag_, + OUString searchString_, OUString replaceString_, + css::lang::Locale Locale_, + const sal_Int32 changedChars_, const sal_Int32 deletedChars_, const sal_Int32 insertedChars_, + const TransliterationFlags& transliterateFlags_) + : algorithmType(algorithmType_) + , searchFlag(searchFlag_) + , searchString(std::move(searchString_)) + , replaceString(std::move(replaceString_)) + , Locale(std::move(Locale_)) + , changedChars(changedChars_) + , deletedChars(deletedChars_) + , insertedChars(insertedChars_) + , transliterateFlags(transliterateFlags_) + { + } +}; + +/** + * This is a wrapper around com::sun::star::util::SearchOptions and SearchOptions2, + * but using the more type-safe TransliterationFlags enum. + */ +struct SAL_WARN_UNUSED SearchOptions2 : public SearchOptions { + + sal_Int16 AlgorithmType2; + sal_Int32 WildcardEscapeCharacter; + + SearchOptions2& operator=(css::util::SearchOptions2 const & other) + { + SearchOptions::operator=(other); + AlgorithmType2 = other.AlgorithmType2; + WildcardEscapeCharacter = other.WildcardEscapeCharacter; + return *this; + } + + + css::util::SearchOptions2 toUnoSearchOptions2() const + { + return css::util::SearchOptions2(algorithmType, searchFlag, + searchString, replaceString, + Locale, + changedChars, deletedChars, insertedChars, + static_cast(transliterateFlags), + AlgorithmType2, WildcardEscapeCharacter); + } + + SearchOptions2() + : AlgorithmType2(0) + , WildcardEscapeCharacter(0) + {} + + SearchOptions2(const css::util::SearchAlgorithms& algorithmType_, const sal_Int32 searchFlag_, + const OUString& searchString_, const OUString& replaceString_, + const css::lang::Locale& Locale_, + const sal_Int32 changedChars_, const sal_Int32 deletedChars_, const sal_Int32 insertedChars_, + const TransliterationFlags& transliterateFlags_, + const sal_Int16 AlgorithmType2_, const sal_Int32 WildcardEscapeCharacter_) + : SearchOptions(algorithmType_, searchFlag_, searchString_, replaceString_, Locale_, changedChars_, deletedChars_, insertedChars_, transliterateFlags_) + , AlgorithmType2(AlgorithmType2_) + , WildcardEscapeCharacter(WildcardEscapeCharacter_) + {} +}; + +}; // namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/transliteration.hxx b/include/i18nutil/transliteration.hxx new file mode 100644 index 000000000..7de575999 --- /dev/null +++ b/include/i18nutil/transliteration.hxx @@ -0,0 +1,133 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_TRANSLITERATION_HXX +#define INCLUDED_I18NUTIL_TRANSLITERATION_HXX + +#include +#include +#include + +/** + * This is a superset type of the com::sun::star::i18n::TransliterationModules and TransliterationModulesExtra, + * with some extra type checking + */ +enum class TransliterationFlags { + NONE = 0, + /// Transliterate a string from upper case to lower case + UPPERCASE_LOWERCASE = int(css::i18n::TransliterationModules_UPPERCASE_LOWERCASE), + /// Transliterate a string from lower case to upper case + LOWERCASE_UPPERCASE = int(css::i18n::TransliterationModules_LOWERCASE_UPPERCASE), + /// Transliterate a string from half width character to full width character + HALFWIDTH_FULLWIDTH = int(css::i18n::TransliterationModules_HALFWIDTH_FULLWIDTH), + /// Transliterate a string from full width character to half width character + FULLWIDTH_HALFWIDTH = int(css::i18n::TransliterationModules_FULLWIDTH_HALFWIDTH), + /// Transliterate a Japanese string from Katakana to Hiragana + KATAKANA_HIRAGANA = int(css::i18n::TransliterationModules_KATAKANA_HIRAGANA), + /// Transliterate a Japanese string from Hiragana to Katakana + HIRAGANA_KATAKANA = int(css::i18n::TransliterationModules_HIRAGANA_KATAKANA), + /// Transliterate an ASCII number string to Simplified Chinese lower case number string in spellout format + NumToTextLower_zh_CN = int(css::i18n::TransliterationModules_NumToTextLower_zh_CN), + /// Transliterate an ASCII number string to Simplified Chinese upper case number string in spellout format + NumToTextUpper_zh_CN = int(css::i18n::TransliterationModules_NumToTextUpper_zh_CN), + /// Transliterate an ASCII number string to Traditional Chinese lower case number string in spellout format + NumToTextLower_zh_TW = int(css::i18n::TransliterationModules_NumToTextLower_zh_TW), + /// Transliterate an ASCII number string to Traditional Chinese upper case number string in spellout format + NumToTextUpper_zh_TW = int(css::i18n::TransliterationModules_NumToTextUpper_zh_TW), + /// Transliterate an ASCII number string to formal Korean Hangul number string in spellout format + NumToTextFormalHangul_ko = int(css::i18n::TransliterationModules_NumToTextFormalHangul_ko), + /// Transliterate an ASCII number string to formal Korean Hanja lower case number string in spellout format + NumToTextFormalLower_ko = int(css::i18n::TransliterationModules_NumToTextFormalLower_ko), + /// Transliterate an ASCII number string to formal Korean Hanja upper case number string in spellout format + NumToTextFormalUpper_ko = int(css::i18n::TransliterationModules_NumToTextFormalUpper_ko), + + /** The first character of the sentence is put in upper case + */ + SENTENCE_CASE = int(css::i18n::TransliterationModulesExtra::SENTENCE_CASE), + + + /** The first character of the word is put in upper case. + * This one is part + */ + TITLE_CASE = int(css::i18n::TransliterationModulesExtra::TITLE_CASE), + + + /** All characters of the word are to change their case from small letters + * to capital letters and vice versa. + */ + TOGGLE_CASE = int(css::i18n::TransliterationModulesExtra::TOGGLE_CASE), + + NON_IGNORE_MASK = int(css::i18n::TransliterationModules_NON_IGNORE_MASK), + IGNORE_MASK = 0x7fffff00, + + /// Ignore case when comparing strings by transliteration service + IGNORE_CASE = int(css::i18n::TransliterationModules_IGNORE_CASE), + /// Ignore Hiragana and Katakana when comparing strings by transliteration service + IGNORE_KANA = int(css::i18n::TransliterationModules_IGNORE_KANA), // ja_JP + /// Ignore full width and half width character when comparing strings by transliteration service + IGNORE_WIDTH = int(css::i18n::TransliterationModules_IGNORE_WIDTH), // ja_JP + /// Ignore Japanese traditional Kanji character in Japanese fuzzy search + ignoreTraditionalKanji_ja_JP = int(css::i18n::TransliterationModules_IgnoreTraditionalKanji_ja_JP), + /// Ignore Japanese traditional Katakana and Hiragana character in Japanese fuzzy search + ignoreTraditionalKana_ja_JP = int(css::i18n::TransliterationModules_IgnoreTraditionalKana_ja_JP), + /// Ignore dash or minus sign in Japanese fuzzy search + ignoreMinusSign_ja_JP = int(css::i18n::TransliterationModules_IgnoreMinusSign_ja_JP), + /// Ignore Hiragana and Katakana iteration mark in Japanese fuzzy search + ignoreIterationMark_ja_JP = int(css::i18n::TransliterationModules_IgnoreIterationMark_ja_JP), + /// Ignore separator punctuations in Japanese fuzzy search + ignoreSeparator_ja_JP = int(css::i18n::TransliterationModules_IgnoreSeparator_ja_JP), + /// Ignore Katakana and Hiragana Zi/Zi and Zu/Zu in Japanese fuzzy search + ignoreZiZu_ja_JP = int(css::i18n::TransliterationModules_IgnoreZiZu_ja_JP), + /// Ignore Katakana and Hiragana Ba/Gua and Ha/Fa in Japanese fuzzy search + ignoreBaFa_ja_JP = int(css::i18n::TransliterationModules_IgnoreBaFa_ja_JP), + /// Ignore Katakana and Hiragana Tsui/Tea/Ti and Dyi/Ji in Japanese fuzzy search + ignoreTiJi_ja_JP = int(css::i18n::TransliterationModules_IgnoreTiJi_ja_JP), + /// Ignore Katakana and Hiragana Hyu/Fyu and Byu/Gyu in Japanese fuzzy search + ignoreHyuByu_ja_JP = int(css::i18n::TransliterationModules_IgnoreHyuByu_ja_JP), + /// Ignore Katakana and Hiragana Se/Sye and Ze/Je in Japanese fuzzy search + ignoreSeZe_ja_JP = int(css::i18n::TransliterationModules_IgnoreSeZe_ja_JP), + /// Ignore Katakana YA/A which follows the character in either I or E row in Japanese fuzzy search + ignoreIandEfollowedByYa_ja_JP = int(css::i18n::TransliterationModules_IgnoreIandEfollowedByYa_ja_JP), + /// Ignore Katakana KI/KU which follows the character in SA column in Japanese fuzzy search + ignoreKiKuFollowedBySa_ja_JP = int(css::i18n::TransliterationModules_IgnoreKiKuFollowedBySa_ja_JP), + /// Ignore Japanese normal and small sized character in Japanese fuzzy search + ignoreSize_ja_JP = int(css::i18n::TransliterationModules_IgnoreSize_ja_JP), + /// Ignore Japanese prolonged sound mark in Japanese fuzzy search + ignoreProlongedSoundMark_ja_JP = int(css::i18n::TransliterationModules_IgnoreProlongedSoundMark_ja_JP), + /// Ignore middle dot in Japanese fuzzy search + ignoreMiddleDot_ja_JP = int(css::i18n::TransliterationModules_IgnoreMiddleDot_ja_JP), + /// Ignore white space characters, include space, TAB, return, etc. in Japanese fuzzy search + ignoreSpace_ja_JP = int(css::i18n::TransliterationModules_IgnoreSpace_ja_JP), + /// transliterate Japanese small sized character to normal sized character + smallToLarge_ja_JP = int(css::i18n::TransliterationModules_SmallToLarge_ja_JP), + /// transliterate Japanese normal sized character to small sized character + largeToSmall_ja_JP = int(css::i18n::TransliterationModules_LargeToSmall_ja_JP), + + /// Transliterate decomposing and removing diacritics, not only CTL, despite its name. + IGNORE_DIACRITICS_CTL = int(css::i18n::TransliterationModulesExtra::IGNORE_DIACRITICS_CTL), + /// Ignore Kashida mark. + IGNORE_KASHIDA_CTL = int(css::i18n::TransliterationModulesExtra::IGNORE_KASHIDA_CTL) +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/unicode.hxx b/include/i18nutil/unicode.hxx new file mode 100644 index 000000000..c14d22cec --- /dev/null +++ b/include/i18nutil/unicode.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_UNICODE_HXX +#define INCLUDED_I18NUTIL_UNICODE_HXX + +#include +#include +#include +#include +#include + +class LanguageTag; + +struct ScriptTypeList +{ + css::i18n::UnicodeScript from; + css::i18n::UnicodeScript to; + sal_Int16 value; +}; + +class I18NUTIL_DLLPUBLIC unicode +{ +public: + static sal_Int16 getUnicodeType(const sal_Unicode ch); + static sal_Int16 getUnicodeScriptType(const sal_Unicode ch, const ScriptTypeList* typeList, + sal_Int16 unknownType = 0); + static sal_Unicode getUnicodeScriptStart(css::i18n::UnicodeScript type); + static sal_Unicode getUnicodeScriptEnd(css::i18n::UnicodeScript type); + static sal_uInt8 getUnicodeDirection(const sal_Unicode ch); + static sal_uInt32 GetMirroredChar(sal_uInt32); + static bool isControl(const sal_Unicode ch); + static bool isAlpha(const sal_Unicode ch); + static bool isSpace(const sal_Unicode ch); + static bool isWhiteSpace(const sal_Unicode ch); + + /** Check for Unicode variation sequence selectors + + @param nCode A Unicode code point. + + @return True if code is a Unicode variation sequence selector. + */ + static bool isIVSSelector(sal_uInt32 nCode) + { + return (nCode >= 0xFE00 && nCode <= 0xFE0F) // Variation Selectors block + || (nCode >= 0xE0100 && nCode <= 0xE01EF); // Variation Selectors Supplement block + } + + /** Check for base characters of a CJK ideographic variation sequence (IVS) + + @param nCode A Unicode code point. + + @return True if code is a Unicode base character part of CJK IVS + */ + static bool isCJKIVSCharacter(sal_uInt32 nCode) + { + return (nCode >= 0x4E00 && nCode <= 0x9FFF) // CJK Unified Ideographs + || (nCode >= 0x3400 && nCode <= 0x4DBF) // CJK Unified Ideographs Extension A + || (nCode >= 0x20000 && nCode <= 0x2A6DF); // CJK Unified Ideographs Extension B + } + + //Map an ISO 15924 script code to Latin/Asian/Complex/Weak + static sal_Int16 getScriptClassFromUScriptCode(UScriptCode eScript); + + //Return a language that can be written in a given ISO 15924 script code + static OString getExemplarLanguageForUScriptCode(UScriptCode eScript); + + //Format a number as a percentage according to the rules of the given + //language, e.g. 100 -> "100%" for en-US vs "100 %" for de-DE + static OUString formatPercent(double dNumber, const LanguageTag& rLangTag); +}; + +/* + Toggle between a character and its Unicode Notation. + -implements the concept found in Microsoft Word's Alt-X + -accepts sequences of up to 8 hex characters and converts into the corresponding Unicode Character + -example: 0000A78c or 2bc + -accepts sequences of up to 256 characters in Unicode notation + -example: U+00000065u+0331u+308 + -handles complex characters (with combining elements) and the all of the Unicode planes. +*/ +class I18NUTIL_DLLPUBLIC ToggleUnicodeCodepoint +{ +private: + OUStringBuffer maInput; + OUStringBuffer maUtf16; + OUStringBuffer maCombining; + bool mbAllowMoreChars = true; + bool mbRequiresU = false; + bool mbIsHexString = false; + +public: + /** + Build an input string of valid UTF16 units to toggle. + -do not call the other functions until the input process is complete + -build string from Right to Left. (Start from the character to the left of the cursor: move left.) + */ + bool AllowMoreInput(sal_Unicode uChar); + + /** + Validates (and potentially modifies) the input string. + -all non-input functions must use this function to first to validate the input string + -additional input may be prevented after this function is called + */ + OUString StringToReplace(); + OUString ReplacementString(); + + /** + While sInput.getLength() returns the number of utf16 units to delete, + this function returns the number of "characters" to delete - potentially a smaller number + */ + sal_uInt32 CharsToDelete(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/i18nutil/widthfolding.hxx b/include/i18nutil/widthfolding.hxx new file mode 100644 index 000000000..87b909b91 --- /dev/null +++ b/include/i18nutil/widthfolding.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_I18NUTIL_WIDTHFOLDING_HXX +#define INCLUDED_I18NUTIL_WIDTHFOLDING_HXX + +#include +#include +#include +#include + +namespace com::sun::star::uno { template class Sequence; } +namespace i18nutil { class oneToOneMapping; } + +namespace i18nutil { + +#define WIDTHFOLDING_DONT_USE_COMBINED_VU 0x01 + +class UNLESS_MERGELIBS(I18NUTIL_DLLPUBLIC) widthfolding +{ +public: + static oneToOneMapping& getfull2halfTable(); + static oneToOneMapping& gethalf2fullTable(); + + static oneToOneMapping& getfull2halfTableForASC(); + static oneToOneMapping& gethalf2fullTableForJIS(); + + static oneToOneMapping& getfullKana2halfKanaTable(); + static oneToOneMapping& gethalfKana2fullKanaTable(); + + static OUString decompose_ja_voiced_sound_marks(const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, css::uno::Sequence< sal_Int32 >* pOffset); + static sal_Unicode decompose_ja_voiced_sound_marksChar2Char (sal_Unicode inChar); + static OUString compose_ja_voiced_sound_marks(const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, css::uno::Sequence< sal_Int32 >* pOffset, sal_Int32 nFlags = 0 ); + static sal_Unicode getCompositionChar(sal_Unicode c1, sal_Unicode c2); +}; + + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/jvmaccess/classpath.hxx b/include/jvmaccess/classpath.hxx new file mode 100644 index 000000000..416b64a33 --- /dev/null +++ b/include/jvmaccess/classpath.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_JVMACCESS_CLASSPATH_HXX +#define INCLUDED_JVMACCESS_CLASSPATH_HXX + +#include + +#if defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-attributes" +#endif +#include +#if defined __clang__ +#pragma clang diagnostic pop +#endif + +#include +#include + +namespace com::sun::star::uno +{ +class XComponentContext; +} + +namespace com::sun::star::uno +{ +template class Reference; +} + +namespace jvmaccess +{ +/** + Helper functions for class path handling. + */ +namespace ClassPath +{ +/** + translates a class path into a java.net.URL[] instance. + + @param context + a component context; must not be null. + + @param environment + a JNI environment; must not be null. + + @param classPath + a list of zero or more internal (see the + com.sun.star.uri.ExternalUriReferenceTranslator service) URI references, + where any space characters (U+0020) are ignored (and, in particular, separate + adjacent URI references). Any vnd.sun.star.expand URL references in the list + are expanded using the com.sun.star.util.theMacroExpander singleton of the + given context. + + @returns + a local reference to a java.net.URL[] instance containing the external (see + the com.sun.star.uri.ExternalUriReferenceTranslator service) equivalents of + all the URI references in the given classPath. If null, a (still pending) + JNI exception occurred. + + @throws com::sun::star::uno::RuntimeException + */ +JVMACCESS_DLLPUBLIC jobjectArray +translateToUrls(css::uno::Reference const& context, + JNIEnv* environment, std::u16string_view classPath); +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/jvmaccess/jvmaccessdllapi.h b/include/jvmaccess/jvmaccessdllapi.h new file mode 100644 index 000000000..1c57d1484 --- /dev/null +++ b/include/jvmaccess/jvmaccessdllapi.h @@ -0,0 +1,24 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_JVMACCESS_JVMACCESSDLLAPI_H +#define INCLUDED_JVMACCESS_JVMACCESSDLLAPI_H + +#include + +#if defined JVMACCESS_DLLIMPLEMENTATION +#define JVMACCESS_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define JVMACCESS_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define JVMACCESS_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/jvmaccess/unovirtualmachine.hxx b/include/jvmaccess/unovirtualmachine.hxx new file mode 100644 index 000000000..1b424dba9 --- /dev/null +++ b/include/jvmaccess/unovirtualmachine.hxx @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_JVMACCESS_UNOVIRTUALMACHINE_HXX +#define INCLUDED_JVMACCESS_UNOVIRTUALMACHINE_HXX + +#include +#include +#include +#include + +namespace jvmaccess +{ +class VirtualMachine; + +/** An encapsulating wrapper around a Java virtual machine and an appropriate + UNO class loader. + */ +class JVMACCESS_DLLPUBLIC UnoVirtualMachine final : public salhelper::SimpleReferenceObject +{ +public: + /** An exception indicating failure to create a UnoVirtualMachine. + */ + class JVMACCESS_DLLPUBLIC CreationException final + { + public: + CreationException(); + + CreationException(CreationException const&); + + CreationException& operator=(CreationException const&); + }; + + /** Create a wrapper around a Java virtual machine and an appropriate UNO + class loader. + + @param virtualMachine + A Java virtual machine wrapper. Must not be null. + + @param classLoader + A local or global JNI reference, relative to the given virtualMachine, + to an appropriate UNO class loader instance. Must not be null. This + parameter should be of type jobject, not void *, but the exact + definition of jobject is different for different JDK versions, so that + the mangled C++ name of the constructor would depend on the JDK version + used at compile time. + + @exception CreationException + Thrown in case creation fails (due to a JNI problem). + */ + UnoVirtualMachine(rtl::Reference virtualMachine, void* classLoader); + + /** Get the Java virtual machine wrapper. + + @return + The Java virtual machine wrapper. Will never be null. + */ + const rtl::Reference& getVirtualMachine() const; + + /** Get the UNO class loader. + + @return + A global JNI reference to the UNO class loader. (The JNI reference must + not be deleted by client code.) Will never be null. This should be of + type jobject, not void *, but the exact definition of jobject is + different for different JDK versions, so that the mangled C++ name of + the function would depend on the JDK version used at compile time. + */ + void* getClassLoader() const { return m_classLoader; } + +private: + UnoVirtualMachine(UnoVirtualMachine const&) = delete; + UnoVirtualMachine& operator=(UnoVirtualMachine const&) = delete; + + virtual ~UnoVirtualMachine() override; + + rtl::Reference m_virtualMachine; + void* m_classLoader; +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/jvmaccess/virtualmachine.hxx b/include/jvmaccess/virtualmachine.hxx new file mode 100644 index 000000000..e1286e700 --- /dev/null +++ b/include/jvmaccess/virtualmachine.hxx @@ -0,0 +1,154 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX +#define INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX + +#include +#include +#include + +#if defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-attributes" +#endif +#include +#if defined __clang__ +#pragma clang diagnostic pop +#endif + +namespace jvmaccess +{ +/** An encapsulating wrapper around a Java virtual machine. + */ +class JVMACCESS_DLLPUBLIC VirtualMachine final : public salhelper::SimpleReferenceObject +{ +public: + /** A helper to attach a thread to a Java virtual machine. + + @descr + Upon construction of a guard the current thread is attached to the + virtual machine, and upon destruction of the guard the thread is + detached again. For any one thread, multiple instances of this class + may be used in a stack-like fashion (care is taken to only really + detach the thread from the virtual machine upon destruction of the guard + at the bottom of the stack). + */ + class JVMACCESS_DLLPUBLIC AttachGuard + { + public: + /** An exception indicating failure to create an AttachGuard. + */ + class JVMACCESS_DLLPUBLIC CreationException final + { + public: + CreationException(); + + CreationException(CreationException const&); + + CreationException& operator=(CreationException const&); + }; + + /** Attach the current thread to a virtual machine. + + @param rMachine + The virtual machine to attach to. Must not be a null reference. + + @exception CreationException + Thrown in case attaching fails (due to a JNI problem). + */ + explicit AttachGuard(rtl::Reference xMachine); + + /** Detach the current thread from the virtual machine again. + */ + ~AttachGuard(); + + /** Get a JNI environment pointer for the current thread. + + @return + A valid JNI environment pointer. Will never be null. + */ + JNIEnv* getEnvironment() const { return m_pEnvironment; } + + private: + AttachGuard(AttachGuard const&) = delete; + AttachGuard& operator=(AttachGuard const&) = delete; + + rtl::Reference m_xMachine; + JNIEnv* m_pEnvironment; + bool m_bDetach; + }; + + /** Create a wrapper around a Java virtual machine. + + @param pVm + A JNI pointer to virtual machine. Must not be null. + + @param nVersion + The JNI version of the virtual machine pointed to by pVm. Must be at + least JNI_VERSION_1_2. This parameter should be of type jint, not int, + but at least on some platforms the definition of jint changed from + JDK 1.3 (long) to JDK 1.4 (int), so that the mangled C++ name of the + constructor would depend on the JDK version used at compile time. + + @param bDestroy + Whether to destroy the virtual machine when destructing the wrapper + (i.e., whether the wrapper owns the virtual machine pointed to by pVm). + + @param pMainThreadEnv + A valid JNI environment pointer for the current thread; must not be + null. The current thread must be "initially attached" to the virtual + machine while this constructor is being called (i.e., it must be the + thread that has called JNI_CreateJavaVM in case the virtual machine has + been started via the JNI Invocation API, and it must not already have + called DetachCurrentThread; or it must be executing native code called + from a "primordial" virtual machine). This environment pointer was + formerly used to obtain a reference to the thread's current context + class loader (java.lang.Thread.getCurrentClassLoader; if later a native + thread was attached to the virtual machine, that thread's context class + loader would be null, so the AttachGuard first of all set it to the + saved value; this feature has been removed again for performance reasons + and because the default context class loader is often not useful, so + that code relying on a context class loader has to set one explicitly, + anyway). This parameter is currently unused (but may be used again in + the future). + */ + VirtualMachine(JavaVM* pVm, int nVersion, bool bDestroy, JNIEnv const* pMainThreadEnv); + +private: + VirtualMachine(VirtualMachine const&) = delete; + VirtualMachine& operator=(VirtualMachine const&) = delete; + + virtual ~VirtualMachine() override; + + JNIEnv* attachThread(bool* pAttached) const; + + void detachThread() const; + + JavaVM* m_pVm; + jint m_nVersion; + bool m_bDestroy; + + friend class AttachGuard; // to access attachThread, detachThread +}; +} + +#endif // INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/jvmfwk/framework.hxx b/include/jvmfwk/framework.hxx new file mode 100644 index 000000000..8f7eb8a2a --- /dev/null +++ b/include/jvmfwk/framework.hxx @@ -0,0 +1,671 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/** @HTML */ + +#ifndef INCLUDED_JVMFWK_FRAMEWORK_HXX +#define INCLUDED_JVMFWK_FRAMEWORK_HXX + +#include + +#include +#include + +#include +#include +#include +#if defined __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-attributes" +#endif +#include +#if defined __clang__ +#pragma clang diagnostic pop +#endif + +/** @file +

    This library can operate in two modes, application mode and direct mode.

    + + +

    Application Mode

    + In application mode the Java related settings are stored in files. + There are currently three files which need to be accessed. They are determined + by bootstrap parameters:

    +
    +
    UNO_JAVA_JFW_VENDOR_SETTINGS
    +
    contains vendor and version information about JREs as well as the + location of plugin-libraries which are responsible for providing information + about these JREs as well as starting the VMs.
    +
    UNO_JAVA_JFW_USER_DATA
    +
    The file contains settings for a particular user. One can use the macro + $SYSUSERCONFIG in the URL which expands to a directory where the user's data are + kept. On UNIX this would be the home directory and on Windows some sub-directory + of the "Documents and Settings" folder.The content of this file is an + implementation detail and may change in the future.
    +
    UNO_JAVA_JFW_SHARED_DATA
    +
    The file contains settings valid for all users. If a user changes a setting + then it takes precedence over the setting from UNO_JAVA_JFW_SHARED_DATA. + The content of this file is an implementation detail and may change in the future.
    +
    + +

    The values for these parameters must be file URLs and include the file name, for + example:
    + file:///d:/MyApp/javavendors.xml
    + All files are XML files and must have the extension .xml.

    +

    + Modifying the shared settings is currently not supported by the framework. To provide + Java settings for all users one can run OOo and change the settings in the + options dialog. These settings are made persistent in the UNO_JAVA_JFW_USER_DATA. + The file can then be copied into the base installation. + Other users will use automatically these data but can override the settings in + the options dialog. This mechanism may change in the future. +

    +

    If shared Java settings are not supported by an application then it is not + necessary to specify the bootstrap parameter UNO_JAVA_JFW_SHARED_DATA. +

    + +

    Setting the class path used by a Java VM should not be necessary. The locations + of Jar files should be known by a class loader. If a jar file depends on another + jar file then it can be referenced in the manifest file of the first jar. However, + a user may add jars to the class path by using this API. If it becomes necessary + to add files to the class path which is to be used by all users then one can use + the bootstrap parameter UNO_JAVA_JFW_CLASSPATH_URLS. The value contains of file URLs + which must be separated by spaces.

    + + +

    Direct Mode

    + +

    The direct mode is intended for a scenario where no configuration files + are available and a Java VM shall be run. That is, + the files containing the user and shared settings are not specified by the + bootstrap parameters UNO_JAVA_JFW_SHARED_DATA and UNO_JAVA_JFW_USER_DATA. + For example, tools, such as regcomp, may use this framework in a build + environment. Then one would want to use settings which have been specified + by the build environment. The framework would automatically use the + current settings when they change in the environment. +

    + +

    Here are examples how regcomp could be invoked using bootstrap parameters: +

    +

    + regcomp -env:UNO_JAVA_JFW_JREHOME=file:///d:/j2re1.4.2 + -env:"UNO_JAVA_JFW_CLASSPATH=d:\\solver\\bin\\classes.jar;d:\\solver\\bin\\libreoffice.jar" + -register... +

    +

    If UNO_JAVA_JFW_VENDOR_SETTINGS is not set then a plugin library must be specified. For example:

    +

    + regcomp -env:UNO_JAVA_JFW_JREHOME=file:///d:/j2re1.4.2 + -env:"UNO_JAVA_JFW_CLASSPATH=d:\\solver\\bin\\classes.jar;d:\\solver\\bin\\libreoffice.jar" + -register... +

    +

    Additional parameters for the Java VM can be provided. For every parameter + a separate bootstrap parameter must be specified. The names are + UNO_JAVA_JFW_PARAMETER_X, where X is 1,2, .. n. For example:

    +

    + regcomp -env:UNO_JAVA_JFW_PARAMETER_1=-Xdebug + -env:UNO_JAVA_JFW_PARAMETER_2=-Xrunjdwp:transport=dt_socket,server=y,address=8100 + -env:UNO_JAVA_JFW_JREHOME=file:///d:/j2re1.4.2 + -env:"UNO_JAVA_JFW_CLASSPATH=d:\\solver\\bin\\classes.jar;d:\\solver\\bin\\libreoffice.jar" + -register...

    +

    + Here is a complete list of the bootstrap parameter for the direct mode: +

    +
    +
    UNO_JAVA_JFW_JREHOME
    +
    Specifies a file URL to a JRE installation.It must ALWAYS be specified + in direct mode
    +
    UNO_JAVA_JFW_ENV_JREHOME
    +
    Setting this parameter, for example to "1" or "true", + causes the framework to use the environment variable JAVA_HOME. It is expected + that JAVA_HOME contains a system path rather than a file URL. This parameter + and UNO_JAVA_JFW_JREHOME are mutually exclusive
    +
    UNO_JAVA_JFW_CLASSPATH
    +
    Contains the class path which is to be used by the VM. Special character, + such as '\','{','}','$' must be preceded with '\'. See documentation about the + bootstrap parameter.
    +
    UNO_JAVA_JFW_ENV_CLASSPATH
    +
    Setting this parameter,for example to "1" or "true", + causes the framework to use the + environment variable CLASSPATH. If this variable and UNO_JAVA_JFW_CLASSPATH are + set then the class path is composed from UNO_JAVA_JFW_CLASSPATH and the environment + variable CLASSPATH.
    +
    UNO_JAVA_JFW_PARAMETER_X
    +
    Specifies a parameter for the Java VM. The X is replaced by + non-negative natural numbers starting with 1.
    +
    + +

    A note about bootstrap parameters. The implementation of the bootstrap + parameter mechanism interprets the characters '\', '$', '{', '}' as + escape characters. That's why the Windows path contain double back-slashes. + One should also take into account that a console may have also special + escape characters.

    + +

    What mode is used

    +

    + The default mode is application mode. If at least one bootstrap parameter + for the direct mode is provided then direct mode is used.

    + +

    + All settings made by this API are done for the current user if not + mentioned differently.

    +*/ + +/** indicates that there must be an environment set up before the Java process + runs. +

    Therefore, when a Java is selected in OO then the office must be + restarted, so that the changes can take effect.

    + */ +#define JFW_REQUIRE_NEEDRESTART 0x1l + +/** error codes which are returned by functions of this API. + */ +enum javaFrameworkError +{ + JFW_E_NONE, + JFW_E_ERROR, + JFW_E_NO_SELECT, + JFW_E_INVALID_SETTINGS, + JFW_E_NEED_RESTART, + JFW_E_RUNNING_JVM, + JFW_E_JAVA_DISABLED, + JFW_E_NOT_RECOGNIZED, + JFW_E_FAILED_VERSION, + JFW_E_NO_JAVA_FOUND, + JFW_E_VM_CREATION_FAILED, + JFW_E_CONFIGURATION, + JFW_E_DIRECT_MODE +}; + +/** an instance of this struct represents an installation of a Java + Runtime Environment (JRE). + +

    + Instances of this struct are created by the plug-in libraries which are used by + this framework (jvmfwk/vendorplugin.h).

    + */ +struct JavaInfo +{ + /** contains the vendor. + +

    string must be the same as the one obtained from the + Java system property java.vendor. +

    + */ + OUString sVendor; + /** contains the file URL to the installation directory. + */ + OUString sLocation; + /** contains the version of this Java distribution. + +

    The version string must adhere to the rules + about how a version string has to be formed. These rules may + be vendor-dependent. Essentially the strings must syntactically + equal the Java system property java.version. +

    + */ + OUString sVersion; + /** indicates requirements for running the java runtime. + +

    For example, it may be necessary to prepare the environment before + the runtime is created. That could mean, setting the + LD_LIBRARY_PATH + when nRequirements contains the flag + JFW_REQUIRE_NEEDRESTART

    + */ + sal_uInt64 nRequirements; + /** contains data needed for the creation of the java runtime. + +

    There is no rule about the format and content of the sequence's + values. The plug-in libraries can put all data, necessary for + starting the java runtime into this sequence.

    + */ + rtl::ByteSequence arVendorData; +}; + +/** compares two JavaInfo objects for equality. + +

    Two JavaInfo objects are said to be equal if the contained + members of the first JavaInfo are equal to their counterparts + in the second JavaInfo object. The equality of the + OUString members is determined + by operator ==. + Similarly the equality of the rtl::ByteSequence is + also determined by a comparison + function (see rtl::ByteSequence::operator ==).

    +

    + Both argument pointers must be valid.

    + @param pInfoA + the first argument. + @param pInfoB + the second argument which is compared with the first. + @return + true - both object represent the same JRE.
    + false - the objects represent different JREs + */ +JVMFWK_DLLPUBLIC bool jfw_areEqualJavaInfo(JavaInfo const* pInfoA, JavaInfo const* pInfoB); + +/** determines if a Java Virtual Machine is already running. + +

    As long as the office and the JREs only support one + Virtual Machine per process the Java settings, particularly the + selected Java, are not effective immediately after changing when + a VM has already been running. That is, if a JRE A was used to start + a VM and then a JRE B is selected, then JRE B will only be used + after a restart of the office.

    +

    + By determining if a VM is running, the user can be presented a message, + that the changed setting may not be effective immediately.

    + + @return + true iff a VM is running. +*/ +JVMFWK_DLLPUBLIC bool jfw_isVMRunning(); + +/** detects a suitable JRE and configures the framework to use it. + +

    Which JREs can be used is determined by the file javavendors.xml, + which contains version requirements.

    +

    + JREs can be provided by different vendors. + The function obtains information about JRE installations. If none was + found then it also uses a list of paths, which have been registered + by jfw_addJRELocation + to find JREs. Found JREs are examined in the same way.

    +

    + A JRE installation is only selected if it meets the version requirements. + Information about the selected JRE are made persistent so that + subsequent calls to jfw_getSelectedJRE returns this + information.

    +

    + While determining a proper JRE this function takes into account if a + user requires support for assistive technology tools. If user + need that support they have to set up their system accordingly.

    +

    + If the JAVA_HOME environment variable is set, this function prefers + the JRE which the variable refers to over other JREs. + If JAVA_HOME is not set or does not refer to a suitable JRE, + the PATH environment variable is inspected and the respective JREs + are checked for their suitability next.

    +

    + The first JavaInfo object that is detected by the algorithm + as described above is used.

    + + @param pInfo + [out] a JavaInfo pointer, representing the selected JRE. + The JavaInfo is for informational purposes only. It is not + necessary to call jfw_setSelectedJRE afterwards.
    + pInfocan be NULL. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR an error occurred.
    + JFW_E_NO_JAVA_FOUND no JRE was found that meets the requirements.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_findAndSelectJRE(std::unique_ptr* pInfo); + +/** provides information about all available JRE installations. + +

    The function determines dynamically what JREs are available. It uses + the plug-in libraries to provide lists of available JavaInfo + objects where each object represents a JRE (see vendorplugin.h, + getAllJavaInfos). It also uses a list of paths, which have been registered + by jfw_addJRELocation. + It is checked if the path still contains a valid JRE and if so the respective + JavaInfo object will be appended to the array unless there is + already an equal object.

    + + @param parInfo + [out] on returns it contains a vector of JavaInfo pointers. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR an error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met. +*/ +JVMFWK_DLLPUBLIC javaFrameworkError +jfw_findAllJREs(std::vector>* parInfo); + +/** determines if a path points to a Java installation. + +

    If the path belongs to a JRE installation then it returns the + respective JavaInfo object. The function uses the + getJavaInfoByPath function of the plug-ins to obtain the + JavaInfo object. Only if the JRE found at the specified location + meets the version requirements as specified in the javavendors.xml file a + JavaInfo object is returned.
    +

    + The functions only checks if a JRE exists but does not modify any settings. + To make the found JRE the "selected JRE" one has + to call jfw_setSelectedJRE.

    + + @param pPath + [in] a file URL to a directory. + @param ppInfo + [out] the JavaInfo object which represents a JRE found at the + location specified by pPath + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR an error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_NOT_RECOGNIZED neither plug-in library could detect a JRE.
    + JFW_E_FAILED_VERSION a JRE was detected but if failed the version + requirements as determined by the javavendors.xml + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_getJavaInfoByPath(OUString const& pPath, + std::unique_ptr* ppInfo); + +/** starts a Java Virtual Machine (JVM). + +

    The function uses the current settings to start a JVM. The actual + start-up code, however, is provided by the plug-in libraries. The setting + of the "selected Java" contains the information as to what vendor + the respective JRE comes from. In the javavendors.xml there is a mapping of + vendor names to the respective plug-in libraries.

    +

    + The function ultimately calls startJavaVirtualMachine from + the plug-in library.

    +

    + The arOptions + argument contains start arguments which are passed in JavaVMOption structures + to the VM during its creation. These + could be things, such as language settings, proxy settings or any other + properties which shall be obtainable by + java.lang.System.getProperties. One can also pass options which + have a certain meaning to the runtime behaviour such as -ea or -X... However, + one must be sure that these options can be interpreted by the VM.
    + The class path cannot be set this way. The class path is internally composed by + the paths to archives in a certain directory, which is preconfigured in + the internal data store and the respective user setting (see + jfw_setUserClassPath.

    +

    + If a JRE was selected at runtime which was different from the previous + setting and that JRE needs a prepared environment, for example an adapted + LD_LIBRARY_PATH environment variable, then the VM will not be + created and JFW_E_NEED_RESTART error is returned. If a VM is already running + then a JFW_E_RUNNING_JVM is returned.

    + + @param pInfo + [in] optional pointer to a specific JRE; must be caller-freed if not NULL + @param arOptions + [in] the vector containing additional start arguments. + @param ppVM + [out] the JavaVM pointer. + @param ppEnv + [out] the JNIenv pointer. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR an error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_JAVA_DISABLED the use of Java is currently disabled.
    + JFW_E_NO_SELECT there is no JRE selected yet.
    + JFW_E_RUNNING_JVM there is already a VM running.
    + JFW_E_INVALID_SETTINGS the javavendors.xml has been changed and no + JRE has been selected afterwards.
    + JFW_E_NEED_RESTART in the current process a different JRE has been selected + which needs a prepared environment, which has to be done before the office + process. Therefore the new JRE may not be used until the office was restarted.
    + JFW_E_NEED_RESTART is also returned when Java was disabled at the beginning and + then the user enabled it. If then the selected JRE has the requirement + JFW_REQUIRE_NEEDRESTART then this error is returned.
    + JFW_E_VM_CREATION_FAILED the creation of the JVM failed. The creation is performed + by a plug-in library and not by this API. + JFW_E_FAILED_VERSION the "Default Mode" is active. The JRE determined by + JAVA_HOMEdoes not meet the version requirements. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_startVM(JavaInfo const* pInfo, + std::vector const& arOptions, + JavaVM** ppVM, JNIEnv** ppEnv); + +/** determines the JRE that is to be used. + +

    When calling jfw_startVM then a VM is started from + the JRE that is determined by this function.
    + It is not verified if the JRE represented by the JavaInfo + argument meets the requirements as specified by the javavendors.xml file. + However, usually one obtains the JavaInfo object from the + functions jfw_findAllJREs or jfw_getJavaInfoByPath, + which do verify the JREs and pass out only JavaInfo objects + which comply with the version requirements.

    +

    + If pInfo is NULL then the meaning is that no JRE will be + selected. jfw_startVM will then return + JFW_E_NO_SELECT.

    + + @param pInfo + [in] pointer to JavaInfo structure, containing data about a + JRE. The caller must still free pInfo. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_setSelectedJRE(JavaInfo const* pInfo); + +/** provides information about the JRE that is to be used. + +

    If no JRE is currently selected then ppInfo will contain + NULL on return.
    + If the value of the element in the javavendors.xml file was + changed since the time when the last Java was selected then this + function returns JFW_E_INVALID_SETTINGS. This could happen during + a product patch. Then new version requirements may be introduced, so that + the currently selected JRE may not meet these requirements anymore. +

    +

    In direct mode the function returns information about a JRE that was + set by the bootstrap parameter UNO_JAVA_JFW_JREHOME. +

    + @param ppInfo + [out] on return it contains a pointer to a JavaInfo object + that represents the currently selected JRE. When *ppInfo is not + NULL then the function sets the pointer. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_INVALID_SETTINGS the javavendors.xml has been changed and no + JRE has been selected afterwards.
    + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_getSelectedJRE(std::unique_ptr* ppInfo); + +/** determines if Java can be used. + +

    If bEnabled is false then a call + to jfw_startVM will result in an error with the errorcode + JFW_E_JAVA_DISABLED

    + + @param bEnabled + [in] use of Java enabled/disabled. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_setEnabled(bool bEnabled); + +/** provides the information if Java can be used. + +

    That is if the user enabled or disabled the use of Java. +

    + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_getEnabled(bool* pbEnabled); + +/** determines parameters which are passed to VM during its creation. + +

    The strings must be exactly as they are passed on the command line. + For example, one could pass
    + -Xdebug
    + -Xrunjdw:transport=dt_socket,server=y,address=8000
    + in order to enable debugging support. +

    + + @param arParameters + [in] contains the arguments. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_setVMParameters(std::vector const& arArgs); + +/** obtains the currently used start parameters. + + @param parParameters + [out] on returns contains a pointer to the array of the start arguments. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_getVMParameters(std::vector* parParameters); + +/** sets the user class path. + +

    When the VM is started then it is passed the class path. The + class path also contains the user class path set by this function. + The paths contained in pCP must be separated with a + system dependent path separator.

    + + @param pCP + [in] the user class path. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_setUserClassPath(OUString const& pCP); +/** provides the value of the current user class path. + +

    The function returns an empty string if no user class path is set. +

    + + @param ppCP + [out] contains the user class path on return. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_getUserClassPath(OUString* ppCP); + +/** saves the location of a JRE. + +

    When jfw_findAllJREs is called then the paths added by this + function are evaluated. If the location still represents a + JRE then a JavaInfo object is created which is returned along + with all other JavaInfo objects by + jfw_findAllJREs. If the location + cannot be recognized then the location string is ignored.

    +

    + A validation if sLocation points to a JRE is not + performed. To do that one has to use jfw_getJavaInfoByPath. +

    +

    + Adding a path that is already stored causes no error.

    + + @param sLocation + [in] file URL to a directory which contains a JRE. + + @return + JFW_E_NONE function ran successfully.
    + JFW_E_ERROR An error occurred.
    + JFW_E_CONFIGURATION mode was not properly set or their prerequisites + were not met.
    + JFW_E_DIRECT_MODE the function cannot be used in this mode. + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_addJRELocation(OUString const& sLocation); + +/** checks if the installation of the jre still exists. + + This function checks if the JRE described by pInfo still + exists. The check must be very quick because it is called by javaldx + (Linux, Solaris) at start up. + + @param pInfo + [in] the JavaInfo object with information about the JRE. + @param pp_exist + [out] the parameter is set to either true or false. The value is + only valid if the function returns JFW_E_NONE. + + @return + JFW_E_NONE the function ran successfully.
    + JFW_E_ERROR an error occurred during execution.
    + */ +JVMFWK_DLLPUBLIC javaFrameworkError jfw_existJRE(const JavaInfo* pInfo, bool* exist); + +/** locks this API so that it cannot be used by other threads. + +

    If a different thread called this function before then the + current call is blocked until the other thread has called + jfw_unlock(). The function should be called if one + needs an exact snapshot of the current settings. Then the settings + are retrieved one by one without risk that the settings may be changed + by a different thread. Similarity if one needs to make settings which + should become effective at the same time then jfw_lock + should be called. That is, jfw_startVM which uses the + settings cannot be called before all settings have be made.

    +

    + The only functions which is not effected by jfw_lock is + jfw_areEqualJavaInfo. + */ +JVMFWK_DLLPUBLIC void jfw_lock(); + +/** unlocks this API. + +

    This function is called after jfw_lock. It allows other + threads to use this API concurrently.

    +*/ +JVMFWK_DLLPUBLIC void jfw_unlock(); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/jvmfwk/jvmfwkdllapi.hxx b/include/jvmfwk/jvmfwkdllapi.hxx new file mode 100644 index 000000000..bd59abb74 --- /dev/null +++ b/include/jvmfwk/jvmfwkdllapi.hxx @@ -0,0 +1,23 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_JVMFWK_JVMFWKDLLAPI_HXX +#define INCLUDED_JVMFWK_JVMFWKDLLAPI_HXX + +#include + +#if defined JVMFWK_DLLIMPLEMENTATION +#define JVMFWK_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define JVMFWK_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/linguistic/hyphdta.hxx b/include/linguistic/hyphdta.hxx new file mode 100644 index 000000000..48030b571 --- /dev/null +++ b/include/linguistic/hyphdta.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_LINGUISTIC_HYPHDTA_HXX +#define INCLUDED_LINGUISTIC_HYPHDTA_HXX + +#include +#include +#include +#include +#include +#include + +namespace linguistic +{ + +class HyphenatedWord final : + public cppu::WeakImplHelper< css::linguistic2::XHyphenatedWord > +{ + OUString aWord; + OUString aHyphenatedWord; + sal_Int16 nHyphPos; + sal_Int16 nHyphenationPos; + LanguageType nLanguage; + bool bIsAltSpelling; + + HyphenatedWord(const HyphenatedWord &) = delete; + HyphenatedWord & operator = (const HyphenatedWord &) = delete; + +public: + HyphenatedWord(const OUString &rWord, LanguageType nLang, sal_Int16 nHyphenationPos, + const OUString &rHyphenatedWord, sal_Int16 nHyphenPos ); + virtual ~HyphenatedWord() override; + + // XHyphenatedWord + virtual OUString SAL_CALL + getWord() override; + virtual css::lang::Locale SAL_CALL + getLocale() override; + virtual sal_Int16 SAL_CALL + getHyphenationPos() override; + virtual OUString SAL_CALL + getHyphenatedWord() override; + virtual sal_Int16 SAL_CALL + getHyphenPos() override; + virtual sal_Bool SAL_CALL + isAlternativeSpelling() override; + + static css::uno::Reference UNLESS_MERGELIBS(LNG_DLLPUBLIC) CreateHyphenatedWord( + const OUString &rWord, LanguageType nLang, sal_Int16 nHyphenationPos, + const OUString &rHyphenatedWord, sal_Int16 nHyphenPos ); +}; + + +class PossibleHyphens final : + public cppu::WeakImplHelper + < + css::linguistic2::XPossibleHyphens + > +{ + OUString aWord; + OUString aWordWithHyphens; + css::uno::Sequence< sal_Int16 > aOrigHyphenPos; + LanguageType nLanguage; + + PossibleHyphens(const PossibleHyphens &) = delete; + PossibleHyphens & operator = (const PossibleHyphens &) = delete; + +public: + PossibleHyphens(OUString aWord, LanguageType nLang, + OUString aHyphWord, + const css::uno::Sequence< sal_Int16 > &rPositions); + virtual ~PossibleHyphens() override; + + // XPossibleHyphens + virtual OUString SAL_CALL + getWord() override; + virtual css::lang::Locale SAL_CALL + getLocale() override; + virtual OUString SAL_CALL + getPossibleHyphens() override; + virtual css::uno::Sequence< sal_Int16 > SAL_CALL + getHyphenationPositions() override; + + static css::uno::Reference < css::linguistic2::XPossibleHyphens > UNLESS_MERGELIBS(LNG_DLLPUBLIC) CreatePossibleHyphens + (const OUString &rWord, LanguageType nLang, + const OUString &rHyphWord, + const css::uno::Sequence< sal_Int16 > &rPositions); +}; +} // namespace linguistic + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/linguistic/lngdllapi.h b/include/linguistic/lngdllapi.h new file mode 100644 index 000000000..3944d47cf --- /dev/null +++ b/include/linguistic/lngdllapi.h @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_LINGUISTIC_LNGDLLAPI_H +#define INCLUDED_LINGUISTIC_LNGDLLAPI_H + +#include +#include + +#if defined(LNG_DLLIMPLEMENTATION) +#define LNG_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define LNG_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define LNG_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/linguistic/lngprophelp.hxx b/include/linguistic/lngprophelp.hxx new file mode 100644 index 000000000..18dfaa60d --- /dev/null +++ b/include/linguistic/lngprophelp.hxx @@ -0,0 +1,306 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_LINGUISTIC_LNGPROPHELP_HXX +#define INCLUDED_LINGUISTIC_LNGPROPHELP_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::linguistic2 { struct LinguServiceEvent; } +namespace com::sun::star::linguistic2 { class XLinguProperties; } + + +namespace linguistic +{ + +// PropertyChgHelper +// Base class for all XPropertyChangeListener members of the +// various lingu services. + + +// Flags for type of events allowed to be launched +#define AE_SPELLCHECKER 1 +#define AE_HYPHENATOR 2 + +typedef cppu::WeakImplHelper +< + css::beans::XPropertyChangeListener, + css::linguistic2::XLinguServiceEventBroadcaster +> PropertyChgHelperBase; + +class UNLESS_MERGELIBS(LNG_DLLPUBLIC) PropertyChgHelper : + public PropertyChgHelperBase +{ + std::vector< OUString > aPropNames; + css::uno::Reference< css::uno::XInterface > xMyEvtObj; + ::comphelper::OInterfaceContainerHelper3 aLngSvcEvtListeners; + css::uno::Reference< css::beans::XPropertySet > xPropSet; + + int nEvtFlags; // flags for event types allowed to be launched + + // default values + bool bIsIgnoreControlCharacters; + bool bIsUseDictionaryList; + + // return values, will be set to default value or current temporary value + bool bResIsIgnoreControlCharacters; + bool bResIsUseDictionaryList; + + PropertyChgHelper( const PropertyChgHelper & ) = delete; + PropertyChgHelper & operator = ( const PropertyChgHelper & ) = delete; + +protected: + virtual void SetDefaultValues(); + virtual void GetCurrentValues(); + + std::vector< OUString > & GetPropNames() { return aPropNames; } + css::uno::Reference< + css::beans::XPropertySet > & + GetPropSet() { return xPropSet; } + + virtual bool propertyChange_Impl( const css::beans::PropertyChangeEvent& rEvt ); + +public: + PropertyChgHelper( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet, + int nAllowedEvents ); + virtual ~PropertyChgHelper() override; + + virtual void SetTmpPropVals( const css::beans::PropertyValues &rPropVals ); + + // XEventListener + virtual void SAL_CALL + disposing( const css::lang::EventObject& rSource ) override; + + // XPropertyChangeListener + virtual void SAL_CALL + propertyChange( const css::beans::PropertyChangeEvent& rEvt ) override; + + // XLinguServiceEventBroadcaster + virtual sal_Bool SAL_CALL + addLinguServiceEventListener( + const css::uno::Reference< css::linguistic2::XLinguServiceEventListener >& rxListener ) override; + virtual sal_Bool SAL_CALL + removeLinguServiceEventListener( + const css::uno::Reference< css::linguistic2::XLinguServiceEventListener >& rxListener ) override; + + // non-UNO functions + void AddAsPropListener(); + void RemoveAsPropListener(); + void LaunchEvent( const css::linguistic2::LinguServiceEvent& rEvt ); + + const std::vector< OUString > & + GetPropNames() const { return aPropNames; } + const css::uno::Reference< css::beans::XPropertySet > & + GetPropSet() const { return xPropSet; } + const css::uno::Reference< css::uno::XInterface > & + GetEvtObj() const { return xMyEvtObj; } +}; + + +class PropertyHelper_Thes final : + public PropertyChgHelper +{ + PropertyHelper_Thes( const PropertyHelper_Thes & ) = delete; + PropertyHelper_Thes & operator = ( const PropertyHelper_Thes & ) = delete; + +public: + PropertyHelper_Thes( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet ); + virtual ~PropertyHelper_Thes() override; + + // XPropertyChangeListener + virtual void SAL_CALL + propertyChange( const css::beans::PropertyChangeEvent& rEvt ) override; +}; + +class UNLESS_MERGELIBS(LNG_DLLPUBLIC) PropertyHelper_Thesaurus +{ + rtl::Reference< PropertyHelper_Thes > mxPropHelper; + + // disallow use of copy-constructor and assignment-operator + PropertyHelper_Thesaurus( const PropertyHelper_Thes & ) = delete; + PropertyHelper_Thesaurus & operator = ( const PropertyHelper_Thes & ) = delete; + +public: + PropertyHelper_Thesaurus( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet ); + ~PropertyHelper_Thesaurus(); + void AddAsPropListener(); + void RemoveAsPropListener(); + void SetTmpPropVals( const css::beans::PropertyValues &rPropVals ); +}; + + +class UNLESS_MERGELIBS(LNG_DLLPUBLIC) PropertyHelper_Spell final : + public PropertyChgHelper +{ + // default values + bool bIsSpellUpperCase; + bool bIsSpellWithDigits; + bool bIsSpellCapitalization; + + // return values, will be set to default value or current temporary value + bool bResIsSpellUpperCase; + bool bResIsSpellWithDigits; + bool bResIsSpellCapitalization; + + PropertyHelper_Spell( const PropertyHelper_Spell & ) = delete; + PropertyHelper_Spell & operator = ( const PropertyHelper_Spell & ) = delete; + + // PropertyChgHelper + virtual void SetDefaultValues() override; + virtual void GetCurrentValues() override; + virtual bool propertyChange_Impl( + const css::beans::PropertyChangeEvent& rEvt ) override; + +public: + PropertyHelper_Spell( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet ); + virtual ~PropertyHelper_Spell() override; + + virtual void SetTmpPropVals( const css::beans::PropertyValues &rPropVals ) override; + + // XPropertyChangeListener + virtual void SAL_CALL + propertyChange( const css::beans::PropertyChangeEvent& rEvt ) override; + + bool IsSpellUpperCase() const { return bResIsSpellUpperCase; } + bool IsSpellWithDigits() const { return bResIsSpellWithDigits; } + bool IsSpellCapitalization() const { return bResIsSpellCapitalization; } +}; + + +class UNLESS_MERGELIBS(LNG_DLLPUBLIC) PropertyHelper_Spelling +{ + rtl::Reference< PropertyHelper_Spell > mxPropHelper; + + // disallow use of copy-constructor and assignment-operator + PropertyHelper_Spelling( const PropertyHelper_Spell & ) = delete; + PropertyHelper_Spelling & operator = ( const PropertyHelper_Spell & ) = delete; + +public: + PropertyHelper_Spelling( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet ); + ~PropertyHelper_Spelling(); + + void AddAsPropListener(); + void RemoveAsPropListener(); + void SetTmpPropVals( const css::beans::PropertyValues &rPropVals ); + bool IsSpellUpperCase() const; + bool IsSpellWithDigits() const; + bool IsSpellCapitalization() const; + /// @throws css::uno::RuntimeException + bool addLinguServiceEventListener( + const css::uno::Reference< css::linguistic2::XLinguServiceEventListener >& rxListener ); + /// @throws css::uno::RuntimeException + bool removeLinguServiceEventListener( + const css::uno::Reference< css::linguistic2::XLinguServiceEventListener >& rxListener ); +}; + + +class PropertyHelper_Hyphen final : + public PropertyChgHelper +{ + // default values + sal_Int16 nHyphMinLeading, + nHyphMinTrailing, + nHyphMinWordLength; + bool bNoHyphenateCaps; + + // return values, will be set to default value or current temporary value + sal_Int16 nResHyphMinLeading, + nResHyphMinTrailing, + nResHyphMinWordLength; + bool bResNoHyphenateCaps; + + PropertyHelper_Hyphen( const PropertyHelper_Hyphen & ) = delete; + PropertyHelper_Hyphen & operator = ( const PropertyHelper_Hyphen & ) = delete; + + // PropertyChgHelper + virtual void SetDefaultValues() override; + virtual void GetCurrentValues() override; + virtual bool propertyChange_Impl( + const css::beans::PropertyChangeEvent& rEvt ) override; + +public: + PropertyHelper_Hyphen( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet); + virtual ~PropertyHelper_Hyphen() override; + + virtual void SetTmpPropVals( const css::beans::PropertyValues &rPropVals ) override; + + // XPropertyChangeListener + virtual void SAL_CALL + propertyChange( const css::beans::PropertyChangeEvent& rEvt ) override; + + sal_Int16 GetMinLeading() const { return nResHyphMinLeading; } + sal_Int16 GetMinTrailing() const { return nResHyphMinTrailing; } + sal_Int16 GetMinWordLength() const { return nResHyphMinWordLength; } + bool IsNoHyphenateCaps() const { return bResNoHyphenateCaps; } +}; + +class UNLESS_MERGELIBS(LNG_DLLPUBLIC) PropertyHelper_Hyphenation +{ + rtl::Reference< PropertyHelper_Hyphen > mxPropHelper; + + // disallow use of copy-constructor and assignment-operator + PropertyHelper_Hyphenation( const PropertyHelper_Hyphen & ) = delete; + PropertyHelper_Hyphenation & operator = ( const PropertyHelper_Hyphen & ) = delete; + +public: + PropertyHelper_Hyphenation( + const css::uno::Reference< css::uno::XInterface > &rxSource, + css::uno::Reference< css::linguistic2::XLinguProperties > const &rxPropSet); + ~PropertyHelper_Hyphenation(); + + void AddAsPropListener(); + void RemoveAsPropListener(); + void SetTmpPropVals( const css::beans::PropertyValues &rPropVals ); + sal_Int16 GetMinLeading() const; + sal_Int16 GetMinTrailing() const; + sal_Int16 GetMinWordLength() const; + bool IsNoHyphenateCaps() const; + /// @throws css::uno::RuntimeException + bool addLinguServiceEventListener( + const css::uno::Reference< css::linguistic2::XLinguServiceEventListener >& rxListener ); + /// @throws css::uno::RuntimeException + bool removeLinguServiceEventListener( + const css::uno::Reference< css::linguistic2::XLinguServiceEventListener >& rxListener ); +}; + +} // namespace linguistic + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/linguistic/lngprops.hxx b/include/linguistic/lngprops.hxx new file mode 100644 index 000000000..2c3dc1d90 --- /dev/null +++ b/include/linguistic/lngprops.hxx @@ -0,0 +1,31 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_LINGUISTIC_LNGPROPS_HXX +#define INCLUDED_LINGUISTIC_LNGPROPS_HXX + +#include + +// maximal number of suggestions to be returned in spelling context-menu +// (may not include results added by looking up user dictionaries) +inline constexpr OUStringLiteral UPN_MAX_NUMBER_OF_SUGGESTIONS = u"MaxNumberOfSuggestions"; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/linguistic/misc.hxx b/include/linguistic/misc.hxx new file mode 100644 index 000000000..02b3d44b3 --- /dev/null +++ b/include/linguistic/misc.hxx @@ -0,0 +1,196 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_LINGUISTIC_MISC_HXX +#define INCLUDED_LINGUISTIC_MISC_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::frame { class XDesktop2; } +namespace com::sun::star::linguistic2 { class XDictionary; } +namespace com::sun::star::linguistic2 { class XDictionaryEntry; } +namespace com::sun::star::linguistic2 { class XHyphenatedWord; } +namespace com::sun::star::linguistic2 { class XLinguProperties; } +namespace com::sun::star::linguistic2 { class XSearchableDictionaryList; } +namespace osl { class Mutex; } + +class CharClass; +class LocaleDataWrapper; + + +inline constexpr OUStringLiteral SN_GRAMMARCHECKER = u"com.sun.star.linguistic2.Proofreader"; +inline constexpr OUStringLiteral SN_SPELLCHECKER = u"com.sun.star.linguistic2.SpellChecker"; +inline constexpr OUStringLiteral SN_HYPHENATOR = u"com.sun.star.linguistic2.Hyphenator"; +inline constexpr OUStringLiteral SN_THESAURUS = u"com.sun.star.linguistic2.Thesaurus"; + + +namespace linguistic +{ + + +// AddEntryToDic return values +enum class DictionaryError +{ + NONE, FULL, READONLY, UNKNOWN, NOT_EXISTS +}; + +// values assigned to capitalization types +enum class CapType +{ + UNKNOWN, + NOCAP, + INITCAP, + ALLCAP, + MIXED +}; + +LNG_DLLPUBLIC ::osl::Mutex& GetLinguMutex(); + +const LocaleDataWrapper & GetLocaleDataWrapper( LanguageType nLang ); + +sal_Int32 LevDistance( std::u16string_view rTxt1, std::u16string_view rTxt2 ); + +/** Convert Locale to LanguageType for legacy handling. + Linguistic specific handling of an empty locale denoting LANGUAGE_NONE. + Does not resolve empty locale as system locale. + */ +LNG_DLLPUBLIC LanguageType LinguLocaleToLanguage( const css::lang::Locale& rLocale ); + +/** Convert LanguageType to Locale for legacy handling. + Linguistic specific handling of LANGUAGE_NONE resulting in an empty locale. + Avoid use! + */ +LNG_DLLPUBLIC css::lang::Locale LinguLanguageToLocale( LanguageType nLanguage ); + +/** Checks if a LanguageType is one of the values that denote absence of + language or undetermined language or multiple languages, in short all + values used in linguistic context that do not denote a specific language. + */ +LNG_DLLPUBLIC bool LinguIsUnspecified( LanguageType nLanguage ); + +/** The same as LinguIsUnspecified(LanguageType) but taking a BCP 47 language + tag string instead. */ +LNG_DLLPUBLIC bool LinguIsUnspecified( std::u16string_view rBcp47 ); + +std::vector< LanguageType > + LocaleSeqToLangVec( css::uno::Sequence< css::lang::Locale > const &rLocaleSeq ); +css::uno::Sequence + LocaleSeqToLangSeq( css::uno::Sequence< css::lang::Locale > const &rLocaleSeq ); + +// checks if file pointed to by rURL is readonly +// and may also check return if such a file exists or not +bool IsReadOnly( const OUString &rURL, bool *pbExist = nullptr ); + +// checks if a file with the given URL exists +bool FileExists( const OUString &rURL ); + + +OUString GetDictionaryWriteablePath(); +std::vector< OUString > GetDictionaryPaths(); + +/// @returns a URL for a new and writable dictionary rDicName. +/// The URL will point to the path given by 'GetDictionaryWriteablePath' +LNG_DLLPUBLIC OUString GetWritableDictionaryURL( std::u16string_view rDicName ); + +LNG_DLLPUBLIC sal_Int32 GetPosInWordToCheck( std::u16string_view rTxt, sal_Int32 nPos ); + +css::uno::Reference< css::linguistic2::XHyphenatedWord > + RebuildHyphensAndControlChars( + const OUString &rOrigWord, + css::uno::Reference< css::linguistic2::XHyphenatedWord > const &rxHyphWord ); + + +LNG_DLLPUBLIC bool IsUpper( const OUString &rText, sal_Int32 nPos, sal_Int32 nLen, LanguageType nLanguage ); + +inline bool IsUpper( const OUString &rText, LanguageType nLanguage ) { return IsUpper( rText, 0, rText.getLength(), nLanguage ); } +LNG_DLLPUBLIC CapType capitalType(const OUString&, CharClass const *); + +LNG_DLLPUBLIC bool HasDigits( const OUString &rText ); +LNG_DLLPUBLIC bool IsNumeric( std::u16string_view rText ); + + +LNG_DLLPUBLIC css::uno::Reference< css::linguistic2::XLinguProperties > GetLinguProperties(); +css::uno::Reference< css::linguistic2::XSearchableDictionaryList > GetDictionaryList(); +css::uno::Reference< css::linguistic2::XDictionary > GetIgnoreAllList(); + + +bool IsUseDicList( const css::beans::PropertyValues &rProperties, + const css::uno::Reference< css::beans::XPropertySet > &rxPropSet ); + +bool IsIgnoreControlChars( const css::beans::PropertyValues &rProperties, + const css::uno::Reference< css::beans::XPropertySet > &rxPropSet ); + +css::uno::Reference< + css::linguistic2::XDictionaryEntry > + SearchDicList( + const css::uno::Reference< css::linguistic2::XSearchableDictionaryList >& rDicList, + const OUString& rWord, LanguageType nLanguage, + bool bSearchPosDics, bool bSearchSpellEntry ); + +LNG_DLLPUBLIC DictionaryError AddEntryToDic( + css::uno::Reference< css::linguistic2::XDictionary > const &rxDic, + const OUString &rWord, bool bIsNeg, + const OUString &rRplcTxt, + bool bStripDot = true ); + +LNG_DLLPUBLIC bool SaveDictionaries( const css::uno::Reference< css::linguistic2::XSearchableDictionaryList > &xDicList ); + +// AppExitLstnr: +// virtual base class that calls it AtExit function when the application +// (ie the Desktop) is about to terminate + +class AppExitListener : + public cppu::WeakImplHelper< css::frame::XTerminateListener > +{ + css::uno::Reference< css::frame::XDesktop2 > xDesktop; + +public: + AppExitListener(); + virtual ~AppExitListener() override; + + virtual void AtExit() = 0; + + void Activate(); + void Deactivate(); + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + // XTerminateListener + virtual void SAL_CALL queryTermination( const css::lang::EventObject& aEvent ) override; + virtual void SAL_CALL notifyTermination( const css::lang::EventObject& aEvent ) override; +}; + +} // namespace linguistic + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/linguistic/spelldta.hxx b/include/linguistic/spelldta.hxx new file mode 100644 index 000000000..d0057ffbd --- /dev/null +++ b/include/linguistic/spelldta.hxx @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_LINGUISTIC_SPELLDTA_HXX +#define INCLUDED_LINGUISTIC_SPELLDTA_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::linguistic2 { class XSearchableDictionaryList; } + + +namespace linguistic +{ + +std::vector< OUString > + MergeProposalSeqs( + std::vector< OUString > &rAlt1, + std::vector< OUString > &rAlt2 ); + +void SeqRemoveNegEntries( + std::vector< OUString > &rSeq, + css::uno::Reference< css::linguistic2::XSearchableDictionaryList > const &rxDicList, + LanguageType nLanguage ); + +void SearchSimilarText( const OUString &rText, LanguageType nLanguage, + css::uno::Reference< css::linguistic2::XSearchableDictionaryList > const &xDicList, + std::vector< OUString > & rDicListProps ); + + +class SpellAlternatives final + : public cppu::WeakImplHelper + < + css::linguistic2::XSpellAlternatives, + css::linguistic2::XSetSpellAlternatives + > +{ + css::uno::Sequence< OUString > aAlt; // list of alternatives, may be empty. + OUString aWord; + sal_Int16 nType; // type of failure + LanguageType nLanguage; + +public: + UNLESS_MERGELIBS(LNG_DLLPUBLIC) SpellAlternatives(); + SpellAlternatives(OUString aWord, LanguageType nLang, + const css::uno::Sequence< OUString > &rAlternatives ); + virtual ~SpellAlternatives() override; + SpellAlternatives(const SpellAlternatives&) = delete; + SpellAlternatives& operator=( const SpellAlternatives& ) = delete; + + // XSpellAlternatives + virtual OUString SAL_CALL getWord( ) override; + virtual css::lang::Locale SAL_CALL getLocale( ) override; + virtual ::sal_Int16 SAL_CALL getFailureType( ) override; + virtual ::sal_Int16 SAL_CALL getAlternativesCount( ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getAlternatives( ) override; + + // XSetSpellAlternatives + virtual void SAL_CALL setAlternatives( const css::uno::Sequence< OUString >& aAlternatives ) override; + virtual void SAL_CALL setFailureType( ::sal_Int16 nFailureType ) override; + + // non-interface specific functions + void UNLESS_MERGELIBS(LNG_DLLPUBLIC) SetWordLanguage(const OUString &rWord, LanguageType nLang); + void UNLESS_MERGELIBS(LNG_DLLPUBLIC) SetFailureType(sal_Int16 nTypeP); + void UNLESS_MERGELIBS(LNG_DLLPUBLIC) SetAlternatives( const css::uno::Sequence< OUString > &rAlt ); + static css::uno::Reference < css::linguistic2::XSpellAlternatives > UNLESS_MERGELIBS(LNG_DLLPUBLIC) CreateSpellAlternatives( + const OUString &rWord, LanguageType nLang, sal_Int16 nTypeP, const css::uno::Sequence< OUString > &rAlt ); +}; + +} // namespace linguistic + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/any.hxx b/include/o3tl/any.hxx new file mode 100644 index 000000000..0acccff64 --- /dev/null +++ b/include/o3tl/any.hxx @@ -0,0 +1,325 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_ANY_HXX +#define INCLUDED_O3TL_ANY_HXX + +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +// Some functionality related to css::uno::Any that would ideally be part of +// , but (for now) cannot be for some reason. + +namespace o3tl { + +namespace detail { + +struct Void {}; + +template struct Optional { using type = T const *; }; +template<> struct Optional { using type = std::optional; }; +template<> struct Optional { using type = std::optional; }; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template<> struct Optional { + using type = std::optional; +}; +template struct Optional> { + using type = std::optional const>; +}; +template<> struct Optional> { + using type = css::uno::Reference const *; +}; + +template struct IsDerivedReference: std::false_type {}; +template struct IsDerivedReference>: + std::true_type +{}; +template<> struct IsDerivedReference>: + std::false_type +{}; + +template struct IsUnoSequenceType: std::false_type {}; +template struct IsUnoSequenceType>: + std::true_type +{}; + +template inline std::optional tryGetConverted( + css::uno::Any const & any) +{ + T v; + return (any >>= v) + ? std::optional(std::move(v)) : std::optional(); +} + +} + +/** Try to access the value of a specific type stored in an Any. + + In trying to obtain a value, the same set of conversions as supported by + ">>=" are considered. + + The returned object is a proxy. Proxies can be either positive or negative. + Each proxy can be contextually converted to bool, yielding true iff the + proxy is positive. For a positive proxy P representing a value of requested + type T, for any T other than void, the expression *P yields that value of + type T. (Technically, the proxy is either a plain pointer or a + std::optional, depending on whether a plain pointer into the given Any can + be returned for the specified type.) + + @attention A proxy returned from this function must not outlive the + corresponding Any passed into this function (as it may constitute a pointer + into the Any's internals). That is the reason why this function is + restricted to lvalue arguments (i.e., to non-temporary Any objects), to + avoid misuses like + @code + css::uno::Any f(); + + if (auto p = o3tl::tryAccess(f())) { + return p->Name; + } + @endcode + + @note Ideally this would be a public member function of css::uno::Any (at + least conditional on LIBO_INTERNAL_ONLY, as it requires C++11). However, as + std::optional (which would be needed to implement the proxies) is only + available since C++14, we need to use std::optional for now. But To not + make every entity that includes depend on + boost_headers, keep this here for now. + + @tparam T the C++ representation of a UNO type that can be contained in a + UNO ANY (i.e., any UNO type other than ANY itself). The legacy C++ + representations sal_Bool, cppu::UnoVoidType, cppu::UnoUnsignedShortType, + cppu::UnoCharType, and cppu::UnoSequenceType are not supported. Must be a + complete type or void. + + @param any an Any value. + + @return a positive proxy for the value of the specified type obtained from + the given Any, or a negative proxy if no such value can be obtained. +*/ +template inline +typename std::enable_if< + !(detail::IsDerivedReference::value + || detail::IsUnoSequenceType::value + || std::is_base_of::value), + typename detail::Optional::type>::type +tryAccess(css::uno::Any const & any) { + // CHAR, STRING, TYPE, sequence types, enum types, struct types, exception + // types, and com.sun.star.uno.XInterface interface type: + return cppu::UnoType::get().isAssignableFrom(any.getValueType()) + ? static_cast(any.getValue()) : nullptr; +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return any.hasValue() + ? std::optional() + : std::optional(detail::Void()); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> inline detail::Optional::type tryAccess( + css::uno::Any const & any) +{ + return detail::tryGetConverted(any); +} + +template<> detail::Optional::type tryAccess( + css::uno::Any const &) = delete; + +template<> detail::Optional::type tryAccess( + css::uno::Any const &) = delete; + +/* + +// Already prevented by std::is_base_of requiring T to +// be complete: + +template<> detail::Optional::type +tryAccess(css::uno::Any const &) = delete; + +template<> detail::Optional::type +tryAccess(css::uno::Any const &) = delete; + +template<> detail::Optional::type +tryAccess(css::uno::Any const &) = delete; + +*/ + +template inline +typename std::enable_if< + detail::IsDerivedReference::value, + typename detail::Optional::type>::type +tryAccess(css::uno::Any const & any) { + return detail::tryGetConverted(any); +} + +template typename detail::Optional::type tryAccess( + css::uno::Any const volatile &&) = delete; + +/** Access the value of a specific type stored in an Any, throwing an exception + on failure. + + @attention A proxy returned from this function must not outlive the + corresponding Any passed into this function (as it may constitute a pointer + into the Any's internals). However, unlike with tryAccess, the benefit of + allowing this function to operate on temporaries appears to outweigh its + dangers. + + @note Ideally this would be a public member function of css::uno::Any. See + tryAccess for details. + + @tparam T the C++ representation of a UNO type that can be contained in a + UNO ANY. See tryAccess for details. + + @param any an Any value. + + @return a positive proxy for the value of the specified type obtained from + the given Any. See tryAccess for details. + + @throws css::uno::RuntimeException when a value of the requested type + cannot be obtained. +*/ +template inline typename detail::Optional::type doAccess( + css::uno::Any const & any) +{ + auto opt = tryAccess(any); + if (!opt) { + throw css::uno::RuntimeException( + OUString( + cppu_Any_extraction_failure_msg( + &any, cppu::UnoType::get().getTypeLibType()), + SAL_NO_ACQUIRE)); + } + return opt; +} + +/** Access the value of a specific type stored in an Any, knowing the Any + contains a value of a matching type. + + @attention A proxy returned from this function must not outlive the + corresponding Any passed into this function (as it may constitute a pointer + into the Any's internals). However, unlike with tryAccess, the benefit of + allowing this function to operate on temporaries appears to outweigh its + dangers. + + @note Ideally this would be a public member function of css::uno::Any. See + tryAccess for details. + + @tparam T the C++ representation of a UNO type that can be contained in a + UNO ANY. See tryAccess for details. + + @param any an Any value. + + @return a positive proxy for the value of the specified type obtained from + the given Any. See tryAccess for details. +*/ +template inline typename detail::Optional::type forceAccess( + css::uno::Any const & any) +{ + auto opt = tryAccess(any); + assert(opt); + return opt; +} + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/char16_t2wchar_t.hxx b/include/o3tl/char16_t2wchar_t.hxx new file mode 100644 index 000000000..6ffab02e7 --- /dev/null +++ b/include/o3tl/char16_t2wchar_t.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_CHAR16_T2WCHAR_T_HXX +#define INCLUDED_O3TL_CHAR16_T2WCHAR_T_HXX + +#include + +namespace o3tl { + +#if defined _WIN32 +// Helpers for safe conversion between wchar_t and char16_t in MSVC + +static_assert(sizeof(char16_t) == sizeof(wchar_t), + "These helper functions are only applicable to implementations with 16-bit wchar_t"); + +// While other implementations define wchar_t as 32-bit integral value, and mostly use +// char-based UTF-8 string APIs, in MSVC wchar_t is (non-conformant) 16-bit, and Unicode +// support is implemented by Unicode-aware WinAPI functions taking UTF-16 LE strings, +// and also stdlib functions taking those strings. +// +// In LibreOffice, internal string representation is also UTF-16 with system endianness +// (sal_Unicode that is typedef for char16_t); so it is an important implementation concept +// to treat internal strings as directly usable by WinAPI/stdlib functions and vice versa. +// Also, it's important to use safe conversion between unrelated underlying C++ types +// used for MSVC and LibreOffice string storage without plain reinterpret_cast that brings +// risks of masking errors like casting char buffers to wchar_t/char16_t. +// +// Use these helpers for wchar_t (WSTR, WCHAR, OLESTR etc) to char16_t (sal_Unicode) string +// conversions instead of reinterpret-cast in Windows-specific code. +inline wchar_t * toW(char16_t * p) +{ + return reinterpret_cast(p); +} +inline wchar_t const * toW(char16_t const * p) +{ + return reinterpret_cast(p); +} +inline char16_t * toU(wchar_t * p) +{ + return reinterpret_cast(p); +} +inline char16_t const * toU(wchar_t const * p) +{ + return reinterpret_cast(p); +} +#endif + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/cow_wrapper.hxx b/include/o3tl/cow_wrapper.hxx new file mode 100644 index 000000000..cc823f60e --- /dev/null +++ b/include/o3tl/cow_wrapper.hxx @@ -0,0 +1,387 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_COW_WRAPPER_HXX +#define INCLUDED_O3TL_COW_WRAPPER_HXX + +#include + +#include +#include + +namespace o3tl +{ + /** Thread-unsafe refcounting + + This is the default locking policy for cow_wrapper. No + locking/guarding against concurrent access is performed + whatsoever. + */ + struct UnsafeRefCountingPolicy + { + typedef std::size_t ref_count_t; + static void incrementCount( ref_count_t& rCount ) { ++rCount; } + static bool decrementCount( ref_count_t& rCount ) { return --rCount != 0; } + }; + + /** Thread-safe refcounting + + Use this to have the cow_wrapper refcounting mechanisms employ + the thread-safe oslInterlockedCount . + */ + struct ThreadSafeRefCountingPolicy + { + typedef oslInterlockedCount ref_count_t; + static void incrementCount( ref_count_t& rCount ) { osl_atomic_increment(&rCount); } + static bool decrementCount( ref_count_t& rCount ) + { + return osl_atomic_decrement(&rCount) != 0; + } + }; + + /** Copy-on-write wrapper. + + This template provides copy-on-write semantics for the wrapped + type: when copying, the operation is performed shallow, + i.e. different cow_wrapper objects share the same underlying + instance. Only when accessing the underlying object via + non-const methods, a unique copy is provided. + + The type parameter T must satisfy the following + requirements: it must be default-constructible, copyable (it + need not be assignable), and be of non-reference type. Note + that, despite the fact that this template provides access to + the wrapped type via pointer-like methods + (operator->() and operator*()), it does + not work like e.g. the std smart pointer wrappers + (shared_ptr, unique_ptr, etc.). Internally, the cow_wrapper + holds a by-value instance of the wrapped object. This is to + avoid one additional heap allocation, and providing access via + operator->()/operator*() is because + operator.() cannot be overridden. + + Regarding thread safety: this wrapper is not + thread-safe per se, because cow_wrapper has no way of + synchronizing the potentially many different cow_wrapper + instances, that reference a single shared value_type + instance. That said, when passing + ThreadSafeRefCountingPolicy as the + MTPolicy parameter, accessing a thread-safe + pointee through multiple cow_wrapper instances might be + thread-safe, if the individual pointee methods are + thread-safe, including pointee's copy + constructor. Any wrapped object that needs external + synchronisation (e.g. via an external mutex, which arbitrates + access to object methods, and can be held across multiple + object method calls) cannot easily be dealt with in a + thread-safe way, because, as noted, objects are shared behind + the client's back. + + @attention if one wants to use the pimpl idiom together with + cow_wrapper (i.e. put an opaque type into the cow_wrapper), + then all methods in the surrounding class needs to be + non-inline (including destructor, copy constructor + and assignment operator). + + @example +
    +class cow_wrapper_client_impl;
    +
    +class cow_wrapper_client
    +{
    +public:
    +    cow_wrapper_client();
    +    cow_wrapper_client( const cow_wrapper_client& );
    +    cow_wrapper_client( cow_wrapper_client&& );
    +    ~cow_wrapper_client();
    +
    +    cow_wrapper_client& operator=( const cow_wrapper_client& );
    +    cow_wrapper_client& operator=( cow_wrapper_client&& );
    +
    +    void modify( int nVal );
    +    int queryUnmodified() const;
    +
    +private:
    +    o3tl::cow_wrapper< cow_wrapper_client_impl > maImpl;
    +};
    +        
    + and the implementation file would look like this: +
    +class cow_wrapper_client_impl
    +{
    +public:
    +    void setValue( int nVal ) { mnValue = nVal; }
    +    int getValue() const { return mnValue; }
    +
    +private:
    +    int mnValue;
    +}
    +
    +cow_wrapper_client::cow_wrapper_client() :
    +    maImpl()
    +{
    +}
    +cow_wrapper_client::cow_wrapper_client( const cow_wrapper_client& rSrc ) :
    +    maImpl( rSrc.maImpl )
    +{
    +}
    +cow_wrapper_client::cow_wrapper_client( cow_wrapper_client& rSrc ) :
    +    maImpl( std::move( rSrc.maImpl ) )
    +{
    +}
    +cow_wrapper_client::~cow_wrapper_client()
    +{
    +}
    +cow_wrapper_client& cow_wrapper_client::operator=( const cow_wrapper_client& rSrc )
    +{
    +    maImpl = rSrc.maImpl;
    +    return *this;
    +}
    +cow_wrapper_client& cow_wrapper_client::operator=( cow_wrapper_client&& rSrc )
    +{
    +    maImpl = std::move( rSrc.maImpl );
    +    return *this;
    +}
    +void cow_wrapper_client::modify( int nVal )
    +{
    +    maImpl->setValue( nVal );
    +}
    +int cow_wrapper_client::queryUnmodified() const
    +{
    +    return maImpl->getValue();
    +}
    +        
    + */ + template class cow_wrapper + { + /** shared value object - gets cloned before cow_wrapper hands + out a non-const reference to it + */ + struct impl_t + { + impl_t(const impl_t&) = delete; + impl_t& operator=(const impl_t&) = delete; + + impl_t() : + m_value(), + m_ref_count(1) + { + } + + explicit impl_t( const T& v ) : + m_value(v), + m_ref_count(1) + { + } + + explicit impl_t( T&& v ) : + m_value(std::move(v)), + m_ref_count(1) + { + } + + T m_value; + typename MTPolicy::ref_count_t m_ref_count; + }; + + void release() + { + if( m_pimpl && !MTPolicy::decrementCount(m_pimpl->m_ref_count) ) + { + delete m_pimpl; + m_pimpl = nullptr; + } + } + + public: + typedef T value_type; + typedef T* pointer; + typedef const T* const_pointer; + typedef MTPolicy mt_policy; + + /** Default-construct wrapped type instance + */ + cow_wrapper() : + m_pimpl( new impl_t() ) + { + } + + /** Copy-construct wrapped type instance from given object + */ + explicit cow_wrapper( const value_type& r ) : + m_pimpl( new impl_t(r) ) + { + } + + /** Move-construct wrapped type instance from given object + */ + explicit cow_wrapper( value_type&& r ) : + m_pimpl( new impl_t(std::move(r)) ) + { + } + + /** Shallow-copy given cow_wrapper + */ + explicit cow_wrapper( const cow_wrapper& rSrc ) : // nothrow + m_pimpl( rSrc.m_pimpl ) + { + MTPolicy::incrementCount( m_pimpl->m_ref_count ); + } + + /** Move-construct and steal rSrc shared resource + */ + explicit cow_wrapper( cow_wrapper&& rSrc ) noexcept : + m_pimpl( rSrc.m_pimpl ) + { + rSrc.m_pimpl = nullptr; + } + + // Only intended to be used by std::optional specialisations + explicit cow_wrapper( std::nullopt_t ) noexcept : + m_pimpl( nullptr ) + { + } + + // Only intended to be used by std::optional specialisations + explicit cow_wrapper( const cow_wrapper& rSrc, std::nullopt_t ) : // nothrow + m_pimpl( rSrc.m_pimpl ) + { + if (m_pimpl) + MTPolicy::incrementCount( m_pimpl->m_ref_count ); + } + + ~cow_wrapper() // nothrow, if ~T does not throw + { + release(); + } + + /// now sharing rSrc cow_wrapper instance with us + cow_wrapper& operator=( const cow_wrapper& rSrc ) // nothrow + { + // this already guards against self-assignment + MTPolicy::incrementCount( rSrc.m_pimpl->m_ref_count ); + + release(); + m_pimpl = rSrc.m_pimpl; + + return *this; + } + + /// stealing rSrc's resource + cow_wrapper& operator=(cow_wrapper&& rSrc) noexcept + { + // self-movement guts ourself, see also 17.6.4.9 + release(); + m_pimpl = rSrc.m_pimpl; + + rSrc.m_pimpl = nullptr; + + return *this; + } + + /// unshare with any other cow_wrapper instance + value_type& make_unique() + { + if( m_pimpl->m_ref_count > 1 ) + { + impl_t* pimpl = new impl_t(m_pimpl->m_value); + release(); + m_pimpl = pimpl; + } + + return m_pimpl->m_value; + } + + /// true, if not shared with any other cow_wrapper instance + bool is_unique() const // nothrow + { + return !m_pimpl || m_pimpl->m_ref_count == 1; + } + + /// return number of shared instances (1 for unique object) + typename MTPolicy::ref_count_t use_count() const // nothrow + { + return m_pimpl ? m_pimpl->m_ref_count : 0; + } + + void swap(cow_wrapper& r) // never throws + { + std::swap(m_pimpl, r.m_pimpl); + } + + pointer operator->() { return &make_unique(); } + value_type& operator*() { return make_unique(); } + const_pointer operator->() const { return &m_pimpl->m_value; } + const value_type& operator*() const { return m_pimpl->m_value; } + + pointer get() { return &make_unique(); } + const_pointer get() const { return &m_pimpl->m_value; } + + /// true, if both cow_wrapper internally share the same object + bool same_object( const cow_wrapper& rOther ) const + { + return rOther.m_pimpl == m_pimpl; + } + + // Only intended to be used by std::optional specialisations + bool empty() const { return m_pimpl == nullptr; } + // Only intended to be used by std::optional specialisations + void set_empty() + { + if (m_pimpl) + { + release(); + m_pimpl = nullptr; + } + } + + private: + impl_t* m_pimpl; + }; + + + template inline bool operator==( const cow_wrapper& a, + const cow_wrapper& b ) + { + return a.same_object(b) || *a == *b; + } + + template inline bool operator!=( const cow_wrapper& a, + const cow_wrapper& b ) + { + return !a.same_object(b) && *a != *b; + } + + template inline bool operator<( const cow_wrapper& a, + const cow_wrapper& b ) + { + return *a < *b; + } + + template inline void swap( cow_wrapper& a, + cow_wrapper& b ) + { + a.swap(b); + } + +} + +#endif /* INCLUDED_O3TL_COW_WRAPPER_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/cppunittraitshelper.hxx b/include/o3tl/cppunittraitshelper.hxx new file mode 100644 index 000000000..2a6fb8836 --- /dev/null +++ b/include/o3tl/cppunittraitshelper.hxx @@ -0,0 +1,28 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_CPPUNITTRAITSHELPER_HXX +#define INCLUDED_O3TL_CPPUNITTRAITSHELPER_HXX + +#include + +#include +#include + +#include + +// ostream << char16_t is deleted since C++20 (but just keep outputting numeric values): +template <> inline std::string CppUnit::assertion_traits::toString(char16_t const& x) +{ + return assertion_traits::toString(std::uint_least16_t(x)); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/deleter.hxx b/include/o3tl/deleter.hxx new file mode 100644 index 000000000..76d8d5a35 --- /dev/null +++ b/include/o3tl/deleter.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_DELETER_HXX +#define INCLUDED_O3TL_DELETER_HXX + +#include + +#include + +#if defined(__COVERITY__) +#define suppress_fun_call_w_exception(expr) \ + do \ + { \ + try \ + { \ + expr; \ + } \ + catch (...) \ + { \ + std::terminate(); \ + } \ + } while (false) +#else +#define suppress_fun_call_w_exception(expr) \ + do \ + { \ + expr; \ + } while (false) +#endif + +namespace o3tl +{ +/** To markup std::unique_ptr that coverity warns might throw exceptions + which won't throw in practice, or where std::terminate is + an acceptable response if they do +*/ +template struct default_delete +{ + void operator()(T* p) noexcept { suppress_fun_call_w_exception(delete p); } +}; + +struct free_delete +{ + void operator()(void* p) { std::free(p); } +}; + +template void reset_preserve_ptr_during(uniqueptr& ptr) +{ + // HACK: for the case where the dtor of the obj held by ptr will trigger + // functions which expect ptr to still be set during the dtor. + // e.g. SdrObject::GetBroadcaster() is called during the destructor + // in SdrEdgeObj::Notify(). So delete first, then clear the pointer + delete ptr.get(); + // coverity[leaked_storage] - not a leak, deleted on line above + (void)ptr.release(); +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/enumarray.hxx b/include/o3tl/enumarray.hxx new file mode 100644 index 000000000..a3c09d56b --- /dev/null +++ b/include/o3tl/enumarray.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_ENUMARRAY_HXX +#define INCLUDED_O3TL_ENUMARRAY_HXX + +#include +#include +#include + +namespace o3tl { + +template +class enumarray_iterator; +template +class enumarray_const_iterator; + +/// +/// This is a container convenience class for arrays indexed by enum values. +/// +/// This assumes that the 'enum class' definition +/// - starts at zero +/// - has no holes in its sequence of values +/// - defines a value called LAST which refers to the greatest constant. +/// +/// \param E the 'enum class' type. +/// \param V the value type to be stored in the array +template +class enumarray final +{ +public: + typedef enumarray self_type; + typedef enumarray_iterator iterator; + typedef enumarray_const_iterator const_iterator; + + typedef V value_type; + typedef E key_type; + typedef size_t size_type; + + static const size_type max_index = static_cast(E::LAST); + + const V& operator[](E index) const + { + assert(index>=static_cast(0) && index<=E::LAST); + return detail_values[static_cast(index)]; + } + + V& operator[](E index) + { + assert(index>=static_cast(0) && index<=E::LAST); + return detail_values[static_cast(index)]; + } + + void fill(V val) + { for (size_type i=0; i<=max_index; ++i) detail_values[i] = val; } + + static size_type size() { return max_index + 1; } + iterator begin() { return iterator(*this, 0); } + iterator end() { return iterator(*this, size()); } + const_iterator begin() const { return const_iterator(*this, 0); } + const_iterator end() const { return const_iterator(*this, size()); } + + V* data() { return detail_values; } + +//private: + V detail_values[max_index + 1]; +}; + + +template +class enumarray_iterator { + EA* m_buf; + size_t m_pos; +public: + typedef enumarray_iterator self_type; + typedef typename EA::value_type value_type; + typedef typename EA::key_type key_type; + typedef std::bidirectional_iterator_tag iterator_category; //should be random access, but that would require define subtraction operators on the enums + typedef + typename std::make_signed< + typename std::underlying_type::type>::type + difference_type; + typedef typename EA::value_type* pointer; + typedef typename EA::value_type& reference; + + enumarray_iterator(EA& b, size_t start_pos) + : m_buf(&b), m_pos(start_pos) {} + value_type& operator*() const { return (*m_buf)[static_cast(m_pos)]; } + value_type* operator->() const { return &(operator*()); } + self_type& operator++() { ++m_pos; return *this; } + bool operator!=(self_type const & other) const { return m_buf != other.m_buf || m_pos != other.m_pos; } + bool operator==(self_type const & other) const { return m_buf == other.m_buf && m_pos == other.m_pos; } +}; + +template +class enumarray_const_iterator { + EA const * m_buf; + size_t m_pos; +public: + typedef enumarray_const_iterator self_type; + typedef typename EA::value_type const value_type; + typedef typename EA::key_type key_type; + typedef std::bidirectional_iterator_tag iterator_category; //should be random access, but that would require define subtraction operators on the enums + typedef + typename std::make_signed< + typename std::underlying_type::type>::type + difference_type; + typedef typename EA::value_type const * pointer; + typedef typename EA::value_type const & reference; + + enumarray_const_iterator(EA const & b, size_t start_pos) + : m_buf(&b), m_pos(start_pos) {} + value_type& operator*() const { return (*m_buf)[static_cast(m_pos)]; } + value_type* operator->() const { return &(operator*()); } + self_type& operator++() { ++m_pos; return *this; } + bool operator!=(self_type const & other) const { return m_buf != other.m_buf || m_pos != other.m_pos; } + bool operator==(self_type const & other) const { return m_buf == other.m_buf && m_pos == other.m_pos; } +}; + +}; // namespace o3tl + +#endif /* INCLUDED_O3TL_ENUMARRAY_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/enumrange.hxx b/include/o3tl/enumrange.hxx new file mode 100644 index 000000000..60f069c9f --- /dev/null +++ b/include/o3tl/enumrange.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_ENUMRANGE_HXX +#define INCLUDED_O3TL_ENUMRANGE_HXX + +namespace o3tl { + +/// +/// This is a container convenience class iterating over scoped enumerations. +/// +/// This assumes that the 'enum class' definition +/// - starts at zero +/// - has no holes in its sequence of values +/// - defines a value called LAST which refers to the greatest constant. +/// +/// Use like this: +/// enum class COLOR { RED, GREEN, BLUE, LAST=BLUE }; +/// for( auto e : o3tl::enumrange() ) +/// ....; +/// +/// \param T the 'enum class' type. +template< typename T> +class enumrange +{ +public: + class Iterator + { + public: + Iterator( int value ) : + m_value( value ) + { + } + + T operator*( void ) const + { + return static_cast(m_value); + } + + void operator++( void ) + { + ++m_value; + } + + bool operator!=( Iterator rhs ) const + { + return m_value != rhs.m_value; + } + + private: + int m_value; + }; +}; + +template< typename T > +typename enumrange::Iterator begin( enumrange ) +{ + return typename enumrange::Iterator( int(0) ); +} + +template< typename T > +typename enumrange::Iterator end( enumrange ) +{ + return typename enumrange::Iterator( static_cast(T::LAST) + 1 ); +} + +}; // namespace o3tl + +#endif /* INCLUDED_O3TL_ENUMRANGE_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/float_int_conversion.hxx b/include/o3tl/float_int_conversion.hxx new file mode 100644 index 000000000..403bed622 --- /dev/null +++ b/include/o3tl/float_int_conversion.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_FLOAT_INT_CONVERSION_HXX +#define INCLUDED_O3TL_FLOAT_INT_CONVERSION_HXX + +#include + +#include +#include +#include + +namespace o3tl +{ +// Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no +// smaller than `min`: +template +constexpr std::enable_if_t && std::is_integral_v, bool> +convertsToAtLeast(F value, I min) +{ + // If `F(min)`, `F(min) - F(1)` are too large in magnitude for `F`'s precision, then they either + // fall into the same bucket, in which case we should return false if `value` represents that + // bucket, or they are on the boundary of two adjacent buckets, in which case we should return + // true if `value`represents the higher bucket containing `F(min)`: + return value > F(min) - F(1); +} + +// Return true iff `value` of floating-point type `F` converts to a value of integral type `I` no +// larger than `max`: +template +constexpr std::enable_if_t && std::is_integral_v, bool> +convertsToAtMost(F value, I max) +{ + // If `F(max)`, `F(max) + F(1)` are too large in magnitude for `F`'s precision, then they either + // fall into the same bucket, in which case we should return false if `value` represents that + // bucket, or they are on the boundary of two adjacent buckets, in which case we should return + // true if `value`represents the lower bucket containing `F(max)`: + return value < F(max) + F(1); +} + +// Casts a floating-point to an integer, avoiding overflow. Used like: +// sal_Int64 n = o3tl::saturating_cast(f); +template +constexpr std::enable_if_t && std::is_integral_v, I> +saturating_cast(F f) +{ + if constexpr (std::is_signed_v) + if (!convertsToAtLeast(f, std::numeric_limits::min())) + return std::numeric_limits::min(); + if (!convertsToAtMost(f, std::numeric_limits::max())) + return std::numeric_limits::max(); + return f; +} + +// Return `value` of floating-point type `F` rounded to the nearest integer away from zero (which +// can be useful in calls to convertsToAtLeast/Most(roundAway(x), n), to reject x that are +// smaller/larger than n because they have a fractional part): +template std::enable_if_t, F> roundAway(F value) +{ + return value >= 0 ? std::ceil(value) : std::floor(value); +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/functional.hxx b/include/o3tl/functional.hxx new file mode 100644 index 000000000..9ca86924f --- /dev/null +++ b/include/o3tl/functional.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * + * Copyright (c) 1994 + * Hewlett-Packard Company + * + * Copyright (c) 1996-1998 + * Silicon Graphics Computer Systems, Inc. + * + * Copyright (c) 1997 + * Moscow Center for SPARC Technology + * + * Copyright (c) 1999 + * Boris Fomitchev + * + * This material is provided "as is", with absolutely no warranty expressed + * or implied. Any use is at your own risk. + * + * Permission to use or copy this software for any purpose is hereby granted + * without fee, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is granted, + * provided the above notices are retained, and a notice that the code was + * modified is included with the above copyright notice. + * + */ + +/* + * Lifted and paraphrased from STLport - with additions from Fridrich + * Strba and Thorsten Behrens + */ + +#ifndef INCLUDED_O3TL_FUNCTIONAL_HXX +#define INCLUDED_O3TL_FUNCTIONAL_HXX + +namespace o3tl +{ +/// Select first value of a pair +template +struct select1st +{ + typedef P argument_type; + typedef typename P::first_type result_type; + const result_type& operator()( const argument_type& cp ) const { + return cp.first; + } +}; + +/// Select second value of a pair +template +struct select2nd +{ + typedef P argument_type; + typedef typename P::second_type result_type; + const result_type& operator()( const argument_type& cp ) const { + return cp.second; + } +}; + +} // namespace o3tl + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/hash_combine.hxx b/include/o3tl/hash_combine.hxx new file mode 100644 index 000000000..48e142622 --- /dev/null +++ b/include/o3tl/hash_combine.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include + +namespace o3tl +{ +template +inline std::enable_if_t<(sizeof(N) == 4)> hash_combine(N& nSeed, T const* pValue, size_t nCount) +{ + static_assert(sizeof(nSeed) == 4); + for (size_t i = 0; i < nCount; ++i) + { + nSeed ^= std::hash{}(*pValue) + 0x9E3779B9u + (nSeed << 6) + (nSeed >> 2); + ++pValue; + } +} + +template +inline std::enable_if_t<(sizeof(N) == 4)> hash_combine(N& nSeed, T const& nValue) +{ + static_assert(sizeof(nSeed) == 4); + nSeed ^= std::hash{}(nValue) + 0x9E3779B9u + (nSeed << 6) + (nSeed >> 2); +} + +template +inline std::enable_if_t<(sizeof(N) == 8)> hash_combine(N& nSeed, T const* pValue, size_t nCount) +{ + static_assert(sizeof(nSeed) == 8); + for (size_t i = 0; i < nCount; ++i) + { + nSeed ^= std::hash{}(*pValue) + 0x9E3779B97F4A7C15llu + (nSeed << 12) + (nSeed >> 4); + ++pValue; + } +} + +template +inline std::enable_if_t<(sizeof(N) == 8)> hash_combine(N& nSeed, T const& nValue) +{ + static_assert(sizeof(nSeed) == 8); + nSeed ^= std::hash{}(nValue) + 0x9E3779B97F4A7C15llu + (nSeed << 12) + (nSeed >> 4); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/intcmp.hxx b/include/o3tl/intcmp.hxx new file mode 100644 index 000000000..1324afcda --- /dev/null +++ b/include/o3tl/intcmp.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include + +#include + +namespace o3tl +{ +// An approximation of the C++20 integer comparison functions +// ( "Safe integral +// comparisons"): +#if defined __cpp_lib_integer_comparison_functions + +using std::cmp_equal; +using std::cmp_not_equal; +using std::cmp_less; +using std::cmp_greater; +using std::cmp_less_equal; +using std::cmp_greater_equal; + +#else + +template constexpr bool cmp_equal(T1 value1, T2 value2) noexcept +{ + // coverity[same_on_both_sides: FALSE] + if constexpr (std::is_signed_v == std::is_signed_v) + { + return value1 == value2; + } + else if constexpr (std::is_signed_v) + { + return value1 >= 0 && o3tl::make_unsigned(value1) == value2; + } + else + { + return value2 >= 0 && value1 == o3tl::make_unsigned(value2); + } +} + +template constexpr bool cmp_not_equal(T1 value1, T2 value2) noexcept +{ + return !cmp_equal(value1, value2); +} + +template constexpr bool cmp_less(T1 value1, T2 value2) noexcept +{ + if constexpr (std::is_signed_v == std::is_signed_v) + { + return value1 < value2; + } + else if constexpr (std::is_signed_v) + { + return value1 < 0 || o3tl::make_unsigned(value1) < value2; + } + else + { + return value2 >= 0 && value1 < o3tl::make_unsigned(value2); + } +} + +template constexpr bool cmp_greater(T1 value1, T2 value2) noexcept +{ + return cmp_less(value2, value1); +} + +template constexpr bool cmp_less_equal(T1 value1, T2 value2) noexcept +{ + return !cmp_greater(value1, value2); +} + +template constexpr bool cmp_greater_equal(T1 value1, T2 value2) noexcept +{ + return !cmp_less(value1, value2); +} + +#endif + +// A convenient operator syntax around the standard integer comparison functions: +template struct IntCmp +{ + explicit constexpr IntCmp(T theValue) + : value(theValue) + { + } + + T value; +}; + +template constexpr bool operator==(IntCmp value1, IntCmp value2) +{ + return o3tl::cmp_equal(value1.value, value2.value); +} + +template constexpr bool operator!=(IntCmp value1, IntCmp value2) +{ + return o3tl::cmp_not_equal(value1.value, value2.value); +} + +template constexpr bool operator<(IntCmp value1, IntCmp value2) +{ + return o3tl::cmp_less(value1.value, value2.value); +} + +template constexpr bool operator>(IntCmp value1, IntCmp value2) +{ + return o3tl::cmp_greater(value1.value, value2.value); +} + +template constexpr bool operator<=(IntCmp value1, IntCmp value2) +{ + return o3tl::cmp_less_equal(value1.value, value2.value); +} + +template constexpr bool operator>=(IntCmp value1, IntCmp value2) +{ + return o3tl::cmp_greater_equal(value1.value, value2.value); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/lazy_update.hxx b/include/o3tl/lazy_update.hxx new file mode 100644 index 000000000..6f9325dfd --- /dev/null +++ b/include/o3tl/lazy_update.hxx @@ -0,0 +1,89 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_LAZY_UPDATE_HXX +#define INCLUDED_O3TL_LAZY_UPDATE_HXX + +#include + +namespace o3tl +{ + /** Update output object lazily + + This template collects data in input type, and updates the + output type with the given update functor, but only if the + output is requested. Useful if updating is expensive, or input + changes frequently, but output is only comparatively seldom + used. + + @example +
    +LazyUpdate myValue(F);
    +*myValue = newInput;
    +myValue->updateInput( this, that, those );
    +
    +output( *myValue );
    +        
    + or +
    +output( myValue.getOutValue() );
    +        
    + if the compiler does not recognize the const context. + */ + template class LazyUpdate { + public: + LazyUpdate(Func func): func_(std::move(func)), input_(), dirty_(true) {} + + In const & getInValue() const { return input_; } + + Out const & getOutValue() const { return update(); } + + In & operator *() { + dirty_ = true; + return input_; + } + + In * operator ->() { + dirty_ = true; + return &input_; + } + + Out const & operator *() const { return update(); } + + Out const * operator ->() const { return &update(); } + + private: + Out const & update() const { + if (dirty_) { + output_ = func_(input_); + dirty_ = false; + } + return output_; + } + + Func const func_; + In input_; + mutable Out output_; + mutable bool dirty_; + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/lru_map.hxx b/include/o3tl/lru_map.hxx new file mode 100644 index 000000000..859617e5d --- /dev/null +++ b/include/o3tl/lru_map.hxx @@ -0,0 +1,299 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_O3TL_LRU_MAP_HXX +#define INCLUDED_O3TL_LRU_MAP_HXX + +#include +#include +#include +#include +#include +#include + +namespace o3tl +{ +namespace detail +{ +// Helper base class to keep total cost for lru_map with custom item size. +// Custom size is specified by the ValueSize functor, the default of each +// item counting as 1 is specified using the void type. +template class lru_map_base +{ +public: + // Returns total of ValueSize for all items. + size_t total_size() const { return mCurrentSize; } + +protected: + size_t mCurrentSize = 0; // sum of ValueSize for all items +}; + +// By default cost of each item is 1, so it doesn't need to be tracked. +template <> class lru_map_base +{ +}; +} // namespace + +/** LRU map + * + * Similar to unordered_map (it actually uses it) with additionally functionality + * which removes the entries that have been "least recently used" when the size + * hits the specified capacity. + * + * It only implements the minimal methods needed and the implementation is NOT + * thread safe. + * + * The implementation is as simple as possible but it still uses O(1) complexity + * for most of the operations with a combination unordered map and linked list. + * + * It is optionally possible to specify a function for ValueSize template + * argument (that can be called as 'size_t func(Value)') that will return + * a size (cost) for an item instead of the default size of 1 for each item. + * The size of an item must not change for an item (if needed, re-insert + * the item). A newly inserted item is guaranteed to be in the container, + * even if its size exceeds the maximum size. + * + **/ +template , + class KeyEqual = std::equal_to, class ValueSize = void> +class lru_map final : public detail::lru_map_base +{ +public: + typedef typename std::pair key_value_pair_t; + +private: + typedef std::list list_t; + typedef typename list_t::iterator list_iterator_t; + typedef typename list_t::const_iterator list_const_iterator_t; + + typedef std::unordered_map map_t; + typedef typename map_t::iterator map_iterator_t; + typedef typename map_t::const_iterator map_const_iterator_t; + + list_t mLruList; + map_t mLruMap; + size_t mMaxSize; + + void addSize(const Value& value) + { + // by default total size is equal to number of items + if constexpr (!std::is_void_v) + this->mCurrentSize += ValueSize()(value); + } + + void removeSize(const Value& value) + { + // by default total size is equal to number of items + if constexpr (!std::is_void_v) + { + size_t itemSize = ValueSize()(value); + assert(itemSize <= this->mCurrentSize); + this->mCurrentSize -= itemSize; + } + } + + void removeOldestItem() + { + removeSize(mLruList.back().second); + // remove from map + mLruMap.erase(mLruList.back().first); + // remove from list + mLruList.pop_back(); + } + + void checkLRUItemInsert() + { + if constexpr (std::is_void_v) + { // One added, so it's enough to remove one, if needed. + if (mLruMap.size() > mMaxSize) + removeOldestItem(); + } + else + { + // This must leave at least one item (it's called from insert). + while (this->mCurrentSize > mMaxSize && mLruList.size() > 1) + removeOldestItem(); + } + } + + void checkLRUItemUpdate() + { + // Item update does not change total size by default. + if constexpr (!std::is_void_v) + { + // This must leave at least one item (it's called from insert). + while (this->mCurrentSize > mMaxSize && mLruList.size() > 1) + removeOldestItem(); + } + } + + void checkLRUMaxSize() + { + if constexpr (std::is_void_v) + { + while (mLruMap.size() > mMaxSize) + removeOldestItem(); + } + else + { + while (this->mCurrentSize > mMaxSize) + removeOldestItem(); + } + } + + void clearSize() + { + if constexpr (!std::is_void_v) + { +#ifdef DBG_UTIL + for (const key_value_pair_t& item : mLruList) + removeSize(item.second); + assert(this->mCurrentSize == 0); +#else + this->mCurrentSize = 0; +#endif + } + } + +public: + typedef list_iterator_t iterator; + typedef list_const_iterator_t const_iterator; + + lru_map(size_t nMaxSize) + : mMaxSize(nMaxSize) + { + assert(mMaxSize > 0); + } + ~lru_map() + { + clearSize(); + // Some code .e.g. SalBitmap likes to remove itself from a cache during it's destructor, which means we + // get calls into lru_map while we are in destruction, so use the swap-and-clear idiom to avoid those problems. + mLruMap.clear(); + list_t().swap(mLruList); + } + + void setMaxSize(size_t nMaxSize) + { + mMaxSize = nMaxSize; + assert(mMaxSize > 0); + checkLRUMaxSize(); + } + + void insert(key_value_pair_t& rPair) + { + map_iterator_t i = mLruMap.find(rPair.first); + + if (i == mLruMap.end()) // doesn't exist -> add to queue and map + { + addSize(rPair.second); + // add to front of the list + mLruList.push_front(rPair); + // add the list position (iterator) to the map + auto it = mLruList.begin(); + mLruMap[it->first] = it; + checkLRUItemInsert(); + } + else // already exists -> replace value + { + // update total cost + removeSize(i->second->second); + addSize(rPair.second); + // replace value + i->second->second = rPair.second; + // bring to front of the lru list + mLruList.splice(mLruList.begin(), mLruList, i->second); + checkLRUItemUpdate(); + } + } + + void insert(key_value_pair_t&& rPair) + { + map_iterator_t i = mLruMap.find(rPair.first); + + if (i == mLruMap.end()) // doesn't exist -> add to list and map + { + addSize(rPair.second); + // add to front of the list + mLruList.push_front(std::move(rPair)); + // add the list position (iterator) to the map + auto it = mLruList.begin(); + mLruMap[it->first] = it; + checkLRUItemInsert(); + } + else // already exists -> replace value + { + removeSize(i->second->second); + addSize(rPair.second); + // replace value + i->second->second = std::move(rPair.second); + // push to back of the lru list + mLruList.splice(mLruList.begin(), mLruList, i->second); + checkLRUItemUpdate(); + } + } + + list_const_iterator_t find(const Key& key) + { + const map_iterator_t i = mLruMap.find(key); + if (i == mLruMap.cend()) // can't find entry for the key + { + // return empty iterator + return mLruList.cend(); + } + else + { + // push to back of the lru list + mLruList.splice(mLruList.begin(), mLruList, i->second); + return i->second; + } + } + + // reverse-iterates the list removing all items matching the predicate + template void remove_if(UnaryPredicate pred) + { + auto it = mLruList.rbegin(); + while (it != mLruList.rend()) + { + if (pred(*it)) + { + removeSize(it->second); + mLruMap.erase(it->first); + it = decltype(it){ mLruList.erase(std::next(it).base()) }; + } + else + ++it; + } + } + + list_const_iterator_t begin() const { return mLruList.cbegin(); } + + list_const_iterator_t end() const { return mLruList.cend(); } + + size_t size() const + { + assert(mLruMap.size() == mLruList.size()); + return mLruMap.size(); + } + + // size_t total_size() const; - only if custom ValueSize + + void clear() + { + clearSize(); + mLruMap.clear(); + mLruList.clear(); + } +}; +} + +#endif /* INCLUDED_O3TL_LRU_MAP_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/make_shared.hxx b/include/o3tl/make_shared.hxx new file mode 100644 index 000000000..5d4d98e42 --- /dev/null +++ b/include/o3tl/make_shared.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_MAKE_SHARED_HXX +#define INCLUDED_O3TL_MAKE_SHARED_HXX + +#include +#include +#include + +namespace o3tl +{ +/** Allocate an array stored in a shared_ptr, calling operator delete[]. + Note that this is only allowed for arithmetic types because shared_ptr + implicitly converts to sub-types. + */ +template std::shared_ptr make_shared_array(size_t const size) +{ + static_assert(std::is_arithmetic::value, "only arrays of arithmetic types allowed"); + return std::shared_ptr(new T[size], std::default_delete()); +} + +/** To markup std::shared_ptr that coverity warns might throw exceptions + which won't throw in practice, or where std::terminate is + an acceptable response if they do +*/ +template std::shared_ptr make_shared(Args&&... args) +{ +#if defined(__COVERITY__) + return std::shared_ptr(new T(std::forward(args)...), o3tl::default_delete()); +#else + return std::make_shared(std::forward(args)...); +#endif +} + +} // namespace o3tl + +#endif // INCLUDED_O3TL_MAKE_SHARED_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/numeric.hxx b/include/o3tl/numeric.hxx new file mode 100644 index 000000000..9980319a6 --- /dev/null +++ b/include/o3tl/numeric.hxx @@ -0,0 +1,28 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_NUMERIC_HXX +#define INCLUDED_O3TL_NUMERIC_HXX + +#include + +namespace o3tl +{ + struct divide_by_zero final : public std::runtime_error + { + explicit divide_by_zero() + : std::runtime_error("divide by zero") + { + } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/runtimetooustring.hxx b/include/o3tl/runtimetooustring.hxx new file mode 100644 index 000000000..6d6f27ac1 --- /dev/null +++ b/include/o3tl/runtimetooustring.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_RUNTIMETOOUSTRING_HXX +#define INCLUDED_O3TL_RUNTIMETOOUSTRING_HXX + +#include + +#include +#include + +#include +#include +#include +#include + +namespace o3tl +{ +/** Convert an NTBS from the C++ runtime to an OUString. + + This is used to convert an NTBS as provided by std::exception::what or + std::type_info::name into an OUString in a "lossless" way. The conversion + is done using RTL_TEXTENCODING_ISO_8859_1, so each char in the input maps + to one Unicode character in the output. +*/ +inline OUString runtimeToOUString(char const* runtimeString) +{ + OUString s; + bool ok = rtl_convertStringToUString( + &s.pData, runtimeString, std::strlen(runtimeString), RTL_TEXTENCODING_ISO_8859_1, + (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR | RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR + | RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR)); + assert(ok); + (void)ok; + return s; +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/safeCoInitUninit.hxx b/include/o3tl/safeCoInitUninit.hxx new file mode 100644 index 000000000..0ceb4a974 --- /dev/null +++ b/include/o3tl/safeCoInitUninit.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#if defined _WIN32 +#include + +// for CoInitializeEx / CoUninitialize +#include + +#include + +// for std::abort +#include + +namespace o3tl +{ +// Helpers for safe calls to CoInitializeEx and CoUninitialize in MSVC +// Indeed if a thread has been already initialized with a concurrency model +// (in LO case COINIT_APARTMENTTHREADED or COINIT_MULTITHREADED) +// CoInitializeEx can't succeed without calling first CoUninitialize +// also, CoUninitialize must be called the number of times CoInitializeEx has been called +inline HRESULT safeCoInitializeEx(DWORD dwCoInit, int& nbReinit) +{ + HRESULT hr; + while ((hr = CoInitializeEx(nullptr, dwCoInit)) == RPC_E_CHANGED_MODE) + { + // so we're in RPC_E_CHANGED_MODE case + // the pb was it was already initialized with a different concurrency model + // close this init + CoUninitialize(); + // and increment counter for dtr part + ++nbReinit; + + // and keep on the loop if there were multi initializations + } + if (FAILED(hr)) + std::abort(); + return hr; +} + +inline void safeCoUninitializeReinit(DWORD dwCoInit, int nbReinit) +{ + CoUninitialize(); + // Put back all the inits, if there were, before the use of the caller to safeCoInitializeEx + for (int i = 0; i < nbReinit; ++i) + CoInitializeEx(nullptr, dwCoInit); +} +} +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/safeint.hxx b/include/o3tl/safeint.hxx new file mode 100644 index 000000000..c697a9316 --- /dev/null +++ b/include/o3tl/safeint.hxx @@ -0,0 +1,236 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include +#include +#include + +#if defined(_MSC_VER) +#include +#else +#ifndef __has_builtin +# define __has_builtin(x) 0 +#endif +#endif + +namespace o3tl +{ + +template inline T saturating_add(T a, T b) +{ + if (b >= 0) { + if (a <= std::numeric_limits::max() - b) { + return a + b; + } else { + return std::numeric_limits::max(); + } + } else { + if (a >= std::numeric_limits::min() - b) { + return a + b; + } else { + return std::numeric_limits::min(); + } + } +} + +template inline T saturating_sub(T a, T b) +{ + if (b >= 0) { + if (a >= std::numeric_limits::min() + b) { + return a - b; + } else { + return std::numeric_limits::min(); + } + } else { + if (a <= std::numeric_limits::max() + b) { + return a - b; + } else { + return std::numeric_limits::max(); + } + } +} + +template inline +typename std::enable_if::value, T>::type saturating_toggle_sign( + T a) +{ + if (a == std::numeric_limits::min()) + return std::numeric_limits::max(); + return a * -1; +} + +#if defined(_MSC_VER) + +template inline bool checked_multiply(T a, T b, T& result) +{ + return !msl::utilities::SafeMultiply(a, b, result); +} + +template inline bool checked_add(T a, T b, T& result) +{ + return !msl::utilities::SafeAdd(a, b, result); +} + +template inline bool checked_sub(T a, T b, T& result) +{ + return !msl::utilities::SafeSubtract(a, b, result); +} + +#elif (defined __GNUC__ && !defined __clang__) || (__has_builtin(__builtin_mul_overflow) && !(defined ANDROID && defined __clang__) && !(defined(__clang__) && (defined(__arm__) || defined(__i386__)))) +// 32-bit clang fails with undefined reference to `__mulodi4' + +template inline bool checked_multiply(T a, T b, T& result) +{ + return __builtin_mul_overflow(a, b, &result); +} + +template inline bool checked_add(T a, T b, T& result) +{ + return __builtin_add_overflow(a, b, &result); +} + +template inline bool checked_sub(T a, T b, T& result) +{ + return __builtin_sub_overflow(a, b, &result); +} + +#else + +//https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow +template inline typename std::enable_if::value, bool>::type checked_multiply(T a, T b, T& result) +{ + if (a > 0) { /* a is positive */ + if (b > 0) { /* a and b are positive */ + if (a > (std::numeric_limits::max() / b)) { + return true; /* Handle error */ + } + } else { /* a positive, b nonpositive */ + if (b < (std::numeric_limits::min() / a)) { + return true; /* Handle error */ + } + } /* a positive, b nonpositive */ + } else { /* a is nonpositive */ + if (b > 0) { /* a is nonpositive, b is positive */ + if (a < (std::numeric_limits::min() / b)) { + return true; /* Handle error */ + } + } else { /* a and b are nonpositive */ + if ( (a != 0) && (b < (std::numeric_limits::max() / a))) { + return true; /* Handle error */ + } + } /* End if a and b are nonpositive */ + } /* End if a is nonpositive */ + + result = a * b; + + return false; +} + +//https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap +template inline typename std::enable_if::value, bool>::type checked_multiply(T a, T b, T& result) +{ + if (b && a > std::numeric_limits::max() / b) { + return true;/* Handle error */ + } + + result = a * b; + + return false; +} + +//https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow +template inline typename std::enable_if::value, bool>::type checked_add(T a, T b, T& result) +{ + if (((b > 0) && (a > (std::numeric_limits::max() - b))) || + ((b < 0) && (a < (std::numeric_limits::min() - b)))) { + return true; + } + + result = a + b; + + return false; +} + +//https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap +template inline typename std::enable_if::value, bool>::type checked_add(T a, T b, T& result) +{ + if (std::numeric_limits::max() - a < b) { + return true;/* Handle error */ + } + + result = a + b; + + return false; +} + +//https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow +template inline typename std::enable_if::value, bool>::type checked_sub(T a, T b, T& result) +{ + if ((b > 0 && a < std::numeric_limits::min() + b) || + (b < 0 && a > std::numeric_limits::max() + b)) { + return true; + } + + result = a - b; + + return false; +} + +//https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap +template inline typename std::enable_if::value, bool>::type checked_sub(T a, T b, T& result) +{ + if (a < b) { + return true; + } + + result = a - b; + + return false; +} + +#endif + +template constexpr std::enable_if_t, std::make_unsigned_t> +make_unsigned(T value) +{ + assert(value >= 0); + return value; +} + +template constexpr std::enable_if_t, T1> +clamp_to_unsigned(T2 value) { + if constexpr (std::is_unsigned_v) { + // coverity[result_independent_of_operands] - suppress warning for template + return value <= std::numeric_limits::max() ? value : std::numeric_limits::max(); + } else { + static_assert(std::is_signed_v); + return value < 0 ? 0 : clamp_to_unsigned(make_unsigned(value)); + } +} + +// An implicit conversion from T2 to T1, useful in places where an explicit conversion from T2 to +// T1 is needed (e.g., in list initialization, if the implicit conversion would be narrowing) but +// tools like -fsanitize=implicit-conversion should still be able to detect truncation: +template constexpr T1 narrowing(T2 value) { return value; } + +// std::min wrapped to inform coverity that the result is now deemed sanitized +// coverity[ -taint_source ] +template [[nodiscard]] inline T sanitizing_min(T a, T b) +{ + return std::min(a, b); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/sorted_vector.hxx b/include/o3tl/sorted_vector.hxx new file mode 100644 index 000000000..13c0b25f8 --- /dev/null +++ b/include/o3tl/sorted_vector.hxx @@ -0,0 +1,421 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_SORTED_VECTOR_HXX +#define INCLUDED_O3TL_SORTED_VECTOR_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace o3tl +{ + +// forward declared because it's default template arg for sorted_vector +template +struct find_unique; + +/** Represents a sorted vector of values. + + @tpl Value class of item to be stored in container + @tpl Compare comparison method + @tpl Find look up index of a Value in the array +*/ +template< + typename Value, + typename Compare = std::less, + template class Find = find_unique, + bool = std::is_copy_constructible::value > +class sorted_vector +{ +private: + typedef Find Find_t; + typedef typename std::vector vector_t; + typedef typename std::vector::iterator iterator; +public: + typedef typename std::vector::const_iterator const_iterator; + typedef typename std::vector::const_reverse_iterator const_reverse_iterator; + typedef typename std::vector::difference_type difference_type; + typedef typename std::vector::size_type size_type; + typedef Value value_type; + + constexpr sorted_vector( std::initializer_list init ) + : m_vector(init) + { + std::sort(m_vector.begin(), m_vector.end(), Compare()); + } + sorted_vector() = default; + sorted_vector(sorted_vector const&) = default; + sorted_vector(sorted_vector&&) = default; + + sorted_vector& operator=(sorted_vector const&) = default; + sorted_vector& operator=(sorted_vector&&) = default; + + // MODIFIERS + + std::pair insert( Value&& x ) + { + std::pair const ret(Find_t()(m_vector.begin(), m_vector.end(), x)); + if (!ret.second) + { + const_iterator const it = m_vector.insert(m_vector.begin() + (ret.first - m_vector.begin()), std::move(x)); + return std::make_pair(it, true); + } + return std::make_pair(ret.first, false); + } + + std::pair insert( const Value& x ) + { + std::pair const ret(Find_t()(m_vector.begin(), m_vector.end(), x)); + if (!ret.second) + { + const_iterator const it = m_vector.insert(m_vector.begin() + (ret.first - m_vector.begin()), x); + return std::make_pair(it, true); + } + return std::make_pair(ret.first, false); + } + + size_type erase( const Value& x ) + { + std::pair const ret(Find_t()(m_vector.begin(), m_vector.end(), x)); + if (ret.second) + { + m_vector.erase(m_vector.begin() + (ret.first - m_vector.begin())); + return 1; + } + return 0; + } + + void erase_at(size_t index) + { + m_vector.erase(m_vector.begin() + index); + } + + // like C++ 2011: erase with const_iterator (doesn't change sort order) + const_iterator erase(const_iterator const& position) + { // C++98 has vector::erase(iterator), so call that + return m_vector.erase(m_vector.begin() + (position - m_vector.begin())); + } + + void erase(const_iterator const& first, const_iterator const& last) + { + m_vector.erase(m_vector.begin() + (first - m_vector.begin()), + m_vector.begin() + (last - m_vector.begin())); + } + + /** + * make erase return the removed element, otherwise there is no useful way of extracting a std::unique_ptr + * from this. + */ + Value erase_extract( size_t index ) + { + Value val = std::move(m_vector[index]); + m_vector.erase(m_vector.begin() + index); + return val; + } + + void clear() + { + m_vector.clear(); + } + + void swap(sorted_vector & other) + { + m_vector.swap(other.m_vector); + } + + void reserve(size_type amount) + { + m_vector.reserve(amount); + } + + // ACCESSORS + + size_type size() const + { + return m_vector.size(); + } + + bool empty() const + { + return m_vector.empty(); + } + + // Only return a const iterator, so that the vector cannot be directly updated. + const_iterator begin() const + { + return m_vector.begin(); + } + + // Only return a const iterator, so that the vector cannot be directly updated. + const_iterator end() const + { + return m_vector.end(); + } + + // Only return a const iterator, so that the vector cannot be directly updated. + const_reverse_iterator rbegin() const + { + return m_vector.rbegin(); + } + + // Only return a const iterator, so that the vector cannot be directly updated. + const_reverse_iterator rend() const + { + return m_vector.rend(); + } + + const Value& front() const + { + return m_vector.front(); + } + + const Value& back() const + { + return m_vector.back(); + } + + const Value& operator[]( size_t index ) const + { + return m_vector.operator[]( index ); + } + + // OPERATIONS + + const_iterator lower_bound( const Value& x ) const + { + return std::lower_bound( m_vector.begin(), m_vector.end(), x, Compare() ); + } + + const_iterator upper_bound( const Value& x ) const + { + return std::upper_bound( m_vector.begin(), m_vector.end(), x, Compare() ); + } + + /* Searches the container for an element with a value of x + * and returns an iterator to it if found, otherwise it returns an + * iterator to sorted_vector::end (the element past the end of the container). + * + * Only return a const iterator, so that the vector cannot be directly updated. + */ + const_iterator find( const Value& x ) const + { + std::pair const ret(Find_t()(m_vector.begin(), m_vector.end(), x)); + return (ret.second) ? ret.first : m_vector.end(); + } + + size_type count(const Value& v) const + { + return find(v) != end() ? 1 : 0; + } + + bool operator==(const sorted_vector & other) const + { + return m_vector == other.m_vector; + } + + bool operator!=(const sorted_vector & other) const + { + return m_vector != other.m_vector; + } + + void insert(sorted_vector const& rOther) + { + // optimization for the rather common case that we are overwriting this with the contents + // of another sorted vector + if ( empty() ) + m_vector.insert(m_vector.begin(), rOther.m_vector.begin(), rOther.m_vector.end()); + else + insert_internal( rOther.m_vector ); + } + + void insert_sorted_unique_vector(const std::vector& rOther) + { + assert( std::is_sorted(rOther.begin(), rOther.end(), Compare())); + assert( std::unique(rOther.begin(), rOther.end(), compare_equal) == rOther.end()); + if ( empty() ) + m_vector.insert(m_vector.begin(), rOther.m_vector.begin(), rOther.m_vector.end()); + else + insert_internal( rOther ); + } + + void insert_sorted_unique_vector(std::vector&& rOther) + { + assert( std::is_sorted(rOther.begin(), rOther.end(), Compare())); + assert( std::unique(rOther.begin(), rOther.end(), compare_equal) == rOther.end()); + if ( empty() ) + m_vector.swap( rOther ); + else + insert_internal( rOther ); + } + + /* Clear() elements in the vector, and free them one by one. */ + void DeleteAndDestroyAll() + { + for (const_iterator it = m_vector.begin(); it != m_vector.end(); ++it) + { + delete *it; + } + + clear(); + } + + // fdo#58793: some existing code in Writer (SwpHintsArray) + // routinely modifies the members of the vector in a way that + // violates the sort order, and then re-sorts the array. + // This is a kludge to enable that code to work. + // If you are calling this function, you are Doing It Wrong! + void Resort() + { + std::stable_sort(m_vector.begin(), m_vector.end(), Compare()); + } + +private: + static bool compare_equal( const Value& v1, const Value& v2 ) + { // Synthetize == check from < check for std::unique asserts above. + return !Compare()( v1, v2 ) && !Compare()( v2, v1 ); + } + + void insert_internal( const std::vector& rOther ) + { + // Do a union in one pass rather than repeated insert() that could repeatedly + // move large amounts of data. + vector_t tmp; + tmp.reserve( m_vector.size() + rOther.size()); + std::set_union( m_vector.begin(), m_vector.end(), + rOther.begin(), rOther.end(), + std::back_inserter( tmp ), Compare()); + m_vector.swap( tmp ); + } + + vector_t m_vector; +}; + +/* Specialise the template for cases like Value = std::unique_ptr, where + MSVC2017 needs some help +*/ +template< + typename Value, + typename Compare, + template class Find > +class sorted_vector : public sorted_vector +{ +public: + using sorted_vector::sorted_vector; + typedef sorted_vector super_sorted_vector; + + sorted_vector(sorted_vector const&) = delete; + sorted_vector& operator=(sorted_vector const&) = delete; + + sorted_vector() = default; + sorted_vector(sorted_vector&&) = default; + sorted_vector& operator=(sorted_vector&&) = default; + + /** + * implement find for sorted_vectors containing std::unique_ptr + */ + typename super_sorted_vector::const_iterator find( typename Value::element_type const * x ) const + { + Value tmp(const_cast(x)); + auto ret = super_sorted_vector::find(tmp); + tmp.release(); + return ret; + } + /** + * implement upper_bound for sorted_vectors containing std::unique_ptr + */ + typename super_sorted_vector::const_iterator upper_bound( typename Value::element_type const * x ) const + { + Value tmp(const_cast(x)); + auto ret = super_sorted_vector::upper_bound(tmp); + tmp.release(); + return ret; + } + /** + * implement lower_bound for sorted_vectors containing std::unique_ptr + */ + typename super_sorted_vector::const_iterator lower_bound( typename Value::element_type const * x ) const + { + Value tmp(const_cast(x)); + auto ret = super_sorted_vector::lower_bound(tmp); + tmp.release(); + return ret; + } +}; + + +/** Implements an ordering function over a pointer, where the comparison uses the < operator on the pointed-to types. + Very useful for the cases where we put pointers to objects inside a sorted_vector. +*/ +template struct less_ptr_to +{ + bool operator() ( T* const& lhs, T* const& rhs ) const + { + return (*lhs) < (*rhs); + } +}; + +template struct less_uniqueptr_to +{ + bool operator() ( std::unique_ptr const& lhs, std::unique_ptr const& rhs ) const + { + return (*lhs) < (*rhs); + } +}; + +/** the elements are totally ordered by Compare, + for no 2 elements !Compare(a,b) && !Compare(b,a) is true + */ +template +struct find_unique +{ + typedef typename sorted_vector ::const_iterator const_iterator; + std::pair operator()( + const_iterator first, const_iterator last, + Value const& v) + { + const_iterator const it = std::lower_bound(first, last, v, Compare()); + return std::make_pair(it, (it != last && !Compare()(v, *it))); + } +}; + +/** the elements are partially ordered by Compare, + 2 elements are allowed if they are not the same element (pointer equal) + */ +template +struct find_partialorder_ptrequals +{ + typedef typename sorted_vector::const_iterator const_iterator; + std::pair operator()( + const_iterator first, const_iterator last, + Value const& v) + { + std::pair const its = + std::equal_range(first, last, v, Compare()); + for (const_iterator it = its.first; it != its.second; ++it) + { + if (v == *it) + { + return std::make_pair(it, true); + } + } + return std::make_pair(its.first, false); + } +}; + +} // namespace o3tl +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/span.hxx b/include/o3tl/span.hxx new file mode 100644 index 000000000..cfe4c1ffa --- /dev/null +++ b/include/o3tl/span.hxx @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_SPAN_HXX +#define INCLUDED_O3TL_SPAN_HXX + +#include + +#include + +#if HAVE_CPP_SPAN + +#include + +namespace o3tl { using std::span; } + +#else + +#include +#include +#include +#include +#include + +namespace o3tl { + +/** A barebones approximation of C++20 . +*/ +template +class span { +public: + using value_type = T; + using pointer = value_type *; + using const_pointer = value_type const *; + using reference = value_type &; + using const_reference = value_type const &; + using const_iterator = const_pointer; + using iterator = pointer; + using const_reverse_iterator = std::reverse_iterator; + using reverse_iterator = std::reverse_iterator; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + + constexpr span() noexcept : data_(nullptr), size_(0) {} + + template + constexpr span (T (&a)[N]) noexcept : data_(a), size_(N) {} + + constexpr span (T *a, size_type len) noexcept + : data_(a), size_(len) + { + // not terribly sure about this, might need to strengthen it + assert(a != nullptr || len == 0); + } + + template + constexpr span(const std::vector& vec) + : data_(vec.data()), size_(vec.size()) {} + + /** for assigning from span to span */ + constexpr span (const span::type>& other) noexcept + : data_(other.data()), size_(other.size()) {} + + constexpr bool empty() const noexcept { return size_ == 0; } + + constexpr iterator begin() const noexcept { return data_; } + constexpr iterator end() const noexcept { return begin() + size(); } + + reverse_iterator rbegin() const noexcept + { return reverse_iterator(end()); } + reverse_iterator rend() const noexcept + { return reverse_iterator(begin()); } + + constexpr size_type size() const noexcept { return size_; } + + constexpr reference operator [](size_type pos) const { + assert(pos < size()); + return data_[pos]; + } + + constexpr pointer data() const noexcept { return data_; } + +private: + pointer data_; + size_type size_; +}; + +} // namespace o3tl + +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/sprintf.hxx b/include/o3tl/sprintf.hxx new file mode 100644 index 000000000..6491f4ad1 --- /dev/null +++ b/include/o3tl/sprintf.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +namespace o3tl +{ +// A drop-in replacement for safe uses of std::sprintf where it is statically known that the +// provided buffer is large enough. Compared to a plain use of std::sprintf, using o3tl::sprintf +// for one makes it explicit that the call is considerd safe and for another avoids deprecation +// warnings on platforms like the macOS 13 SDK that mark std::sprintf as deprecated. Many simple +// uses of std::sprintf across the code base can be replaced with alternative code using e.g. +// OString::number. This is for the remaining formatting-rich cases for which there is no easy +// replacement yet in our C++17 baseline. Ultimately, it should be removed again once alternatives +// for those remaining cases, like C++20 std::format, are available. +template +int sprintf(char (&s)[N], char const* format, T&&... arguments) +{ + auto const n = std::snprintf(s, N, format, std::forward(arguments)...); + assert(n < 0 || o3tl::make_unsigned(n) < N); + (void)n; + return n; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/string_view.hxx b/include/o3tl/string_view.hxx new file mode 100644 index 000000000..f6c2a4aa7 --- /dev/null +++ b/include/o3tl/string_view.hxx @@ -0,0 +1,487 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include +#include +#include + +#include +#include +#include + +namespace o3tl +{ +// Like OUString::equalsIgnoreAsciiCase, but for two std::u16string_view: +inline bool equalsAscii(std::u16string_view s1, const char* s2) +{ + return rtl_ustr_ascii_compare_WithLength(s1.data(), s1.size(), s2) == 0; +} + +// Like OUString::equalsAsciiL +inline bool equalsAscii(std::u16string_view s1, std::string_view s2) +{ + return rtl_ustr_ascii_shortenedCompare_WithLength(s1.data(), s1.size(), s2.data(), s2.size()) + == 0; +} + +// Like OUString::equalsIgnoreAsciiCase, but for two std::u16string_view: +inline bool equalsIgnoreAsciiCase(std::u16string_view s1, std::u16string_view s2) +{ + if (s1.size() != s2.size()) + return false; + if (s1.data() == s2.data()) + return true; + return rtl_ustr_compareIgnoreAsciiCase_WithLength(s1.data(), s1.size(), s2.data(), s2.size()) + == 0; +}; + +inline bool equalsIgnoreAsciiCase(std::string_view s1, std::string_view s2) +{ + if (s1.size() != s2.size()) + return false; + if (s1.data() == s2.data()) + return true; + return rtl_str_compareIgnoreAsciiCase_WithLength(s1.data(), s1.size(), s2.data(), s2.size()) + == 0; +}; + +// Like OUString::compareToIgnoreAsciiCase, but for two std::u16string_view: +inline int compareToIgnoreAsciiCase(std::u16string_view s1, std::u16string_view s2) +{ + return rtl_ustr_compareIgnoreAsciiCase_WithLength(s1.data(), s1.size(), s2.data(), s2.size()); +}; + +// Like OUString::matchIgnoreAsciiCase, but for two std::u16string_view: +inline bool matchIgnoreAsciiCase(std::u16string_view s1, std::u16string_view s2, + sal_Int32 fromIndex = 0) +{ + return rtl_ustr_shortenedCompareIgnoreAsciiCase_WithLength( + s1.data() + fromIndex, s1.size() - fromIndex, s2.data(), s2.size(), s2.size()) + == 0; +} + +// Similar to O[U]String::getToken, returning the first token of a std::[u16]string_view starting +// at a given position. +// +// Attention: There are two sets of o3tl::getToken overloads here. This first set has an interface +// based on std::size_t length parameters, and its semantics don't match those of +// O[U]String::getToken exactly (buf if needed, it can be extended to return the n'th token instead +// of just the first, and/or support an initial position of npos, to make the semantics match). +template > +inline std::basic_string_view getToken(std::basic_string_view sv, + charT delimiter, std::size_t& position) +{ + assert(position <= sv.size()); + auto const n = sv.find(delimiter, position); + std::basic_string_view t; + if (n == std::string_view::npos) + { + t = sv.substr(position); + position = std::string_view::npos; + } + else + { + t = sv.substr(position, n - position); + position = n + 1; + } + return t; +} +// The following two overloads prevent overload resolution mistakes that would occur with their +// template counterpart, when sv is of a type that is implicitly convertible to basic_string_view +// (like OString or OUString), in which case overload resolution would erroneously choose the +// three-argument overloads (taking sv, nToken, cTok) from the second set of +// o3tl::getToken overloads below: +inline std::string_view getToken(std::string_view sv, char delimiter, std::size_t& position) +{ + return getToken(sv, delimiter, position); +} +inline std::u16string_view getToken(std::u16string_view sv, char16_t delimiter, + std::size_t& position) +{ + return getToken(sv, delimiter, position); +} + +// Similar to O[U]String::getToken. +// +// Attention: There are two sets of o3tl::getToken overloads here. This second set has an +// interface based on sal_Int32 length parameters, and is meant to be a drop-in replacement for +// O[U]String::getToken. +template > +inline std::basic_string_view getToken(std::basic_string_view pStr, + sal_Int32 nToken, charT cTok, + sal_Int32& rnIndex) +{ + assert(o3tl::IntCmp(rnIndex) <= o3tl::IntCmp(pStr.size())); + + // Return an empty string and set rnIndex to -1 if either nToken or rnIndex is + // negative: + if (rnIndex >= 0 && nToken >= 0) + { + const charT* pOrgCharStr = pStr.data(); + const charT* pCharStr = pOrgCharStr + rnIndex; + sal_Int32 nLen = pStr.size() - rnIndex; + sal_Int32 nTokCount = 0; + const charT* pCharStrStart = pCharStr; + while (nLen > 0) + { + if (*pCharStr == cTok) + { + nTokCount++; + + if (nTokCount > nToken) + break; + if (nTokCount == nToken) + pCharStrStart = pCharStr + 1; + } + + pCharStr++; + nLen--; + } + if (nTokCount >= nToken) + { + if (nLen > 0) + rnIndex = pCharStr - pOrgCharStr + 1; + else + rnIndex = -1; + return std::basic_string_view(pCharStrStart, pCharStr - pCharStrStart); + } + } + + rnIndex = -1; + return std::basic_string_view(); +} +// The following two overloads prevent deduction failures that would occur with their template +// counterpart, when sv is of a type that is implicitly convertible to basic_string_view (like +// OString or OUString): +inline std::string_view getToken(std::string_view sv, sal_Int32 nToken, char cTok, + sal_Int32& rnIndex) +{ + return getToken(sv, nToken, cTok, rnIndex); +} +inline std::u16string_view getToken(std::u16string_view sv, sal_Int32 nToken, char16_t cTok, + sal_Int32& rnIndex) +{ + return getToken(sv, nToken, cTok, rnIndex); +} +inline std::string_view getToken(std::string_view sv, sal_Int32 nToken, char cTok) +{ + sal_Int32 nIndex = 0; + return getToken(sv, nToken, cTok, nIndex); +} +inline std::u16string_view getToken(std::u16string_view sv, sal_Int32 nToken, char16_t cTok) +{ + sal_Int32 nIndex = 0; + return getToken(sv, nToken, cTok, nIndex); +} + +// Implementations of C++20 std::basic_string_view::starts_with and +// std::basic_string_view::ends_with, until we can use those directly on all platforms: +template > +constexpr bool starts_with(std::basic_string_view sv, + std::basic_string_view x) noexcept +{ +#if defined __cpp_lib_starts_ends_with + return sv.starts_with(x); +#else + return sv.substr(0, x.size()) == x; +#endif +} +template > +constexpr bool starts_with(std::basic_string_view sv, charT x) noexcept +{ +#if defined __cpp_lib_starts_ends_with + return sv.starts_with(x); +#else + return !sv.empty() && traits::eq(sv.front(), x); +#endif +} +template > +constexpr bool starts_with(std::basic_string_view sv, charT const* x) +{ +#if defined __cpp_lib_starts_ends_with + return sv.starts_with(x); +#else + return starts_with(sv, std::basic_string_view(x)); +#endif +} +template > +constexpr bool ends_with(std::basic_string_view sv, + std::basic_string_view x) noexcept +{ +#if defined __cpp_lib_ends_ends_with + return sv.ends_with(x); +#else + return sv.size() >= x.size() + && sv.compare(sv.size() - x.size(), std::basic_string_view::npos, x) == 0; +#endif +} +template > +constexpr bool ends_with(std::basic_string_view sv, charT x) noexcept +{ +#if defined __cpp_lib_ends_ends_with + return sv.ends_with(x); +#else + return !sv.empty() && traits::eq(sv.back(), x); +#endif +} +template > +constexpr bool ends_with(std::basic_string_view sv, charT const* x) +{ +#if defined __cpp_lib_ends_ends_with + return sv.ends_with(x); +#else + return ends_with(sv, std::basic_string_view(x)); +#endif +} +// The following overloads prevent deduction failures that would occur with their template +// counterparts, when x is of a type that is implicitly convertible to basic_string_view (like +// OString or OUString, and we only bother to provide overloads for the char and char16_t cases, not +// also for char32_t and wchar_t, nor for C++20 char8_t): +constexpr bool starts_with(std::string_view sv, std::string_view x) noexcept +{ + return starts_with(sv, x); +} +constexpr bool starts_with(std::u16string_view sv, std::u16string_view x) noexcept +{ + return starts_with(sv, x); +} +constexpr bool ends_with(std::string_view sv, std::string_view x) noexcept +{ + return ends_with(sv, x); +} +constexpr bool ends_with(std::u16string_view sv, std::u16string_view x) noexcept +{ + return ends_with(sv, x); +} + +// Variants of C++20 std::basic_string_view::starts_with and +// std::basic_string_view::ends_with that have a rest out parameter, similar to our OString and +// OUString startsWith and endsWith member functions: +template > +constexpr bool starts_with(std::basic_string_view sv, + std::basic_string_view x, + std::basic_string_view* rest) noexcept +{ + assert(rest != nullptr); + auto const found = starts_with(sv, x); + if (found) + { + *rest = sv.substr(x.length()); + } + return found; +} +template > +constexpr bool starts_with(std::basic_string_view sv, charT x, + std::basic_string_view* rest) noexcept +{ + assert(rest != nullptr); + auto const found = starts_with(sv, x); + if (found) + { + *rest = sv.substr(1); + } + return found; +} +template > +constexpr bool starts_with(std::basic_string_view sv, charT const* x, + std::basic_string_view* rest) +{ + assert(rest != nullptr); + auto const found = starts_with(sv, x); + if (found) + { + *rest = sv.substr(traits::length(x)); + } + return found; +} +template > +constexpr bool ends_with(std::basic_string_view sv, + std::basic_string_view x, + std::basic_string_view* rest) noexcept +{ + assert(rest != nullptr); + auto const found = ends_with(sv, x); + if (found) + { + *rest = sv.substr(0, sv.length() - x.length()); + } + return found; +} +template > +constexpr bool ends_with(std::basic_string_view sv, charT x, + std::basic_string_view* rest) noexcept +{ + assert(rest != nullptr); + auto const found = ends_with(sv, x); + if (found) + { + *rest = sv.substr(0, sv.length() - 1); + } + return found; +} +template > +constexpr bool ends_with(std::basic_string_view sv, charT const* x, + std::basic_string_view* rest) +{ + assert(rest != nullptr); + auto const found = ends_with(sv, x); + if (found) + { + *rest = sv.substr(0, sv.length() - traits::length(x)); + } + return found; +} +// The following overloads prevent deduction failures that would occur with their template +// counterparts, when x is of a type that is implicitly convertible to basic_string_view (like +// OString or OUString, and we only bother to provide overloads for the char and char16_t cases, not +// also for char32_t and wchar_t, nor for C++20 char8_t): +constexpr bool starts_with(std::string_view sv, std::string_view x, std::string_view* rest) noexcept +{ + return starts_with(sv, x, rest); +} +constexpr bool starts_with(std::u16string_view sv, std::u16string_view x, + std::u16string_view* rest) noexcept +{ + return starts_with(sv, x, rest); +} +constexpr bool ends_with(std::string_view sv, std::string_view x, std::string_view* rest) noexcept +{ + return ends_with(sv, x, rest); +} +constexpr bool ends_with(std::u16string_view sv, std::u16string_view x, + std::u16string_view* rest) noexcept +{ + return ends_with(sv, x, rest); +} + +namespace internal +{ +// copy of implIsWhitespace from sal/rtl/strtmpl.hxx +inline bool implIsWhitespace(sal_Unicode c) +{ + /* Space or Control character? */ + if ((c <= 32) && c) + return true; + + /* Only in the General Punctuation area Space or Control characters are included? */ + if ((c < 0x2000) || (c > 0x206F)) + return false; + + if (((c >= 0x2000) && (c <= 0x200B)) || /* All Spaces */ + (c == 0x2028) || /* LINE SEPARATOR */ + (c == 0x2029)) /* PARAGRAPH SEPARATOR */ + return true; + + return false; +} +} // namespace internal + +// Like OUString::trim, but for std::u16string_view: +// copy of the trimView code from sal/rtl/strtmpl.hxx +inline std::u16string_view trim(std::u16string_view str) +{ + sal_Int32 nLen = str.size(); + sal_Int32 nPreSpaces = 0; + sal_Int32 nPostSpaces = 0; + sal_Int32 nIndex = str.size() - 1; + + while ((nPreSpaces < nLen) && internal::implIsWhitespace(*(str.data() + nPreSpaces))) + nPreSpaces++; + + while ((nIndex > nPreSpaces) && internal::implIsWhitespace(*(str.data() + nIndex))) + { + nPostSpaces++; + nIndex--; + } + + return std::u16string_view{ str.data() + nPreSpaces, + static_cast(nLen - nPostSpaces - nPreSpaces) }; +} + +// Like OString::trim, but for std::string_view: +// copy of the trimView code from sal/rtl/strtmpl.hxx +inline std::string_view trim(std::string_view str) +{ + sal_Int32 nLen = str.size(); + sal_Int32 nPreSpaces = 0; + sal_Int32 nPostSpaces = 0; + sal_Int32 nIndex = str.size() - 1; + + while ((nPreSpaces < nLen) && internal::implIsWhitespace(*(str.data() + nPreSpaces))) + nPreSpaces++; + + while ((nIndex > nPreSpaces) && internal::implIsWhitespace(*(str.data() + nIndex))) + { + nPostSpaces++; + nIndex--; + } + + return std::string_view{ str.data() + nPreSpaces, + static_cast(nLen - nPostSpaces - nPreSpaces) }; +} + +// Like OString::toInt32, but for std::string_view: +inline sal_Int32 toInt32(std::u16string_view str, sal_Int16 radix = 10) +{ + sal_Int64 n = rtl_ustr_toInt64_WithLength(str.data(), radix, str.size()); + if (n < SAL_MIN_INT32 || n > SAL_MAX_INT32) + n = 0; + return n; +} +inline sal_Int32 toInt32(std::string_view str, sal_Int16 radix = 10) +{ + sal_Int64 n = rtl_str_toInt64_WithLength(str.data(), radix, str.size()); + if (n < SAL_MIN_INT32 || n > SAL_MAX_INT32) + n = 0; + return n; +} + +// Like OString::toUInt32, but for std::string_view: +inline sal_uInt32 toUInt32(std::u16string_view str, sal_Int16 radix = 10) +{ + sal_Int64 n = rtl_ustr_toInt64_WithLength(str.data(), radix, str.size()); + if (n < 0 || n > SAL_MAX_UINT32) + n = 0; + return n; +} +inline sal_uInt32 toUInt32(std::string_view str, sal_Int16 radix = 10) +{ + sal_Int64 n = rtl_str_toInt64_WithLength(str.data(), radix, str.size()); + if (n < 0 || n > SAL_MAX_UINT32) + n = 0; + return n; +} + +// Like OString::toInt64, but for std::string_view: +inline sal_Int64 toInt64(std::u16string_view str, sal_Int16 radix = 10) +{ + return rtl_ustr_toInt64_WithLength(str.data(), radix, str.size()); +} +inline sal_Int64 toInt64(std::string_view str, sal_Int16 radix = 10) +{ + return rtl_str_toInt64_WithLength(str.data(), radix, str.size()); +} + +// Like OString::toDouble, but for std::string_view: +inline double toDouble(std::u16string_view str) +{ + return rtl_math_uStringToDouble(str.data(), str.data() + str.size(), '.', 0, nullptr, nullptr); +} +inline double toDouble(std::string_view str) +{ + return rtl_math_stringToDouble(str.data(), str.data() + str.size(), '.', 0, nullptr, nullptr); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/strong_int.hxx b/include/o3tl/strong_int.hxx new file mode 100644 index 000000000..821079558 --- /dev/null +++ b/include/o3tl/strong_int.hxx @@ -0,0 +1,156 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_STRONG_INT_HXX +#define INCLUDED_O3TL_STRONG_INT_HXX + +#include +#include +#include +#include + +namespace o3tl +{ + +#if !defined __COVERITY__ + +namespace detail { + +template constexpr +typename std::enable_if< + std::is_signed::value && std::is_signed::value, bool>::type +isInRange(T2 value) { + return value >= std::numeric_limits::min() + && value <= std::numeric_limits::max(); +} + +template constexpr +typename std::enable_if< + std::is_signed::value && std::is_unsigned::value, bool>::type +isInRange(T2 value) { + return value + <= static_cast::type>( + std::numeric_limits::max()); +} + +template constexpr +typename std::enable_if< + std::is_unsigned::value && std::is_signed::value, bool>::type +isInRange(T2 value) { + return value >= 0 + && (static_cast::type>(value) + <= std::numeric_limits::max()); +} + +template constexpr +typename std::enable_if< + std::is_unsigned::value && std::is_unsigned::value, bool>::type +isInRange(T2 value) { + return value <= std::numeric_limits::max(); +} + +} + +#endif + +/// +/// Wrap up an integer type so that we prevent accidental conversion to other integer types. +/// +/// e.g. +/// typedef o3tl::strong_int MyInt; +/// +/// \param UNDERLYING_TYPE the underlying scalar type +/// \param PHANTOM_TYPE a type tag, used to distinguish this instantiation of the template +/// from other instantiations with the same UNDERLYING_TYPE. +/// +template +struct strong_int +{ +public: + template explicit constexpr strong_int( + T value, + typename std::enable_if::value, int>::type = 0): + m_value(value) + { +#if !defined __COVERITY__ + // catch attempts to pass in out-of-range values early + assert(detail::isInRange(value) + && "out of range"); +#endif + } + strong_int() : m_value(0) {} + + explicit constexpr operator UNDERLYING_TYPE() const { return m_value; } + explicit operator bool() const { return m_value != 0; } + UNDERLYING_TYPE get() const { return m_value; } + + bool operator<(strong_int const & other) const { return m_value < other.m_value; } + bool operator<=(strong_int const & other) const { return m_value <= other.m_value; } + bool operator>(strong_int const & other) const { return m_value > other.m_value; } + bool operator>=(strong_int const & other) const { return m_value >= other.m_value; } + bool operator==(strong_int const & other) const { return m_value == other.m_value; } + bool operator!=(strong_int const & other) const { return m_value != other.m_value; } + strong_int& operator++() { ++m_value; return *this; } + strong_int operator++(int) { UNDERLYING_TYPE nOldValue = m_value; ++m_value; return strong_int(nOldValue); } + strong_int& operator--() { --m_value; return *this; } + strong_int operator--(int) { UNDERLYING_TYPE nOldValue = m_value; --m_value; return strong_int(nOldValue); } + strong_int& operator+=(strong_int const & other) { m_value += other.m_value; return *this; } + strong_int& operator-=(strong_int const & other) { m_value -= other.m_value; return *this; } + strong_int& operator%=(strong_int const & other) { m_value %= other.m_value; return *this; } + strong_int& operator*=(strong_int const & other) { m_value *= other.m_value; return *this; } + strong_int& operator/=(strong_int const & other) { m_value /= other.m_value; return *this; } + [[nodiscard]] + strong_int operator%(strong_int const & other) const { return strong_int(m_value % other.m_value); } + [[nodiscard]] + strong_int operator-() const { return strong_int(-m_value); } + [[nodiscard]] + strong_int operator*(strong_int const & other) const { return strong_int(m_value * other.m_value); } + [[nodiscard]] + strong_int operator/(strong_int const & other) const { return strong_int(m_value / other.m_value); } + + bool anyOf(strong_int v) const { + return *this == v; + } + + template + bool anyOf(strong_int first, Args... args) const { + return *this == first || anyOf(args...); + } + +private: + UNDERLYING_TYPE m_value; +}; + +template +strong_int operator+(strong_int const & lhs, strong_int const & rhs) +{ + return strong_int(lhs.get() + rhs.get()); +} + +template +strong_int operator-(strong_int const & lhs, strong_int const & rhs) +{ + return strong_int(lhs.get() - rhs.get()); +} + +}; // namespace o3tl + +#endif /* INCLUDED_O3TL_STRONG_INT_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/temporary.hxx b/include/o3tl/temporary.hxx new file mode 100644 index 000000000..50d006e26 --- /dev/null +++ b/include/o3tl/temporary.hxx @@ -0,0 +1,27 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_TEMPORARY_HXX +#define INCLUDED_O3TL_TEMPORARY_HXX + +#include + +namespace o3tl +{ +// Cast an rvalue to an lvalue. Can be useful if a function parameter is a pointer/reference to T, +// and some call site doesn't need the value beyond the call itself (e.g., in a call like +// std::modf(x, &o3tl::temporary(double())) to obtain the fractional part of x, ignoring the +// integral part). +template constexpr T& temporary(T&& x) { return static_cast(x); } +template constexpr T& temporary(T&) = delete; +} + +#endif /* INCLUDED_O3TL_TEMPORARY_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/typed_flags_set.hxx b/include/o3tl/typed_flags_set.hxx new file mode 100644 index 000000000..413ee9579 --- /dev/null +++ b/include/o3tl/typed_flags_set.hxx @@ -0,0 +1,325 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_TYPED_FLAGS_SET_HXX +#define INCLUDED_O3TL_TYPED_FLAGS_SET_HXX + +#include + +#include +#include + +#include + +namespace o3tl { + +namespace detail { + +template constexpr +typename std::enable_if::value, bool>::type isNonNegative( + T value) +{ + return value >= 0; +} + +template constexpr +typename std::enable_if::value, bool>::type isNonNegative(T) +{ + return true; +} + +} + +template struct typed_flags {}; + +/// Mark a (scoped) enumeration as a set of bit flags, with accompanying +/// operations. +/// +/// template<> +/// struct o3tl::typed_flags: o3tl::is_typed_flags {}; +/// +/// All relevant values must be non-negative. (Typically, the enumeration's +/// underlying type will either be fixed and unsigned, or it will be unfixed--- +/// and can thus default to a signed type---and all enumerators will have non- +/// negative values.) +/// +/// \param E the enumeration type. +/// \param M the all-bits-set value for the bit flags. +template::type M> +struct is_typed_flags { + static_assert( + M >= 0, "is_typed_flags expects only non-negative bit values"); + + typedef E Self; + + class Wrap { + public: + typedef is_typed_flags Unwrapped; + + explicit constexpr Wrap(typename std::underlying_type::type value): + value_(value) + { + assert(detail::isNonNegative(value)); + assert( + static_cast::type>(~0) == M + // avoid "operands don't affect result" warnings when M + // covers all bits of the underlying type + || (value & ~M) == 0); + } + + constexpr operator E() const { return static_cast(value_); } + + explicit constexpr operator typename std::underlying_type::type() + const + { return value_; } + + explicit constexpr operator bool() const { return value_ != 0; } + + private: + typename std::underlying_type::type value_; + }; + + static typename std::underlying_type::type const mask = M; +}; + +} + +template +constexpr typename o3tl::typed_flags::Wrap operator ~(E rhs) { + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::typed_flags::mask + & ~o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator ~( + typename o3tl::typed_flags::Wrap rhs) +{ + return static_cast::Wrap>( + o3tl::typed_flags::mask + & ~o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator ^( + E lhs, E rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + ^ o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator ^( + E lhs, typename o3tl::typed_flags::Wrap rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + ^ o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator ^( + typename o3tl::typed_flags::Wrap lhs, E rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + ^ o3tl::to_underlying(rhs)); +} + +template constexpr +typename o3tl::typed_flags::Wrap operator ^( + W lhs, W rhs) +{ + return static_cast( + o3tl::to_underlying(lhs) + ^ o3tl::to_underlying(rhs)); +} + +template +constexpr typename o3tl::typed_flags::Wrap operator &(E lhs, E rhs) { + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + & o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator &( + E lhs, typename o3tl::typed_flags::Wrap rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + & o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator &( + typename o3tl::typed_flags::Wrap lhs, E rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + & o3tl::to_underlying(rhs)); +} + +template constexpr +typename o3tl::typed_flags::Wrap operator &( + W lhs, W rhs) +{ + return static_cast( + o3tl::to_underlying(lhs) + & o3tl::to_underlying(rhs)); +} + +template +constexpr typename o3tl::typed_flags::Wrap operator |(E lhs, E rhs) { + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + | o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator |( + E lhs, typename o3tl::typed_flags::Wrap rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + | o3tl::to_underlying(rhs)); +} + +template constexpr typename o3tl::typed_flags::Wrap operator |( + typename o3tl::typed_flags::Wrap lhs, E rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + return static_cast::Wrap>( + o3tl::to_underlying(lhs) + | o3tl::to_underlying(rhs)); +} + +template constexpr +typename o3tl::typed_flags::Wrap operator |( + W lhs, W rhs) +{ + return static_cast( + o3tl::to_underlying(lhs) + | o3tl::to_underlying(rhs)); +} + +template +inline typename o3tl::typed_flags::Self operator &=(E & lhs, E rhs) { + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + lhs = lhs & rhs; + return lhs; +} + +template +inline typename o3tl::typed_flags::Self operator &=( + E & lhs, typename o3tl::typed_flags::Wrap rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + lhs = lhs & rhs; + return lhs; +} + +template +inline typename o3tl::typed_flags::Self operator |=(E & lhs, E rhs) { + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + lhs = lhs | rhs; + return lhs; +} + +template +inline typename o3tl::typed_flags::Self operator |=( + E & lhs, typename o3tl::typed_flags::Wrap rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + lhs = lhs | rhs; + return lhs; +} + +template +inline typename o3tl::typed_flags::Self operator ^=(E & lhs, E rhs) { + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(rhs))); + lhs = lhs ^ rhs; + return lhs; +} + +template +inline typename o3tl::typed_flags::Self operator ^=( + E & lhs, typename o3tl::typed_flags::Wrap rhs) +{ + assert( + o3tl::detail::isNonNegative( + o3tl::to_underlying(lhs))); + lhs = lhs ^ rhs; + return lhs; +} + +#endif /* INCLUDED_O3TL_TYPED_FLAGS_SET_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/underlyingenumvalue.hxx b/include/o3tl/underlyingenumvalue.hxx new file mode 100644 index 000000000..a913ab385 --- /dev/null +++ b/include/o3tl/underlyingenumvalue.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_UNDERLYINGENUMVALUE_HXX +#define INCLUDED_O3TL_UNDERLYINGENUMVALUE_HXX + +#include + +#include + +namespace o3tl +{ +// An implementation of C++23 std::to_underlying +// For a value e of an enumeration type T, return the corresponding value of T's underlying type: +template constexpr std::underlying_type_t to_underlying(T e) +{ + return static_cast>(e); +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/unit_conversion.hxx b/include/o3tl/unit_conversion.hxx new file mode 100644 index 000000000..67830f0d1 --- /dev/null +++ b/include/o3tl/unit_conversion.hxx @@ -0,0 +1,261 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace o3tl +{ +// Length units +enum class Length +{ + mm100 = 0, // 1/100th mm + mm10, // 1/10 mm, corresponds to MapUnit::Map10thMM + mm, // millimeter + cm, // centimeter + m, // meter + km, // kilometer + emu, // English Metric Unit: 1/360000 cm, 1/914400 in + twip, // "Twentieth of a point" aka "dxa": 1/20 pt + pt, // Point: 1/72 in + pc, // Pica: 1/6 in, corresponds to FieldUnit::PICA and MeasureUnit::PICA + in1000, // 1/1000 in, corresponds to MapUnit::Map1000thInch + in100, // 1/100 in, corresponds to MapUnit::Map100thInch + in10, // 1/10 in, corresponds to MapUnit::Map10thInch + in, // inch + ft, // foot + mi, // mile + master, // PPT Master Unit: 1/576 in + px, // "pixel" unit: 15 twip (96 ppi), corresponds to MeasureUnit::PIXEL + ch, // "char" unit: 210 twip (14 px), corresponds to FieldUnit::CHAR + line, // "line" unit: 312 twip, corresponds to FieldUnit::LINE + count, // <== add new units above this last entry + invalid = -1 +}; + +// If other categories of units would be needed (like time), a separate scoped enum +// should be created, respective conversion array prepared in detail namespace, and +// respective md(NewUnit, NewUnit) overload introduced, which would allow using +// o3tl::convert(), o3tl::convertSaturate() and o3tl::getConversionMulDiv() with the +// new category in a type-safe way, without mixing unrelated units. + +namespace detail +{ +// Common utilities + +// A special function to avoid compiler warning comparing signed and unsigned values +template constexpr bool isBetween(I n, sal_Int64 min, sal_Int64 max) +{ + assert(max > 0 && min < 0); + if constexpr (std::is_signed_v) + return n >= min && n <= max; + else + return n <= sal_uInt64(max); +} + +// Ensure correct rounding for both positive and negative integers +template , int> = 0> +constexpr sal_Int64 MulDiv(I n, sal_Int64 m, sal_Int64 d) +{ + assert(m > 0 && d > 0); + assert(isBetween(n, (SAL_MIN_INT64 + d / 2) / m, (SAL_MAX_INT64 - d / 2) / m)); + return (n >= 0 ? (n * m + d / 2) : (n * m - d / 2)) / d; +} +template , int> = 0> +constexpr double MulDiv(F f, sal_Int64 m, sal_Int64 d) +{ + assert(m > 0 && d > 0); + return f * (double(m) / d); +} + +template , int> = 0> +constexpr sal_Int64 MulDiv(I n, sal_Int64 m, sal_Int64 d, bool& bOverflow, sal_Int64 nDefault) +{ + if (!isBetween(n, (SAL_MIN_INT64 + d / 2) / m, (SAL_MAX_INT64 - d / 2) / m)) + { + bOverflow = true; + return nDefault; + } + bOverflow = false; + return MulDiv(n, m, d); +} + +template , int> = 0> +constexpr sal_Int64 MulDivSaturate(I n, sal_Int64 m, sal_Int64 d) +{ + if (!isBetween(n, (SAL_MIN_INT64 + d / 2) / m, (SAL_MAX_INT64 - d / 2) / m)) + { + if (m > d && !isBetween(n, SAL_MIN_INT64 / m * d + d / 2, SAL_MAX_INT64 / m * d - d / 2)) + return n > 0 ? SAL_MAX_INT64 : SAL_MIN_INT64; // saturate + return (n >= 0 ? n + d / 2 : n - d / 2) / d * m; // divide before multiplication + } + return MulDiv(n, m, d); +} + +template constexpr std::common_type_t asserting_gcd(M m, N n) +{ + auto ret = std::gcd(m, n); + assert(ret != 0); + return ret; +} + +// Packs integral multiplier and divisor for conversion from one unit to another +struct m_and_d +{ + sal_Int64 m; // multiplier + sal_Int64 d; // divisor + constexpr m_and_d(sal_Int64 _m, sal_Int64 _d) + : m(_m / asserting_gcd(_m, _d)) // make sure to use smallest quotients here because + , d(_d / asserting_gcd(_m, _d)) // they will be multiplied when building final table + { + assert(_m > 0 && _d > 0); + } +}; + +// Resulting static array N x N of all quotients to convert between all units. The +// quotients are minimal to allow largest range of converted numbers without overflow. +// Maybe o3tl::enumarray could be used here, but it's not constexpr yet. +template constexpr auto prepareMDArray(const m_and_d (&mdBase)[N]) +{ + std::array, N> a{}; + for (int i = 0; i < N; ++i) + { + a[i][i] = 1; + for (int j = 0; j < i; ++j) + { + assert(mdBase[i].m < SAL_MAX_INT64 / mdBase[j].d); + assert(mdBase[i].d < SAL_MAX_INT64 / mdBase[j].m); + const sal_Int64 m = mdBase[i].m * mdBase[j].d, d = mdBase[i].d * mdBase[j].m; + const sal_Int64 g = asserting_gcd(m, d); + a[i][j] = m / g; + a[j][i] = d / g; + } + } + return a; +} + +// A generic template used for fundamental arithmetic types +template constexpr sal_Int64 md(U i, U /*j*/) { return i; } + +// Length units implementation + +// Array of conversion quotients for mm, used to build final conversion table. Entries +// are { multiplier, divider } to convert respective unit *to* mm. Order of elements +// corresponds to order in o3tl::Length enum (Length::count and Length::invalid omitted). +constexpr m_and_d mdBaseLen[] = { + { 1, 100 }, // mm100 => mm + { 1, 10 }, // mm10 => mm + { 1, 1 }, // mm => mm + { 10, 1 }, // cm => mm + { 1000, 1 }, // m => mm + { 1000000, 1 }, // km => mm + { 1, 36000 }, // emu => mm + { 254, 10 * 1440 }, // twip => mm + { 254, 10 * 72 }, // pt => mm + { 254, 10 * 6 }, // pc => mm + { 254, 10000 }, // in1000 => mm + { 254, 1000 }, // in100 => mm + { 254, 100 }, // in10 => mm + { 254, 10 }, // in => mm + { 254 * 12, 10 }, // ft => mm + { 254 * 12 * 5280, 10 }, // mi => mm + { 254, 10 * 576 }, // master => mm + { 254 * 15, 10 * 1440 }, // px => mm + { 254 * 210, 10 * 1440 }, // ch => mm + { 254 * 312, 10 * 1440 }, // line => mm +}; +static_assert(std::size(mdBaseLen) == static_cast(Length::count), + "mdBaseL must have an entry for each unit in o3tl::Length"); + +// The resulting multipliers and divisors array +constexpr auto aLengthMDArray = prepareMDArray(mdBaseLen); + +// an overload taking Length +constexpr sal_Int64 md(Length i, Length j) +{ + const int nI = static_cast(i), nJ = static_cast(j); + assert(nI >= 0 && o3tl::make_unsigned(nI) < aLengthMDArray.size()); + assert(nJ >= 0 && o3tl::make_unsigned(nJ) < aLengthMDArray.size()); + return aLengthMDArray[nI][nJ]; +} + +// here might go overloads of md() taking other units ... +} + +// Unchecked conversion. Takes a number value, multiplier and divisor +template constexpr auto convert(N n, sal_Int64 mul, sal_Int64 div) +{ + return detail::MulDiv(n, mul, div); +} + +// Unchecked conversion. Takes a number value and units defined in this header +template constexpr auto convert(N n, U from, U to) +{ + return convert(n, detail::md(from, to), detail::md(to, from)); +} + +// Convert to twips - for convenience as we do this a lot +template constexpr auto toTwips(N number, Length from) +{ + return convert(number, from, Length::twip); +} + +// Returns nDefault if intermediate multiplication overflows sal_Int64 (only for integral types). +// On return, bOverflow indicates if overflow happened. nDefault is returned when overflow occurs. +template +constexpr auto convert(N n, U from, U to, bool& bOverflow, sal_Int64 nDefault = 0) +{ + return detail::MulDiv(n, detail::md(from, to), detail::md(to, from), bOverflow, nDefault); +} + +// Conversion with saturation (only for integral types). For too large input returns SAL_MAX_INT64. +// When intermediate multiplication would overflow, but the end result is in sal_Int64 range, the +// precision is decreased because of inversion of multiplication and division. +template constexpr auto convertSaturate(N n, U from, U to) +{ + return detail::MulDivSaturate(n, detail::md(from, to), detail::md(to, from)); +} + +// Conversion with saturation (only for integral types), optimized for return types smaller than +// sal_Int64. In this case, it's easier to clamp input values to known bounds, than to do some +// preprocessing to handle too large input values, just to clamp the result anyway. Use it like: +// +// sal_Int32 n = convertNarrowing(m); +template && std::is_integral_v && sizeof(Out) < sizeof(sal_Int64), + int> = 0> +constexpr Out convertNarrowing(N n) +{ + constexpr sal_Int64 nMin = convertSaturate(std::numeric_limits::min(), to, from); + constexpr sal_Int64 nMax = convertSaturate(std::numeric_limits::max(), to, from); + if (static_cast(n) > nMax) + return std::numeric_limits::max(); + if (static_cast(n) < nMin) + return std::numeric_limits::min(); + return convert(n, from, to); +} + +// Return a pair { multiplier, divisor } for a given conversion +template constexpr std::pair getConversionMulDiv(U from, U to) +{ + return { detail::md(from, to), detail::md(to, from) }; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/unreachable.hxx b/include/o3tl/unreachable.hxx new file mode 100644 index 000000000..604f7a2f7 --- /dev/null +++ b/include/o3tl/unreachable.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_UNREACHABLE_HXX +#define INCLUDED_O3TL_UNREACHABLE_HXX + +#include + +#include +#include + +// An approximation of C++23 std::unreachable +// ( "Function to mark +// unreachable code"). + +#if defined __cpp_lib_unreachable + +#define O3TL_UNREACHABLE (::std::unreachable()) + +#else + +// This fallback implementation is inspired by LLVM's LLVM_BUILTIN_UNREACHABLE +// (llvm/include/llvm/Support/Compiler.h). + +#if defined _MSC_VER +#define O3TL_UNREACHABLE_detail __assume(false) +#else // assuming Clang or GCC with support for: +#define O3TL_UNREACHABLE_detail __builtin_unreachable() +#endif + +#define O3TL_UNREACHABLE \ + do \ + { \ + assert(false); \ + O3TL_UNREACHABLE_detail; \ + } while (false) + +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/unsafe_downcast.hxx b/include/o3tl/unsafe_downcast.hxx new file mode 100644 index 000000000..b49994eff --- /dev/null +++ b/include/o3tl/unsafe_downcast.hxx @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_O3TL_UNSAFE_DOWNCAST_HXX +#define INCLUDED_O3TL_UNSAFE_DOWNCAST_HXX + +#include +#include + +namespace o3tl +{ +// Do a downcast from polymorphic `BasePtr` to `DerivedPtr` when it is known that `p` is actually +// pointing to an object of derived type (or is a nullptr). This is potentially cheaper than +// dynamic_cast and helps to avoid Coverity warnings about unchecked dynamic_cast. +template +std::enable_if_t< + (std::is_pointer_v< + DerivedPtr> && std::is_pointer_v && std::is_base_of_v, std::remove_pointer_t>), + DerivedPtr> +unsafe_downcast(BasePtr p) +{ + assert(p == nullptr || dynamic_cast(p) != nullptr); + return static_cast(p); +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/o3tl/vector_pool.hxx b/include/o3tl/vector_pool.hxx new file mode 100644 index 000000000..eec1a1a3c --- /dev/null +++ b/include/o3tl/vector_pool.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_O3TL_VECTOR_POOL_HXX +#define INCLUDED_O3TL_VECTOR_POOL_HXX + +#include +#include + +namespace o3tl +{ + namespace detail + { + template class simple_pool_impl : + public Container + { + typedef typename Container::value_type value_type; + std::ptrdiff_t mnFirstFreeIndex; + + public: + simple_pool_impl() : + mnFirstFreeIndex(-1) + {} + + std::ptrdiff_t alloc() + { + return store(ValueType()); + } + + std::ptrdiff_t store(const ValueType& rCopy) + { + if( mnFirstFreeIndex != -1 ) + { + std::ptrdiff_t nIdx=mnFirstFreeIndex; + mnFirstFreeIndex = this->at(mnFirstFreeIndex).nextFree; + this->at(nIdx).value = rCopy; + this->at(nIdx).nextFree = -1; + + return nIdx; + } + else + { + this->push_back(value_type(rCopy)); + return this->size()-1; + } + } + + void free( std::ptrdiff_t nIdx ) + { + this->at(nIdx).nextFree = mnFirstFreeIndex; + mnFirstFreeIndex = nIdx; + } + + const ValueType& get( std::ptrdiff_t nIdx ) const + { + return this->operator[](nIdx).value; + } + ValueType& get( std::ptrdiff_t nIdx ) + { + return this->operator[](nIdx).value; + } + }; + + template< typename ValueType > struct struct_from_value + { + struct type + { + type() : + value(), + nextFree(-1) + {} + explicit type( ValueType val ) : + value(std::move(val)), + nextFree(-1) + {} + + ValueType value; + std::ptrdiff_t nextFree; + }; + }; + } + + /** Simple vector-based memory pool allocator + + This template can be used to provide simple pooled memory + allocation from a container class that adheres to the stl + random access container concept. Note that alloc/free works + with _indices_ into the container! + + @example +
    +vector_pool myPool;
    +int nIdx=myPool.alloc();
    +myPool[nIdx] = myVal;
    + ... do stuff ...
    +myPool.free(nIdx);
    +        
    + */ + template struct vector_pool : + public detail::simple_pool_impl::type > > + {}; +} + +#endif /* INCLUDED_O3TL_VECTOR_POOL_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/o3tl/vector_utils.hxx b/include/o3tl/vector_utils.hxx new file mode 100644 index 000000000..1fe34bcaf --- /dev/null +++ b/include/o3tl/vector_utils.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include +#include + +namespace o3tl +{ +// removes duplicated elements in a vector +template void remove_duplicates(std::vector& rVector) +{ + std::unordered_set aSet; + auto aEnd = std::copy_if(rVector.begin(), rVector.end(), rVector.begin(), + [&aSet](T const& rElement) { return aSet.insert(rElement).second; }); + rVector.erase(aEnd, rVector.end()); +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/onlineupdate/mar.h b/include/onlineupdate/mar.h new file mode 100644 index 000000000..0e21efb92 --- /dev/null +++ b/include/onlineupdate/mar.h @@ -0,0 +1,198 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et cindent: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef MAR_H__ +#define MAR_H__ + +#include "mozilla/Assertions.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* We have a MAX_SIGNATURES limit so that an invalid MAR will never + * waste too much of either updater's or signmar's time. + * It is also used at various places internally and will affect memory usage. + * If you want to increase this value above 9 then you need to adjust parsing + * code in tool/mar.c. +*/ +#define MAX_SIGNATURES 8 +#ifdef __cplusplus +static_assert(MAX_SIGNATURES <= 9, "too many signatures"); +#else +MOZ_STATIC_ASSERT(MAX_SIGNATURES <= 9, "too many signatures"); +#endif + +struct ProductInformationBlock { + const char *MARChannelID; + const char *productVersion; +}; + +/** + * The MAR item data structure. + */ +typedef struct MarItem_ { + struct MarItem_ *next; /* private field */ + uint32_t offset; /* offset into archive */ + uint32_t length; /* length of data in bytes */ + uint32_t flags; /* contains file mode bits */ + char name[1]; /* file path */ +} MarItem; + +#define TABLESIZE 256 + +struct MarFile_ { + FILE *fp; + MarItem *item_table[TABLESIZE]; +}; + +typedef struct MarFile_ MarFile; + +/** + * Signature of callback function passed to mar_enum_items. + * @param mar The MAR file being visited. + * @param item The MAR item being visited. + * @param data The data parameter passed by the caller of mar_enum_items. + * @return A non-zero value to stop enumerating. + */ +typedef int (* MarItemCallback)(MarFile *mar, const MarItem *item, void *data); + +/** + * Open a MAR file for reading. + * @param path Specifies the path to the MAR file to open. This path must + * be compatible with fopen. + * @return NULL if an error occurs. + */ +MarFile *mar_open(const char *path); + +#ifdef _WIN32 +MarFile *mar_wopen(const wchar_t *path); +#endif + +/** + * Close a MAR file that was opened using mar_open. + * @param mar The MarFile object to close. + */ +void mar_close(MarFile *mar); + +/** + * Find an item in the MAR file by name. + * @param mar The MarFile object to query. + * @param item The name of the item to query. + * @return A const reference to a MAR item or NULL if not found. + */ +const MarItem *mar_find_item(MarFile *mar, const char *item); + +/** + * Enumerate all MAR items via callback function. + * @param mar The MAR file to enumerate. + * @param callback The function to call for each MAR item. + * @param data A caller specified value that is passed along to the + * callback function. + * @return 0 if the enumeration ran to completion. Otherwise, any + * non-zero return value from the callback is returned. + */ +int mar_enum_items(MarFile *mar, MarItemCallback callback, void *data); + +/** + * Read from MAR item at given offset up to bufsize bytes. + * @param mar The MAR file to read. + * @param item The MAR item to read. + * @param offset The byte offset relative to the start of the item. + * @param buf A pointer to a buffer to copy the data into. + * @param bufsize The length of the buffer to copy the data into. + * @return The number of bytes written or a negative value if an + * error occurs. + */ +int mar_read(MarFile *mar, const MarItem *item, int offset, char *buf, + int bufsize); + +/** + * Create a MAR file from a set of files. + * @param dest The path to the file to create. This path must be + * compatible with fopen. + * @param numfiles The number of files to store in the archive. + * @param files The list of null-terminated file paths. Each file + * path must be compatible with fopen. + * @param infoBlock The information to store in the product information block. + * @return A non-zero value if an error occurs. + */ +int mar_create(const char *dest, + int numfiles, + char **files, + struct ProductInformationBlock *infoBlock); + +/** + * Extract a MAR file to the current working directory. + * @param path The path to the MAR file to extract. This path must be + * compatible with fopen. + * @return A non-zero value if an error occurs. + */ +int mar_extract(const char *path); + +#define MAR_MAX_CERT_SIZE (16*1024) // Way larger than necessary + +/* Read the entire file (not a MAR file) into a newly-allocated buffer. + * This function does not write to stderr. Instead, the caller should + * write whatever error messages it sees fit. The caller must free the returned + * buffer using free(). + * + * @param filePath The path to the file that should be read. + * @param maxSize The maximum valid file size. + * @param data On success, *data will point to a newly-allocated buffer + * with the file's contents in it. + * @param size On success, *size will be the size of the created buffer. + * + * @return 0 on success, -1 on error + */ +int mar_read_entire_file(const char * filePath, + uint32_t maxSize, + /*out*/ const uint8_t * *data, + /*out*/ uint32_t *size); + +/** + * Verifies a MAR file by verifying each signature with the corresponding + * certificate. That is, the first signature will be verified using the first + * certificate given, the second signature will be verified using the second + * certificate given, etc. The signature count must exactly match the number of + * certificates given, and all signature verifications must succeed. + * We do not check that the certificate was issued by any trusted authority. + * We assume it to be self-signed. We do not check whether the certificate + * is valid for this usage. + * + * @param mar The already opened MAR file. + * @param certData Pointer to the first element in an array of certificate + * file data. + * @param certDataSizes Pointer to the first element in an array for size of + * the cert data. + * @param certCount The number of elements in certData and certDataSizes + * @return 0 on success + * a negative number if there was an error + * a positive number if the signature does not verify + */ +int mar_verify_signatures(MarFile *mar, + const uint8_t * const *certData, + const uint32_t *certDataSizes, + uint32_t certCount); + +/** + * Reads the product info block from the MAR file's additional block section. + * The caller is responsible for freeing the fields in infoBlock + * if the return is successful. + * + * @param infoBlock Out parameter for where to store the result to + * @return 0 on success, -1 on failure +*/ +int +mar_read_product_info_block(MarFile *mar, + struct ProductInformationBlock *infoBlock); + +#ifdef __cplusplus +} +#endif + +#endif /* MAR_H__ */ diff --git a/include/onlineupdate/mar_cmdline.h b/include/onlineupdate/mar_cmdline.h new file mode 100644 index 000000000..ef6867f06 --- /dev/null +++ b/include/onlineupdate/mar_cmdline.h @@ -0,0 +1,110 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef MAR_CMDLINE_H__ +#define MAR_CMDLINE_H__ + +/* We use NSPR here just to import the definition of uint32_t */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct ProductInformationBlock; + +/** + * Determines MAR file information. + * + * @param path The path of the MAR file to check. + * @param hasSignatureBlock Optional out parameter specifying if the MAR + * file has a signature block or not. + * @param numSignatures Optional out parameter for storing the number + * of signatures in the MAR file. + * @param hasAdditionalBlocks Optional out parameter specifying if the MAR + * file has additional blocks or not. + * @param offsetAdditionalBlocks Optional out parameter for the offset to the + * first additional block. Value is only valid if + * hasAdditionalBlocks is not equal to 0. + * @param numAdditionalBlocks Optional out parameter for the number of + * additional blocks. Value is only valid if + * has_additional_blocks is not equal to 0. + * @return 0 on success and non-zero on failure. + */ +int get_mar_file_info(const char *path, + int *hasSignatureBlock, + uint32_t *numSignatures, + int *hasAdditionalBlocks, + uint32_t *offsetAdditionalBlocks, + uint32_t *numAdditionalBlocks); + +/** + * Reads the product info block from the MAR file's additional block section. + * The caller is responsible for freeing the fields in infoBlock + * if the return is successful. + * + * @param infoBlock Out parameter for where to store the result to + * @return 0 on success, -1 on failure +*/ +int +read_product_info_block(char *path, + struct ProductInformationBlock *infoBlock); + +/** + * Refreshes the product information block with the new information. + * The input MAR must not be signed or the function call will fail. + * + * @param path The path to the MAR file whose product info block + * should be refreshed. + * @param infoBlock Out parameter for where to store the result to + * @return 0 on success, -1 on failure +*/ +int +refresh_product_info_block(const char *path, + struct ProductInformationBlock *infoBlock); + +/** + * Writes out a copy of the MAR at src but with the signature block stripped. + * + * @param src The path of the source MAR file + * @param dest The path of the MAR file to write out that + has no signature block + * @return 0 on success + * -1 on error +*/ +int +strip_signature_block(const char *src, const char * dest); + +/** + * Extracts a signature from a MAR file, base64 encodes it, and writes it out + * + * @param src The path of the source MAR file + * @param sigIndex The index of the signature to extract + * @param dest The path of file to write the signature to + * @return 0 on success + * -1 on error +*/ +int +extract_signature(const char *src, uint32_t sigIndex, const char * dest); + +/** + * Imports a base64 encoded signature into a MAR file + * + * @param src The path of the source MAR file + * @param sigIndex The index of the signature to import + * @param base64SigFile A file which contains the signature to import + * @param dest The path of the destination MAR file with replaced signature + * @return 0 on success + * -1 on error +*/ +int +import_signature(const char *src, + uint32_t sigIndex, + const char * base64SigFile, + const char *dest); + +#ifdef __cplusplus +} +#endif + +#endif /* MAR_CMDLINE_H__ */ diff --git a/include/onlineupdate/mar_private.h b/include/onlineupdate/mar_private.h new file mode 100644 index 000000000..319564b74 --- /dev/null +++ b/include/onlineupdate/mar_private.h @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et cindent: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef MAR_PRIVATE_H__ +#define MAR_PRIVATE_H__ + +#include "limits.h" +#include "mozilla/Assertions.h" +#include + +#define BLOCKSIZE 4096 +#define ROUND_UP(n, incr) (((n) / (incr) + 1) * (incr)) + +#define MAR_ID "MAR1" +#define MAR_ID_SIZE 4 + +/* The signature block comes directly after the header block + which is 16 bytes */ +#define SIGNATURE_BLOCK_OFFSET 16 + +/* Make sure the file is less than 500MB. We do this to protect against + invalid MAR files. */ +#define MAX_SIZE_OF_MAR_FILE ((int64_t)1824288000) + +/* Existing code makes assumptions that the file size is + smaller than LONG_MAX. */ +MOZ_STATIC_ASSERT(MAX_SIZE_OF_MAR_FILE < ((int64_t)LONG_MAX), + "max mar file size is too big"); + +/* We store at most the size up to the signature block + 4 + bytes per BLOCKSIZE bytes */ +MOZ_STATIC_ASSERT(sizeof(BLOCKSIZE) < + (SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t)), + "BLOCKSIZE is too big"); + +/* The maximum size of any signature supported by current and future + implementations of the signmar program. */ +#define MAX_SIGNATURE_LENGTH 2048 + +/* Each additional block has a unique ID. + The product information block has an ID of 1. */ +#define PRODUCT_INFO_BLOCK_ID 1 + +#define MAR_ITEM_SIZE(namelen) (3*sizeof(uint32_t) + (namelen) + 1) + +/* Product Information Block (PIB) constants */ +#define PIB_MAX_MAR_CHANNEL_ID_SIZE 63 +#define PIB_MAX_PRODUCT_VERSION_SIZE 31 + +/* The mar program is compiled as a host bin so we don't have access to NSPR at + runtime. For that reason we use ntohl, htonl, and define HOST_TO_NETWORK64 + instead of the NSPR equivalents. */ +#ifdef _WIN32 +#include +#define ftello _ftelli64 +#define fseeko _fseeki64 +#else +#define _FILE_OFFSET_BITS 64 +#include +#include +#endif + +#include + +#define HOST_TO_NETWORK64(x) ( \ + ((((uint64_t) x) & 0xFF) << 56) | \ + ((((uint64_t) x) >> 8) & 0xFF) << 48) | \ + (((((uint64_t) x) >> 16) & 0xFF) << 40) | \ + (((((uint64_t) x) >> 24) & 0xFF) << 32) | \ + (((((uint64_t) x) >> 32) & 0xFF) << 24) | \ + (((((uint64_t) x) >> 40) & 0xFF) << 16) | \ + (((((uint64_t) x) >> 48) & 0xFF) << 8) | \ + (((uint64_t) x) >> 56) +#define NETWORK_TO_HOST64 HOST_TO_NETWORK64 + +#endif /* MAR_PRIVATE_H__ */ diff --git a/include/onlineupdate/mozilla/Assertions.h b/include/onlineupdate/mozilla/Assertions.h new file mode 100644 index 000000000..29b4588fd --- /dev/null +++ b/include/onlineupdate/mozilla/Assertions.h @@ -0,0 +1,503 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Implementations of runtime and static assertion macros for C and C++. */ + +#ifndef mozilla_Assertions_h +#define mozilla_Assertions_h + +#if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus) +#define MOZ_DUMP_ASSERTION_STACK +#endif + +#include "Attributes.h" +#include "Compiler.h" +#include "Likely.h" +#include "MacroArgs.h" +#ifdef MOZ_DUMP_ASSERTION_STACK +#include "nsTraceRefcnt.h" +#endif + +#include +#include +#include +#ifdef _WIN32 + /* + * TerminateProcess and GetCurrentProcess are defined in , which + * further depends on . We hardcode these few definitions manually + * because those headers clutter the global namespace with a significant + * number of undesired macros and symbols. + */ +# ifdef __cplusplus +extern "C" { +# endif +__declspec(dllimport) int __stdcall +TerminateProcess(void* hProcess, unsigned int uExitCode); +__declspec(dllimport) void* __stdcall GetCurrentProcess(void); +# ifdef __cplusplus +} +# endif +#else +# include +#endif +#ifdef ANDROID +# include +#endif + +/* + * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. + * In C++11, static_assert is provided by the compiler to the same effect. + * This can be useful when you make certain assumptions about what must hold for + * optimal, or even correct, behavior. For example, you might assert that the + * size of a struct is a multiple of the target architecture's word size: + * + * struct S { ... }; + * // C + * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, + * "S should be a multiple of word size for efficiency"); + * // C++11 + * static_assert(sizeof(S) % sizeof(size_t) == 0, + * "S should be a multiple of word size for efficiency"); + * + * This macro can be used in any location where both an extern declaration and a + * typedef could be used. + */ +#ifndef __cplusplus + /* + * Some of the definitions below create an otherwise-unused typedef. This + * triggers compiler warnings with some versions of gcc, so mark the typedefs + * as permissibly-unused to disable the warnings. + */ +# if defined(__GNUC__) +# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) +# else +# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */ +# endif +# define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y +# define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y) +# if defined(__SUNPRO_CC) + /* + * The Sun Studio C++ compiler is buggy when declaring, inside a function, + * another extern'd function with an array argument whose length contains a + * sizeof, triggering the error message "sizeof expression not accepted as + * size of array parameter". This bug (6688515, not public yet) would hit + * defining moz_static_assert as a function, so we always define an extern + * array for Sun Studio. + * + * We include the line number in the symbol name in a best-effort attempt + * to avoid conflicts (see below). + */ +# define MOZ_STATIC_ASSERT(cond, reason) \ + extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1] +# elif defined(__COUNTER__) + /* + * If there was no preferred alternative, use a compiler-agnostic version. + * + * Note that the non-__COUNTER__ version has a bug in C++: it can't be used + * in both |extern "C"| and normal C++ in the same translation unit. (Alas + * |extern "C"| isn't allowed in a function.) The only affected compiler + * we really care about is gcc 4.2. For that compiler and others like it, + * we include the line number in the function name to do the best we can to + * avoid conflicts. These should be rare: a conflict would require use of + * MOZ_STATIC_ASSERT on the same line in separate files in the same + * translation unit, *and* the uses would have to be in code with + * different linkage, *and* the first observed use must be in C++-linkage + * code. + */ +# define MOZ_STATIC_ASSERT(cond, reason) \ + typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE +# else +# define MOZ_STATIC_ASSERT(cond, reason) \ + extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE +# endif + +#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) +#else +#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Prints |aStr| as an assertion failure (using aFilename and aLine as the + * location of the assertion) to the standard debug-output channel. + * + * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This + * method is primarily for internal use in this header, and only secondarily + * for use in implementing release-build assertions. + */ +static MOZ_COLD MOZ_ALWAYS_INLINE void +MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine) + MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS +{ +#ifdef ANDROID + __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", + "Assertion failure: %s, at %s:%d\n", + aStr, aFilename, aLine); +#else + fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine); +#if defined (MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API) + nsTraceRefcnt::WalkTheStack(stderr); +#endif + fflush(stderr); +#endif +} + +static MOZ_COLD MOZ_ALWAYS_INLINE void +MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine) + MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS +{ +#ifdef ANDROID + __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", + "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); +#else + fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); +#if defined(MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API) + nsTraceRefcnt::WalkTheStack(stderr); +#endif + fflush(stderr); +#endif +} + +/** + * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should + * call MOZ_CRASH instead. + */ +#if defined(_MSC_VER) + /* + * On MSVC use the __debugbreak compiler intrinsic, which produces an inline + * (not nested in a system function) breakpoint. This distinctively invokes + * Breakpad without requiring system library symbols on all stack-processing + * machines, as a nested breakpoint would require. + * + * We use TerminateProcess with the exit code aborting would generate + * because we don't want to invoke atexit handlers, destructors, library + * unload handlers, and so on when our process might be in a compromised + * state. + * + * We don't use abort() because it'd cause Windows to annoyingly pop up the + * process error dialog multiple times. See bug 345118 and bug 426163. + * + * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the + * compiler doesn't hassle us to provide a return statement after a + * MOZ_REALLY_CRASH() call. + * + * (Technically these are Windows requirements, not MSVC requirements. But + * practically you need MSVC for debugging, and we only ship builds created + * by MSVC, so doing it this way reduces complexity.) + */ + +__declspec(noreturn) __inline void MOZ_NoReturn() {} + +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + ::__debugbreak(); \ + *((volatile int*) NULL) = __LINE__; \ + ::TerminateProcess(::GetCurrentProcess(), 3); \ + ::MOZ_NoReturn(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + __debugbreak(); \ + *((volatile int*) NULL) = __LINE__; \ + TerminateProcess(GetCurrentProcess(), 3); \ + MOZ_NoReturn(); \ + } while (0) +# endif +#else +# ifdef __cplusplus +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = __LINE__; \ + ::abort(); \ + } while (0) +# else +# define MOZ_REALLY_CRASH() \ + do { \ + *((volatile int*) NULL) = __LINE__; \ + abort(); \ + } while (0) +# endif +#endif + +/* + * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a + * Breakpad-compatible way, in both debug and release builds. + * + * MOZ_CRASH is a good solution for "handling" failure cases when you're + * unwilling or unable to handle them more cleanly -- for OOM, for likely memory + * corruption, and so on. It's also a good solution if you need safe behavior + * in release builds as well as debug builds. But if the failure is one that + * should be debugged and fixed, MOZ_ASSERT is generally preferable. + * + * The optional explanation-string, if provided, must be a string literal + * explaining why we're crashing. This argument is intended for use with + * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's + * obvious why we're crashing. + * + * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an + * explanation-string, we print the string to stderr. Otherwise, we don't + * print anything; this is because we want MOZ_CRASH to be 100% safe in release + * builds, and it's hard to print to stderr safely when memory might have been + * corrupted. + */ +#ifndef DEBUG +# define MOZ_CRASH(...) MOZ_REALLY_CRASH() +#else +# define MOZ_CRASH(...) \ + do { \ + MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } while (0) +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* + * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in + * debug builds. If it is, execution continues. Otherwise, an error message + * including the expression and the explanation-string (if provided) is printed, + * an attempt is made to invoke any existing debugger, and execution halts. + * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition + * which can correctly be falsy. + * + * The optional explanation-string, if provided, must be a string literal + * explaining the assertion. It is intended for use with assertions whose + * correctness or rationale is non-obvious, and for assertions where the "real" + * condition being tested is best described prosaically. Don't provide an + * explanation if it's not actually helpful. + * + * // No explanation needed: pointer arguments often must not be NULL. + * MOZ_ASSERT(arg); + * + * // An explanation can be helpful to explain exactly how we know an + * // assertion is valid. + * MOZ_ASSERT(state == WAITING_FOR_RESPONSE, + * "given that and , we must have..."); + * + * // Or it might disambiguate multiple identical (save for their location) + * // assertions of the same expression. + * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), + * "we already set [[PrimitiveThis]] for this Boolean object"); + * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), + * "we already set [[PrimitiveThis]] for this String object"); + * + * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs + * *only* during debugging, not "in the field". If you want the latter, use + * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well. + * + * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and + * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare + * enough to require real user testing to hit, but is not security-sensitive. + * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT + * is firing, it should promptly be converted to a MOZ_ASSERT while the failure + * is being investigated, rather than letting users suffer. + */ + +/* + * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against + * accidentally passing something unintended in lieu of an assertion condition. + */ + +#ifdef __cplusplus +# include "TypeTraits.h" +namespace mozilla { +namespace detail { + +template +struct IsFunction +{ + static const bool value = false; +}; + +template +struct IsFunction +{ + static const bool value = true; +}; + +template +struct AssertionConditionType +{ + typedef typename RemoveReference::Type ValueT; + static_assert(!IsArray::value, + "Expected boolean assertion condition, got an array or a " + "string!"); + static_assert(!IsFunction::value, + "Expected boolean assertion condition, got a function! Did " + "you intend to call that function?"); + static_assert(!IsFloatingPoint::value, + "It's often a bad idea to assert that a floating-point number " + "is nonzero, because such assertions tend to intermittently " + "fail. Shouldn't your code gracefully handle this case instead " + "of asserting? Anyway, if you really want to do that, write an " + "explicit boolean condition, like !!x or x!=0."); + + static const bool isValid = true; +}; + +} // namespace detail +} // namespace mozilla +# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \ + static_assert(mozilla::detail::AssertionConditionType::isValid, \ + "invalid assertion condition") +#else +# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) +#endif + +/* First the single-argument form. */ +#define MOZ_ASSERT_HELPER1(expr) \ + do { \ + MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ + if (MOZ_UNLIKELY(!(expr))) { \ + MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } \ + } while (0) +/* Now the two-argument form. */ +#define MOZ_ASSERT_HELPER2(expr, explain) \ + do { \ + MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ + if (MOZ_UNLIKELY(!(expr))) { \ + MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ + MOZ_REALLY_CRASH(); \ + } \ + } while (0) + +#define MOZ_RELEASE_ASSERT_GLUE(a, b) a b +#define MOZ_RELEASE_ASSERT(...) \ + MOZ_RELEASE_ASSERT_GLUE( \ + MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \ + (__VA_ARGS__)) + +#ifdef DEBUG +# define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__) +#else +# define MOZ_ASSERT(...) do { } while (0) +#endif /* DEBUG */ + +#ifdef RELEASE_BUILD +# define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT +#else +# define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT +#endif + +/* + * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is + * true. + * + * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num)); + * + * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is + * designed to catch bugs during debugging, not "in the field". + */ +#ifdef DEBUG +# define MOZ_ASSERT_IF(cond, expr) \ + do { \ + if (cond) { \ + MOZ_ASSERT(expr); \ + } \ + } while (0) +#else +# define MOZ_ASSERT_IF(cond, expr) do { } while (0) +#endif + +/* + * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that + * it is undefined behavior for execution to reach this point. No guarantees + * are made about what will happen if this is reached at runtime. Most code + * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra + * asserts. + */ +#if defined(__clang__) || defined(__GNUC__) +# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() +#elif defined(_MSC_VER) +# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) +#else +# ifdef __cplusplus +# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() +# else +# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() +# endif +#endif + +/* + * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it + * can assume that the macro call cannot be reached during execution. This lets + * the compiler generate better-optimized code under some circumstances, at the + * expense of the program's behavior being undefined if control reaches the + * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE. + * + * In Gecko, you probably should not use this macro outside of performance- or + * size-critical code, because it's unsafe. If you don't care about code size + * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. + * + * SpiderMonkey is a different beast, and there it's acceptable to use + * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely. + * + * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid + * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE + * call. + * + * Example usage: + * + * enum ValueType { + * VALUE_STRING, + * VALUE_INT, + * VALUE_FLOAT + * }; + * + * int ptrToInt(ValueType type, void* value) { + * { + * // We know for sure that type is either INT or FLOAT, and we want this + * // code to run as quickly as possible. + * switch (type) { + * case VALUE_INT: + * return *(int*) value; + * case VALUE_FLOAT: + * return (int) *(float*) value; + * default: + * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType"); + * } + * } + */ + +/* + * Unconditional assert in debug builds for (assumed) unreachable code paths + * that have a safe return without crashing in release builds. + */ +#define MOZ_ASSERT_UNREACHABLE(reason) \ + MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason) + +#define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \ + do { \ + MOZ_ASSERT_UNREACHABLE(reason); \ + MOZ_ASSUME_UNREACHABLE_MARKER(); \ + } while (0) + +/* + * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided + * expression, in debug builds and in release builds both. Then, in debug + * builds only, the value of the expression is asserted either true or false + * using MOZ_ASSERT. + */ +#ifdef DEBUG +# define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr)) +# define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr)) +#else +# define MOZ_ALWAYS_TRUE(expr) ((void)(expr)) +# define MOZ_ALWAYS_FALSE(expr) ((void)(expr)) +#endif + +#undef MOZ_DUMP_ASSERTION_STACK + +#endif /* mozilla_Assertions_h */ diff --git a/include/onlineupdate/mozilla/Attributes.h b/include/onlineupdate/mozilla/Attributes.h new file mode 100644 index 000000000..74b77a38d --- /dev/null +++ b/include/onlineupdate/mozilla/Attributes.h @@ -0,0 +1,481 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Implementations of various class and method modifier attributes. */ + +#ifndef mozilla_Attributes_h +#define mozilla_Attributes_h + +#include "Compiler.h" + +/* + * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the + * method decorated with it must be inlined, even if the compiler thinks + * otherwise. This is only a (much) stronger version of the inline hint: + * compilers are not guaranteed to respect it (although they're much more likely + * to do so). + * + * The MOZ_ALWAYS_INLINE_EVEN_DEBUG macro is yet stronger. It tells the + * compiler to inline even in DEBUG builds. It should be used very rarely. + */ +#if defined(_MSC_VER) +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline +#elif defined(__GNUC__) +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline +#else +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline +#endif + +#if !defined(DEBUG) +# define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG +#elif defined(_MSC_VER) && !defined(__cplusplus) +# define MOZ_ALWAYS_INLINE __inline +#else +# define MOZ_ALWAYS_INLINE inline +#endif + +#if defined(_MSC_VER) +/* + * g++ requires -std=c++0x or -std=gnu++0x to support C++11 functionality + * without warnings (functionality used by the macros below). These modes are + * detectable by checking whether __GXX_EXPERIMENTAL_CXX0X__ is defined or, more + * standardly, by checking whether __cplusplus has a C++11 or greater value. + * Current versions of g++ do not correctly set __cplusplus, so we check both + * for forward compatibility. + * + * Even though some versions of MSVC support explicit conversion operators, we + * don't indicate support for them here, due to + * http://stackoverflow.com/questions/20498142/visual-studio-2013-explicit-keyword-bug + */ +# define MOZ_HAVE_NEVER_INLINE __declspec(noinline) +# define MOZ_HAVE_NORETURN __declspec(noreturn) +# ifdef __clang__ + /* clang-cl probably supports constexpr and explicit conversions. */ +# if __has_extension(cxx_constexpr) +# define MOZ_HAVE_CXX11_CONSTEXPR +# endif +# if __has_extension(cxx_explicit_conversions) +# define MOZ_HAVE_EXPLICIT_CONVERSION +# endif +# endif +#elif defined(__clang__) + /* + * Per Clang documentation, "Note that marketing version numbers should not + * be used to check for language features, as different vendors use different + * numbering schemes. Instead, use the feature checking macros." + */ +# ifndef __has_extension +# define __has_extension __has_feature /* compatibility, for older versions of clang */ +# endif +# if __has_extension(cxx_constexpr) +# define MOZ_HAVE_CXX11_CONSTEXPR +# endif +# if __has_extension(cxx_explicit_conversions) +# define MOZ_HAVE_EXPLICIT_CONVERSION +# endif +# if __has_attribute(noinline) +# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) +# endif +# if __has_attribute(noreturn) +# define MOZ_HAVE_NORETURN __attribute__((noreturn)) +# endif +#elif defined(__GNUC__) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) || (defined(__cplusplus) && __cplusplus >= 201103L) +# define MOZ_HAVE_CXX11_CONSTEXPR +# if MOZ_GCC_VERSION_AT_LEAST(4, 8, 0) +# define MOZ_HAVE_CXX11_CONSTEXPR_IN_TEMPLATES +# endif +# define MOZ_HAVE_EXPLICIT_CONVERSION +# endif +# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) +# define MOZ_HAVE_NORETURN __attribute__((noreturn)) +#endif + +/* + * When built with clang analyzer (a.k.a scan-build), define MOZ_HAVE_NORETURN + * to mark some false positives + */ +#ifdef __clang_analyzer__ +# if __has_extension(attribute_analyzer_noreturn) +# define MOZ_HAVE_ANALYZER_NORETURN __attribute__((analyzer_noreturn)) +# endif +#endif + +/* + * The MOZ_CONSTEXPR specifier declares that a C++11 compiler can evaluate a + * function at compile time. A constexpr function cannot examine any values + * except its arguments and can have no side effects except its return value. + * The MOZ_CONSTEXPR_VAR specifier tells a C++11 compiler that a variable's + * value may be computed at compile time. It should be preferred to just + * marking variables as MOZ_CONSTEXPR because if the compiler does not support + * constexpr it will fall back to making the variable const, and some compilers + * do not accept variables being marked both const and constexpr. + */ +#ifdef MOZ_HAVE_CXX11_CONSTEXPR +# define MOZ_CONSTEXPR constexpr +# define MOZ_CONSTEXPR_VAR constexpr +# ifdef MOZ_HAVE_CXX11_CONSTEXPR_IN_TEMPLATES +# define MOZ_CONSTEXPR_TMPL constexpr +# else +# define MOZ_CONSTEXPR_TMPL +# endif +#else +# define MOZ_CONSTEXPR /* no support */ +# define MOZ_CONSTEXPR_VAR const +# define MOZ_CONSTEXPR_TMPL +#endif + +/* + * MOZ_EXPLICIT_CONVERSION is a specifier on a type conversion + * overloaded operator that declares that a C++11 compiler should restrict + * this operator to allow only explicit type conversions, disallowing + * implicit conversions. + * + * Example: + * + * template + * class Ptr + * { + * T* mPtr; + * MOZ_EXPLICIT_CONVERSION operator bool() const + * { + * return mPtr != nullptr; + * } + * }; + * + */ +#ifdef MOZ_HAVE_EXPLICIT_CONVERSION +# define MOZ_EXPLICIT_CONVERSION explicit +#else +# define MOZ_EXPLICIT_CONVERSION /* no support */ +#endif + +/* + * MOZ_NEVER_INLINE is a macro which expands to tell the compiler that the + * method decorated with it must never be inlined, even if the compiler would + * otherwise choose to inline the method. Compilers aren't absolutely + * guaranteed to support this, but most do. + */ +#if defined(MOZ_HAVE_NEVER_INLINE) +# define MOZ_NEVER_INLINE MOZ_HAVE_NEVER_INLINE +#else +# define MOZ_NEVER_INLINE /* no support */ +#endif + +/* + * MOZ_NORETURN, specified at the start of a function declaration, indicates + * that the given function does not return. (The function definition does not + * need to be annotated.) + * + * MOZ_NORETURN void abort(const char* msg); + * + * This modifier permits the compiler to optimize code assuming a call to such a + * function will never return. It also enables the compiler to avoid spurious + * warnings about not initializing variables, or about any other seemingly-dodgy + * operations performed after the function returns. + * + * This modifier does not affect the corresponding function's linking behavior. + */ +#if defined(MOZ_HAVE_NORETURN) +# define MOZ_NORETURN MOZ_HAVE_NORETURN +#else +# define MOZ_NORETURN /* no support */ +#endif + +/** + * MOZ_COLD tells the compiler that a function is "cold", meaning infrequently + * executed. This may lead it to optimize for size more aggressively than speed, + * or to allocate the body of the function in a distant part of the text segment + * to help keep it from taking up unnecessary icache when it isn't in use. + * + * Place this attribute at the very beginning of a function definition. For + * example, write + * + * MOZ_COLD int foo(); + * + * or + * + * MOZ_COLD int foo() { return 42; } + */ +#if defined(__GNUC__) || defined(__clang__) +# define MOZ_COLD __attribute__ ((cold)) +#else +# define MOZ_COLD +#endif + +/** + * MOZ_NONNULL tells the compiler that some of the arguments to a function are + * known to be non-null. The arguments are a list of 1-based argument indexes + * identifying arguments which are known to be non-null. + * + * Place this attribute at the very beginning of a function definition. For + * example, write + * + * MOZ_NONNULL(1, 2) int foo(char *p, char *q); + */ +#if defined(__GNUC__) || defined(__clang__) +# define MOZ_NONNULL(...) __attribute__ ((nonnull(__VA_ARGS__))) +#else +# define MOZ_NONNULL(...) +#endif + +/* + * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS, specified at the end of a function + * declaration, indicates that for the purposes of static analysis, this + * function does not return. (The function definition does not need to be + * annotated.) + * + * MOZ_ReportCrash(const char* s, const char* file, int ln) + * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS + * + * Some static analyzers, like scan-build from clang, can use this information + * to eliminate false positives. From the upstream documentation of scan-build: + * "This attribute is useful for annotating assertion handlers that actually + * can return, but for the purpose of using the analyzer we want to pretend + * that such functions do not return." + * + */ +#if defined(MOZ_HAVE_ANALYZER_NORETURN) +# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS MOZ_HAVE_ANALYZER_NORETURN +#else +# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS /* no support */ +#endif + +/* + * MOZ_ASAN_DENYLIST is a macro to tell AddressSanitizer (a compile-time + * instrumentation shipped with Clang and GCC) to not instrument the annotated + * function. Furthermore, it will prevent the compiler from inlining the + * function because inlining currently breaks the denylisting mechanism of + * AddressSanitizer. + */ +#if defined(__has_feature) +# if __has_feature(address_sanitizer) +# define MOZ_HAVE_ASAN_DENYLIST +# endif +#elif defined(__GNUC__) +# if defined(__SANITIZE_ADDRESS__) +# define MOZ_HAVE_ASAN_DENYLIST +# endif +#endif + +#if defined(MOZ_HAVE_ASAN_DENYLIST) +# define MOZ_ASAN_DENYLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) +#else +# define MOZ_ASAN_DENYLIST /* nothing */ +#endif + +/* + * MOZ_TSAN_DENYLIST is a macro to tell ThreadSanitizer (a compile-time + * instrumentation shipped with Clang) to not instrument the annotated function. + * Furthermore, it will prevent the compiler from inlining the function because + * inlining currently breaks the denylisting mechanism of ThreadSanitizer. + */ +#if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define MOZ_TSAN_DENYLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) +# else +# define MOZ_TSAN_DENYLIST /* nothing */ +# endif +#else +# define MOZ_TSAN_DENYLIST /* nothing */ +#endif + +/** + * MOZ_ALLOCATOR tells the compiler that the function it marks returns either a + * "fresh", "pointer-free" block of memory, or nullptr. "Fresh" means that the + * block is not pointed to by any other reachable pointer in the program. + * "Pointer-free" means that the block contains no pointers to any valid object + * in the program. It may be initialized with other (non-pointer) values. + * + * Placing this attribute on appropriate functions helps GCC analyze pointer + * aliasing more accurately in their callers. + * + * GCC warns if a caller ignores the value returned by a function marked with + * MOZ_ALLOCATOR: it is hard to imagine cases where dropping the value returned + * by a function that meets the criteria above would be intentional. + * + * Place this attribute after the argument list and 'this' qualifiers of a + * function definition. For example, write + * + * void *my_allocator(size_t) MOZ_ALLOCATOR; + * + * or + * + * void *my_allocator(size_t bytes) MOZ_ALLOCATOR { ... } + */ +#if defined(__GNUC__) || defined(__clang__) +# define MOZ_ALLOCATOR __attribute__ ((malloc, warn_unused_result)) +#else +# define MOZ_ALLOCATOR +#endif + +/** + * MOZ_WARN_UNUSED_RESULT tells the compiler to emit a warning if a function's + * return value is not used by the caller. + * + * Place this attribute at the very beginning of a function definition. For + * example, write + * + * MOZ_WARN_UNUSED_RESULT int foo(); + * + * or + * + * MOZ_WARN_UNUSED_RESULT int foo() { return 42; } + */ +#if defined(__GNUC__) || defined(__clang__) +# define MOZ_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result)) +#else +# define MOZ_WARN_UNUSED_RESULT +#endif + +#ifdef __cplusplus + +/* + * The following macros are attributes that support the static analysis plugin + * included with Mozilla, and will be implemented (when such support is enabled) + * as C++11 attributes. Since such attributes are legal pretty much everywhere + * and have subtly different semantics depending on their placement, the + * following is a guide on where to place the attributes. + * + * Attributes that apply to a struct or class precede the name of the class: + * (Note that this is different from the placement of final for classes!) + * + * class MOZ_CLASS_ATTRIBUTE SomeClass {}; + * + * Attributes that apply to functions follow the parentheses and const + * qualifiers but precede final, override and the function body: + * + * void DeclaredFunction() MOZ_FUNCTION_ATTRIBUTE; + * void SomeFunction() MOZ_FUNCTION_ATTRIBUTE {} + * void PureFunction() const MOZ_FUNCTION_ATTRIBUTE = 0; + * void OverriddenFunction() MOZ_FUNCTION_ATTRIBUTE override; + * + * Attributes that apply to variables or parameters follow the variable's name: + * + * int variable MOZ_VARIABLE_ATTRIBUTE; + * + * Attributes that apply to types follow the type name: + * + * typedef int MOZ_TYPE_ATTRIBUTE MagicInt; + * int MOZ_TYPE_ATTRIBUTE someVariable; + * int* MOZ_TYPE_ATTRIBUTE magicPtrInt; + * int MOZ_TYPE_ATTRIBUTE* ptrToMagicInt; + * + * Attributes that apply to statements precede the statement: + * + * MOZ_IF_ATTRIBUTE if (x == 0) + * MOZ_DO_ATTRIBUTE do { } while (0); + * + * Attributes that apply to labels precede the label: + * + * MOZ_LABEL_ATTRIBUTE target: + * goto target; + * MOZ_CASE_ATTRIBUTE case 5: + * MOZ_DEFAULT_ATTRIBUTE default: + * + * The static analyses that are performed by the plugin are as follows: + * + * MOZ_MUST_OVERRIDE: Applies to all C++ member functions. All immediate + * subclasses must provide an exact override of this method; if a subclass + * does not override this method, the compiler will emit an error. This + * attribute is not limited to virtual methods, so if it is applied to a + * nonvirtual method and the subclass does not provide an equivalent + * definition, the compiler will emit an error. + * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is + * expected to live on the stack, so it is a compile-time error to use it, or + * an array of such objects, as a global or static variable, or as the type of + * a new expression (unless placement new is being used). If a member of + * another class uses this class, or if another class inherits from this + * class, then it is considered to be a stack class as well, although this + * attribute need not be provided in such cases. + * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is + * expected to live on the stack or in static storage, so it is a compile-time + * error to use it, or an array of such objects, as the type of a new + * expression (unless placement new is being used). If a member of another + * class uses this class, or if another class inherits from this class, then + * it is considered to be a non-heap class as well, although this attribute + * need not be provided in such cases. + * MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS: Applies to all classes that are + * intended to prevent introducing static initializers. This attribute + * currently makes it a compile-time error to instantiate these classes + * anywhere other than at the global scope, or as a static member of a class. + * MOZ_TRIVIAL_CTOR_DTOR: Applies to all classes that must have both a trivial + * constructor and a trivial destructor. Setting this attribute on a class + * makes it a compile-time error for that class to get a non-trivial + * constructor or destructor for any reason. + * MOZ_HEAP_ALLOCATOR: Applies to any function. This indicates that the return + * value is allocated on the heap, and will as a result check such allocations + * during MOZ_STACK_CLASS and MOZ_NONHEAP_CLASS annotation checking. + * MOZ_IMPLICIT: Applies to constructors. Implicit conversion constructors + * are disallowed by default unless they are marked as MOZ_IMPLICIT. This + * attribute must be used for constructors which intend to provide implicit + * conversions. + * MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT: Applies to functions. Makes it a compile + * time error to pass arithmetic expressions on variables to the function. + * MOZ_OWNING_REF: Applies to declarations of pointer types. This attribute + * tells the compiler that the raw pointer is a strong reference, and that + * property is somehow enforced by the code. This can make the compiler + * ignore these pointers when validating the usage of pointers otherwise. + * MOZ_NON_OWNING_REF: Applies to declarations of pointer types. This attribute + * tells the compiler that the raw pointer is a weak reference, and that + * property is somehow enforced by the code. This can make the compiler + * ignore these pointers when validating the usage of pointers otherwise. + * MOZ_UNSAFE_REF: Applies to declarations of pointer types. This attribute + * should be used for non-owning references that can be unsafe, and their + * safety needs to be validated through code inspection. The string argument + * passed to this macro documents the safety conditions. + * MOZ_NO_ADDREF_RELEASE_ON_RETURN: Applies to function declarations. Makes it + * a compile time error to call AddRef or Release on the return value of a + * function. This is intended to be used with operator->() of our smart + * pointer classes to ensure that the refcount of an object wrapped in a + * smart pointer is not manipulated directly. + */ +#ifdef MOZ_CLANG_PLUGIN +# define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) +# define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) +# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) +# define MOZ_TRIVIAL_CTOR_DTOR __attribute__((annotate("moz_trivial_ctor_dtor"))) +# ifdef DEBUG + /* in debug builds, these classes do have non-trivial constructors. */ +# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) +# else +# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) \ + MOZ_TRIVIAL_CTOR_DTOR +# endif +# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit"))) +# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT __attribute__((annotate("moz_no_arith_expr_in_arg"))) +# define MOZ_OWNING_REF __attribute__((annotate("moz_strong_ref"))) +# define MOZ_NON_OWNING_REF __attribute__((annotate("moz_weak_ref"))) +# define MOZ_UNSAFE_REF(reason) __attribute__((annotate("moz_strong_ref"))) +# define MOZ_NO_ADDREF_RELEASE_ON_RETURN __attribute__((annotate("moz_no_addref_release_on_return"))) +/* + * It turns out that clang doesn't like void func() __attribute__ {} without a + * warning, so use pragmas to disable the warning. This code won't work on GCC + * anyways, so the warning is safe to ignore. + */ +# define MOZ_HEAP_ALLOCATOR \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((annotate("moz_heap_allocator"))) \ + _Pragma("clang diagnostic pop") +#else +# define MOZ_MUST_OVERRIDE /* nothing */ +# define MOZ_STACK_CLASS /* nothing */ +# define MOZ_NONHEAP_CLASS /* nothing */ +# define MOZ_TRIVIAL_CTOR_DTOR /* nothing */ +# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS /* nothing */ +# define MOZ_IMPLICIT /* nothing */ +# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT /* nothing */ +# define MOZ_HEAP_ALLOCATOR /* nothing */ +# define MOZ_OWNING_REF /* nothing */ +# define MOZ_NON_OWNING_REF /* nothing */ +# define MOZ_UNSAFE_REF(reason) /* nothing */ +# define MOZ_NO_ADDREF_RELEASE_ON_RETURN /* nothing */ +#endif /* MOZ_CLANG_PLUGIN */ + +#endif /* __cplusplus */ + +#endif /* mozilla_Attributes_h */ diff --git a/include/onlineupdate/mozilla/Compiler.h b/include/onlineupdate/mozilla/Compiler.h new file mode 100644 index 000000000..6d6fcbbb1 --- /dev/null +++ b/include/onlineupdate/mozilla/Compiler.h @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Various compiler checks. */ + +#ifndef mozilla_Compiler_h +#define mozilla_Compiler_h + +#define MOZ_IS_GCC 0 +#define MOS_IS_MSVC 0 + +#if !defined(__clang__) && defined(__GNUC__) + +# undef MOZ_IS_GCC +# define MOZ_IS_GCC 1 + /* + * This macro should simplify gcc version checking. For example, to check + * for gcc 4.7.1 or later, check `#if MOZ_GCC_VERSION_AT_LEAST(4, 7, 1)`. + */ +# define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \ + ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ + >= ((major) * 10000 + (minor) * 100 + (patchlevel))) +# if !MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# error "mfbt (and Gecko) require at least gcc 4.7 to build." +# endif + +#elif defined(_MSC_VER) + +# undef MOZ_IS_MSVC +# define MOZ_IS_MSVC 1 + +#endif + +/* + * The situation with standard libraries is a lot worse than with compilers, + * particularly as clang and gcc could end up using one of three or so standard + * libraries, and they may not be up-to-snuff with newer C++11 versions. To + * detect the library, we're going to include cstddef (which is a small header + * which will be transitively included by everybody else at some point) to grab + * the version macros and deduce macros from there. + */ +#ifdef __cplusplus +# include +# ifdef _STLPORT_MAJOR +# define MOZ_USING_STLPORT 1 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ + (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) +# elif defined(_LIBCPP_VERSION) + /* + * libc++, unfortunately, doesn't appear to have useful versioning macros. + * Hopefully, the recommendations of N3694 with respect to standard libraries + * will get applied instead and we won't need to worry about version numbers + * here. + */ +# define MOZ_USING_LIBCXX 1 +# elif defined(__GLIBCXX__) +# define MOZ_USING_LIBSTDCXX 1 + /* + * libstdc++ is also annoying and doesn't give us useful versioning macros + * for the library. If we're using gcc, then assume that libstdc++ matches + * the compiler version. If we're using clang, we're going to have to fake + * major/minor combinations by looking for newly-defined config macros. + */ +# if MOZ_IS_GCC +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) +# elif defined(_GLIBCXX_THROW_OR_ABORT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 8)) +# elif defined(_GLIBCXX_NOEXCEPT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 7)) +# elif defined(_GLIBCXX_USE_DEPRECATED) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 6)) +# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 5)) +# elif defined(_GLIBCXX_BEGIN_EXTERN_C) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 4)) +# elif defined(_GLIBCXX_VISIBILITY_ATTR) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 3)) +# elif defined(_GLIBCXX_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 2)) +# else +# error "Your version of libstdc++ is unknown to us and is likely too old." +# endif +# endif + + // Flesh out the defines for everyone else +# ifndef MOZ_USING_STLPORT +# define MOZ_USING_STLPORT 0 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +# ifndef MOZ_USING_LIBCXX +# define MOZ_USING_LIBCXX 0 +# endif +# ifndef MOZ_USING_LIBSTDCXX +# define MOZ_USING_LIBSTDCXX 0 +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +#endif /* __cplusplus */ + +#endif /* mozilla_Compiler_h */ diff --git a/include/onlineupdate/mozilla/Likely.h b/include/onlineupdate/mozilla/Likely.h new file mode 100644 index 000000000..5625bb226 --- /dev/null +++ b/include/onlineupdate/mozilla/Likely.h @@ -0,0 +1,23 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a + * boolean predicate should be branch-predicted. + */ + +#ifndef mozilla_Likely_h +#define mozilla_Likely_h + +#if defined(__clang__) || defined(__GNUC__) +#define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) +#define MOZ_UNLIKELY(x) (__builtin_expect(!!(x), 0)) +#else +#define MOZ_LIKELY(x) (!!(x)) +#define MOZ_UNLIKELY(x) (!!(x)) +#endif + +#endif /* mozilla_Likely_h */ diff --git a/include/onlineupdate/mozilla/MacroArgs.h b/include/onlineupdate/mozilla/MacroArgs.h new file mode 100644 index 000000000..c8b733821 --- /dev/null +++ b/include/onlineupdate/mozilla/MacroArgs.h @@ -0,0 +1,105 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * Implements various macros meant to ease the use of variadic macros. + */ + +#ifndef mozilla_MacroArgs_h +#define mozilla_MacroArgs_h + +/* + * MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) counts the number of variadic + * arguments and prefixes it with |aPrefix|. For example: + * + * MOZ_PASTE_PREFIX_AND_ARG_COUNT(, foo, 42) expands to 2 + * MOZ_PASTE_PREFIX_AND_ARG_COUNT(A, foo, 42, bar) expands to A3 + * + * You must pass in between 1 and 50 (inclusive) variadic arguments, past + * |aPrefix|. It is not legal to do + * + * MOZ_PASTE_PREFIX_AND_ARG_COUNT(prefix) + * + * (that is, pass in 0 variadic arguments). To ensure that a compile-time + * error occurs when these constraints are violated, use the + * MOZ_STATIC_ASSERT_VALID_ARG_COUNT macro with the same variaidc arguments + * wherever this macro is used. + * + * Passing (__VA_ARGS__, ) rather than simply calling + * MOZ_MACROARGS_ARG_COUNT_HELPER2(__VA_ARGS__, ) very + * carefully tiptoes around a MSVC bug where it improperly expands __VA_ARGS__ + * as a single token in argument lists. For details, see: + * + * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement + * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 + */ +#define MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) \ + MOZ_MACROARGS_ARG_COUNT_HELPER((__VA_ARGS__, \ + aPrefix##50, aPrefix##49, aPrefix##48, aPrefix##47, aPrefix##46, \ + aPrefix##45, aPrefix##44, aPrefix##43, aPrefix##42, aPrefix##41, \ + aPrefix##40, aPrefix##39, aPrefix##38, aPrefix##37, aPrefix##36, \ + aPrefix##35, aPrefix##34, aPrefix##33, aPrefix##32, aPrefix##31, \ + aPrefix##30, aPrefix##29, aPrefix##28, aPrefix##27, aPrefix##26, \ + aPrefix##25, aPrefix##24, aPrefix##23, aPrefix##22, aPrefix##21, \ + aPrefix##20, aPrefix##19, aPrefix##18, aPrefix##17, aPrefix##16, \ + aPrefix##15, aPrefix##14, aPrefix##13, aPrefix##12, aPrefix##11, \ + aPrefix##10, aPrefix##9, aPrefix##8, aPrefix##7, aPrefix##6, \ + aPrefix##5, aPrefix##4, aPrefix##3, aPrefix##2, aPrefix##1, aPrefix##0)) + +#define MOZ_MACROARGS_ARG_COUNT_HELPER(aArgs) \ + MOZ_MACROARGS_ARG_COUNT_HELPER2 aArgs + +#define MOZ_MACROARGS_ARG_COUNT_HELPER2( \ + a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, \ + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, \ + a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, \ + a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, \ + a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, \ + a51, ...) a51 + +/* + * MOZ_STATIC_ASSERT_VALID_ARG_COUNT ensures that a compile-time error occurs + * when the argument count constraints of MOZ_PASTE_PREFIX_AND_ARG_COUNT are + * violated. Use this macro wherever MOZ_PASTE_PREFIX_AND_ARG_COUNT is used + * and pass it the same variadic arguments. + * + * This macro employs a few dirty tricks to function. To detect the zero + * argument case, |(__VA_ARGS__)| is stringified, sizeof-ed, and compared to + * what it should be in the absence of arguments. + * + * Detecting too many arguments is a little trickier. With a valid argument + * count and a prefix of 1, MOZ_PASTE_PREFIX_AND_ARG_COUNT expands to e.g. 14. + * With a prefix of 0.0, it expands to e.g. 0.04. If there are too many + * arguments, it expands to the first argument over the limit. If this + * exceeding argument is a number, the assertion will fail as there is no + * number than can simultaneously be both > 10 and == 0. If the exceeding + * argument is not a number, a compile-time error should still occur due to + * the operations performed on it. + */ +#define MOZ_MACROARGS_STRINGIFY_HELPER(x) #x +#define MOZ_STATIC_ASSERT_VALID_ARG_COUNT(...) \ + static_assert( \ + sizeof(MOZ_MACROARGS_STRINGIFY_HELPER((__VA_ARGS__))) != sizeof("()") && \ + (MOZ_PASTE_PREFIX_AND_ARG_COUNT(1, __VA_ARGS__)) > 10 && \ + (int)(MOZ_PASTE_PREFIX_AND_ARG_COUNT(0.0, __VA_ARGS__)) == 0, \ + "MOZ_STATIC_ASSERT_VALID_ARG_COUNT requires 1 to 50 arguments") /* ; */ + +/* + * MOZ_ARGS_AFTER_N expands to its arguments excluding the first |N| + * arguments. For example: + * + * MOZ_ARGS_AFTER_2(a, b, c, d) expands to: c, d + */ +#define MOZ_ARGS_AFTER_1(a1, ...) __VA_ARGS__ +#define MOZ_ARGS_AFTER_2(a1, a2, ...) __VA_ARGS__ + +/* + * MOZ_ARG_N expands to its |N|th argument. + */ +#define MOZ_ARG_1(a1, ...) a1 +#define MOZ_ARG_2(a1, a2, ...) a2 + +#endif /* mozilla_MacroArgs_h */ diff --git a/include/onlineupdate/mozilla/TypeTraits.h b/include/onlineupdate/mozilla/TypeTraits.h new file mode 100644 index 000000000..7ca9d3315 --- /dev/null +++ b/include/onlineupdate/mozilla/TypeTraits.h @@ -0,0 +1,1116 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Template-based metaprogramming and type-testing facilities. */ + +#ifndef mozilla_TypeTraits_h +#define mozilla_TypeTraits_h + +#include "Types.h" + +/* + * These traits are approximate copies of the traits and semantics from C++11's + * header. Don't add traits not in that header! When all + * platforms provide that header, we can convert all users and remove this one. + */ + +#include + +namespace mozilla { + +/* Forward declarations. */ + +template struct RemoveCV; + +/* 20.9.3 Helper classes [meta.help] */ + +/** + * Helper class used as a base for various type traits, exposed publicly + * because exposes it as well. + */ +template +struct IntegralConstant +{ + static const T value = Value; + typedef T ValueType; + typedef IntegralConstant Type; +}; + +/** Convenient aliases. */ +typedef IntegralConstant TrueType; +typedef IntegralConstant FalseType; + +/* 20.9.4 Unary type traits [meta.unary] */ + +/* 20.9.4.1 Primary type categories [meta.unary.cat] */ + +namespace detail { + +template +struct IsVoidHelper : FalseType {}; + +template<> +struct IsVoidHelper : TrueType {}; + +} // namespace detail + +/** + * IsVoid determines whether a type is void. + * + * mozilla::IsVoid::value is false; + * mozilla::IsVoid::value is true; + * mozilla::IsVoid::value is false; + * mozilla::IsVoid::value is true. + */ +template +struct IsVoid : detail::IsVoidHelper::Type> {}; + +namespace detail { + +template +struct IsIntegralHelper : FalseType {}; + +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +template<> struct IsIntegralHelper : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsIntegralHelper : TrueType {}; +#endif + +} /* namespace detail */ + +/** + * IsIntegral determines whether a type is an integral type. + * + * mozilla::IsIntegral::value is true; + * mozilla::IsIntegral::value is true; + * mozilla::IsIntegral::value is true; + * mozilla::IsIntegral::value is false; + * mozilla::IsIntegral::value is false; + * + * Note that the behavior of IsIntegral on char16_t and char32_t is + * unspecified. + */ +template +struct IsIntegral : detail::IsIntegralHelper::Type> +{}; + +template +struct IsSame; + +namespace detail { + +template +struct IsFloatingPointHelper + : IntegralConstant::value || + IsSame::value || + IsSame::value> +{}; + +} // namespace detail + +/** + * IsFloatingPoint determines whether a type is a floating point type (float, + * double, long double). + * + * mozilla::IsFloatingPoint::value is false; + * mozilla::IsFloatingPoint::value is true; + * mozilla::IsFloatingPoint::value is true; + * mozilla::IsFloatingPoint::value is false. + */ +template +struct IsFloatingPoint + : detail::IsFloatingPointHelper::Type> +{}; + +namespace detail { + +template +struct IsArrayHelper : FalseType {}; + +template +struct IsArrayHelper : TrueType {}; + +template +struct IsArrayHelper : TrueType {}; + +} // namespace detail + +/** + * IsArray determines whether a type is an array type, of known or unknown + * length. + * + * mozilla::IsArray::value is false; + * mozilla::IsArray::value is true; + * mozilla::IsArray::value is true. + */ +template +struct IsArray : detail::IsArrayHelper::Type> +{}; + +namespace detail { + +template +struct IsPointerHelper : FalseType {}; + +template +struct IsPointerHelper : TrueType {}; + +} // namespace detail + +/** + * IsPointer determines whether a type is a possibly-CV-qualified pointer type + * (but not a pointer-to-member type). + * + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is true; + * mozilla::IsPointer::value is false; + * mozilla::IsPointer::value is false. + * mozilla::IsPointer::value is false + */ +template +struct IsPointer : detail::IsPointerHelper::Type> +{}; + +/** + * IsLvalueReference determines whether a type is an lvalue reference. + * + * mozilla::IsLvalueReference::value is false; + * mozilla::IsLvalueReference::value is false; + * mozilla::IsLvalueReference::value is false; + * mozilla::IsLvalueReference::value is false; + * mozilla::IsLvalueReference::value is false; + * mozilla::IsLvalueReference::value is true; + * mozilla::IsLvalueReference::value is false. + */ +template +struct IsLvalueReference : FalseType {}; + +template +struct IsLvalueReference : TrueType {}; + +/** + * IsRvalueReference determines whether a type is an rvalue reference. + * + * mozilla::IsRvalueReference::value is false; + * mozilla::IsRvalueReference::value is false; + * mozilla::IsRvalueReference::value is false; + * mozilla::IsRvalueReference::value is false; + * mozilla::IsRvalueReference::value is false; + * mozilla::IsRvalueReference::value is false; + * mozilla::IsRvalueReference::value is true. + */ +template +struct IsRvalueReference : FalseType {}; + +template +struct IsRvalueReference : TrueType {}; + +namespace detail { + +// __is_enum is a supported extension across all of our supported compilers. +template +struct IsEnumHelper + : IntegralConstant +{}; + +} // namespace detail + +/** + * IsEnum determines whether a type is an enum type. + * + * mozilla::IsEnum::value is true; + * mozilla::IsEnum::value is false; + * mozilla::IsEnum::value is false; + */ +template +struct IsEnum + : detail::IsEnumHelper::Type> +{}; + +namespace detail { + +// __is_class is a supported extension across all of our supported compilers: +// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html +// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits +// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx +template +struct IsClassHelper + : IntegralConstant +{}; + +} // namespace detail + +/** + * IsClass determines whether a type is a class type (but not a union). + * + * struct S {}; + * union U {}; + * mozilla::IsClass::value is false; + * mozilla::IsClass::value is true; + * mozilla::IsClass::value is false; + */ +template +struct IsClass + : detail::IsClassHelper::Type> +{}; + +/* 20.9.4.2 Composite type traits [meta.unary.comp] */ + +/** + * IsReference determines whether a type is an lvalue or rvalue reference. + * + * mozilla::IsReference::value is false; + * mozilla::IsReference::value is false; + * mozilla::IsReference::value is true; + * mozilla::IsReference::value is false; + * mozilla::IsReference::value is true; + * mozilla::IsReference::value is false; + * mozilla::IsReference::value is false; + * mozilla::IsReference::value is true; + * mozilla::IsReference::value is true; + * mozilla::IsReference::value is true. + */ +template +struct IsReference + : IntegralConstant::value || IsRvalueReference::value> +{}; + +/** + * IsArithmetic determines whether a type is arithmetic. A type is arithmetic + * iff it is an integral type or a floating point type. + * + * mozilla::IsArithmetic::value is true; + * mozilla::IsArithmetic::value is true; + * mozilla::IsArithmetic::value is false. + */ +template +struct IsArithmetic + : IntegralConstant::value || IsFloatingPoint::value> +{}; + +/* 20.9.4.3 Type properties [meta.unary.prop] */ + +/** + * IsConst determines whether a type is const or not. + * + * mozilla::IsConst::value is false; + * mozilla::IsConst::value is true; + * mozilla::IsConst::value is false. + */ +template +struct IsConst : FalseType {}; + +template +struct IsConst : TrueType {}; + +/** + * IsVolatile determines whether a type is volatile or not. + * + * mozilla::IsVolatile::value is false; + * mozilla::IsVolatile::value is true; + * mozilla::IsVolatile::value is false. + */ +template +struct IsVolatile : FalseType {}; + +template +struct IsVolatile : TrueType {}; + +/** + * Traits class for identifying POD types. Until C++11 there's no automatic + * way to detect PODs, so for the moment this is done manually. Users may + * define specializations of this class that inherit from mozilla::TrueType and + * mozilla::FalseType (or equivalently mozilla::IntegralConstant, or conveniently from mozilla::IsPod for composite types) as needed to + * ensure correct IsPod behavior. + */ +template +struct IsPod : public FalseType {}; + +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +template<> struct IsPod : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsPod : TrueType {}; +#endif +template struct IsPod : TrueType {}; + +namespace detail { + +// __is_empty is a supported extension across all of our supported compilers: +// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html +// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits +// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx +template +struct IsEmptyHelper + : IntegralConstant::value && __is_empty(T)> +{}; + +} // namespace detail + +/** + * IsEmpty determines whether a type is a class (but not a union) that is empty. + * + * A class is empty iff it and all its base classes have no non-static data + * members (except bit-fields of length 0) and no virtual member functions, and + * no base class is empty or a virtual base class. + * + * Intuitively, empty classes don't have any data that has to be stored in + * instances of those classes. (The size of the class must still be non-zero, + * because distinct array elements of any type must have different addresses. + * However, if the Empty Base Optimization is implemented by the compiler [most + * compilers implement it, and in certain cases C++11 requires it], the size of + * a class inheriting from an empty |Base| class need not be inflated by + * |sizeof(Base)|.) And intuitively, non-empty classes have data members and/or + * vtable pointers that must be stored in each instance for proper behavior. + * + * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); + * union U1 { int x; }; + * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); + * struct E1 {}; + * struct E2 { int : 0 }; + * struct E3 : E1 {}; + * struct E4 : E2 {}; + * static_assert(mozilla::IsEmpty::value && + * mozilla::IsEmpty::value && + * mozilla::IsEmpty::value && + * mozilla::IsEmpty::value, + * "all empty"); + * union U2 { E1 e1; }; + * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); + * struct NE1 { int x; }; + * struct NE2 : virtual E1 {}; + * struct NE3 : E2 { virtual ~NE3() {} }; + * struct NE4 { virtual void f() {} }; + * static_assert(!mozilla::IsEmpty::value && + * !mozilla::IsEmpty::value && + * !mozilla::IsEmpty::value && + * !mozilla::IsEmpty::value, + * "all empty"); + */ +template +struct IsEmpty : detail::IsEmptyHelper::Type> +{}; + + +namespace detail { + +template::value, + bool = IsIntegral::value, + typename NoCV = typename RemoveCV::Type> +struct IsSignedHelper; + +// Floating point is signed. +template +struct IsSignedHelper : TrueType {}; + +// Integral is conditionally signed. +template +struct IsSignedHelper + : IntegralConstant +{}; + +// Non-floating point, non-integral is not signed. +template +struct IsSignedHelper : FalseType {}; + +} // namespace detail + +/** + * IsSigned determines whether a type is a signed arithmetic type. |char| is + * considered a signed type if it has the same representation as |signed char|. + * + * mozilla::IsSigned::value is true; + * mozilla::IsSigned::value is false; + * mozilla::IsSigned::value is false; + * mozilla::IsSigned::value is true. + */ +template +struct IsSigned : detail::IsSignedHelper {}; + +namespace detail { + +template::value, + bool = IsIntegral::value, + typename NoCV = typename RemoveCV::Type> +struct IsUnsignedHelper; + +// Floating point is not unsigned. +template +struct IsUnsignedHelper : FalseType {}; + +// Integral is conditionally unsigned. +template +struct IsUnsignedHelper + : IntegralConstant::value || bool(NoCV(1) < NoCV(-1)))> +{}; + +// Non-floating point, non-integral is not unsigned. +template +struct IsUnsignedHelper : FalseType {}; + +} // namespace detail + +/** + * IsUnsigned determines whether a type is an unsigned arithmetic type. + * + * mozilla::IsUnsigned::value is false; + * mozilla::IsUnsigned::value is true; + * mozilla::IsUnsigned::value is true; + * mozilla::IsUnsigned::value is false. + */ +template +struct IsUnsigned : detail::IsUnsignedHelper {}; + +/* 20.9.5 Type property queries [meta.unary.prop.query] */ + +/* 20.9.6 Relationships between types [meta.rel] */ + +/** + * IsSame tests whether two types are the same type. + * + * mozilla::IsSame::value is true; + * mozilla::IsSame::value is true; + * mozilla::IsSame::value is false; + * mozilla::IsSame::value is true; + * mozilla::IsSame::value is false; + * mozilla::IsSame::value is true. + */ +template +struct IsSame : FalseType {}; + +template +struct IsSame : TrueType {}; + +namespace detail { + +#if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) + +template +struct BaseOfTester : IntegralConstant {}; + +#else + +// The trickery used to implement IsBaseOf here makes it possible to use it for +// the cases of private and multiple inheritance. This code was inspired by the +// sample code here: +// +// http://stackoverflow.com/questions/2910979/how-is-base-of-works +template +struct BaseOfHelper +{ +public: + operator Base*() const; + operator Derived*(); +}; + +template +struct BaseOfTester +{ +private: + template + static char test(Derived*, T); + static int test(Base*, int); + +public: + static const bool value = + sizeof(test(BaseOfHelper(), int())) == sizeof(char); +}; + +template +struct BaseOfTester +{ +private: + template + static char test(Derived*, T); + static int test(Base*, int); + +public: + static const bool value = + sizeof(test(BaseOfHelper(), int())) == sizeof(char); +}; + +template +struct BaseOfTester : FalseType {}; + +template +struct BaseOfTester : TrueType {}; + +template +struct BaseOfTester : TrueType {}; + +#endif + +} /* namespace detail */ + +/* + * IsBaseOf allows to know whether a given class is derived from another. + * + * Consider the following class definitions: + * + * class A {}; + * class B : public A {}; + * class C {}; + * + * mozilla::IsBaseOf::value is true; + * mozilla::IsBaseOf::value is false; + */ +template +struct IsBaseOf + : IntegralConstant::value> +{}; + +namespace detail { + +template +struct ConvertibleTester +{ +private: + static From create(); + + template + static char test(To to); + + template + static int test(...); + +public: + static const bool value = + sizeof(test(create())) == sizeof(char); +}; + +} // namespace detail + +/** + * IsConvertible determines whether a value of type From will implicitly convert + * to a value of type To. For example: + * + * struct A {}; + * struct B : public A {}; + * struct C {}; + * + * mozilla::IsConvertible::value is true; + * mozilla::IsConvertible::value is true; + * mozilla::IsConvertible::value is true; + * mozilla::IsConvertible::value is true; + * mozilla::IsConvertible::value is false; + * mozilla::IsConvertible::value is false; + * mozilla::IsConvertible::value is false; + * mozilla::IsConvertible::value is false. + * + * For obscure reasons, you can't use IsConvertible when the types being tested + * are related through private inheritance, and you'll get a compile error if + * you try. Just don't do it! + * + * Note - we need special handling for void, which ConvertibleTester doesn't + * handle. The void handling here doesn't handle const/volatile void correctly, + * which could be easily fixed if the need arises. + */ +template +struct IsConvertible + : IntegralConstant::value> +{}; + +template +struct IsConvertible + : IntegralConstant::value> +{}; + +template +struct IsConvertible + : IntegralConstant::value> +{}; + +template<> +struct IsConvertible + : TrueType +{}; + +/* 20.9.7 Transformations between types [meta.trans] */ + +/* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ + +/** + * RemoveConst removes top-level const qualifications on a type. + * + * mozilla::RemoveConst::Type is int; + * mozilla::RemoveConst::Type is int; + * mozilla::RemoveConst::Type is const int*; + * mozilla::RemoveConst::Type is int*. + */ +template +struct RemoveConst +{ + typedef T Type; +}; + +template +struct RemoveConst +{ + typedef T Type; +}; + +/** + * RemoveVolatile removes top-level volatile qualifications on a type. + * + * mozilla::RemoveVolatile::Type is int; + * mozilla::RemoveVolatile::Type is int; + * mozilla::RemoveVolatile::Type is volatile int*; + * mozilla::RemoveVolatile::Type is int*. + */ +template +struct RemoveVolatile +{ + typedef T Type; +}; + +template +struct RemoveVolatile +{ + typedef T Type; +}; + +/** + * RemoveCV removes top-level const and volatile qualifications on a type. + * + * mozilla::RemoveCV::Type is int; + * mozilla::RemoveCV::Type is int; + * mozilla::RemoveCV::Type is int; + * mozilla::RemoveCV::Type is int*. + */ +template +struct RemoveCV +{ + typedef typename RemoveConst::Type>::Type Type; +}; + +/* 20.9.7.2 Reference modifications [meta.trans.ref] */ + +/** + * Converts reference types to the underlying types. + * + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + */ + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct Conditional; + +namespace detail { + +enum Voidness { TIsVoid, TIsNotVoid }; + +template::value ? TIsVoid : TIsNotVoid> +struct AddLvalueReferenceHelper; + +template +struct AddLvalueReferenceHelper +{ + typedef void Type; +}; + +template +struct AddLvalueReferenceHelper +{ + typedef T& Type; +}; + +} // namespace detail + +/** + * AddLvalueReference adds an lvalue & reference to T if one isn't already + * present. (Note: adding an lvalue reference to an rvalue && reference in + * essence replaces the && with a &&, per C+11 reference collapsing rules. For + * example, int&& would become int&.) + * + * The final computed type will only *not* be an lvalue reference if T is void. + * + * mozilla::AddLvalueReference::Type is int&; + * mozilla::AddLvalueRference::Type is volatile int&; + * mozilla::AddLvalueReference::Type is void*&; + * mozilla::AddLvalueReference::Type is void; + * mozilla::AddLvalueReference::Type is struct S&. + */ +template +struct AddLvalueReference + : detail::AddLvalueReferenceHelper +{}; + +namespace detail { + +template::value ? TIsVoid : TIsNotVoid> +struct AddRvalueReferenceHelper; + +template +struct AddRvalueReferenceHelper +{ + typedef void Type; +}; + +template +struct AddRvalueReferenceHelper +{ + typedef T&& Type; +}; + +} // namespace detail + +/** + * AddRvalueReference adds an rvalue && reference to T if one isn't already + * present. (Note: adding an rvalue reference to an lvalue & reference in + * essence keeps the &, per C+11 reference collapsing rules. For example, + * int& would remain int&.) + * + * The final computed type will only *not* be a reference if T is void. + * + * mozilla::AddRvalueReference::Type is int&&; + * mozilla::AddRvalueRference::Type is volatile int&; + * mozilla::AddRvalueRference::Type is const int&&; + * mozilla::AddRvalueReference::Type is void*&&; + * mozilla::AddRvalueReference::Type is void; + * mozilla::AddRvalueReference::Type is struct S&. + */ +template +struct AddRvalueReference + : detail::AddRvalueReferenceHelper +{}; + +/* 20.2.4 Function template declval [declval] */ + +/** + * DeclVal simplifies the definition of expressions which occur as unevaluated + * operands. It converts T to a reference type, making it possible to use in + * decltype expressions even if T does not have a default constructor, e.g.: + * decltype(DeclVal().foo()) + */ +template +typename AddRvalueReference::Type DeclVal(); + +/* 20.9.7.3 Sign modifications [meta.trans.sign] */ + +template +struct EnableIf; + +namespace detail { + +template +struct WithC : Conditional +{}; + +template +struct WithV : Conditional +{}; + + +template +struct WithCV : WithC::Type> +{}; + +template +struct CorrespondingSigned; + +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef signed char Type; }; +template<> +struct CorrespondingSigned { typedef short Type; }; +template<> +struct CorrespondingSigned { typedef int Type; }; +template<> +struct CorrespondingSigned { typedef long Type; }; +template<> +struct CorrespondingSigned { typedef long long Type; }; + +template::Type, + bool IsSignedIntegerType = IsSigned::value && + !IsSame::value> +struct MakeSigned; + +template +struct MakeSigned +{ + typedef T Type; +}; + +template +struct MakeSigned + : WithCV::value, IsVolatile::value, + typename CorrespondingSigned::Type> +{}; + +} // namespace detail + +/** + * MakeSigned produces the corresponding signed integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already a signed integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is an unsigned integer type, the signed variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the integral type of the same size as T, with the lowest rank, + * with T's const/volatile qualifiers, is produced. (This basically only acts + * to produce signed char when T = char.) + * + * mozilla::MakeSigned::Type is signed long; + * mozilla::MakeSigned::Type is volatile int; + * mozilla::MakeSigned::Type is const signed short; + * mozilla::MakeSigned::Type is const signed char; + * mozilla::MakeSigned is an error; + * mozilla::MakeSigned is an error. + */ +template +struct MakeSigned + : EnableIf::value && + !IsSame::Type>::value, + typename detail::MakeSigned + >::Type +{}; + +namespace detail { + +template +struct CorrespondingUnsigned; + +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned char Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned short Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned int Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long Type; }; +template<> +struct CorrespondingUnsigned { typedef unsigned long long Type; }; + + +template::Type, + bool IsUnsignedIntegerType = IsUnsigned::value && + !IsSame::value> +struct MakeUnsigned; + +template +struct MakeUnsigned +{ + typedef T Type; +}; + +template +struct MakeUnsigned + : WithCV::value, IsVolatile::value, + typename CorrespondingUnsigned::Type> +{}; + +} // namespace detail + +/** + * MakeUnsigned produces the corresponding unsigned integer type for a given + * integral type T, with the const/volatile qualifiers of T. T must be a + * possibly-const/volatile-qualified integral type that isn't bool. + * + * If T is already an unsigned integer type (not including char!), then T is + * produced. + * + * Otherwise, if T is a signed integer type, the unsigned variety of T, with + * T's const/volatile qualifiers, is produced. + * + * Otherwise, the unsigned integral type of the same size as T, with the lowest + * rank, with T's const/volatile qualifiers, is produced. (This basically only + * acts to produce unsigned char when T = char.) + * + * mozilla::MakeUnsigned::Type is unsigned long; + * mozilla::MakeUnsigned::Type is volatile unsigned int; + * mozilla::MakeUnsigned::Type is const unsigned short; + * mozilla::MakeUnsigned::Type is const unsigned char; + * mozilla::MakeUnsigned is an error; + * mozilla::MakeUnsigned is an error. + */ +template +struct MakeUnsigned + : EnableIf::value && + !IsSame::Type>::value, + typename detail::MakeUnsigned + >::Type +{}; + +/* 20.9.7.4 Array modifications [meta.trans.arr] */ + +/** + * RemoveExtent produces either the type of the elements of the array T, or T + * itself. + * + * mozilla::RemoveExtent::Type is int; + * mozilla::RemoveExtent::Type is const int; + * mozilla::RemoveExtent::Type is volatile int; + * mozilla::RemoveExtent::Type is long[17]. + */ +template +struct RemoveExtent +{ + typedef T Type; +}; + +template +struct RemoveExtent +{ + typedef T Type; +}; + +template +struct RemoveExtent +{ + typedef T Type; +}; + +/* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ + +namespace detail { + +template +struct RemovePointerHelper +{ + typedef T Type; +}; + +template +struct RemovePointerHelper +{ + typedef Pointee Type; +}; + +} // namespace detail + +/** + * Produces the pointed-to type if a pointer is provided, else returns the input + * type. Note that this does not dereference pointer-to-member pointers. + * + * struct S { bool m; void f(); }; + * mozilla::RemovePointer::Type is int; + * mozilla::RemovePointer::Type is int; + * mozilla::RemovePointer::Type is int; + * mozilla::RemovePointer::Type is int; + * mozilla::RemovePointer::Type is const long; + * mozilla::RemovePointer::Type is void; + * mozilla::RemovePointer::Type is void (S::*)(); + * mozilla::RemovePointer::Type is void(); + * mozilla::RemovePointer::Type is bool S::*. + */ +template +struct RemovePointer + : detail::RemovePointerHelper::Type> +{}; + +/* 20.9.7.6 Other transformations [meta.trans.other] */ + +/** + * EnableIf is a struct containing a typedef of T if and only if B is true. + * + * mozilla::EnableIf::Type is int; + * mozilla::EnableIf::Type is a compile-time error. + * + * Use this template to implement SFINAE-style (Substitution Failure Is not An + * Error) requirements. For example, you might use it to impose a restriction + * on a template parameter: + * + * template + * class PodVector // vector optimized to store POD (memcpy-able) types + * { + * EnableIf::value, T>::Type* vector; + * size_t length; + * ... + * }; + */ +template +struct EnableIf +{}; + +template +struct EnableIf +{ + typedef T Type; +}; + +/** + * Conditional selects a class between two, depending on a given boolean value. + * + * mozilla::Conditional::Type is A; + * mozilla::Conditional::Type is B; + */ +template +struct Conditional +{ + typedef A Type; +}; + +template +struct Conditional +{ + typedef B Type; +}; + +} /* namespace mozilla */ + +#endif /* mozilla_TypeTraits_h */ diff --git a/include/onlineupdate/mozilla/Types.h b/include/onlineupdate/mozilla/Types.h new file mode 100644 index 000000000..9d1e34b6d --- /dev/null +++ b/include/onlineupdate/mozilla/Types.h @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* mfbt foundational types and macros. */ + +#ifndef mozilla_Types_h +#define mozilla_Types_h + +/* + * This header must be valid C and C++, includable by code embedding either + * SpiderMonkey or Gecko. + */ + +/* Expose all types and size_t. */ +#include +#include + +/* Implement compiler and linker macros needed for APIs. */ + +/* + * MOZ_EXPORT is used to declare and define a symbol or type which is externally + * visible to users of the current library. It encapsulates various decorations + * needed to properly export the method's symbol. + * + * api.h: + * extern MOZ_EXPORT int MeaningOfLife(void); + * extern MOZ_EXPORT int LuggageCombination; + * + * api.c: + * int MeaningOfLife(void) { return 42; } + * int LuggageCombination = 12345; + * + * If you are merely sharing a method across files, just use plain |extern|. + * These macros are designed for use by library interfaces -- not for normal + * methods or data used cross-file. + */ +#if defined(_WIN32) +# define MOZ_EXPORT __declspec(dllexport) +#else /* Unix */ +# ifdef HAVE_VISIBILITY_ATTRIBUTE +# define MOZ_EXPORT __attribute__((visibility("default"))) +# elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# define MOZ_EXPORT __global +# else +# define MOZ_EXPORT /* nothing */ +# endif +#endif + + +/* + * Whereas implementers use MOZ_EXPORT to declare and define library symbols, + * users use MOZ_IMPORT_API and MOZ_IMPORT_DATA to access them. Most often the + * implementer of the library will expose an API macro which expands to either + * the export or import version of the macro, depending upon the compilation + * mode. + */ +#ifdef _WIN32 +# if defined(__MWERKS__) +# define MOZ_IMPORT_API /* nothing */ +# else +# define MOZ_IMPORT_API __declspec(dllimport) +# endif +#else +# define MOZ_IMPORT_API MOZ_EXPORT +#endif + +#if defined(_WIN32) && !defined(__MWERKS__) +# define MOZ_IMPORT_DATA __declspec(dllimport) +#else +# define MOZ_IMPORT_DATA MOZ_EXPORT +#endif + +/* + * Consistent with the above comment, the MFBT_API and MFBT_DATA macros expose + * export mfbt declarations when building mfbt, and they expose import mfbt + * declarations when using mfbt. + */ +#if defined(IMPL_MFBT) +# define MFBT_API MOZ_EXPORT +# define MFBT_DATA MOZ_EXPORT +#else + /* + * On linux mozglue is linked in the program and we link libxul.so with + * -z,defs. Normally that causes the linker to reject undefined references in + * libxul.so, but as a loophole it allows undefined references to weak + * symbols. We add the weak attribute to the import version of the MFBT API + * macros to exploit this. + */ +# if defined(MOZ_GLUE_IN_PROGRAM) && !defined(MOZILLA_XPCOMRT_API) +# define MFBT_API __attribute__((weak)) MOZ_IMPORT_API +# define MFBT_DATA __attribute__((weak)) MOZ_IMPORT_DATA +# else +# define MFBT_API MOZ_IMPORT_API +# define MFBT_DATA MOZ_IMPORT_DATA +# endif +#endif + +/* + * C symbols in C++ code must be declared immediately within |extern "C"| + * blocks. However, in C code, they need not be declared specially. This + * difference is abstracted behind the MOZ_BEGIN_EXTERN_C and MOZ_END_EXTERN_C + * macros, so that the user need not know whether he is being used in C or C++ + * code. + * + * MOZ_BEGIN_EXTERN_C + * + * extern MOZ_EXPORT int MostRandomNumber(void); + * ...other declarations... + * + * MOZ_END_EXTERN_C + * + * This said, it is preferable to just use |extern "C"| in C++ header files for + * its greater clarity. + */ +#ifdef __cplusplus +# define MOZ_BEGIN_EXTERN_C extern "C" { +# define MOZ_END_EXTERN_C } +#else +# define MOZ_BEGIN_EXTERN_C +# define MOZ_END_EXTERN_C +#endif + +/* + * GCC's typeof is available when decltype is not. + */ +#if defined(__GNUC__) && defined(__cplusplus) && \ + !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L +# define decltype __typeof__ +#endif + +#endif /* mozilla_Types_h */ diff --git a/include/onlineupdate/mozilla/nsTraceRefcnt.h b/include/onlineupdate/mozilla/nsTraceRefcnt.h new file mode 100644 index 000000000..c5b1de7e8 --- /dev/null +++ b/include/onlineupdate/mozilla/nsTraceRefcnt.h @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +#ifndef nsTraceRefcnt_h___ +#define nsTraceRefcnt_h___ + +#include // for FILE +#include "nscore.h" + +class nsTraceRefcnt +{ +public: + static void Shutdown(); + + enum StatisticsType { + ALL_STATS, + NEW_STATS + }; + + static nsresult DumpStatistics(StatisticsType aType = ALL_STATS, + FILE* aOut = 0); + + static void ResetStatistics(); + + static void DemangleSymbol(const char* aSymbol, char* aBuffer, int aBufLen); + + static void WalkTheStack(FILE* aStream); + + /** + * This is a variant of |WalkTheStack| that uses |CodeAddressService| to cache + * the results of |NS_DescribeCodeAddress|. If |WalkTheStackCached| is being + * called frequently, it will be a few orders of magnitude faster than + * |WalkTheStack|. However, the cache uses a lot of memory, which can cause + * OOM crashes. Therefore, this should only be used for things like refcount + * logging which walk the stack extremely frequently. + */ + static void WalkTheStackCached(FILE* aStream); + + /** + * Tell nsTraceRefcnt whether refcounting, allocation, and destruction + * activity is legal. This is used to trigger assertions for any such + * activity that occurs because of static constructors or destructors. + */ + static void SetActivityIsLegal(bool aLegal); +}; + +#define NS_TRACE_REFCNT_CONTRACTID "@mozilla.org/xpcom/trace-refcnt;1" +#define NS_TRACE_REFCNT_CID \ +{ /* e3e7511e-a395-4924-94b1-d527861cded4 */ \ + 0xe3e7511e, \ + 0xa395, \ + 0x4924, \ + {0x94, 0xb1, 0xd5, 0x27, 0x86, 0x1c, 0xde, 0xd4} \ +} \ + +//////////////////////////////////////////////////////////////////////////////// +// And now for that utility that you've all been asking for... + +extern "C" void +NS_MeanAndStdDev(double aNumberOfValues, + double aSumOfValues, double aSumOfSquaredValues, + double* aMeanResult, double* aStdDevResult); + +//////////////////////////////////////////////////////////////////////////////// +#endif diff --git a/include/oox/core/binarycodec.hxx b/include/oox/core/binarycodec.hxx new file mode 100644 index 000000000..e7bfbaaa4 --- /dev/null +++ b/include/oox/core/binarycodec.hxx @@ -0,0 +1,42 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_BINARYCODEC_HXX +#define INCLUDED_OOX_CORE_BINARYCODEC_HXX + +#include + +#include +#include + +namespace com::sun::star { + namespace beans { struct NamedValue; } +} + +namespace oox { class AttributeList; } + +namespace oox::core::CodecHelper +{ + /** Returns the password hash if it is in the required 16-bit limit. */ + OOX_DLLPUBLIC sal_uInt16 getPasswordHash( const AttributeList& rAttribs, sal_Int32 nElement ); +} // namespace oox::core::CodecHelper + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/contexthandler.hxx b/include/oox/core/contexthandler.hxx new file mode 100644 index 000000000..503b36d0c --- /dev/null +++ b/include/oox/core/contexthandler.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_CONTEXTHANDLER_HXX +#define INCLUDED_OOX_CORE_CONTEXTHANDLER_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace xml::sax { class XFastAttributeList; } + namespace xml::sax { class XLocator; } +} + +namespace oox { class SequenceInputStream; } + +namespace oox::core { + +class XmlFilterBase; +struct Relation; +class Relations; + +class ContextHandler; +typedef ::rtl::Reference< ContextHandler > ContextHandlerRef; + +struct FragmentBaseData; +typedef std::shared_ptr< FragmentBaseData > FragmentBaseDataRef; + +typedef ::cppu::WeakImplHelper< css::xml::sax::XFastContextHandler > ContextHandler_BASE; + +class OOX_DLLPUBLIC ContextHandler : public ContextHandler_BASE +{ +public: + explicit ContextHandler( const ContextHandler& rParent ); + virtual ~ContextHandler() override; + + /** Returns the filter instance. */ + XmlFilterBase& getFilter() const; + /** Returns the relations of the current fragment. */ + const Relations& getRelations() const; + /** Returns the full path of the current fragment. */ + const OUString& getFragmentPath() const; + + /** Returns the full fragment path for the target of the passed relation. */ + OUString getFragmentPathFromRelation( const Relation& rRelation ) const; + /** Returns the full fragment path for the passed relation identifier. */ + OUString getFragmentPathFromRelId( const OUString& rRelId ) const; + /** Returns the full fragment path for the first relation of the passed type. */ + OUString getFragmentPathFromFirstType( std::u16string_view rType ) const; + OUString getFragmentPathFromFirstTypeFromOfficeDoc( std::u16string_view rType ) const; + + // com.sun.star.xml.sax.XFastContextHandler interface --------------------- + + virtual void SAL_CALL startFastElement( ::sal_Int32 Element, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL startUnknownElement( const OUString& Namespace, const OUString& Name, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL endFastElement( ::sal_Int32 Element ) override; + virtual void SAL_CALL endUnknownElement( const OUString& Namespace, const OUString& Name ) override; + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext( const OUString& Namespace, const OUString& Name, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL characters( const OUString& aChars ) override; + + // record context interface ----------------------------------------------- + + virtual ContextHandlerRef createRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ); + virtual void startRecord( sal_Int32 nRecId, SequenceInputStream& rStrm ); + virtual void endRecord( sal_Int32 nRecId ); + +protected: + /** Helper constructor for the FragmentHandler. */ + explicit ContextHandler( const FragmentBaseDataRef& rxBaseData ); + + void implSetLocator( const css::uno::Reference< css::xml::sax::XLocator >& rxLocator ); + +#ifdef _MSC_VER + ContextHandler() {} // workaround +#endif + +private: + ContextHandler& operator=( const ContextHandler& ) = delete; + +private: + FragmentBaseDataRef mxBaseData; ///< Base data of the fragment. +}; + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/contexthandler2.hxx b/include/oox/core/contexthandler2.hxx new file mode 100644 index 000000000..9843a40e9 --- /dev/null +++ b/include/oox/core/contexthandler2.hxx @@ -0,0 +1,291 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_CONTEXTHANDLER2_HXX +#define INCLUDED_OOX_CORE_CONTEXTHANDLER2_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace xml::sax { class XFastAttributeList; } + namespace xml::sax { class XFastContextHandler; } +} + +namespace oox { + class AttributeList; + class SequenceInputStream; +} + +namespace oox::core { + +const sal_Int32 XML_ROOT_CONTEXT = SAL_MAX_INT32; + +struct ElementInfo; + +/** Helper class that provides a context stack. + + Fragment handlers and context handlers derived from this helper class will + track the identifiers of the visited elements in a stack. The idea is to + use the same instance of a fragment handler or context handler to process + several nested elements in an XML stream. For that, the abstract function + onCreateContext() has to return 'this' for the passed element. + + Derived classes have to implement the createFastChildContext(), + startFastElement(), characters(), and endFastElement() functions from the + com.sun.star.xml.sax.XFastContextHandler interface by simply forwarding + them to the respective implCreateChildContext(), implStartElement(), + implCharacters(), and implEndElement() functions of this helper. This is + implemented already in the classes ContextHandler2 and FragmentHandler2. + The new abstract functions have to be implemented according to the elements + to be processed. + + Similarly, for binary import, derived classes have to forward the + createRecordContext(), startRecord(), and endRecord() functions from the + ContextHandler class to the implCreateRecordContext(), implStartRecord(), + and implEndRecord() functions of this helper. Again, this is implemented + already in the classes ContextHandler2 and FragmentHandler2. + */ +class OOX_DLLPUBLIC ContextHandler2Helper +{ +public: + explicit ContextHandler2Helper( bool bEnableTrimSpace, XmlFilterBase& rFilter ); + explicit ContextHandler2Helper( const ContextHandler2Helper& rParent ); + virtual ~ContextHandler2Helper(); + + // allow instances to be stored in ::rtl::Reference + virtual void SAL_CALL acquire() noexcept = 0; + virtual void SAL_CALL release() noexcept = 0; + + // interface -------------------------------------------------------------- + + /** Will be called to create a context handler for the passed element. + + Usually 'this' can be returned to improve performance by reusing the + same instance to process several elements. Used by OOXML import only. + */ + virtual ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) = 0; + + /** Will be called when a new element has been started. + + This function is called at the context handler returned from + onCreateContext(), or, for root elements of an XML stream, at the + fragment handler itself. + + The current element identifier can be accessed with getCurrentElement() + or isCurrentElement(). Used by OOXML import only. + */ + virtual void onStartElement( const AttributeList& rAttribs ) = 0; + + /** Will be called before a new child element starts, or if the current + element is about to be left. + + This helper function collects all text fragments received by the + characters() function (such as encoded characters which are passed in + separate calls to the characters() function), and passes the + concatenated and trimmed string. + + The current element identifier can be accessed with getCurrentElement() + or isCurrentElement(). Used by OOXML import only. + */ + virtual void onCharacters( const OUString& rChars ) = 0; + + /** Will be called when the current element is about to be left. + + The current element identifier can be accessed with getCurrentElement() + or isCurrentElement(). Used by OOXML import only. + */ + virtual void onEndElement() = 0; + + /** Will be called to create a context handler for the passed record. + + Usually 'this' can be returned to improve performance by reusing the + same instance to process several records. Used by BIFF import only. + */ + virtual ContextHandlerRef onCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ) = 0; + + /** Will be called when a new record block in a binary stream has been + started. + + The current record identifier can be accessed with getCurrentElement() + or isCurrentElement(). Used by BIFF import only. + */ + virtual void onStartRecord( SequenceInputStream& rStrm ) = 0; + + /** Will be called when the current record block is about to be left. + + The current record identifier can be accessed with getCurrentElement() + or isCurrentElement(). Used by BIFF import only. + */ + virtual void onEndRecord() = 0; + + // helpers ---------------------------------------------------------------- + + /** Returns the identifier of the currently processed element. Ignores MCE elements in stack */ + sal_Int32 getCurrentElement() const; + + /** Returns the identifier of the currently processed element - Including MCE root elements */ + sal_Int32 getCurrentElementWithMce() const; + + /** Returns true, if nElement contains the identifier of the currently + processed element. */ + bool isCurrentElement( sal_Int32 nElement ) const + { return getCurrentElement() == nElement; } + + /** Returns true, if either nElement1 or nElement2 contain the identifier + of the currently processed element. */ + bool isCurrentElement( sal_Int32 nElement1, sal_Int32 nElement2 ) const + { return isCurrentElement( nElement1 ) || isCurrentElement( nElement2 ); } + + /** Returns the identifier of the specified parent element. */ + sal_Int32 getParentElement( sal_Int32 nCountBack = 1 ) const; + + /** Returns true, if nElement contains the identifier of the specified + parent element. */ + bool isParentElement( sal_Int32 nElement, sal_Int32 nCountBack = 1 ) const + { return getParentElement( nCountBack ) == nElement; } + + /** Returns true, if the element currently processed is the root element of + the context or fragment handler. */ + bool isRootElement() const; + + // implementation --------------------------------------------------------- + +protected: + /** Must be called from createFastChildContext() in derived classes. */ + css::uno::Reference< css::xml::sax::XFastContextHandler > + implCreateChildContext( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ); + + /** Must be called from startFastElement() in derived classes. */ + void implStartElement( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ); + + /** Must be called from characters() in derived classes. */ + void implCharacters( std::u16string_view rChars ); + + /** Must be called from endFastElement() in derived classes. */ + void implEndElement( sal_Int32 nElement ); + + /** Must be called from createRecordContext() in derived classes. */ + ContextHandlerRef implCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ); + + /** Must be called from startRecord() in derived classes. */ + void implStartRecord( sal_Int32 nRecId, SequenceInputStream& rStrm ); + + /** Must be called from endRecord() in derived classes. */ + void implEndRecord( sal_Int32 nRecId ); + + bool prepareMceContext( sal_Int32 nElement, const AttributeList& rAttribs ); + XmlFilterBase& getDocFilter() const { return mrFilter; } + + enum class MCE_STATE + { + Started, + FoundChoice + }; + + MCE_STATE getMCEState() const { return aMceState.back(); } + void setMCEState( MCE_STATE aState ) { aMceState.back() = aState; } + void addMCEState( MCE_STATE aState ) { aMceState.push_back( aState ); } + void removeMCEState() { aMceState.pop_back(); } + bool isMCEStateEmpty() const { return aMceState.empty(); } + +private: + ContextHandler2Helper& operator=( const ContextHandler2Helper& ) = delete; + + ElementInfo& pushElementInfo( sal_Int32 nElement ); + void popElementInfo(); + void processCollectedChars(); + +private: + typedef std::vector< ElementInfo > ContextStack; + typedef std::shared_ptr< ContextStack > ContextStackRef; + + ContextStackRef mxContextStack; ///< Stack of all processed elements. + size_t mnRootStackSize; ///< Stack size on construction time. + std::vector aMceState; + +protected: + bool mbEnableTrimSpace; ///< True = trim whitespace in characters(). + XmlFilterBase& mrFilter; +}; + +class OOX_DLLPUBLIC ContextHandler2 : public ContextHandler, public ContextHandler2Helper +{ +public: + explicit ContextHandler2( ContextHandler2Helper const & rParent ); + virtual ~ContextHandler2() override; + + ContextHandler2(ContextHandler2 const &) = default; + ContextHandler2(ContextHandler2 &&) = default; + ContextHandler2 & operator =(ContextHandler2 const &) = delete; // due to ContextHandler + ContextHandler2 & operator =(ContextHandler2 &&) = delete; // due to ContextHandler + + // resolve ambiguity from base classes + virtual void SAL_CALL acquire() noexcept override { ContextHandler::acquire(); } + virtual void SAL_CALL release() noexcept override { ContextHandler::release(); } + + // com.sun.star.xml.sax.XFastContextHandler interface --------------------- + + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL + createFastChildContext( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ) final override; + + virtual void SAL_CALL startFastElement( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ) final override; + + virtual void SAL_CALL characters( const OUString& rChars ) final override; + + virtual void SAL_CALL endFastElement( sal_Int32 nElement ) final override; + + // oox.core.ContextHandler interface -------------------------------------- + + virtual ContextHandlerRef createRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ) override; + virtual void startRecord( sal_Int32 nRecId, SequenceInputStream& rStrm ) override; + virtual void endRecord( sal_Int32 nRecId ) override; + + // oox.core.ContextHandler2Helper interface ------------------------------- + + virtual ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + virtual void onStartElement( const AttributeList& rAttribs ) override; + virtual void onCharacters( const OUString& rChars ) override; + virtual void onEndElement() override; + + virtual ContextHandlerRef onCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ) override; + virtual void onStartRecord( SequenceInputStream& rStrm ) override; + virtual void onEndRecord() override; +}; + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/fastparser.hxx b/include/oox/core/fastparser.hxx new file mode 100644 index 000000000..058bd344b --- /dev/null +++ b/include/oox/core/fastparser.hxx @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_FASTPARSER_HXX +#define INCLUDED_OOX_CORE_FASTPARSER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XInputStream; } + namespace uno { class XComponentContext; } + namespace xml::sax { class XFastDocumentHandler; } + namespace xml::sax { class XFastParser; } + namespace xml::sax { class XFastTokenHandler; } + namespace xml::sax { struct InputSource; } +} + +namespace oox { + struct NamespaceMap; + class StorageBase; +} + +namespace sax_fastparser { + class FastSaxParser; +} + +namespace oox::core { + + +/** Wrapper for a fast SAX parser that works on automatically generated OOXML + token and namespace identifiers. + */ +class OOX_DLLPUBLIC FastParser +{ +public: + /// @throws css::uno::RuntimeException + explicit FastParser(); + + FastParser(const FastParser&) = delete; + FastParser& operator=(const FastParser&) = delete; + + ~FastParser(); + + /** Registers an OOXML namespace at the parser. + @throws css::lang::IllegalArgumentException + @throws css::uno::RuntimeException + */ + void registerNamespace( sal_Int32 nNamespaceId ); + + /** Sets the passed document handler that will receive the SAX parser events. + @throws css::uno::RuntimeException + */ + void setDocumentHandler( + const css::uno::Reference< css::xml::sax::XFastDocumentHandler >& rxDocHandler ); + + void clearDocumentHandler(); + + /** Parses the passed SAX input source. + @param bCloseStream True = closes the stream in the input source after parsing. + @throws css::xml::sax::SAXException + @throws css::io::IOException + @throws css::uno::RuntimeException + */ + void parseStream( const css::xml::sax::InputSource& rInputSource, bool bCloseStream = false ); + + /** Parses the passed input stream. + @param bCloseStream True = closes the passed stream after parsing. + @throws css::xml::sax::SAXException + @throws css::io::IOException + @throws css::uno::RuntimeException + */ + void parseStream( + const css::uno::Reference< css::io::XInputStream >& rxInStream, + const OUString& rStreamName ); + + /** Parses a stream from the passed storage with the specified name. + @param bCloseStream True = closes the stream after parsing. + @throws css::xml::sax::SAXException + @throws css::io::IOException + @throws css::uno::RuntimeException + */ + void parseStream( StorageBase& rStorage, const OUString& rStreamName ); + + const css::uno::Reference< css::xml::sax::XFastTokenHandler >& + getTokenHandler() const { return mxTokenHandler; } + +private: + css::uno::Reference mxTokenHandler; + const NamespaceMap& mrNamespaceMap; + rtl::Reference mxParser; +}; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/fasttokenhandler.hxx b/include/oox/core/fasttokenhandler.hxx new file mode 100644 index 000000000..396474b98 --- /dev/null +++ b/include/oox/core/fasttokenhandler.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_FASTTOKENHANDLER_HXX +#define INCLUDED_OOX_CORE_FASTTOKENHANDLER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace oox { class TokenMap; } + +namespace oox::core { + + +/** Wrapper implementing the com.sun.star.xml.sax.XFastTokenHandler API interface + that provides access to the tokens generated from the internal token name list. + */ +class OOX_DLLPUBLIC FastTokenHandler final : + public cppu::ImplInheritanceHelper< sax_fastparser::FastTokenHandlerBase, css::lang::XServiceInfo > +{ +public: + explicit FastTokenHandler(); + virtual ~FastTokenHandler() override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + + // XFastTokenHandler + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getUTF8Identifier( sal_Int32 nToken ) override; + virtual sal_Int32 SAL_CALL getTokenFromUTF8( const css::uno::Sequence< sal_Int8 >& Identifier ) override; + + // Much faster direct C++ shortcut to the method that matters + virtual sal_Int32 getTokenDirect( const char *pToken, sal_Int32 nLength ) const override; + +private: + const TokenMap& mrTokenMap; ///< Reference to global token map singleton. +}; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/filterbase.hxx b/include/oox/core/filterbase.hxx new file mode 100644 index 000000000..73b8e2d8e --- /dev/null +++ b/include/oox/core/filterbase.hxx @@ -0,0 +1,274 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_FILTERBASE_HXX +#define INCLUDED_OOX_CORE_FILTERBASE_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { struct PropertyValue; } + namespace drawing { class XShape; } + namespace frame { class XFrame; } + namespace frame { class XModel; } + namespace io { class XInputStream; } + namespace io { class XOutputStream; } + namespace io { class XStream; } + namespace lang { class XComponent; } + namespace lang { class XMultiServiceFactory; } + namespace task { class XStatusIndicator; } + namespace uno { class XComponentContext; } +} + +namespace comphelper { + class SequenceAsHashMap; +} +namespace utl { + class MediaDescriptor; +} + +namespace oox { + class GraphicHelper; + class ModelObjectHelper; +} + +namespace oox::ole { + class OleObjectHelper; + class VbaProject; +} + +namespace oox::core { + +enum OoxmlVersion +{ + ECMA_DIALECT, + ISOIEC_29500_2008 +}; + +struct FilterBaseImpl; + +typedef ::cppu::WeakImplHelper< + css::lang::XServiceInfo, + css::lang::XInitialization, + css::document::XImporter, + css::document::XExporter, + css::document::XFilter > + FilterBase_BASE; + +class OOX_DLLPUBLIC FilterBase : public FilterBase_BASE, public ::cppu::BaseMutex +{ +public: + /// @throws css::uno::RuntimeException + explicit FilterBase( + const css::uno::Reference< css::uno::XComponentContext >& rxContext ); + + virtual ~FilterBase() override; + + /** Returns true, if filter is an import filter. */ + bool isImportFilter() const; + /** Returns true, if filter is an export filter. */ + bool isExportFilter() const; + + OoxmlVersion getVersion() const; + + /** Derived classes implement import of the entire document. */ + virtual bool importDocument() = 0; + + /** Derived classes implement export of the entire document. */ + virtual bool exportDocument() = 0; + + + /** Returns the component context passed in the filter constructor (always existing). */ + const css::uno::Reference< css::uno::XComponentContext >& + getComponentContext() const; + + /** Returns the document model (always existing). */ + const css::uno::Reference< css::frame::XModel >& + getModel() const; + + /** Returns the service factory provided by the document model (always existing). */ + const css::uno::Reference< css::lang::XMultiServiceFactory >& + getModelFactory() const; + + /** Returns the frame that will contain the document model (may be null). */ + const css::uno::Reference< css::frame::XFrame >& + getTargetFrame() const; + + /** Returns the status indicator (may be null). */ + const css::uno::Reference< css::task::XStatusIndicator >& + getStatusIndicator() const; + + /** Returns the FilterData */ + ::comphelper::SequenceAsHashMap& getFilterData() const; + + /** Returns the media descriptor. */ + utl::MediaDescriptor& getMediaDescriptor() const; + + /** Returns the URL of the imported or exported file. */ + const OUString& getFileUrl() const; + + /** Returns an absolute URL for the passed relative or absolute URL. */ + OUString getAbsoluteUrl( const OUString& rUrl ) const; + + /** Returns the base storage of the imported/exported file. */ + StorageRef const & getStorage() const; + + /** Opens and returns the specified input stream from the base storage. + + @param rStreamName + The name of the embedded storage stream. The name may contain + slashes to open streams from embedded substorages. If base stream + access has been enabled in the storage, the base stream can be + accessed by passing an empty string as stream name. + */ + css::uno::Reference< css::io::XInputStream > + openInputStream( const OUString& rStreamName ) const; + + /** Opens and returns the specified output stream from the base storage. + + @param rStreamName + The name of the embedded storage stream. The name may contain + slashes to open streams from embedded substorages. If base stream + access has been enabled in the storage, the base stream can be + accessed by passing an empty string as stream name. + */ + css::uno::Reference< css::io::XOutputStream > + openOutputStream( const OUString& rStreamName ) const; + + /** Commits changes to base storage (and substorages) */ + void commitStorage() const; + + // helpers ---------------------------------------------------------------- + + /** Returns a helper for the handling of graphics and graphic objects. */ + GraphicHelper& getGraphicHelper() const; + + /** Returns a helper with containers for various named drawing objects for + the imported document. */ + ModelObjectHelper& getModelObjectHelper() const; + + ModelObjectHelper& getModelObjectHelperForModel( + const css::uno::Reference& xFactory) const; + + /** Returns a helper for the handling of OLE objects. */ + ::oox::ole::OleObjectHelper& getOleObjectHelper() const; + + /** Returns the VBA project manager. */ + ::oox::ole::VbaProject& getVbaProject() const; + + /** Imports the raw binary data from the specified stream. + @return True, if the data could be imported from the stream. */ + bool importBinaryData( StreamDataSequence & orDataSeq, const OUString& rStreamName ); + + // com.sun.star.lang.XServiceInfo interface ------------------------------- + + virtual sal_Bool SAL_CALL + supportsService( const OUString& rServiceName ) override; + + virtual css::uno::Sequence< OUString > SAL_CALL + getSupportedServiceNames() override; + + // com.sun.star.lang.XInitialization interface ---------------------------- + + /** Receives user defined arguments. + + @param rArgs + the sequence of arguments passed to the filter. The implementation + expects one or two arguments. The first argument shall be the + com.sun.star.lang.XMultiServiceFactory interface of the global + service factory. The optional second argument may contain a + sequence of com.sun.star.beans.NamedValue objects. The different + filter implementations may support different arguments. + */ + virtual void SAL_CALL initialize( + const css::uno::Sequence< css::uno::Any >& rArgs ) override; + + // com.sun.star.document.XImporter interface ------------------------------ + + virtual void SAL_CALL setTargetDocument( + const css::uno::Reference< css::lang::XComponent >& rxDocument ) override; + + // com.sun.star.document.XExporter interface ------------------------------ + + virtual void SAL_CALL setSourceDocument( + const css::uno::Reference< css::lang::XComponent >& rxDocument ) override; + + // com.sun.star.document.XFilter interface -------------------------------- + + virtual sal_Bool SAL_CALL filter( + const css::uno::Sequence< css::beans::PropertyValue >& rMediaDescSeq ) override; + + virtual void SAL_CALL cancel() override; + + bool exportVBA() const; + + bool isExportTemplate() const; + +protected: + virtual css::uno::Reference< css::io::XInputStream > + implGetInputStream( utl::MediaDescriptor& rMediaDesc ) const; + virtual css::uno::Reference< css::io::XStream > + implGetOutputStream( utl::MediaDescriptor& rMediaDesc ) const; + + virtual bool implFinalizeExport( utl::MediaDescriptor& rMediaDescriptor ); + + css::uno::Reference< css::io::XStream > const & + getMainDocumentStream( ) const; + +private: + void setMediaDescriptor( + const css::uno::Sequence< css::beans::PropertyValue >& rMediaDescSeq ); + + /** Derived classes may create a specialized graphic helper, e.g. for + resolving palette colors. */ + virtual GraphicHelper* implCreateGraphicHelper() const; + + /** Derived classes create a VBA project manager object. */ + virtual ::oox::ole::VbaProject* implCreateVbaProject() const = 0; + + virtual StorageRef implCreateStorage( + const css::uno::Reference< css::io::XInputStream >& rxInStream ) const = 0; + virtual StorageRef implCreateStorage( + const css::uno::Reference< css::io::XStream >& rxOutStream ) const = 0; + +private: + std::unique_ptr< FilterBaseImpl > mxImpl; +}; + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/filterdetect.hxx b/include/oox/core/filterdetect.hxx new file mode 100644 index 000000000..ec0cd81a5 --- /dev/null +++ b/include/oox/core/filterdetect.hxx @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_FILTERDETECT_HXX +#define INCLUDED_OOX_CORE_FILTERDETECT_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { struct PropertyValue; } + namespace io { class XInputStream; } + namespace uno { class XComponentContext; } + namespace xml::sax { class XFastAttributeList; } + namespace xml::sax { class XFastContextHandler; } + namespace xml::sax { class XLocator; } +} + +namespace utl { class MediaDescriptor; } + +namespace oox { class AttributeList; } + +namespace oox::core { + +enum class OOXMLVariant { + ECMA_Transitional, + ISO_Transitional, + ISO_Strict +}; + + +/** Document handler specifically designed for detecting OOXML file formats. + + It takes a reference to the filter string object via its constructor, and + puts the name of the detected filter to it, if it successfully finds one. + */ +class FilterDetectDocHandler final : public ::cppu::WeakImplHelper< css::xml::sax::XFastDocumentHandler > +{ +public: + explicit FilterDetectDocHandler( const css::uno::Reference< css::uno::XComponentContext >& rxContext, OUString& rFilter, const OUString& rFileName ); + virtual ~FilterDetectDocHandler() override; + + // XFastDocumentHandler + virtual void SAL_CALL startDocument() override; + virtual void SAL_CALL endDocument() override; + virtual void SAL_CALL processingInstruction( const OUString& rTarget, const OUString& rData ) override; + virtual void SAL_CALL setDocumentLocator( const css::uno::Reference< css::xml::sax::XLocator >& xLocator ) override; + + // XFastContextHandler + virtual void SAL_CALL startFastElement( sal_Int32 nElement, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL startUnknownElement( const OUString& Namespace, const OUString& Name, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL endFastElement( sal_Int32 Element ) override; + virtual void SAL_CALL endUnknownElement( const OUString& Namespace, const OUString& Name ) override; + virtual css::uno::Reference< XFastContextHandler > SAL_CALL createFastChildContext( sal_Int32 Element, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual css::uno::Reference< XFastContextHandler > SAL_CALL createUnknownChildContext( const OUString& Namespace, const OUString& Name, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL characters( const OUString& aChars ) override; + +private: + void parseRelationship( const AttributeList& rAttribs ); + + OUString getFilterNameFromContentType( std::u16string_view rContentType, const OUString& rFileName ); + void parseContentTypesDefault( const AttributeList& rAttribs ); + void parseContentTypesOverride( const AttributeList& rAttribs ); + +private: + typedef ::std::vector< sal_Int32 > ContextVector; + + OUString& mrFilterName; + OUString maFileName; + ContextVector maContextStack; + OUString maTargetPath; + OOXMLVariant maOOXMLVariant; + css::uno::Reference< css::uno::XComponentContext > mxContext; +}; + + +class OOX_DLLPUBLIC FilterDetect final : public ::cppu::WeakImplHelper +{ +public: + /// @throws css::uno::RuntimeException + explicit FilterDetect( const css::uno::Reference< css::uno::XComponentContext >& rxContext ); + virtual ~FilterDetect() override; + + /** Tries to extract an unencrypted ZIP package from the passed media + descriptor. + + First, this function checks if the input stream provided by the media + descriptor property 'InputStream' contains a ZIP package. If yes, this + stream is returned. + + Second, this function checks if the 'ComponentData' property exists and + contains a sequence of com.sun.star.beans.NamedValue. If yes, a named + value is searched with the name 'DecryptedPackage' and a value of type + com.sun.star.io.XStream. If the input stream provided by this XStream + contains a ZIP package, this input stream is returned. + + Third, this function checks if the input stream of the media descriptor + contains an OLE package. If yes, it checks the existence of the streams + 'EncryptionInfo' and 'EncryptedPackage' and tries to decrypt the package + into a temporary file. This may include requesting a password from the + media descriptor property 'Password' or from the user, using the + interaction handler provided by the descriptor. On success, and if the + decrypted package is a ZIP package, the XStream of the temporary file + is stored in the property 'ComponentData' of the media descriptor and + its input stream is returned. + */ + css::uno::Reference< css::io::XInputStream > + extractUnencryptedPackage( utl::MediaDescriptor& rMediaDesc ) const; + + // com.sun.star.lang.XServiceInfo interface ------------------------------- + + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + + // com.sun.star.document.XExtendedFilterDetection interface --------------- + + /** Detects MS Office 2007 file types and supports package decryption. + + The following file types are detected: + - MS Word 2007 XML Document (*.docx, *.docm) + - MS Word 2007 XML Template (*.dotx, *.dotm) + - MS Excel 2007 XML Document (*.xlsx, *.xlsm) + - MS Excel 2007 BIFF12 Document (*.xlsb) + - MS Excel 2007 XML Template (*.xltx, *.xltm) + - MS Powerpoint 2007 XML Document (*.pptx, *.pptm) + - MS Powerpoint 2007 XML Template (*.potx, *.potm) + + If the package is encrypted, the detection tries to decrypt it into a + temporary file. The user may be asked for a password. The XStream + interface of the temporary file will be stored in the 'ComponentData' + property of the passed media descriptor. + */ + virtual OUString SAL_CALL + detect( css::uno::Sequence< css::beans::PropertyValue >& rMediaDescSeq ) override; + +private: + css::uno::Reference< css::uno::XComponentContext > mxContext; +}; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/fragmenthandler.hxx b/include/oox/core/fragmenthandler.hxx new file mode 100644 index 000000000..a3263ca1f --- /dev/null +++ b/include/oox/core/fragmenthandler.hxx @@ -0,0 +1,139 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_FRAGMENTHANDLER_HXX +#define INCLUDED_OOX_CORE_FRAGMENTHANDLER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XInputStream; } + namespace xml::sax { class XFastAttributeList; } + namespace xml::sax { class XFastContextHandler; } + namespace xml::sax { class XLocator; } +} + +namespace oox::core { + +class XmlFilterBase; + +/** Base data of a fragment. + + This data is stored in a separate struct to make it accessible in every + child context handler of the fragment. + */ +struct FragmentBaseData +{ + XmlFilterBase& mrFilter; + const OUString maFragmentPath; + css::uno::Reference< css::xml::sax::XLocator > + mxLocator; + RelationsRef mxRelations; + + explicit FragmentBaseData( + XmlFilterBase& rFilter, + const OUString& rFragmentPath, + RelationsRef const & xRelations ); +}; + + +/** Describes record identifiers used to create contexts in a binary stream. + + If a record is used to start a new context, usually the record identifier + increased by 1 is used to mark the end of this context, e.g. the Excel + record SHEETDATA == 0x0091 starts the context, and the record + SHEETDATA_END == 0x0092 ends this context. But some records are used to + start a new context, though there is no identifier to end this context, + e.g. the ROW or EXTROW records. These record identifiers can be marked by + setting the mnEndRecId member of this struct to -1. + */ +struct RecordInfo +{ + sal_Int32 mnStartRecId; ///< Record identifier for context start. + sal_Int32 mnEndRecId; ///< Record identifier for context end, -1 = no record. +}; + + +typedef ::cppu::ImplInheritanceHelper< ContextHandler, css::xml::sax::XFastDocumentHandler > FragmentHandler_BASE; + +class OOX_DLLPUBLIC FragmentHandler : public FragmentHandler_BASE +{ +public: + explicit FragmentHandler( XmlFilterBase& rFilter, const OUString& rFragmentPath ); + virtual ~FragmentHandler() override; + + FragmentHandler(FragmentHandler const &) = default; + FragmentHandler(FragmentHandler &&) = default; + FragmentHandler & operator =(FragmentHandler const &) = delete; // due to ContextHandler + FragmentHandler & operator =(FragmentHandler &&) = delete; // due to ContextHandler + + /** Returns the com.sun.star.xml.sax.XFastContextHandler interface of this context. */ + css::uno::Reference< css::xml::sax::XFastContextHandler > + getFastContextHandler() { return static_cast< ContextHandler* >( this ); } + + // com.sun.star.xml.sax.XFastDocumentHandler interface -------------------- + + virtual void SAL_CALL startDocument() override; + virtual void SAL_CALL endDocument() override; + virtual void SAL_CALL processingInstruction( const OUString& rTarget, const OUString& rData ) override; + virtual void SAL_CALL setDocumentLocator( const css::uno::Reference< css::xml::sax::XLocator >& rxLocator ) override; + + // com.sun.star.xml.sax.XFastContextHandler interface --------------------- + + virtual void SAL_CALL startFastElement( ::sal_Int32 Element, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL startUnknownElement( const OUString& Namespace, const OUString& Name, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL endFastElement( ::sal_Int32 Element ) override; + virtual void SAL_CALL endUnknownElement( const OUString& Namespace, const OUString& Name ) override; + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext( const OUString& Namespace, const OUString& Name, const css::uno::Reference< css::xml::sax::XFastAttributeList >& Attribs ) override; + virtual void SAL_CALL characters( const OUString& aChars ) override; + + // XML stream handling ---------------------------------------------------- + + /** Opens the fragment stream referred by the own fragment path. Derived + classes may provide specialized stream implementations. */ + virtual css::uno::Reference< css::io::XInputStream > + openFragmentStream() const; + + // binary records --------------------------------------------------------- + + virtual const RecordInfo* getRecordInfos() const; + +protected: + explicit FragmentHandler( XmlFilterBase& rFilter, const OUString& rFragmentPath, RelationsRef xRelations ); +}; + +typedef ::rtl::Reference< FragmentHandler > FragmentHandlerRef; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/fragmenthandler2.hxx b/include/oox/core/fragmenthandler2.hxx new file mode 100644 index 000000000..05b2b2d0b --- /dev/null +++ b/include/oox/core/fragmenthandler2.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_FRAGMENTHANDLER2_HXX +#define INCLUDED_OOX_CORE_FRAGMENTHANDLER2_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace xml::sax { class XFastAttributeList; } + namespace xml::sax { class XFastContextHandler; } +} + +namespace oox { + class AttributeList; + class SequenceInputStream; +} + +namespace oox::core { + +class XmlFilterBase; + +class OOX_DLLPUBLIC FragmentHandler2 : public FragmentHandler, public ContextHandler2Helper +{ +public: + explicit FragmentHandler2( + XmlFilterBase& rFilter, + const OUString& rFragmentPath, + bool bEnableTrimSpace = true ); + virtual ~FragmentHandler2() override; + + FragmentHandler2(FragmentHandler2 const &) = default; + FragmentHandler2(FragmentHandler2 &&) = default; + FragmentHandler2 & operator =(FragmentHandler2 const &) = delete; // due to FragmentHandler + FragmentHandler2 & operator =(FragmentHandler2 &&) = delete; // due to FragmentHandler + + // resolve ambiguity from base classes + virtual void SAL_CALL acquire() noexcept override { FragmentHandler::acquire(); } + virtual void SAL_CALL release() noexcept override { FragmentHandler::release(); } + + // com.sun.star.xml.sax.XFastContextHandler interface --------------------- + + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL + createFastChildContext( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ) final override; + + virtual void SAL_CALL startFastElement( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ) final override; + + virtual void SAL_CALL characters( const OUString& rChars ) final override; + + virtual void SAL_CALL endFastElement( sal_Int32 nElement ) final override; + + // com.sun.star.xml.sax.XFastDocumentHandler interface -------------------- + + virtual void SAL_CALL startDocument() override; + + virtual void SAL_CALL endDocument() override; + + // oox.core.ContextHandler interface -------------------------------------- + + virtual ContextHandlerRef createRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ) override; + virtual void startRecord( sal_Int32 nRecId, SequenceInputStream& rStrm ) override; + virtual void endRecord( sal_Int32 nRecId ) override; + + // oox.core.ContextHandler2Helper interface ------------------------------- + + virtual ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + virtual void onStartElement( const AttributeList& rAttribs ) override; + virtual void onCharacters( const OUString& rChars ) override; + virtual void onEndElement() override; + + virtual ContextHandlerRef onCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ) override; + virtual void onStartRecord( SequenceInputStream& rStrm ) override; + virtual void onEndRecord() override; + + // oox.core.FragmentHandler2 interface ------------------------------------ + + virtual void initializeImport(); + virtual void finalizeImport(); +}; + +typedef ::rtl::Reference< FragmentHandler2 > FragmentHandler2Ref; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/recordparser.hxx b/include/oox/core/recordparser.hxx new file mode 100644 index 000000000..d8525ac8e --- /dev/null +++ b/include/oox/core/recordparser.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_RECORDPARSER_HXX +#define INCLUDED_OOX_CORE_RECORDPARSER_HXX + +#include +#include + +#include +#include +#include +#include +#include + +namespace oox { +namespace core { + +namespace prv { + class ContextStack; + class Locator; +} + + +struct RecordInputSource +{ + BinaryInputStreamRef mxInStream; + OUString maSystemId; +}; + + +class RecordParser final +{ +public: + RecordParser(); + ~RecordParser(); + + void setFragmentHandler( const ::rtl::Reference< FragmentHandler >& rxHandler ); + + /// @throws css::xml::sax::SAXException + /// @throws css::io::IOException + /// @throws css::uno::RuntimeException + void parseStream( const RecordInputSource& rInputSource ); + + const RecordInputSource& getInputSource() const { return maSource; } + +private: + /** Returns a RecordInfo struct that contains the passed record identifier + as context start identifier. */ + const RecordInfo* getStartRecordInfo( sal_Int32 nRecId ) const; + /** Returns a RecordInfo struct that contains the passed record identifier + as context end identifier. */ + const RecordInfo* getEndRecordInfo( sal_Int32 nRecId ) const; + +private: + typedef ::std::map< sal_Int32, RecordInfo > RecordInfoMap; + + RecordInputSource maSource; + ::rtl::Reference< FragmentHandler > mxHandler; + ::rtl::Reference< prv::Locator > mxLocator; + ::std::unique_ptr< prv::ContextStack > mxStack; + RecordInfoMap maStartMap; + RecordInfoMap maEndMap; +}; + + +} // namespace core +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/relations.hxx b/include/oox/core/relations.hxx new file mode 100644 index 000000000..166652afe --- /dev/null +++ b/include/oox/core/relations.hxx @@ -0,0 +1,120 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_RELATIONS_HXX +#define INCLUDED_OOX_CORE_RELATIONS_HXX + +#include +#include +#include +#include + +#include +#include + +namespace oox::core { + + +/** Expands to an OUString containing an 'officeDocument' transitional relation type created + from the passed literal(!) ASCII(!) character array. */ +#define CREATE_OFFICEDOC_RELATION_TYPE( ascii ) \ + ( u"http://schemas.openxmlformats.org/officeDocument/2006/relationships/" ascii ) + +/** Expands to an OUString containing an 'officeDocument' strict relation type created + from the passed literal(!) ASCII(!) character array. */ +#define CREATE_OFFICEDOC_RELATION_TYPE_STRICT( ascii ) \ + ( "http://purl.oclc.org/ooxml/officeDocument/relationships/" ascii ) + +/** Expands to an OUString containing an MS Office specific relation type + created from the passed literal(!) ASCII(!) character array. */ +#define CREATE_MSOFFICE_RELATION_TYPE( ascii ) \ + ( u"http://schemas.microsoft.com/office/2006/relationships/" ascii ) + +#define CREATE_XL_CONTENT_TYPE( ascii ) \ + ( "application/vnd.openxmlformats-officedocument.spreadsheetml." ascii "+xml" ) + +struct Relation +{ + OUString maId; + OUString maType; + OUString maTarget; + bool mbExternal; + + Relation() : mbExternal( false ) {} +}; + + +class Relations; +typedef std::shared_ptr< Relations > RelationsRef; + +class OOX_DLLPUBLIC Relations +{ +public: + explicit Relations( const OUString& rFragmentPath ); + + size_t size() const { return maMap.size(); } + size_t count( const OUString& rId ) const { return maMap.count( rId ); } + ::std::map< OUString, Relation >::const_iterator begin() const + { + return maMap.begin(); + } + ::std::map< OUString, Relation >::const_iterator end() const + { + return maMap.end(); + } + template + void emplace(Args&&... args) + { + maMap.emplace(std::forward(args)...); + } + + /** Returns the path of the fragment this relations collection is related to. */ + const OUString& getFragmentPath() const { return maFragmentPath; } + + /** Returns the relation with the passed relation identifier. */ + const Relation* getRelationFromRelId( const OUString& rId ) const; + /** Returns the first relation with the passed type. */ + const Relation* getRelationFromFirstType( std::u16string_view rType ) const; + /** Finds all relations associated with the passed type. */ + RelationsRef getRelationsFromTypeFromOfficeDoc( std::u16string_view rType ) const; + + /** Returns the external target of the relation with the passed relation identifier. */ + OUString getExternalTargetFromRelId( const OUString& rRelId ) const; + /** Returns the internal target of the relation with the passed relation identifier. */ + OUString getInternalTargetFromRelId( const OUString& rRelId ) const; + + /** Returns the full fragment path for the target of the passed relation. */ + OUString getFragmentPathFromRelation( const Relation& rRelation ) const; + /** Returns the full fragment path for the passed relation identifier. */ + OUString getFragmentPathFromRelId( const OUString& rRelId ) const; + /** Returns the full fragment path for the first relation of the passed type. */ + OUString getFragmentPathFromFirstType( std::u16string_view rType ) const; + OUString getFragmentPathFromFirstTypeFromOfficeDoc( std::u16string_view rType ) const; + +private: + ::std::map< OUString, Relation > maMap; + OUString maFragmentPath; +}; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/relationshandler.hxx b/include/oox/core/relationshandler.hxx new file mode 100644 index 000000000..ec8f77e92 --- /dev/null +++ b/include/oox/core/relationshandler.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_RELATIONSHANDLER_HXX +#define INCLUDED_OOX_CORE_RELATIONSHANDLER_HXX + +#include +#include +#include +#include + +namespace com::sun::star { + namespace xml::sax { class XFastAttributeList; } + namespace xml::sax { class XFastContextHandler; } +} + +namespace oox::core { + +class XmlFilterBase; + +class RelationsFragment final : public FragmentHandler +{ +public: + explicit RelationsFragment( + XmlFilterBase& rFilter, + const RelationsRef& xRelations ); + + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL + createFastChildContext( + sal_Int32 nElement, + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ) override; + +private: + RelationsRef mxRelations; +}; + + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/core/xmlfilterbase.hxx b/include/oox/core/xmlfilterbase.hxx new file mode 100644 index 000000000..35312fda5 --- /dev/null +++ b/include/oox/core/xmlfilterbase.hxx @@ -0,0 +1,297 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CORE_XMLFILTERBASE_HXX +#define INCLUDED_OOX_CORE_XMLFILTERBASE_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace document { class XDocumentProperties; } + namespace io { class XInputStream; } + namespace io { class XOutputStream; } + namespace io { class XStream; } + namespace text { class XText; } + namespace text { class XTextCursor; } + namespace text { class XTextField; } + namespace uno { class XComponentContext; } + namespace xml::dom { class XDocument; } + namespace xml::sax { class XFastSAXSerializable; } +} + +namespace oox { + namespace drawingml { class Theme; } + namespace drawingml::chart { class ChartConverter; } + namespace drawingml::table { + class TableStyleList; + typedef std::shared_ptr< TableStyleList > TableStyleListPtr; + } + namespace vml { class Drawing; } +} + +namespace rtl { template class Reference; } + +namespace sax_fastparser { + class FastSerializerHelper; + + typedef std::shared_ptr< FastSerializerHelper > FSHelperPtr; +} + +namespace utl { class MediaDescriptor; } + +namespace oox::drawingml +{ +class Shape; +} + +namespace oox::core { + +class FragmentHandler; +class FastParser; + +struct TextField { + css::uno::Reference< css::text::XText > xText; + css::uno::Reference< css::text::XTextCursor > xTextCursor; + css::uno::Reference< css::text::XTextField > xTextField; +}; +typedef std::vector< TextField > TextFieldStack; + +struct XmlFilterBaseImpl; + +using ShapePairs + = std::map, css::uno::Reference>; +using NamedShapePairs = std::map; + +class OOX_DLLPUBLIC XmlFilterBase : public FilterBase +{ +public: + /// @throws css::uno::RuntimeException + explicit XmlFilterBase( + const css::uno::Reference< css::uno::XComponentContext >& rxContext ); + + virtual ~XmlFilterBase() override; + + /** Has to be implemented by each filter, returns the current theme. */ + virtual const ::oox::drawingml::Theme* getCurrentTheme() const = 0; + + /** May be implemented by filters which handle Diagrams, default returns empty ptr */ + virtual std::shared_ptr<::oox::drawingml::Theme> getCurrentThemePtr() const; + + /** Has to be implemented by each filter to return the collection of VML shapes. */ + virtual ::oox::vml::Drawing* getVmlDrawing() = 0; + + /** Has to be implemented by each filter, returns a filter-specific chart + converter object, that should be global per imported document. */ + virtual ::oox::drawingml::chart::ChartConverter* getChartConverter() = 0; + + /** Helper to switch chart data table - specifically for xlsx imports */ + virtual void useInternalChartDataTable( bool /*bInternal*/ ) { } + + /** Has to be implemented by each filter to return the table style list. */ + virtual ::oox::drawingml::table::TableStyleListPtr getTableStyles() = 0; + + + OUString getFragmentPathFromFirstTypeFromOfficeDoc( std::u16string_view rPart ); + + /** Imports a fragment using the passed fragment handler, which contains + the full path to the fragment stream. + + @return True, if the fragment could be imported. + */ + bool importFragment( const rtl::Reference& rxHandler ); + bool importFragment( const rtl::Reference& rxHandler, FastParser& rParser ); + + /** Imports a fragment into an xml::dom::XDocument. + + @param rFragmentPath path to fragment + + @return a non-empty reference to the XDocument, if the + fragment could be imported. + */ + css::uno::Reference< css::xml::dom::XDocument> importFragment( const OUString& rFragmentPath ); + + /** Imports a fragment from an xml::dom::XDocument using the + passed fragment handler + + @param rxHandler fragment handler; path to fragment is + ignored, input source is the rxSerializer + + @param rxSerializer usually retrieved from a + xml::dom::XDocument, will get serialized into rxHandler + + @return true, if the fragment could be imported. + */ + bool importFragment( const ::rtl::Reference< FragmentHandler >& rxHandler, + const css::uno::Reference< css::xml::sax::XFastSAXSerializable >& rxSerializer ); + + /** Imports the relations fragment associated with the specified fragment. + + @return The relations collection of the specified fragment. + */ + RelationsRef importRelations( const OUString& rFragmentPath ); + + /** Adds new relation. + + @param rType + Relation type. + + @param rTarget + Relation target. + + @return Added relation Id. + */ + OUString addRelation( const OUString& rType, std::u16string_view rTarget ); + + /** Adds new relation to part's relations. + + @param rPartName + Part name the relations are related to. The relations will be stored in /_rels/.rels. + + @param rType + Relation type. + + @param rTarget + Relation target. + + @return Added relation Id. + */ + OUString addRelation( const css::uno::Reference< css::io::XOutputStream >& rOutputStream, const OUString& rType, std::u16string_view rTarget, bool bExternal = false ); + + /** Returns a stack of used textfields, used by the pptx importer to replace links to slidepages with the real page name */ + TextFieldStack& getTextFieldStack() const; + + /** Opens and returns the specified output stream from the base storage with specified media type. + + @param rStreamName + The name of the embedded storage stream. The name may contain + slashes to open streams from embedded substorages. If base stream + access has been enabled in the storage, the base stream can be + accessed by passing an empty string as stream name. + + @param rMediaType + The media type string, used in [Content_Types].xml stream in base + storage. + + @return The opened output stream. + */ + css::uno::Reference< css::io::XOutputStream > + openFragmentStream( + const OUString& rStreamName, + const OUString& rMediaType ); + + /** Opens specified output stream from the base storage with specified + media type and returns new fast serializer for that stream. + + @param rStreamName + The name of the embedded storage stream. The name may contain + slashes to open streams from embedded substorages. If base stream + access has been enabled in the storage, the base stream can be + accessed by passing an empty string as stream name. + + @param rMediaType + The media type string, used in [Content_Types].xml stream in base + storage. + + @return newly created serializer helper. + */ + ::sax_fastparser::FSHelperPtr + openFragmentStreamWithSerializer( + const OUString& rStreamName, + const OUString& rMediaType ); + + /** Returns new unique ID for exported document. + + @return newly created ID. + */ + sal_Int32 GetUniqueId() { return mnMaxDocId++; } + + /** Write the document properties into into the current OPC package. + + @param xProperties The document properties to export. + */ + void exportDocumentProperties( const css::uno::Reference< css::document::XDocumentProperties >& xProperties, bool bSecurityOptOpenReadOnly ); + + /** Write the customXml entries we are preserving (xlsx and pptx only). */ + void exportCustomFragments(); + + /** Read the document properties and also the customXml entries (xlsx and pptx only). */ + void importDocumentProperties(); + + static void putPropertiesToDocumentGrabBag(const css::uno::Reference& xDstDoc, + const comphelper::SequenceAsHashMap& rProperties); + + static FastParser* createParser(); + + bool isMSO2007Document() const; + bool isMSODocument() const; + + /// Signal that an MSO 2007-created SmartArt was found, need to warn the + /// user about it. + void setMissingExtDrawing(); + + void setDiagramFontHeights(NamedShapePairs* pDiagramFontHeights); + NamedShapePairs* getDiagramFontHeights(); + + void checkDocumentProperties( + const css::uno::Reference& xDocProps); + + OUString getNamespaceURL(sal_Int32 nNSID) const; + +protected: + virtual css::uno::Reference< css::io::XInputStream > + implGetInputStream( utl::MediaDescriptor& rMediaDesc ) const override; + + virtual css::uno::Reference< css::io::XStream > + implGetOutputStream( utl::MediaDescriptor& rMediaDesc ) const override; + + virtual bool implFinalizeExport( utl::MediaDescriptor& rMediaDescriptor ) override; + +private: + virtual StorageRef implCreateStorage( + const css::uno::Reference< css::io::XInputStream >& rxInStream ) const override; + virtual StorageRef implCreateStorage( + const css::uno::Reference< css::io::XStream >& rxOutStream ) const override; + + void importCustomFragments(css::uno::Reference const & xDocumentStorage); + +private: + ::std::unique_ptr< XmlFilterBaseImpl > mxImpl; + sal_Int32 mnRelId; + sal_Int32 mnMaxDocId; + bool mbMSO2007; + bool mbMSO; +protected: + bool mbMissingExtDrawing; +}; + +} // namespace oox::core + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/AgileEngine.hxx b/include/oox/crypto/AgileEngine.hxx new file mode 100644 index 000000000..ece492871 --- /dev/null +++ b/include/oox/crypto/AgileEngine.hxx @@ -0,0 +1,147 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_CRYPTO_AGILEENGINE_HXX +#define INCLUDED_OOX_CRYPTO_AGILEENGINE_HXX + +#include + +#include +#include +#include +#include +#include + +namespace oox { + class BinaryXInputStream; + class BinaryXOutputStream; +} + +namespace oox::crypto { + +struct OOX_DLLPUBLIC AgileEncryptionInfo +{ + sal_Int32 spinCount; + sal_Int32 saltSize; + sal_Int32 keyBits; + sal_Int32 hashSize; + sal_Int32 blockSize; + + OUString cipherAlgorithm; + OUString cipherChaining; + OUString hashAlgorithm; + + std::vector keyDataSalt; + + // Key Encryptor + std::vector saltValue; + std::vector encryptedVerifierHashInput; + std::vector encryptedVerifierHashValue; + std::vector encryptedKeyValue; + + // HMAC + std::vector hmacKey; + std::vector hmacHash; + std::vector hmacCalculatedHash; + std::vector hmacEncryptedKey; // encrypted Key + std::vector hmacEncryptedValue; // encrypted Hash +}; + +struct OOX_DLLPUBLIC AgileEncryptionParameters +{ + sal_Int32 spinCount; + sal_Int32 saltSize; + sal_Int32 keyBits; + sal_Int32 hashSize; + sal_Int32 blockSize; + + OUString cipherAlgorithm; + OUString cipherChaining; + OUString hashAlgorithm; +}; + +enum class AgileEncryptionPreset +{ + AES_128_SHA1, + AES_256_SHA512, +}; + +class OOX_DLLPUBLIC AgileEngine final : public CryptoEngine +{ +private: + AgileEncryptionInfo mInfo; + AgileEncryptionPreset meEncryptionPreset; + + void calculateHashFinal(const OUString& rPassword, std::vector& aHashFinal); + + void calculateBlock( + std::vector const & rBlock, + std::vector& rHashFinal, + std::vector& rInput, + std::vector& rOutput); + + void encryptBlock( + std::vector const & rBlock, + std::vector& rHashFinal, + std::vector& rInput, + std::vector& rOutput); + + static Crypto::CryptoType cryptoType(const AgileEncryptionInfo& rInfo); + +public: + AgileEngine(); + + AgileEncryptionInfo& getInfo() { return mInfo;} + + void setPreset(AgileEncryptionPreset ePreset) + { + meEncryptionPreset = ePreset; + } + + // Decryption + + void decryptEncryptionKey(OUString const & rPassword); + bool decryptAndCheckVerifierHash(OUString const & rPassword); + + bool generateEncryptionKey(OUString const & rPassword) override; + bool readEncryptionInfo(css::uno::Reference & rxInputStream) override; + bool decrypt(BinaryXInputStream& aInputStream, + BinaryXOutputStream& aOutputStream) override; + + bool checkDataIntegrity() override; + + bool decryptHmacKey(); + bool decryptHmacValue(); + + // Encryption + + void writeEncryptionInfo(BinaryXOutputStream& rStream) override; + + void encrypt(const css::uno::Reference& rxInputStream, + css::uno::Reference& rxOutputStream, + sal_uInt32 nSize) override; + + bool setupEncryption(OUString const & rPassword) override; + + bool generateAndEncryptVerifierHash(OUString const & rPassword); + + bool encryptHmacKey(); + bool encryptHmacValue(); + + bool encryptEncryptionKey(OUString const & rPassword); + void setupEncryptionParameters(AgileEncryptionParameters const & rAgileEncryptionParameters); + bool setupEncryptionKey(OUString const & rPassword); +}; + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/CryptTools.hxx b/include/oox/crypto/CryptTools.hxx new file mode 100644 index 000000000..c8c142007 --- /dev/null +++ b/include/oox/crypto/CryptTools.hxx @@ -0,0 +1,120 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_CRYPTO_CRYPTTOOLS_HXX +#define INCLUDED_OOX_CRYPTO_CRYPTTOOLS_HXX + +#include +#include + +#include +#include + +namespace oox::crypto { + +/** Rounds up the input to the nearest multiple + * + * For example: + * input 1, multiple 16 = 16 + * input 16, multiple 16 = 16 + * input 17, multiple 16 = 32 + * input 31, multiple 16 = 32 + */ +template +T roundUp(T input, T multiple) +{ + if (input % multiple == 0) + return input; + return ((input / multiple) * multiple) + multiple; +} + +enum class CryptoHashType +{ + SHA1, + SHA256, + SHA512 +}; + +struct CryptoImpl; + +class OOX_DLLPUBLIC Crypto +{ +public: + enum CryptoType + { + UNKNOWN, + AES_128_ECB, + AES_128_CBC, + AES_256_CBC, + }; + +protected: + std::unique_ptr mpImpl; + +protected: + Crypto(); + +public: + virtual ~Crypto(); +}; + +class Decrypt final : public Crypto +{ +public: + Decrypt(std::vector& key, std::vector& iv, CryptoType type); + + sal_uInt32 update( + std::vector& output, + std::vector& input, + sal_uInt32 inputLength = 0); + + + static sal_uInt32 aes128ecb( + std::vector& output, + std::vector& input, + std::vector& key ); + +}; + +class Encrypt final : public Crypto +{ +public: + Encrypt(std::vector& key, std::vector& iv, CryptoType type); + + sal_uInt32 update( + std::vector& output, + std::vector& input, + sal_uInt32 inputLength = 0); +}; + +class OOX_DLLPUBLIC CryptoHash final : public Crypto +{ + sal_Int32 mnHashSize; +public: + CryptoHash(std::vector& rKey, CryptoHashType eType); + bool update(std::vector& rInput, sal_uInt32 nInputLength = 0); + std::vector finalize(); +}; + + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/CryptoEngine.hxx b/include/oox/crypto/CryptoEngine.hxx new file mode 100644 index 000000000..49009ac7e --- /dev/null +++ b/include/oox/crypto/CryptoEngine.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_CRYPTO_CRYPTOENGINE_HXX +#define INCLUDED_OOX_CRYPTO_CRYPTOENGINE_HXX + +#include + +#include +#include + +#include +#include + +namespace oox { + class BinaryXInputStream; + class BinaryXOutputStream; +} + +namespace oox::crypto { + +class CryptoEngine +{ +protected: + std::vector mKey; + +public: + CryptoEngine() + {} + + virtual ~CryptoEngine() + {} + + // Decryption + virtual bool readEncryptionInfo(css::uno::Reference & rxInputStream) = 0; + + virtual bool generateEncryptionKey(const OUString& rPassword) = 0; + + virtual bool decrypt( + BinaryXInputStream& aInputStream, + BinaryXOutputStream& aOutputStream) = 0; + + // Encryption + virtual void writeEncryptionInfo(BinaryXOutputStream & rStream) = 0; + + virtual bool setupEncryption(const OUString& rPassword) = 0; + + virtual void encrypt(const css::uno::Reference & rxInputStream, + css::uno::Reference & rxOutputStream, + sal_uInt32 nSize) = 0; + + virtual bool checkDataIntegrity() = 0; +}; + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/DocumentDecryption.hxx b/include/oox/crypto/DocumentDecryption.hxx new file mode 100644 index 000000000..33cab866f --- /dev/null +++ b/include/oox/crypto/DocumentDecryption.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_CRYPTO_DOCUMENTDECRYPTION_HXX +#define INCLUDED_OOX_CRYPTO_DOCUMENTDECRYPTION_HXX + +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { struct NamedValue; } + namespace io { class XInputStream; } + namespace io { class XStream; } + namespace uno { class XComponentContext; } + namespace packages { class XPackageEncryption; } +} + +namespace oox::ole { class OleStorage; } + +namespace oox::crypto { + +class DocumentDecryption +{ +private: + css::uno::Reference< css::uno::XComponentContext > mxContext; + oox::ole::OleStorage& mrOleStorage; + css::uno::Sequence maStreamsSequence; + css::uno::Reference< css::packages::XPackageEncryption > mxPackageEncryption; + +public: + DocumentDecryption(const css::uno::Reference< css::uno::XComponentContext >& rxContext, oox::ole::OleStorage& rOleStorage); + + bool decrypt(const css::uno::Reference< css::io::XStream >& xDocumentStream); + bool readEncryptionInfo(); + bool generateEncryptionKey(const OUString& rPassword); + + css::uno::Sequence< css::beans::NamedValue > createEncryptionData(const OUString& rPassword); + +}; + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/DocumentEncryption.hxx b/include/oox/crypto/DocumentEncryption.hxx new file mode 100644 index 000000000..c2a3bd4ed --- /dev/null +++ b/include/oox/crypto/DocumentEncryption.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_CRYPTO_DOCUMENTENCRYPTION_HXX +#define INCLUDED_OOX_CRYPTO_DOCUMENTENCRYPTION_HXX + +#include +#include + +namespace com::sun::star { + namespace io { class XStream; } + namespace packages { class XPackageEncryption; } + namespace beans { struct NamedValue; } + namespace uno { class XComponentContext; } +} + +namespace oox::ole { class OleStorage; } + +namespace oox::crypto { + +class DocumentEncryption +{ +private: + css::uno::Reference< css::uno::XComponentContext > mxContext; + css::uno::Reference< css::io::XStream > mxDocumentStream; + oox::ole::OleStorage& mrOleStorage; + + css::uno::Reference< css::packages::XPackageEncryption > mxPackageEncryption; + const css::uno::Sequence< css::beans::NamedValue >& mMediaEncData; + +public: + DocumentEncryption(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + css::uno::Reference< css::io::XStream > const & xDocumentStream, + oox::ole::OleStorage& rOleStorage, + const css::uno::Sequence< css::beans::NamedValue >& rMediaEncData); + + bool encrypt(); + +}; + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/Standard2007Engine.hxx b/include/oox/crypto/Standard2007Engine.hxx new file mode 100644 index 000000000..8a7aec3e6 --- /dev/null +++ b/include/oox/crypto/Standard2007Engine.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_CRYPTO_STANDARD2007ENGINE_HXX +#define INCLUDED_OOX_CRYPTO_STANDARD2007ENGINE_HXX + +#include +#include +#include +#include +#include + +namespace oox { + class BinaryXInputStream; + class BinaryXOutputStream; +} + +namespace oox::crypto { + +class OOX_DLLPUBLIC Standard2007Engine final : public CryptoEngine +{ + msfilter::StandardEncryptionInfo mInfo; + + bool generateVerifier(); + bool calculateEncryptionKey(const OUString& rPassword); + +public: + Standard2007Engine() = default; + + bool readEncryptionInfo(css::uno::Reference & rxInputStream) override; + + virtual bool generateEncryptionKey(OUString const & rPassword) override; + + virtual bool decrypt( + BinaryXInputStream& aInputStream, + BinaryXOutputStream& aOutputStream) override; + + bool checkDataIntegrity() override; + + void encrypt(const css::uno::Reference& rxInputStream, + css::uno::Reference& rxOutputStream, + sal_uInt32 nSize) override; + + virtual void writeEncryptionInfo(BinaryXOutputStream& rStream) override; + + virtual bool setupEncryption(OUString const & rPassword) override; + +}; + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/crypto/StrongEncryptionDataSpace.hxx b/include/oox/crypto/StrongEncryptionDataSpace.hxx new file mode 100644 index 000000000..cd7156515 --- /dev/null +++ b/include/oox/crypto/StrongEncryptionDataSpace.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_CRYPTO_STRONGENCRYPTINDATASPACE_HXX +#define INCLUDED_OOX_CRYPTO_STRONGENCRYPTINDATASPACE_HXX + +#include + +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star::uno +{ +class XComponentContext; +} + +namespace oox::crypto +{ +class StrongEncryptionDataSpace final + : public cppu::WeakImplHelper +{ + css::uno::Reference mxContext; + std::unique_ptr mCryptoEngine; + + css::uno::Reference + getStream(const css::uno::Sequence& rStreams, + std::u16string_view sStreamName); + +public: + StrongEncryptionDataSpace(const css::uno::Reference& rxContext); + + // Decryption + + virtual sal_Bool SAL_CALL generateEncryptionKey(const OUString& rPassword) override; + virtual sal_Bool SAL_CALL + readEncryptionInfo(const css::uno::Sequence& aStreams) override; + virtual sal_Bool SAL_CALL + decrypt(const css::uno::Reference& rxInputStream, + css::uno::Reference& rxOutputStream) override; + + virtual sal_Bool SAL_CALL checkDataIntegrity() override; + + // Encryption + + virtual css::uno::Sequence + SAL_CALL encrypt(const css::uno::Reference& rxInputStream) override; + + virtual sal_Bool SAL_CALL + setupEncryption(const css::uno::Sequence& rMediaEncData) override; + + virtual css::uno::Sequence + SAL_CALL createEncryptionData(const OUString& rPassword) override; + + // com.sun.star.lang.XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService(const OUString& rServiceName) override; + virtual css::uno::Sequence SAL_CALL getSupportedServiceNames() override; +}; + +} // namespace oox::crypto + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/dllapi.h b/include/oox/dllapi.h new file mode 100644 index 000000000..a03fd0b21 --- /dev/null +++ b/include/oox/dllapi.h @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DLLAPI_H +#define INCLUDED_OOX_DLLAPI_H + +#include + +#if defined OOX_DLLIMPLEMENTATION +#define OOX_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define OOX_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/chart/chartconverter.hxx b/include/oox/drawingml/chart/chartconverter.hxx new file mode 100644 index 000000000..fcf3b2fee --- /dev/null +++ b/include/oox/drawingml/chart/chartconverter.hxx @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_CHART_CHARTCONVERTER_HXX +#define INCLUDED_OOX_DRAWINGML_CHART_CHARTCONVERTER_HXX + +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Point; } + namespace awt { struct Size; } + namespace drawing { class XShapes; } + namespace chart2 { class XChartDocument; } + namespace chart2::data { class XDataProvider; } + namespace chart2::data { class XDataSequence; } +} + +namespace oox::core { class XmlFilterBase; } + +namespace oox::drawingml::chart { + +struct ChartSpaceModel; +struct DataSequenceModel; + + +class OOX_DLLPUBLIC ChartConverter +{ +public: + explicit ChartConverter(); + virtual ~ChartConverter(); + + /** Converts the passed OOXML chart model to the passed chart2 document. + + @param rChartModel The filled MSOOXML chart model structure. + + @param rxChartDoc The UNO chart document model to be initialized. + + @param rxExternalPage If null, all embedded shapes will be inserted + into the internal drawing page of the chart document. If not null, + all embedded shapes will be inserted into this shapes collection. + + @param rChartPos The position of the chart shape in its drawing page, + in 1/100 mm. Will be used only, if parameter rxExternalPage is not + null, for correct positioning of the embedded shapes in the + external drawing page. + + @param rChartSize The size of the chart shape in 1/100 mm. Needed for + calculation of position and size of the chart elements (diagram, + titles, legend, etc.) and embedded shapes. + */ + void convertFromModel( + ::oox::core::XmlFilterBase& rFilter, + ChartSpaceModel& rChartModel, + const css::uno::Reference< css::chart2::XChartDocument >& rxChartDoc, + const css::uno::Reference< css::drawing::XShapes >& rxExternalPage, + const css::awt::Point& rChartPos, + const css::awt::Size& rChartSize ); + + /** Creates an internal data provider. Derived classes may override this + function to create an external data provider. */ + virtual void createDataProvider( + const css::uno::Reference< css::chart2::XChartDocument >& rxChartDoc ); + + /** Creates a data sequence from a formula. Dummy implementation. Derived + classes have to override this function to actually parse the formula. */ + virtual css::uno::Reference + createDataSequence( + const css::uno::Reference& rxDataProvider, + const DataSequenceModel& rDataSeq, const OUString& rRole, + const OUString& aRoleQualifier ); + +private: + ChartConverter( const ChartConverter& ) = delete; + ChartConverter& operator=( const ChartConverter& ) = delete; +}; + + +} // namespace oox::drawingml::chart + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/chart/datasourcemodel.hxx b/include/oox/drawingml/chart/datasourcemodel.hxx new file mode 100644 index 000000000..49b8dcd90 --- /dev/null +++ b/include/oox/drawingml/chart/datasourcemodel.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_CHART_DATASOURCEMODEL_HXX +#define INCLUDED_OOX_DRAWINGML_CHART_DATASOURCEMODEL_HXX + +#include + +#include +#include +#include +#include + +enum class SvNumFormatType : sal_Int16; + +namespace oox::drawingml::chart { + + +struct DataSequenceModel +{ + typedef ::std::map< sal_Int32, css::uno::Any > AnyMap; + + AnyMap maData; /// Map of values, indexed by point identifier. + OUString maFormula; /// Formula reference, e.g. into a spreadsheet. + OUString maFormatCode; /// Number format for double values. + sal_Int32 mnPointCount; /// Number of points in this series source. + sal_Int32 mnLevelCount; /// Number of category levels. + SvNumFormatType meFormatType; /// Type of number format in maFormatCode. + + explicit DataSequenceModel(); + ~DataSequenceModel(); +}; + + +struct DataSourceModel +{ + typedef ModelRef< DataSequenceModel > DataSequenceRef; + + DataSequenceRef mxDataSeq; /// The data sequence or formula link of this source. + + explicit DataSourceModel(); + ~DataSourceModel(); +}; + + +} // namespace oox::drawingml::chart + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/chart/modelbase.hxx b/include/oox/drawingml/chart/modelbase.hxx new file mode 100644 index 000000000..581713bbc --- /dev/null +++ b/include/oox/drawingml/chart/modelbase.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_CHART_MODELBASE_HXX +#define INCLUDED_OOX_DRAWINGML_CHART_MODELBASE_HXX + +#include + +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::drawingml::chart { + +template< typename ModelType > +class ModelRef : public std::shared_ptr< ModelType > +{ +public: + ModelRef() {} + ModelRef( const std::shared_ptr< ModelType >& rxModel ) : std::shared_ptr< ModelType >( rxModel ) {} + + bool is() const { return this->get() != nullptr; } + + ModelType& create() { (*this) = std::make_shared(); return **this; } + template< typename Param1Type > + ModelType& create( const Param1Type& rParam1 ) { (*this) = std::make_shared( rParam1 ); return **this; } + template< typename Param1Type, typename Param2Type > + ModelType& create( const Param1Type& rParam1, const Param2Type& rParam2 ) { (*this) = std::make_shared( rParam1, rParam2 ); return **this; } + + ModelType& getOrCreate() { if( !*this ) (*this) = std::make_shared(); return **this; } + template< typename Param1Type > + ModelType& getOrCreate( const Param1Type& rParam1 ) { if( !*this ) (*this) = std::make_shared( rParam1 ); return **this; } +}; + +template< typename ModelType > +class ModelVector : public RefVector< ModelType > +{ +public: + typedef typename RefVector< ModelType >::value_type value_type; + typedef typename RefVector< ModelType >::size_type size_type; + + ModelType& create() { return append( std::make_shared() ); } + template< typename Param1Type > + ModelType& create( const Param1Type& rParam1 ) { return append( std::make_shared( rParam1 ) ); } + template< typename Param1Type, typename Param2Type > + ModelType& create( const Param1Type& rParam1, const Param2Type& rParam2 ) { return append( std::make_shared( rParam1, rParam2 ) ); } + +private: + ModelType& append( std::shared_ptr pModel ) + { + assert(pModel); + auto pTmp = pModel.get(); + this->push_back( std::move(pModel) ); + return *pTmp; + } +}; + +template< typename KeyType, typename ModelType > +class ModelMap : public RefMap< KeyType, ModelType > +{ +public: + typedef typename RefMap< KeyType, ModelType >::key_type key_type; + typedef typename RefMap< KeyType, ModelType >::mapped_type mapped_type; + typedef typename RefMap< KeyType, ModelType >::value_type value_type; + + ModelType& create( KeyType eKey ) { return insert( eKey, new ModelType ); } + +private: + ModelType& insert( KeyType eKey, ModelType* pModel ) { (*this)[ eKey ].reset( pModel ); return *pModel; } +}; + +struct NumberFormat +{ + OUString maFormatCode; /// Number format code. + bool mbSourceLinked; /// True = number format linked to source data. + + NumberFormat(); + + void setAttributes( const AttributeList& rAttribs ); +}; + +struct LayoutModel +{ + double mfX; /// Left position of this object. + double mfY; /// Top position of this object. + double mfW; /// Width of this object. + double mfH; /// Height of this object. + sal_Int32 mnXMode; /// Mode for left position. + sal_Int32 mnYMode; /// Mode for top position. + sal_Int32 mnWMode; /// Mode for width. + sal_Int32 mnHMode; /// Mode for height. + sal_Int32 mnTarget; /// Layout target for plot area. + bool mbAutoLayout; /// True = automatic positioning. + + LayoutModel(); +}; + +} // namespace oox::drawingml::chart + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/clrscheme.hxx b/include/oox/drawingml/clrscheme.hxx new file mode 100644 index 000000000..a4f0b6534 --- /dev/null +++ b/include/oox/drawingml/clrscheme.hxx @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_CLRSCHEME_HXX +#define INCLUDED_OOX_DRAWINGML_CLRSCHEME_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace oox::drawingml { + +enum PredefinedClrSchemeId { + dk1 = 0, + lt1, + dk2, + lt2, + accent1, + accent2, + accent3, + accent4, + accent5, + accent6, + hlink, + folHlink, + Count +}; + +static std::map PredefinedClrNames = +{ + { dk1, "dk1" }, + { lt1, "lt1" }, + { dk2, "dk2" }, + { lt2, "lt2" }, + { accent1, "accent1" }, + { accent2, "accent2" }, + { accent3, "accent3" }, + { accent4, "accent4" }, + { accent5, "accent5" }, + { accent6, "accent6" }, + { hlink, "hlink" }, + { folHlink, "folHlink" } +}; + +class ClrMap +{ + std::map < sal_Int32, sal_Int32 > maClrMap; + +public: + + bool getColorMap( sal_Int32& nClrToken ); + void setColorMap( sal_Int32 nClrToken, sal_Int32 nMappedClrToken ); +}; + +typedef std::shared_ptr< ClrMap > ClrMapPtr; + +class OOX_DLLPUBLIC ClrScheme +{ + std::vector< std::pair > maClrScheme; + OUString maName; + +public: + + bool getColor( sal_Int32 nSchemeClrToken, ::Color& rColor ) const; + void setColor( sal_Int32 nSchemeClrToken, ::Color nColor ); + + bool getColorByIndex(size_t nIndex, + ::Color& rColor) const; + + void SetName(const OUString& rName) { maName = rName; } + const OUString& GetName() const { return maName; } + + void ToAny(css::uno::Any& rVal) const; +}; + +} + +#endif // INCLUDED_OOX_DRAWINGML_CLRSCHEME_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/color.hxx b/include/oox/drawingml/color.hxx new file mode 100644 index 000000000..b28c92698 --- /dev/null +++ b/include/oox/drawingml/color.hxx @@ -0,0 +1,167 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_COLOR_HXX +#define INCLUDED_OOX_DRAWINGML_COLOR_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace oox { class GraphicHelper; } + +namespace oox::drawingml { + + +class OOX_DLLPUBLIC Color +{ +public: + Color(); + + /** Returns the RGB value for the passed DrawingML color token, or nDefaultRgb on error. */ + static ::Color getDmlPresetColor( sal_Int32 nToken, ::Color nDefaultRgb ); + /** Returns the RGB value for the passed VML color token, or nDefaultRgb on error. */ + static ::Color getVmlPresetColor( sal_Int32 nToken, ::Color nDefaultRgb ); + /** Returns the RGB value for the passed VML color token, or nDefaultRgb on error. */ + static ::Color getHighlightColor(sal_Int32 nToken, ::Color nDefaultRgb); + + /** Sets the color to unused state. */ + void setUnused(); + /** Sets an RGB value (hexadecimal RRGGBB) from the a:srgbClr element. */ + void setSrgbClr( sal_Int32 nRgb ); + void setSrgbClr( ::Color nRgb ); + /** Sets the percentual RGB values from the a:scrgbClr element. */ + void setScrgbClr( sal_Int32 nR, sal_Int32 nG, sal_Int32 nB ); + /** Sets the HSL values from the a:hslClr element. */ + void setHslClr( sal_Int32 nHue, sal_Int32 nSat, sal_Int32 nLum ); + /** Sets a predefined color from the a:prstClr element. */ + void setPrstClr( sal_Int32 nToken ); + /** Sets a predefined color from the w:highlight element. */ + void setHighlight(sal_Int32 nToken); + /** Sets a scheme color from the a:schemeClr element. */ + void setSchemeClr( sal_Int32 nToken ); + /** Sets the scheme name from the a:schemeClr element for interoperability purposes */ + void setSchemeName( const OUString& sSchemeName ) { msSchemeName = sSchemeName; } + /** Sets a system color from the a:sysClr element. */ + void setSysClr( sal_Int32 nToken, sal_Int32 nLastRgb ); + /** Sets a palette color index. */ + void setPaletteClr( sal_Int32 nPaletteIdx ); + + /** Inserts the passed color transformation. */ + void addTransformation( sal_Int32 nElement, sal_Int32 nValue = -1 ); + /** Inserts Chart specific color tint (-1.0...0.0 = shade, 0.0...1.0 = tint). */ + void addChartTintTransformation( double fTint ); + /** Inserts Excel specific color tint (-1.0...0.0 = shade, 0.0...1.0 = tint). */ + void addExcelTintTransformation( double fTint ); + /** Removes all color transformations. */ + void clearTransformations(); + /** Removes transparence from the color. */ + void clearTransparence(); + + /** Overwrites this color with the passed color, if it is used. */ + void assignIfUsed( const Color& rColor ) { if( rColor.isUsed() ) *this = rColor; } + + /** Returns true, if the color is initialized. */ + bool isUsed() const { return meMode != COLOR_UNUSED; } + /** Returns true, if the color is a placeholder color in theme style lists. */ + bool isPlaceHolder() const { return meMode == COLOR_PH; } + /** Returns the final RGB color value. + @param nPhClr Actual color for the phClr placeholder color used in theme style lists. */ + ::Color getColor( const GraphicHelper& rGraphicHelper, ::Color nPhClr = API_RGB_TRANSPARENT ) const; + + /** Returns true, if the color is transparent. */ + bool hasTransparency() const; + /** Returns the transparency of the color (0 = opaque, 100 = full transparent). */ + sal_Int16 getTransparency() const; + + /** Returns the scheme name from the a:schemeClr element for interoperability purposes */ + const OUString& getSchemeColorName() const { return msSchemeName; } + sal_Int16 getSchemeColorIndex() const; + sal_Int16 getTintOrShade() const; + sal_Int16 getLumMod() const; + sal_Int16 getLumOff() const; + + /** Returns the unaltered list of transformations for interoperability purposes */ + const css::uno::Sequence< css::beans::PropertyValue >& getTransformations() const { return maInteropTransformations;} + + /** Translates between color transformation tokens and their names */ + static OUString getColorTransformationName( sal_Int32 nElement ); + /** Translates between color transformation token names and the corresponding token */ + static sal_Int32 getColorTransformationToken( std::u16string_view sName ); + + /// Compares this color with rOther. + bool equals(const Color& rOther, const GraphicHelper& rGraphicHelper, ::Color nPhClr) const; + +private: + /** Internal helper for getColor(). */ + void setResolvedRgb( ::Color nRgb ) const; + + /** Converts the color components to RGB values. */ + void toRgb() const; + /** Converts the color components to CRGB values (gamma corrected percentage). */ + void toCrgb() const; + /** Converts the color components to HSL values. */ + void toHsl() const; + +private: + enum ColorMode + { + COLOR_UNUSED, /// Color is not used, or undefined. + COLOR_RGB, /// Absolute RGB (r/g/b: 0...255). + COLOR_CRGB, /// Relative RGB (r/g/b: 0...100000). + COLOR_HSL, /// HSL (hue: 0...21600000, sat/lum: 0...100000). + COLOR_SCHEME, /// Color from scheme. + COLOR_PALETTE, /// Color from application defined palette. + COLOR_SYSTEM, /// Color from system palette. + COLOR_PH, /// Placeholder color in theme style lists. + COLOR_FINAL /// Finalized RGB color. + }; + + struct Transformation + { + sal_Int32 mnToken; + sal_Int32 mnValue; + + explicit Transformation( sal_Int32 nToken, sal_Int32 nValue ) : mnToken( nToken ), mnValue( nValue ) {} + }; + + mutable ColorMode meMode; /// Current color mode. + mutable std::vector< Transformation > + maTransforms; /// Color transformations. + mutable sal_Int32 mnC1; /// Red, red%, hue, scheme token, palette index, system token, or final RGB. + mutable sal_Int32 mnC2; /// Green, green%, saturation, or system default RGB. + mutable sal_Int32 mnC3; /// Blue, blue%, or luminance. + sal_Int32 mnAlpha; /// Alpha value (color opacity). + + OUString msSchemeName; /// Scheme name from the a:schemeClr element for interoperability purposes + css::uno::Sequence< css::beans::PropertyValue > + maInteropTransformations; /// Unaltered list of transformations for interoperability purposes +}; + +} // namespace oox::drawingml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/connectorshapecontext.hxx b/include/oox/drawingml/connectorshapecontext.hxx new file mode 100644 index 000000000..c9819ae85 --- /dev/null +++ b/include/oox/drawingml/connectorshapecontext.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_CONNECTORSHAPECONTEXT_HXX +#define INCLUDED_OOX_DRAWINGML_CONNECTORSHAPECONTEXT_HXX + +#include +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class ContextHandler2Helper; } + +namespace oox::drawingml { + + struct ConnectorShapeProperties + { + bool mbStartShape; + OUString maDestShapeId; + sal_Int32 mnDestGlueId; + }; + +class OOX_DLLPUBLIC ConnectorShapeContext final : public ShapeContext +{ + std::vector& mrConnectorShapePropertiesList; + ShapePtr mpConnectorShapePtr; + +public: + ConnectorShapeContext(::oox::core::ContextHandler2Helper const& rParent, + const ShapePtr& pMasterShapePtr, const ShapePtr& pGroupShapePtr, + std::vector& rConnectorShapePropertiesList); + virtual ~ConnectorShapeContext() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; +}; + +} + +#endif // INCLUDED_OOX_DRAWINGML_CONNECTORSHAPECONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/diagram/diagram.hxx b/include/oox/drawingml/diagram/diagram.hxx new file mode 100644 index 000000000..b3e79d461 --- /dev/null +++ b/include/oox/drawingml/diagram/diagram.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_DIAGRAM_DIAGRAM_HXX +#define INCLUDED_OOX_DRAWINGML_DIAGRAM_DIAGRAM_HXX + +#include +#include +#include +#include + +#include +#include + +namespace oox::drawingml { + +/** load diagram data, and put resulting graphic into shape + + This method loads the diagram data fragments from the given paths, + generate and layout the shapes, and push it as children into the + referenced shape. + */ +void loadDiagram( ShapePtr const & pShape, + core::XmlFilterBase& rFilter, + const OUString& rDataModelPath, + const OUString& rLayoutPath, + const OUString& rQStylePath, + const OUString& rColorStylePath, + const oox::core::Relations& rRelations ); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/drawingmltypes.hxx b/include/oox/drawingml/drawingmltypes.hxx new file mode 100644 index 000000000..5fe86d564 --- /dev/null +++ b/include/oox/drawingml/drawingmltypes.hxx @@ -0,0 +1,235 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_DRAWINGMLTYPES_HXX +#define INCLUDED_OOX_DRAWINGML_DRAWINGMLTYPES_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace drawing { struct Hatch; } + namespace xml::sax { class XFastAttributeList; } +} + +namespace oox::drawingml { + + +const sal_Int32 PER_PERCENT = 1000; +const sal_Int32 MAX_PERCENT = 100 * PER_PERCENT; + +const sal_Int32 PER_DEGREE = 60000; +const sal_Int32 MAX_DEGREE = 360 * PER_DEGREE; + + +struct LineProperties; +typedef std::shared_ptr< LineProperties > LinePropertiesPtr; + +struct FillProperties; +typedef std::shared_ptr< FillProperties > FillPropertiesPtr; + +struct GraphicProperties; +typedef std::shared_ptr< GraphicProperties > GraphicPropertiesPtr; + +struct Shape3DProperties; +typedef std::shared_ptr< Shape3DProperties > Shape3DPropertiesPtr; + +struct TextCharacterProperties; +typedef std::shared_ptr< TextCharacterProperties > TextCharacterPropertiesPtr; + +struct EffectProperties; +typedef std::shared_ptr< EffectProperties > EffectPropertiesPtr; + +class TextBody; +typedef std::shared_ptr< TextBody > TextBodyPtr; + +class TextListStyle; +typedef std::shared_ptr< TextListStyle > TextListStylePtr; + +class Shape; +typedef std::shared_ptr< Shape > ShapePtr; +typedef std::weak_ptr< Shape > WeakShapePtr; + +class Theme; +typedef std::shared_ptr< Theme > ThemePtr; + + +namespace table { + +class TableProperties; +typedef std::shared_ptr< TableProperties > TablePropertiesPtr; + +} // namespace table + + +/** converts the attributes from a CT_TLPoint into an awt Point with 1/1000% */ +css::awt::Point GetPointPercent( const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttribs ); + + +/** converts the attributes from a CT_Size2D into an awt Size with 1/100th mm */ +css::awt::Size GetSize2D( const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttributes ); + +/** converts the attributes from a CT_RelativeRect to an IntegerRectangle2D */ +css::geometry::IntegerRectangle2D GetRelativeRect( const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttributes ); + +/** converts EMUs into 1/100th mmm */ +sal_Int32 GetCoordinate( sal_Int32 nValue ); + +/** converts an emu string into 1/100th mmm */ +sal_Int32 GetCoordinate( std::u16string_view sValue ); + +/** converts 1/100mm to EMU */ +sal_Int32 GetPointFromCoordinate( sal_Int32 nValue ); + +/** converts a ST_Percentage % string into 1/1000th of % */ +sal_Int32 GetPercent( std::u16string_view sValue ); + +/** Converts a ST_PositiveFixedPercentage to a float. 1.0 == 100% */ +double GetPositiveFixedPercentage( const OUString& sValue ); + +/** converts the ST_TextFontSize to point */ +float GetTextSize( std::u16string_view rValue ); + +/** converts the ST_TextSpacingPoint to 1/100mm */ +sal_Int32 GetTextSpacingPoint( std::u16string_view sValue ); +sal_Int32 GetTextSpacingPoint( const sal_Int32 nValue ); + +/** */ +css::style::TabAlign GetTabAlign( ::sal_Int32 aToken ); + +float GetFontHeight( sal_Int32 nHeight ); + +sal_Int16 GetFontUnderline( sal_Int32 nToken ); + +sal_Int16 GetFontStrikeout( sal_Int32 nToken ); + +sal_Int16 GetCaseMap( sal_Int32 nToken ); + +/** converts a paragraph align to a ParaAdjust */ +css::style::ParagraphAdjust GetParaAdjust( sal_Int32 nAlign ); + +// Converts vertical adjust tokens to a TextVerticalAdjust item +css::drawing::TextVerticalAdjust GetTextVerticalAdjust( sal_Int32 nToken ); + +// Converts a TextVerticalAdjust item to string value appearing in ooxml +OOX_DLLPUBLIC const char* GetTextVerticalAdjust( css::drawing::TextVerticalAdjust eAdjust ); + +// Converts a Hatch object to an ooxml pattern. +const char* GetHatchPattern( const css::drawing::Hatch& rHatch ); + + +// CT_IndexRange +struct IndexRange { + sal_Int32 start; + sal_Int32 end; +}; + +/** retrieve the content of CT_IndexRange */ +IndexRange GetIndexRange( const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttributes ); + +/** +* nRotation is a 100th of a degree and the return value is +* in a 60,000th of a degree +* +* Also rotation is in opposite directions so multiply with -1 +*/ +inline OString calcRotationValue(sal_Int32 nRotation) +{ + if (nRotation > 18000) // 180 degree + { + nRotation -= 36000; + } + nRotation *= -600; + return OString::number(nRotation); +} + +/** Converts the passed 32-bit integer value from 1/100 mm to EMUs. */ +inline sal_Int64 convertHmmToEmu( sal_Int32 nValue ) +{ + return o3tl::convert(nValue, o3tl::Length::mm100, o3tl::Length::emu); +} + +/** Converts the passed 64-bit integer value from EMUs to 1/100 mm. */ +inline sal_Int32 convertEmuToHmm( sal_Int64 nValue ) +{ + return o3tl::convertNarrowing(nValue); +} + +/** Converts the passed 64-bit integer value from EMUs to Points. */ +inline float convertEmuToPoints( sal_Int64 nValue ) +{ + return o3tl::convert(nValue, o3tl::Length::emu, o3tl::Length::pt); +} + +/** Converts the passed double value from points to mm. */ +inline double convertPointToMms(double fValue) +{ + return o3tl::convert(fValue, o3tl::Length::pt, o3tl::Length::mm); +} + +/** A structure for a point with 64-bit integer components. */ +struct EmuPoint +{ + sal_Int64 X; + sal_Int64 Y; + + EmuPoint() : X( 0 ), Y( 0 ) {} + explicit EmuPoint( sal_Int64 nX, sal_Int64 nY ) : X( nX ), Y( nY ) {} +}; + + +/** A structure for a size with 64-bit integer components. */ +struct EmuSize +{ + sal_Int64 Width; + sal_Int64 Height; + + EmuSize() : Width( 0 ), Height( 0 ) {} + explicit EmuSize( sal_Int64 nWidth, sal_Int64 nHeight ) : Width( nWidth ), Height( nHeight ) {} +}; + + +/** A structure for a rectangle with 64-bit integer components. */ +struct EmuRectangle : public EmuPoint, public EmuSize +{ + EmuRectangle() {} + explicit EmuRectangle( sal_Int64 nX, sal_Int64 nY, sal_Int64 nWidth, sal_Int64 nHeight ) : EmuPoint( nX, nY ), EmuSize( nWidth, nHeight ) {} + + void setPos( const EmuPoint& rPos ) { static_cast< EmuPoint& >( *this ) = rPos; } + void setSize( const EmuSize& rSize ) { static_cast< EmuSize& >( *this ) = rSize; } +}; + + +} // namespace oox::drawingml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/graphicshapecontext.hxx b/include/oox/drawingml/graphicshapecontext.hxx new file mode 100644 index 000000000..ffd579f00 --- /dev/null +++ b/include/oox/drawingml/graphicshapecontext.hxx @@ -0,0 +1,111 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_GRAPHICSHAPECONTEXT_HXX +#define INCLUDED_OOX_DRAWINGML_GRAPHICSHAPECONTEXT_HXX + +#include +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class ContextHandler2Helper; } +namespace oox::vml { struct OleObjectInfo; } + +namespace oox::drawingml { + +class OOX_DLLPUBLIC GraphicShapeContext : public ShapeContext +{ +public: + GraphicShapeContext( ::oox::core::ContextHandler2Helper const & rParent, const ShapePtr& pMasterShapePtr, const ShapePtr& pShapePtr ); + + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; +}; + + +class OOX_DLLPUBLIC GraphicalObjectFrameContext final : public ShapeContext +{ +public: + GraphicalObjectFrameContext( ::oox::core::ContextHandler2Helper& rParent, const ShapePtr& pMasterShapePtr, const ShapePtr& pShapePtr, bool bEmbedShapesInChart ); + + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; + virtual void onEndElement() override; + +private: + bool mbEmbedShapesInChart; + ::oox::core::ContextHandler2Helper* mpParent; +}; + + +class OleObjectGraphicDataContext final : public ShapeContext +{ +public: + OleObjectGraphicDataContext( ::oox::core::ContextHandler2Helper const & rParent, const ShapePtr& pShapePtr ); + virtual ~OleObjectGraphicDataContext() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; + virtual void onEndElement() override; + +private: + ::oox::vml::OleObjectInfo& mrOleObjectInfo; +}; + + +class DiagramGraphicDataContext final + : public ShapeContext +{ +public: + DiagramGraphicDataContext( ::oox::core::ContextHandler2Helper const & rParent, const ShapePtr& pShapePtr ); + virtual ~DiagramGraphicDataContext() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; + +private: + OUString msDm; + OUString msLo; + OUString msQs; + OUString msCs; +}; + + +struct ChartShapeInfo; + +class ChartGraphicDataContext final : public ShapeContext +{ +public: + explicit ChartGraphicDataContext( + ::oox::core::ContextHandler2Helper const & rParent, + const ShapePtr& rxShape, bool bEmbedShapes ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( + sal_Int32 nElement, + const ::oox::AttributeList& rAttribs) override; + +private: + ChartShapeInfo& mrChartShapeInfo; +}; + + +} + +#endif // INCLUDED_OOX_DRAWINGML_GRAPHICSHAPECONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/shape.hxx b/include/oox/drawingml/shape.hxx new file mode 100644 index 000000000..5c4f788cd --- /dev/null +++ b/include/oox/drawingml/shape.hxx @@ -0,0 +1,430 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_SHAPE_HXX +#define INCLUDED_OOX_DRAWINGML_SHAPE_HXX + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace basegfx { class B2DHomMatrix; } + +namespace com::sun::star { + namespace awt { struct Rectangle; } + namespace drawing { class XShape; } + namespace drawing { class XShapes; } + namespace uno { class Any; } +} + +namespace oox::core { + class XmlFilterBase; +} + +namespace oox::vml { + struct OleObjectInfo; +} + +namespace svx::diagram { + class IDiagramHelper; +} + +namespace oox::drawingml { + +class Theme; +struct EffectProperties; +struct FillProperties; +struct GraphicProperties; +struct LineProperties; +struct Shape3DProperties; + +class CustomShapeProperties; +typedef std::shared_ptr< CustomShapeProperties > CustomShapePropertiesPtr; + +typedef ::std::map< OUString, ShapePtr > ShapeIdMap; + +typedef std::vector ConnectorShapePropertiesList; + +struct ShapeStyleRef +{ + Color maPhClr; + sal_Int32 mnThemedIdx; + ShapeStyleRef() : mnThemedIdx(0) {} +}; + +typedef ::std::map< sal_Int32, ShapeStyleRef > ShapeStyleRefMap; + +/** Additional information for a chart embedded in a drawing shape. */ +struct ChartShapeInfo +{ + OUString maFragmentPath; ///< Path to related XML stream, e.g. for charts. + bool mbEmbedShapes; ///< True = load chart shapes into chart, false = load into parent drawpage. + + explicit ChartShapeInfo( bool bEmbedShapes ) : mbEmbedShapes( bEmbedShapes ) {} +}; + +/// Attributes for a linked textbox. +struct LinkedTxbxAttr +{ + sal_Int32 id; + sal_Int32 seq; + LinkedTxbxAttr(): id(0),seq(0){}; +}; + +class Diagram; + +class OOX_DLLPUBLIC Shape + : public std::enable_shared_from_this< Shape > +{ +public: + + explicit Shape( const char* pServiceType = nullptr, bool bDefaultHeight = true ); + explicit Shape( const ShapePtr& pSourceShape ); + Shape(Shape const &) = default; + virtual ~Shape(); + Shape & operator =(Shape const &) = default; + + OUString& getServiceName(){ return msServiceName; } + void setServiceName( const char* pServiceName ); + + const OUString& getDiagramDataModelID() const { return msDiagramDataModelID; } + void setDiagramDataModelID( const OUString& rDiagramDataModelID ) { msDiagramDataModelID = rDiagramDataModelID; } + + PropertyMap& getShapeProperties(){ return maShapeProperties; } + + LineProperties& getLineProperties() { return *mpLinePropertiesPtr; } + const LineProperties& getLineProperties() const { return *mpLinePropertiesPtr; } + + FillProperties& getFillProperties() { return *mpFillPropertiesPtr; } + const FillProperties& getFillProperties() const { return *mpFillPropertiesPtr; } + + GraphicProperties& getGraphicProperties() { return *mpGraphicPropertiesPtr; } + const GraphicProperties& getGraphicProperties() const { return *mpGraphicPropertiesPtr; } + + CustomShapePropertiesPtr& getCustomShapeProperties(){ return mpCustomShapePropertiesPtr; } + + OUString& getConnectorName() { return msConnectorName; } + ConnectorShapePropertiesList& getConnectorShapeProperties() { return maConnectorShapePropertiesList; } + void setConnectorShape(bool bConnector) { mbConnector = bConnector; } + bool isConnectorShape() const { return mbConnector; } + + void setBookmark(bool bBookmark) { mbHasBookmark = bBookmark; } + bool hasBookmark() const { return mbHasBookmark; } + + Shape3DProperties& get3DProperties() { return *mp3DPropertiesPtr; } + const Shape3DProperties& get3DProperties() const { return *mp3DPropertiesPtr; } + + table::TablePropertiesPtr const & getTableProperties(); + + EffectProperties& getEffectProperties() const { return *mpEffectPropertiesPtr; } + + void setChildPosition( css::awt::Point nPosition ){ maChPosition = nPosition; } + void setChildSize( css::awt::Size aSize ){ maChSize = aSize; } + + void setPosition( css::awt::Point nPosition ){ maPosition = nPosition; } + const css::awt::Point& getPosition() const { return maPosition; } + + void setSize( css::awt::Size aSize ){ maSize = aSize; } + const css::awt::Size& getSize() const { return maSize; } + + void setRotation( sal_Int32 nRotation ) { mnRotation = nRotation; } + sal_Int32 getRotation() const { return mnRotation; } + void setDiagramRotation( sal_Int32 nRotation ) { mnDiagramRotation = nRotation; } + void setFlip( bool bFlipH, bool bFlipV ) { mbFlipH = bFlipH; mbFlipV = bFlipV; } + bool getFlipH() const { return mbFlipH; } + bool getFlipV() const { return mbFlipV; } + void addChild( const ShapePtr& rChildPtr ) { maChildren.push_back( rChildPtr ); } + std::vector< ShapePtr >& getChildren() { return maChildren; } + + void setName( const OUString& rName ) { msName = rName; } + const OUString& getName( ) const { return msName; } + void setInternalName( const OUString& rInternalName ) { msInternalName = rInternalName; } + const OUString& getInternalName() const { return msInternalName; } + void setId( const OUString& rId ) { msId = rId; } + const OUString& getId() const { return msId; } + void setDescription( const OUString& rDescr ) { msDescription = rDescr; } + void setHidden( bool bHidden ) { mbHidden = bHidden; } + void setHiddenMasterShape( bool bHiddenMasterShape ) { mbHiddenMasterShape = bHiddenMasterShape; } + void setLocked( bool bLocked ) { mbLocked = bLocked; } + void setSubType( sal_Int32 nSubType ) { mnSubType = nSubType; } + sal_Int32 getSubType() const { return mnSubType; } + void setSubTypeIndex( sal_Int32 nSubTypeIndex ) { moSubTypeIndex = nSubTypeIndex; } + const OptValue< sal_Int32 >& getSubTypeIndex() const { return moSubTypeIndex; } + + // setDefaults has to be called if styles are imported (OfficeXML is not storing properties having the default value) + void setDefaults(bool bHeight); + + ::oox::vml::OleObjectInfo& setOleObjectType(); + ChartShapeInfo& setChartType( bool bEmbedShapes ); + void setDiagramType(); + void setTableType(); + + void setTextBody(const TextBodyPtr & pTextBody); + const TextBodyPtr& getTextBody() const { return mpTextBody;} + void setMasterTextListStyle( const TextListStylePtr& pMasterTextListStyle ); + const TextListStylePtr& getMasterTextListStyle() const { return mpMasterTextListStyle; } + + ShapeStyleRefMap& getShapeStyleRefs() { return maShapeStyleRefs; } + const ShapeStyleRefMap& getShapeStyleRefs() const { return maShapeStyleRefs; } + const ShapeStyleRef* getShapeStyleRef( sal_Int32 nRefType ) const; + bool hasShapeStyleRefs() const { return !maShapeStyleRefs.empty(); } + + // addShape is creating and inserting the corresponding XShape. + void addShape( + ::oox::core::XmlFilterBase& rFilterBase, + const Theme* pTheme, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const basegfx::B2DHomMatrix& aTransformation, + const FillProperties& rShapeOrParentShapeFillProps, + ShapeIdMap* pShapeMap = nullptr, + oox::drawingml::ShapePtr pParentGroupShape = nullptr); + + const css::uno::Reference< css::drawing::XShape > & + getXShape() const { return mxShape; } + + void applyShapeReference( const Shape& rReferencedShape, bool bUseText = true ); + const ::std::vector& + getExtDrawings() const { return maExtDrawings; } + void addExtDrawingRelId( const OUString &rRelId ) { maExtDrawings.push_back( rRelId ); } + // Set font color only for extdrawings. + void setFontRefColorForNodes(const Color& rColor) { maFontRefColorForNodes = rColor; } + const Color& getFontRefColorForNodes() const { return maFontRefColorForNodes; } + void setLockedCanvas(bool bLockedCanvas); + bool getLockedCanvas() const { return mbLockedCanvas;} + void setWPGChild(bool bWPG); + bool isWPGChild() const { return mbWPGChild;} + void setWps(bool bWps); + bool getWps() const { return mbWps;} + void setTextBox(bool bTextBox); + const css::uno::Sequence & + getDiagramDoms() const { return maDiagramDoms; } + void setDiagramDoms(const css::uno::Sequence& rDiagramDoms) { maDiagramDoms = rDiagramDoms; } + css::uno::Sequence< css::uno::Sequence< css::uno::Any > >resolveRelationshipsOfTypeFromOfficeDoc( + core::XmlFilterBase& rFilter, const OUString& sFragment, std::u16string_view sType ); + void setLinkedTxbxAttributes(const LinkedTxbxAttr& rhs){ maLinkedTxbxAttr = rhs; }; + void setTxbxHasLinkedTxtBox( const bool rhs){ mbHasLinkedTxbx = rhs; }; + const LinkedTxbxAttr& getLinkedTxbxAttributes() const { return maLinkedTxbxAttr; }; + bool isLinkedTxbx() const { return mbHasLinkedTxbx; }; + + void setZOrder(sal_Int32 nZOrder) { mnZOrder = nZOrder; } + + sal_Int32 getZOrder() const { return mnZOrder; } + + void setZOrderOff(sal_Int32 nZOrderOff) { mnZOrderOff = nZOrderOff; } + + sal_Int32 getZOrderOff() const { return mnZOrderOff; } + + void setDataNodeType(sal_Int32 nDataNodeType) { mnDataNodeType = nDataNodeType; } + + sal_Int32 getDataNodeType() const { return mnDataNodeType; } + + void setAspectRatio(double fAspectRatio) { mfAspectRatio = fAspectRatio; } + + double getAspectRatio() const { return mfAspectRatio; } + + void setVerticalShapesCount(sal_Int32 nVerticalShapesCount) { mnVerticalShapesCount = nVerticalShapesCount; } + sal_Int32 getVerticalShapesCount() const { return mnVerticalShapesCount; } + + /// Changes reference semantics to value semantics for fill properties. + void cloneFillProperties(); + + void keepDiagramDrawing(::oox::core::XmlFilterBase& rFilterBase, const OUString& rFragmentPath); + + // Allows preparation of a local Diagram helper && propagate an eventually + // existing one to the data holder object later + void prepareDiagramHelper(const std::shared_ptr< Diagram >& rDiagramPtr, const std::shared_ptr<::oox::drawingml::Theme>& rTheme); + void propagateDiagramHelper(); + + // for Writer it is necessary to migrate an existing helper to a new Shape + void migrateDiagramHelperToNewShape(const ShapePtr& pTarget); + +protected: + + enum FrameType + { + FRAMETYPE_GENERIC, ///< Generic shape, no special type. + FRAMETYPE_OLEOBJECT, ///< OLE object embedded in a shape. + FRAMETYPE_CHART, ///< Chart embedded in a shape. + FRAMETYPE_DIAGRAM, ///< Complex diagram drawing shape. + FRAMETYPE_TABLE ///< A table embedded in a shape. + }; + + css::uno::Reference< css::drawing::XShape > const & + createAndInsert( + ::oox::core::XmlFilterBase& rFilterBase, + const OUString& rServiceName, + const Theme* pTheme, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + bool bClearText, + bool bDoNotInsertEmptyTextBody, + basegfx::B2DHomMatrix& aTransformation, + const FillProperties& rShapeOrParentShapeFillProps, + oox::drawingml::ShapePtr pParentGroupShape = nullptr + ); + + void addChildren( + ::oox::core::XmlFilterBase& rFilterBase, + Shape& rMaster, + const Theme* pTheme, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + ShapeIdMap* pShapeMap, + const basegfx::B2DHomMatrix& aTransformation ); + + void keepDiagramCompatibilityInfo(); + void convertSmartArtToMetafile( ::oox::core::XmlFilterBase const& rFilterBase ); + + css::uno::Reference< css::drawing::XShape > + renderDiagramToGraphic( ::oox::core::XmlFilterBase const & rFilterBase ); + + OUString finalizeServiceName( + ::oox::core::XmlFilterBase& rFilter, + const OUString& rServiceName, + const css::awt::Rectangle& rShapeRect ); + + virtual void finalizeXShape( + ::oox::core::XmlFilterBase& rFilter, + const css::uno::Reference< css::drawing::XShapes >& rxShapes ); + + void putPropertyToGrabBag( + const OUString& sPropertyName, const css::uno::Any& aPropertyValue ); + void putPropertyToGrabBag( + const css::beans::PropertyValue& pProperty ); + void putPropertiesToGrabBag( + const css::uno::Sequence< css::beans::PropertyValue >& aProperties ); + + FillProperties getActualFillProperties(const Theme* pTheme, const FillProperties* pParentShapeFillProps) const; + LineProperties getActualLineProperties(const Theme* pTheme) const; + EffectProperties getActualEffectProperties(const Theme* pTheme) const; + + std::vector< ShapePtr > maChildren; // only used for group shapes + css::awt::Size maChSize; // only used for group shapes + css::awt::Point maChPosition; // only used for group shapes + + TextBodyPtr mpTextBody; + LinePropertiesPtr mpLinePropertiesPtr; + LinePropertiesPtr mpShapeRefLinePropPtr; + FillPropertiesPtr mpFillPropertiesPtr; + FillPropertiesPtr mpShapeRefFillPropPtr; + GraphicPropertiesPtr mpGraphicPropertiesPtr; + CustomShapePropertiesPtr mpCustomShapePropertiesPtr; + table::TablePropertiesPtr mpTablePropertiesPtr; + Shape3DPropertiesPtr mp3DPropertiesPtr; + EffectPropertiesPtr mpEffectPropertiesPtr; + EffectPropertiesPtr mpShapeRefEffectPropPtr; + PropertyMap maShapeProperties; + PropertyMap maDefaultShapeProperties; + TextListStylePtr mpMasterTextListStyle; + css::uno::Reference< css::drawing::XShape > mxShape; + ConnectorShapePropertiesList maConnectorShapePropertiesList; + + OUString msConnectorName; + OUString msServiceName; + OUString msName; + OUString msInternalName; // used by diagram; not displayed in UI + OUString msId; + OUString msDescription; + sal_Int32 mnSubType; // if this type is not zero, then the shape is a placeholder + OptValue< sal_Int32 > moSubTypeIndex; + + ShapeStyleRefMap maShapeStyleRefs; + + css::awt::Size maSize; + css::awt::Point maPosition; + ::std::vector maExtDrawings; + Color maFontRefColorForNodes; + + FrameType meFrameType; ///< Type for graphic frame shapes. + +private: + + typedef std::shared_ptr< ::oox::vml::OleObjectInfo > OleObjectInfoRef; + typedef std::shared_ptr< ChartShapeInfo > ChartShapeInfoRef; + + OleObjectInfoRef mxOleObjectInfo; ///< Additional data for OLE objects. + ChartShapeInfoRef mxChartShapeInfo; ///< Additional data for chart shapes. + + sal_Int32 mnRotation; + sal_Int32 mnDiagramRotation; // rotates shape prior to sizing, does not affect text rotation + bool mbFlipH; + bool mbFlipV; + bool mbHidden; + bool mbHiddenMasterShape; // master shapes can be hidden in layout slides + // we need separate flag because we don't want + // to propagate it when applying reference shape + bool mbLocked; + bool mbWPGChild; // Is this shape a child of a WPG shape? + bool mbLockedCanvas; ///< Is this shape part of a locked canvas? + bool mbWps; ///< Is this a wps shape? + bool mbTextBox; ///< This shape has a textbox. + LinkedTxbxAttr maLinkedTxbxAttr; + bool mbHasLinkedTxbx; // this text box has linked text box ? + + css::uno::Sequence maDiagramDoms; + + /// Z-Order. + sal_Int32 mnZOrder = 0; + + /// Z-Order offset. + sal_Int32 mnZOrderOff = 0; + + /// Type of data node for an in-diagram shape. + sal_Int32 mnDataNodeType = 0; + + /// Aspect ratio for an in-diagram shape. + double mfAspectRatio = 0; + + /// Number of child shapes to be layouted vertically inside org chart in-diagram shape. + sal_Int32 mnVerticalShapesCount = 0; + + // Is this a connector shape? + bool mbConnector = false; + + // Is shape has bookmark? + bool mbHasBookmark = false; + + // temporary space for DiagramHelper in preparation for collecting data + // Note: I tried to use a unique_ptr here, but existing constructor func does not allow that + svx::diagram::IDiagramHelper* mpDiagramHelper; + + // association-ID to identify the Diagram ModelData + OUString msDiagramDataModelID; +}; + +} + +#endif // INCLUDED_OOX_DRAWINGML_SHAPE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/shapecontext.hxx b/include/oox/drawingml/shapecontext.hxx new file mode 100644 index 000000000..170f50403 --- /dev/null +++ b/include/oox/drawingml/shapecontext.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_SHAPECONTEXT_HXX +#define INCLUDED_OOX_DRAWINGML_SHAPECONTEXT_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::drawingml { + +class OOX_DLLPUBLIC ShapeContext : public ::oox::core::ContextHandler2 +{ +public: + ShapeContext( ::oox::core::ContextHandler2Helper const & rParent, ShapePtr const & pMasterShapePtr, ShapePtr const & pShapePtr ); + virtual ~ShapeContext() override; + + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; + + const ShapePtr& getShape() const { return mpShapePtr;} + +protected: + + ShapePtr mpMasterShapePtr; + ShapePtr mpShapePtr; +}; + +} + +#endif // INCLUDED_OOX_DRAWINGML_SHAPECONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/shapegroupcontext.hxx b/include/oox/drawingml/shapegroupcontext.hxx new file mode 100644 index 000000000..d9dfcbfa5 --- /dev/null +++ b/include/oox/drawingml/shapegroupcontext.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::drawingml { + +class OOX_DLLPUBLIC ShapeGroupContext : public ::oox::core::FragmentHandler2 +{ +public: + ShapeGroupContext( ::oox::core::FragmentHandler2 const & rParent, ShapePtr const & pMasterShapePtr, ShapePtr const & pGroupShapePtr ); + virtual ~ShapeGroupContext() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; + +protected: + ShapePtr mpGroupShapePtr; +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/shapepropertymap.hxx b/include/oox/drawingml/shapepropertymap.hxx new file mode 100644 index 000000000..7870ddee3 --- /dev/null +++ b/include/oox/drawingml/shapepropertymap.hxx @@ -0,0 +1,168 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_SHAPEPROPERTYMAP_HXX +#define INCLUDED_OOX_DRAWINGML_SHAPEPROPERTYMAP_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace oox { class ModelObjectHelper; } + +namespace oox::drawingml { + +/** Enumeration for various properties related to drawing shape formatting. + + This is an abstraction for shape formatting properties that have different + names in various implementations, e.g. drawing shapes vs. chart objects. + + If you *insert* ids into this list, then update spnCommonPropIds, spnLinearPropIds + and spnFilledPropIds of oox/source/drawingml/chart/objectformatter.cxx if + the newly inserted enum is inside the range they cover + */ +enum class ShapeProperty +{ + LineStyle, + LineWidth, + LineColor, + LineTransparency, + LineDash, ///< Explicit line dash or name of a line dash stored in a global container. + LineCap, + LineJoint, + LineStart, ///< Explicit line start marker or name of a line marker stored in a global container. + LineStartWidth, + LineStartCenter, + LineEnd, ///< Explicit line end marker or name of a line marker stored in a global container. + LineEndWidth, + LineEndCenter, + FillStyle, + FillColor, + FillTransparency, + GradientTransparency, + FillGradient, ///< Explicit fill gradient or name of a fill gradient stored in a global container. + FillBitmap, ///< Explicit fill bitmap or name of a fill bitmap stored in a global container. + FillBitmapMode, + FillBitmapSizeX, + FillBitmapSizeY, + FillBitmapOffsetX, + FillBitmapOffsetY, + FillBitmapRectanglePoint, + FillHatch, ///< Explicit fill hatch or name of a fill hatch stored in a global container. + FillBackground, + FillUseSlideBackground, + FillBitmapName, + ShadowXDistance, + ShadowSizeX, + ShadowSizeY, + LAST = ShadowSizeY +}; + +typedef o3tl::enumarray ShapePropertyIds; + +struct OOX_DLLPUBLIC ShapePropertyInfo +{ + const ShapePropertyIds& mrPropertyIds; + bool mbNamedLineMarker; /// True = use named line marker instead of explicit line marker. + bool mbNamedLineDash; /// True = use named line dash instead of explicit line dash. + bool mbNamedFillGradient; /// True = use named fill gradient instead of explicit fill gradient. + bool mbNamedFillBitmap; /// True = use named fill bitmap instead of explicit fill bitmap. + bool mbNamedFillHatch; /// True = use named fill hatch instead of explicit fill hatch. + + static ShapePropertyInfo DEFAULT; /// Default property info (used as default parameter of other methods). + + explicit ShapePropertyInfo(const ShapePropertyIds& rnPropertyIds, + bool bNamedLineMarker, bool bNamedLineDash, + bool bNamedFillGradient, bool bNamedFillBitmap, bool bNamedFillHatch); + + bool has(ShapeProperty ePropId) const + { + return mrPropertyIds[ePropId] >= 0; + } + sal_Int32 operator[](ShapeProperty ePropId) const + { + return mrPropertyIds[ePropId]; + } +}; + +class OOX_DLLPUBLIC ShapePropertyMap : public PropertyMap +{ +public: + explicit ShapePropertyMap(ModelObjectHelper& rModelObjHelper, + const ShapePropertyInfo& rShapePropInfo = ShapePropertyInfo::DEFAULT ); + + /** Returns true, if the specified property is supported. */ + bool supportsProperty( ShapeProperty ePropId ) const; + + /** Returns true, if named line markers are supported, and the specified + line marker has already been inserted into the marker table. */ + bool hasNamedLineMarkerInTable( const OUString& rMarkerName ) const; + + /** Sets the specified shape property to the passed value. */ + bool setAnyProperty( ShapeProperty ePropId, const css::uno::Any& rValue ); + + /** Sets the specified shape property to the passed value. */ + template + bool setProperty(ShapeProperty ePropId, const Type& rValue) + { + return setAnyProperty(ePropId, css::uno::Any(rValue)); + } + bool setProperty(ShapeProperty ePropId, const ::Color& rValue) + { + return setAnyProperty(ePropId, css::uno::Any(rValue)); + } + + using PropertyMap::setAnyProperty; + using PropertyMap::setProperty; + +private: + /** Sets an explicit line marker, or creates a named line marker. */ + bool setLineMarker( sal_Int32 nPropId, const css::uno::Any& rValue ); + /** Sets an explicit line dash, or creates a named line dash. */ + bool setLineDash( sal_Int32 nPropId, const css::uno::Any& rValue ); + /** Sets an explicit fill gradient, or creates a named fill gradient. */ + bool setFillGradient( sal_Int32 nPropId, const css::uno::Any& rValue ); + /** Creates a named transparency gradient. */ + bool setGradientTrans( sal_Int32 nPropId, const css::uno::Any& rValue ); + /** Sets an explicit fill bitmap, or creates a named fill bitmap. */ + bool setFillBitmap( sal_Int32 nPropId, const css::uno::Any& rValue ); + /** Sets an explicit fill bitmap and pushes the name to FillBitmapName */ + bool setFillBitmapName( const css::uno::Any& rValue ); + /** Sets an explicit fill hatch, or creates a named fill hatch. */ + bool setFillHatch( sal_Int32 nPropId, const css::uno::Any& rValue ); + + // not implemented, to prevent implicit conversion from enum to int + css::uno::Any& operator[]( ShapeProperty ePropId ) = delete; + const css::uno::Any& operator[]( ShapeProperty ePropId ) const = delete; + +private: + ModelObjectHelper& mrModelObjHelper; + ShapePropertyInfo maShapePropInfo; +}; + + +} // namespace oox::drawingml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/theme.hxx b/include/oox/drawingml/theme.hxx new file mode 100644 index 000000000..6222a4264 --- /dev/null +++ b/include/oox/drawingml/theme.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_THEME_HXX +#define INCLUDED_OOX_DRAWINGML_THEME_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace drawing { class XDrawPage; } + namespace xml::dom { class XDocument; } +} + +namespace oox::drawingml { + +struct EffectProperties; +struct FillProperties; +struct LineProperties; +struct TextCharacterProperties; + +const sal_Int32 THEMED_STYLE_SUBTLE = 1; +const sal_Int32 THEMED_STYLE_MODERATE = 2; +const sal_Int32 THEMED_STYLE_INTENSE = 3; + +typedef RefVector< FillProperties > FillStyleList; +typedef RefVector< LineProperties > LineStyleList; +typedef RefVector< EffectProperties > EffectStyleList; +typedef RefMap< sal_Int32, TextCharacterProperties > FontScheme; + +class TextFont; + +class OOX_DLLPUBLIC Theme +{ +public: + void setStyleName( const OUString& rStyleName ) { maStyleName = rStyleName; } + void setThemeName(const OUString& rThemeName) { maThemeName = rThemeName; } + + ClrScheme& getClrScheme() { return maClrScheme; } + const ClrScheme& getClrScheme() const { return maClrScheme; } + + FillStyleList& getFillStyleList() { return maFillStyleList; } + const FillStyleList& getFillStyleList() const { return maFillStyleList; } + FillStyleList& getBgFillStyleList() { return maBgFillStyleList; } + const FillStyleList& getBgFillStyleList() const { return maBgFillStyleList; } + /** Returns the fill properties of the passed one-based themed style index. */ + const FillProperties* getFillStyle( sal_Int32 nIndex ) const; + + LineStyleList& getLineStyleList() { return maLineStyleList; } + const LineStyleList& getLineStyleList() const { return maLineStyleList; } + /** Returns the line properties of the passed one-based themed style index. */ + const LineProperties* getLineStyle( sal_Int32 nIndex ) const; + + EffectStyleList& getEffectStyleList() { return maEffectStyleList; } + const EffectStyleList& getEffectStyleList() const { return maEffectStyleList; } + const EffectProperties* getEffectStyle( sal_Int32 nIndex ) const; + + FontScheme& getFontScheme() { return maFontScheme; } + const FontScheme& getFontScheme() const { return maFontScheme; } + /** Returns theme font properties by scheme type (major/minor). */ + const TextCharacterProperties* getFontStyle( sal_Int32 nSchemeType ) const; + /** Returns theme font by placeholder name, e.g. the major latin theme font for the font name '+mj-lt'. */ + const TextFont* resolveFont( const OUString& rName ) const; + + Shape& getSpDef() { return maSpDef; } + const Shape& getSpDef() const { return maSpDef; } + + Shape& getLnDef() { return maLnDef; } + const Shape& getLnDef() const { return maLnDef; } + + Shape& getTxDef() { return maTxDef; } + const Shape& getTxDef() const { return maTxDef; } + + const css::uno::Reference& getFragment() const { return mxFragment; } + void setFragment( const css::uno::Reference< css::xml::dom::XDocument>& xRef ) { mxFragment=xRef; } + + void addTheme(const css::uno::Reference& xDrawPage) const; + +private: + OUString maStyleName; + OUString maThemeName; + ClrScheme maClrScheme; + FillStyleList maFillStyleList; + FillStyleList maBgFillStyleList; + LineStyleList maLineStyleList; + EffectStyleList maEffectStyleList; + FontScheme maFontScheme; + Shape maSpDef; + Shape maLnDef; + Shape maTxDef; + css::uno::Reference< css::xml::dom::XDocument> mxFragment; +}; + + +} // namespace oox::drawingml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/drawingml/themefragmenthandler.hxx b/include/oox/drawingml/themefragmenthandler.hxx new file mode 100644 index 000000000..e433c350d --- /dev/null +++ b/include/oox/drawingml/themefragmenthandler.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DRAWINGML_THEMEFRAGMENTHANDLER_HXX +#define INCLUDED_OOX_DRAWINGML_THEMEFRAGMENTHANDLER_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class XmlFilterBase; } + +namespace oox::drawingml { + +class Theme; + + +class OOX_DLLPUBLIC ThemeFragmentHandler final : public ::oox::core::FragmentHandler2 +{ +public: + explicit ThemeFragmentHandler( + ::oox::core::XmlFilterBase& rFilter, + const OUString& rFragmentPath, + Theme& rTheme ); + virtual ~ThemeFragmentHandler() override; + + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + Theme& mrTheme; +}; + + +} // namespace oox::drawingml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/dump/dffdumper.hxx b/include/oox/dump/dffdumper.hxx new file mode 100644 index 000000000..e129b0a7f --- /dev/null +++ b/include/oox/dump/dffdumper.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DUMP_DFFDUMPER_HXX +#define INCLUDED_OOX_DUMP_DFFDUMPER_HXX + +#include +#include + +#ifdef DBG_UTIL + +namespace oox { class BinaryInputStream; } + +namespace oox::dump { + + +class DffStreamObject final : public SequenceRecordObjectBase +{ +public: + sal_uInt16 getVer() const { return mnInstVer & 0x000F; } + sal_uInt16 getInst() const { return (mnInstVer & 0xFFF0) >> 4; } + bool isContainer() const { return getVer() == 15; } + +private: + DffStreamObject() {} + + using SequenceRecordObjectBase::construct; + + virtual bool implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize ) override; + virtual void implWriteExtHeader() override; + virtual void implDumpRecordBody() override; + + sal_uInt32 dumpDffSimpleColor( const String& rName ); + + void dumpDffOpt(); + sal_uInt16 dumpDffOptPropHeader(); + + sal_uInt16 mnInstVer; + sal_Int32 mnRealSize; +}; + + +} // namespace oox::dump + +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/dump/dumperbase.hxx b/include/oox/dump/dumperbase.hxx new file mode 100644 index 000000000..10d3ed78a --- /dev/null +++ b/include/oox/dump/dumperbase.hxx @@ -0,0 +1,1740 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DUMP_DUMPERBASE_HXX +#define INCLUDED_OOX_DUMP_DUMPERBASE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef DBG_UTIL + +namespace com::sun::star { + namespace io { class XInputStream; } + namespace io { class XOutputStream; } + namespace io { class XTextOutputStream2; } + namespace uno { class XComponentContext; } +} + +namespace oox { + class TextInputStream; +} + +namespace oox::core { + class FilterBase; +} + +namespace oox::dump { + + +inline constexpr OUStringLiteral OOX_DUMP_UNUSED = u"unused"; +inline constexpr OUStringLiteral OOX_DUMP_UNKNOWN = u"?unknown"; + +#define OOX_DUMP_ERRASCII( ascii ) "?err:" ascii + +#define OOX_DUMP_ERR_NOMAP "no-map" +inline constexpr OUStringLiteral OOX_DUMP_ERR_NONAME = u"no-name"; +#define OOX_DUMP_ERR_STREAM "stream-error" + +#define OOX_DUMP_DUMPEXT ".dump" + +const sal_Unicode OOX_DUMP_STRQUOTE = '\''; +const sal_Unicode OOX_DUMP_FMLASTRQUOTE = '"'; +const sal_Unicode OOX_DUMP_ADDRABS = '$'; +const sal_Unicode OOX_DUMP_R1C1ROW = 'R'; +const sal_Unicode OOX_DUMP_R1C1COL = 'C'; +const sal_Unicode OOX_DUMP_R1C1OPEN = '['; +const sal_Unicode OOX_DUMP_R1C1CLOSE = ']'; +const sal_Unicode OOX_DUMP_RANGESEP = ':'; +const sal_Unicode OOX_DUMP_BASECLASS = 'B'; +const sal_Unicode OOX_DUMP_FUNCSEP = ','; +const sal_Unicode OOX_DUMP_LISTSEP = ','; +const sal_Unicode OOX_DUMP_TABSEP = '!'; +const sal_Unicode OOX_DUMP_ARRAYSEP = ';'; +const sal_Unicode OOX_DUMP_EMPTYVALUE = '~'; +const sal_Unicode OOX_DUMP_CMDPROMPT = '?'; +const sal_Unicode OOX_DUMP_PLACEHOLDER = '\x01'; + +typedef ::std::pair< OUString, OUString > OUStringPair; + +typedef ::std::vector< OUString > OUStringVector; +typedef ::std::vector< sal_Int64 > Int64Vector; + + +/** Static helper functions for system file and stream access. */ +class InputOutputHelper +{ +public: + // file names ------------------------------------------------------------- + + static OUString convertFileNameToUrl( const OUString& rFileName ); + static sal_Int32 getFileNamePos( std::u16string_view rFileUrl ); + static std::u16string_view getFileNameExtension( std::u16string_view rFileUrl ); + + // input streams ---------------------------------------------------------- + + static css::uno::Reference< css::io::XInputStream > + openInputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& rFileName ); + + // output streams --------------------------------------------------------- + + static css::uno::Reference< css::io::XOutputStream > + openOutputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& rFileName ); + + static css::uno::Reference< css::io::XTextOutputStream2 > + openTextOutputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XOutputStream >& rxOutStrm, + rtl_TextEncoding eTextEnc ); + + static css::uno::Reference< css::io::XTextOutputStream2 > + openTextOutputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& rFileName, + rtl_TextEncoding eTextEnc ); +}; + + +class BinaryInputStreamRef : public ::oox::BinaryInputStreamRef +{ +public: + BinaryInputStreamRef() {} + + /*implicit*/ BinaryInputStreamRef( std::shared_ptr const & pInStrm ) : + ::oox::BinaryInputStreamRef( pInStrm ) {} + + /*implicit*/ BinaryInputStreamRef( const css::uno::Reference< css::io::XInputStream >& rxInStrm ) : + ::oox::BinaryInputStreamRef( std::make_shared( rxInStrm, true ) ) {} + + template< typename StreamType > + /*implicit*/ BinaryInputStreamRef( const std::shared_ptr< StreamType >& rxInStrm ) : + ::oox::BinaryInputStreamRef( rxInStrm ) {} +}; + + +/** Specifiers for atomic data types. */ +enum DataType +{ + DATATYPE_VOID, ///< No data type. + DATATYPE_INT8, ///< Signed 8-bit integer. + DATATYPE_UINT8, ///< Unsigned 8-bit integer. + DATATYPE_INT16, ///< Signed 16-bit integer. + DATATYPE_UINT16, ///< Unsigned 16-bit integer. + DATATYPE_INT32, ///< Signed 32-bit integer. + DATATYPE_UINT32, ///< Unsigned 32-bit integer. + DATATYPE_INT64, ///< Signed 64-bit integer. + DATATYPE_UINT64, ///< Unsigned 64-bit integer. + DATATYPE_FLOAT, ///< Floating-point, single precision. + DATATYPE_DOUBLE ///< Floating-point, double precision. +}; + + +/** Specifiers for the output format of values. */ +enum FormatType +{ + FORMATTYPE_NONE, ///< No numeric format (e.g. show name only). + FORMATTYPE_DEC, ///< Decimal. + FORMATTYPE_HEX, ///< Hexadecimal. + FORMATTYPE_SHORTHEX, ///< Hexadecimal, as short as possible (no leading zeros). + FORMATTYPE_BIN, ///< Binary. + FORMATTYPE_FIX, ///< Fixed-point. + FORMATTYPE_BOOL ///< Boolean ('true' or 'false'). +}; + + +/** Describes the output format of a data item. + + Data items are written in the following format: + + == + + NAME is the name of the data item. The name is contained in the member + maItemName. If the name is empty, only the value is written (without a + leading equality sign). + + VALUE is the numeric value of the data item. Its format is dependent on the + output format given in the member meFmtType. If the format type is + FORMATTYPE_NONE, no value is written. + + NAME-FROM-LIST is a symbolic name for the current value of the data item. + Various types of name lists produce different names for values, which can + be used for enumerations or names for single bits in bitfields (see class + NameListBase and derived classes). The name of the list is given in the + member maListName. If it is empty, no name is written for the value. + */ +struct ItemFormat +{ + DataType meDataType; ///< Data type of the item. + FormatType meFmtType; ///< Output format for the value. + OUString maItemName; ///< Name of the item. + OUString maListName; ///< Name of a name list to be used for this item. + + explicit ItemFormat(); + + void set( DataType eDataType, FormatType eFmtType, const OUString& rItemName ); + + /** Initializes the struct from a vector of strings containing the item format. + + The vector must contain at least 2 strings. The struct is filled from + the strings in the vector in the following order: + 1) Data type (one of: [u]int8, [u]int16, [u]int32, [u]int64, float, double). + 2) Format type (one of: dec, hex, shorthex, bin, fix, bool, unused, unknown). + 3) Item name (optional). + 4) Name list name (optional). + + @return Iterator pointing to the first unhandled string. + */ + OUStringVector::const_iterator parse( const OUStringVector& rFormatVec ); + + /** Initializes the struct from a string containing the item format. + + The string must have the following format: + DATATYPE,FORMATTYPE[,ITEMNAME[,LISTNAME]] + + DATATYPE is the data type of the item (see above for possible values). + FORMATTYPE is the format type of the item (see above for possible values). + ITEMNAME is the name of the item (optional). + LISTNAME is the name of a name list (optional). + + @return List containing remaining unhandled format strings. + */ + OUStringVector parse( const OUString& rFormatStr ); +}; + + +/** Static helper functions for formatted output to strings. */ +class StringHelper +{ +public: + // append string to string ------------------------------------------------ + + static void appendChar( OUStringBuffer& rStr, sal_Unicode cChar, sal_Int32 nCount ); + static void appendString( OUStringBuffer& rStr, const OUString& rData, sal_Int32 nWidth, sal_Unicode cFill = ' ' ); + + // append decimal --------------------------------------------------------- + + static void appendDec( OUStringBuffer& rStr, sal_uInt8 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_Int8 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_uInt16 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_Int16 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_uInt32 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_Int32 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_uInt64 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, sal_Int64 nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + static void appendDec( OUStringBuffer& rStr, double fData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ); + + // append hexadecimal ----------------------------------------------------- + + static void appendHex( OUStringBuffer& rStr, sal_uInt8 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_Int8 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_uInt16 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_Int16 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_uInt32 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_Int32 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_uInt64 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, sal_Int64 nData, bool bPrefix = true ); + static void appendHex( OUStringBuffer& rStr, double fData, bool bPrefix = true ); + + // append shortened hexadecimal ------------------------------------------- + + static void appendShortHex( OUStringBuffer& rStr, sal_uInt8 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_Int8 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_uInt16 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_Int16 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_uInt32 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_Int32 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_uInt64 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, sal_Int64 nData, bool bPrefix = true ); + static void appendShortHex( OUStringBuffer& rStr, double fData, bool bPrefix = true ); + + // append binary ---------------------------------------------------------- + + static void appendBin( OUStringBuffer& rStr, sal_uInt8 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_Int8 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_uInt16 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_Int16 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_uInt32 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_Int32 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_uInt64 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, sal_Int64 nData, bool bDots = true ); + static void appendBin( OUStringBuffer& rStr, double fData, bool bDots = true ); + + // append fixed-point decimal --------------------------------------------- + + template< typename Type > + static void appendFix( OUStringBuffer& rStr, Type nData, sal_Int32 nWidth = 0 ); + + // append formatted value ------------------------------------------------- + + static void appendBool( OUStringBuffer& rStr, bool bData ); + template< typename Type > + static void appendValue( OUStringBuffer& rStr, Type nData, FormatType eFmtType ); + + // encoded text output ---------------------------------------------------- + + static void appendCChar( OUStringBuffer& rStr, sal_Unicode cChar, bool bPrefix = true ); + static void appendEncChar( OUStringBuffer& rStr, sal_Unicode cChar, sal_Int32 nCount, bool bPrefix = true ); + static void appendEncString( OUStringBuffer& rStr, const OUString& rData, bool bPrefix = true ); + + // token list ------------------------------------------------------------- + + static void appendToken( OUStringBuffer& rStr, std::u16string_view rToken, sal_Unicode cSep = OOX_DUMP_LISTSEP ); + + static void appendIndex( OUStringBuffer& rStr, sal_Int64 nIdx ); + + static std::u16string_view getToken( std::u16string_view rData, sal_Int32& rnPos, sal_Unicode cSep = OOX_DUMP_LISTSEP ); + + /** Encloses the passed string with the passed characters. Uses cOpen, if cClose is NUL. */ + static void enclose( OUStringBuffer& rStr, sal_Unicode cOpen, sal_Unicode cClose = '\0' ); + + // string conversion ------------------------------------------------------ + + static std::u16string_view trimSpaces( std::u16string_view rStr ); + static OUString trimTrailingNul( const OUString& rStr ); + + static OString convertToUtf8( std::u16string_view rStr ); + static DataType convertToDataType( std::u16string_view rStr ); + static FormatType convertToFormatType( std::u16string_view rStr ); + + static bool convertFromDec( sal_Int64& ornData, std::u16string_view rData ); + static bool convertFromHex( sal_Int64& ornData, std::u16string_view rData ); + + static bool convertStringToInt( sal_Int64& ornData, std::u16string_view rData ); + static bool convertStringToDouble( double& orfData, std::u16string_view rData ); + static bool convertStringToBool( std::u16string_view rData ); + + static OUStringPair convertStringToPair( const OUString& rString, sal_Unicode cSep = '=' ); + + // string to list conversion ---------------------------------------------- + + static void convertStringToStringList( OUStringVector& orVec, const OUString& rData, bool bIgnoreEmpty ); + static void convertStringToIntList( Int64Vector& orVec, const OUString& rData, bool bIgnoreEmpty ); +}; + + +template< typename Type > +void StringHelper::appendFix( OUStringBuffer& rStr, Type nData, sal_Int32 nWidth ) +{ + appendDec( rStr, static_cast< double >( nData ) / std::pow( 2.0, 4.0 * sizeof( Type ) ), nWidth ); +} + +template< typename Type > +void StringHelper::appendValue( OUStringBuffer& rStr, Type nData, FormatType eFmtType ) +{ + switch( eFmtType ) + { + case FORMATTYPE_DEC: appendDec( rStr, nData ); break; + case FORMATTYPE_HEX: appendHex( rStr, nData ); break; + case FORMATTYPE_SHORTHEX: appendShortHex( rStr, nData ); break; + case FORMATTYPE_BIN: appendBin( rStr, nData ); break; + case FORMATTYPE_FIX: appendFix( rStr, nData ); break; + case FORMATTYPE_BOOL: appendBool( rStr, static_cast(nData) ); break; // avoid loplugin:pointerbool warning + default:; + } +} + + +class String : public OUString +{ +public: + String() {} + /*implicit*/ String( const OUString& rStr ) : OUString( rStr ) {} + /*implicit*/ String( const char* pcStr ) : OUString( OUString::createFromAscii( pcStr ? pcStr : "" ) ) {} + /*implicit*/ String( sal_Unicode cChar ) : OUString( cChar ) {} + + bool has() const { return getLength() > 0; } + OUString operator()( const char* pcDefault ) const { if( has() ) return *this; return String( pcDefault ); } +}; + +const String EMPTY_STRING; + + +/** Base class for all dumper classes. + + Derived classes implement the virtual function implIsValid(). It should + check all members the other functions rely on. If the function + implIsValid() returns true, all references and pointers can be used without + further checking. + + Overview of all classes in this header file based on this Base class: + + Base + | + +----> NameListBase + | | + | +----> ConstList ------> MultiList + | | + | +----> FlagsList ------> CombiList + | | + | +----> UnitConverter + | + +----> SharedConfigData + | + +----> Config + | + +----> Output + | + +----> StorageIterator + | + +----> ObjectBase + | + +----> StorageObjectBase + | + +----> OutputObjectBase + | | + | +----> InputObjectBase + | | + | +----> BinaryStreamObject + | | + | +----> TextStreamObjectBase + | | | + | | +----> TextStreamObject + | | | + | | +----> XmlStreamObject + | | + | +----> RecordObjectBase + | | + | +----> SequenceRecordObjectBase + | + +----> DumperBase + */ +class Base +{ +public: + virtual ~Base(); + + Base(Base const &) = default; + Base(Base &&) = default; + Base & operator =(Base const &) = default; + Base & operator =(Base &&) = default; + + bool isValid() const { return implIsValid(); } + static bool isValid( const std::shared_ptr< Base >& rxBase ) { return rxBase && rxBase->isValid(); } + +protected: + Base() {} + + virtual bool implIsValid() const = 0; +}; + + +class ConfigItemBase +{ +public: + virtual ~ConfigItemBase(); + void readConfigBlock( TextInputStream& rStrm ); + +protected: + ConfigItemBase() {} + + virtual void implProcessConfigItemStr( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ); + + virtual void implProcessConfigItemInt( + TextInputStream& rStrm, + sal_Int64 nKey, + const OUString& rData ); + + void readConfigBlockContents( + TextInputStream& rStrm ); + +private: + enum LineType { LINETYPE_DATA, LINETYPE_END }; + + static LineType readConfigLine( + TextInputStream& rStrm, + OUString& orKey, + OUString& orData ); + + void processConfigItem( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ); +}; + + +class SharedConfigData; +class Config; + +class NameListBase; +typedef std::shared_ptr< NameListBase > NameListRef; + +/** Base class of all classes providing names for specific values (name lists). + + The idea is to provide a unique interface for all different methods to + write specific names for any values. This can be enumerations (dedicated + names for a subset of values), or names for bits in bit fields. Classes + derived from this base class implement the specific behaviour for the + desired purpose. + */ +class NameListBase : public Base, public ConfigItemBase +{ +public: + typedef ::std::map< sal_Int64, OUString > OUStringMap; + typedef OUStringMap::const_iterator const_iterator; + +public: + virtual ~NameListBase() override; + + /** Sets a name for the specified key. */ + void setName( sal_Int64 nKey, const String& rName ); + + /** Include all names of the passed list. */ + void includeList( const NameListRef& rxList ); + + /** Returns true, if the map contains an entry for the passed key. */ + template< typename Type > + bool hasName( Type nKey ) const + { return maMap.count( static_cast< sal_Int64 >( nKey ) ) != 0; } + + /** Returns the name for the passed key. */ + template< typename Type > + OUString getName( const Config& rCfg, Type nKey ) const + { return implGetName( rCfg, static_cast< sal_Int64 >( nKey ) ); } + + /** Returns a display name for the passed double value. */ + OUString getName( const Config& rCfg, double fValue ) const + { return implGetNameDbl( rCfg, fValue ); } + + /** Returns a map iterator pointing to the first contained name. */ + const_iterator begin() const { return maMap.begin(); } + /** Returns a map iterator pointing one past the last contained name. */ + const_iterator end() const { return maMap.end(); } + +protected: + explicit NameListBase( const SharedConfigData& rCfgData ) : mrCfgData( rCfgData ) {} + + virtual bool implIsValid() const override; + + virtual void implProcessConfigItemStr( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ) override; + + virtual void implProcessConfigItemInt( + TextInputStream& rStrm, + sal_Int64 nKey, + const OUString& rData ) override; + + /** Derived classes set the name for the passed key. */ + virtual void implSetName( sal_Int64 nKey, const OUString& rName ) = 0; + /** Derived classes generate and return the name for the passed key. */ + virtual OUString implGetName( const Config& rCfg, sal_Int64 nKey ) const = 0; + /** Derived classes generate and return the name for the passed double value. */ + virtual OUString implGetNameDbl( const Config& rCfg, double fValue ) const = 0; + /** Derived classes insert all names and other settings from the passed list. */ + virtual void implIncludeList( const NameListBase& rList ) = 0; + + /** Inserts the passed name into the internal map. */ + void insertRawName( sal_Int64 nKey, const OUString& rName ); + /** Returns the name for the passed key, or 0, if nothing found. */ + const OUString* findRawName( sal_Int64 nKey ) const; + +private: + /** Includes name lists, given in a comma separated list of names of the lists. */ + void include( const OUString& rListKeys ); + /** Excludes names from the list, given in a comma separated list of their keys. */ + void exclude( const OUString& rKeys ); + +private: + OUStringMap maMap; + const SharedConfigData& mrCfgData; +}; + + +class ConstList : public NameListBase +{ +public: + explicit ConstList( const SharedConfigData& rCfgData ); + + /** Enables or disables automatic quotation of returned names. */ + void setQuoteNames( bool bQuoteNames ) { mbQuoteNames = bQuoteNames; } + +protected: + virtual void implProcessConfigItemStr( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ) override; + + /** Sets the name for the passed key. */ + virtual void implSetName( sal_Int64 nKey, const OUString& rName ) override; + /** Returns the name for the passed key, or the default name, if key is not contained. */ + virtual OUString implGetName( const Config& rCfg, sal_Int64 nKey ) const override; + /** Returns the name for the passed double value. */ + virtual OUString implGetNameDbl( const Config& rCfg, double fValue ) const override; + /** Inserts all names from the passed list. */ + virtual void implIncludeList( const NameListBase& rList ) override; + +private: + OUString maDefName; + bool mbQuoteNames; +}; + + +class MultiList : public ConstList +{ +public: + explicit MultiList( const SharedConfigData& rCfgData ); + + void setNamesFromVec( sal_Int64 nStartKey, const OUStringVector& rNames ); + +protected: + virtual void implProcessConfigItemStr( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ) override; + + virtual void implSetName( sal_Int64 nKey, const OUString& rName ) override; + +private: + bool mbIgnoreEmpty; +}; + + +class FlagsList : public NameListBase +{ +public: + explicit FlagsList( const SharedConfigData& rCfgData ); + + /** Returns the flags to be ignored on output. */ + sal_Int64 getIgnoreFlags() const { return mnIgnore; } + /** Sets flags to be ignored on output. */ + void setIgnoreFlags( sal_Int64 nIgnore ) { mnIgnore = nIgnore; } + +protected: + virtual void implProcessConfigItemStr( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ) override; + + /** Sets the name for the passed key. */ + virtual void implSetName( sal_Int64 nKey, const OUString& rName ) override; + /** Returns the name for the passed key. */ + virtual OUString implGetName( const Config& rCfg, sal_Int64 nKey ) const override; + /** Returns the name for the passed double value. */ + virtual OUString implGetNameDbl( const Config& rCfg, double fValue ) const override; + /** Inserts all flags from the passed list. */ + virtual void implIncludeList( const NameListBase& rList ) override; + +private: + sal_Int64 mnIgnore; +}; + + +class CombiList : public FlagsList +{ +public: + explicit CombiList( const SharedConfigData& rCfgData ); + +protected: + /** Sets the name for the passed key. */ + virtual void implSetName( sal_Int64 nKey, const OUString& rName ) override; + /** Returns the name for the passed key. */ + virtual OUString implGetName( const Config& rCfg, sal_Int64 nKey ) const override; + /** Inserts all flags from the passed list. */ + virtual void implIncludeList( const NameListBase& rList ) override; + +private: + struct ExtItemFormatKey + { + sal_Int64 mnKey; + ::std::pair< sal_Int64, sal_Int64 > maFilter; + explicit ExtItemFormatKey( sal_Int64 nKey ) : mnKey( nKey ), maFilter( 0, 0 ) {} + bool operator<( const ExtItemFormatKey& rRight ) const; + + }; + struct ExtItemFormat : public ItemFormat + { + bool mbShiftValue; + ExtItemFormat() : mbShiftValue( true ) {} + }; + typedef ::std::map< ExtItemFormatKey, ExtItemFormat > ExtItemFormatMap; + ExtItemFormatMap maFmtMap; +}; + + +class UnitConverter : public NameListBase +{ +public: + explicit UnitConverter( const SharedConfigData& rCfgData ); + + void setUnitName( const String& rUnitName ) { maUnitName = rUnitName; } + void setFactor( double fFactor ) { mfFactor = fFactor; } + +protected: + /** Sets the name for the passed key. */ + virtual void implSetName( sal_Int64 nKey, const OUString& rName ) override; + /** Returns the converted value with appended unit name. */ + virtual OUString implGetName( const Config& rCfg, sal_Int64 nKey ) const override; + /** Returns the converted value with appended unit name. */ + virtual OUString implGetNameDbl( const Config& rCfg, double fValue ) const override; + /** Empty implementation. */ + virtual void implIncludeList( const NameListBase& rList ) override; + +private: + OUString maUnitName; + double mfFactor; +}; + + +class NameListWrapper +{ +public: + NameListWrapper() {} + /*implicit*/ NameListWrapper( const OUString& rListName ) : maName( rListName ) {} + /*implicit*/ NameListWrapper( const char* pcListName ) : maName( pcListName ) {} + /*implicit*/ NameListWrapper( const NameListRef& rxList ) : mxList( rxList ) {} + + bool isEmpty() const { return !mxList && !maName.has(); } + const NameListRef & getNameList( const Config& rCfg ) const; + +private: + String maName; + mutable NameListRef mxList; +}; + +const NameListWrapper NO_LIST; + + +class ItemFormatMap +{ +private: + ::std::map< sal_Int64, ItemFormat > maMap; + +public: + ItemFormatMap() {} + explicit ItemFormatMap( const NameListRef& rxNameList ) { insertFormats( rxNameList ); } + + ::std::map< sal_Int64, ItemFormat >::const_iterator end() const { return maMap.end(); } + ::std::map< sal_Int64, ItemFormat >::const_iterator find(sal_Int64 nId) const + { + return maMap.find(nId); + } + + void insertFormats( const NameListRef& rxNameList ); +}; + + +class SharedConfigData : public Base, public ConfigItemBase +{ +public: + explicit SharedConfigData( + const OUString& rFileName, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const StorageRef& rxRootStrg, + const OUString& rSysFileName ); + + virtual ~SharedConfigData() override; + + const css::uno::Reference< css::uno::XComponentContext >& getContext() const { return mxContext; } + const StorageRef& getRootStorage() const { return mxRootStrg; } + const OUString& getSysFileName() const { return maSysFileName; } + + const OUString* getOption( const OUString& rKey ) const; + + template< typename ListType > + std::shared_ptr< ListType > createNameList( const OUString& rListName ); + void setNameList( const OUString& rListName, const NameListRef& rxList ); + void eraseNameList( const OUString& rListName ); + NameListRef getNameList( const OUString& rListName ) const; + +protected: + virtual bool implIsValid() const override; + virtual void implProcessConfigItemStr( + TextInputStream& rStrm, + const OUString& rKey, + const OUString& rData ) override; + +private: + bool readConfigFile( const OUString& rFileUrl ); + template< typename ListType > + void readNameList( TextInputStream& rStrm, const OUString& rListName ); + void createShortList( const OUString& rData ); + void createUnitConverter( const OUString& rData ); + +private: + typedef ::std::set< OUString > ConfigFileSet; + typedef ::std::map< OUString, OUString > ConfigDataMap; + typedef ::std::map< OUString, NameListRef > NameListMap; + + css::uno::Reference< css::uno::XComponentContext > mxContext; + StorageRef mxRootStrg; + OUString maSysFileName; + ConfigFileSet maConfigFiles; + ConfigDataMap maConfigData; + NameListMap maNameLists; + OUString maConfigPath; + bool mbLoaded; +}; + + +template< typename ListType > +std::shared_ptr< ListType > SharedConfigData::createNameList( const OUString& rListName ) +{ + std::shared_ptr< ListType > xList; + if( !rListName.isEmpty() ) + { + xList = std::make_shared( *this ); + setNameList( rListName, xList ); + } + return xList; +} + +template< typename ListType > +void SharedConfigData::readNameList( TextInputStream& rStrm, const OUString& rListName ) +{ + NameListRef xList = createNameList< ListType >( rListName ); + if( xList ) + xList->readConfigBlock( rStrm ); +} + + +class Config : public Base +{ +public: + explicit Config( + const char* pcEnvVar, + const ::oox::core::FilterBase& rFilter ); + explicit Config( + const char* pcEnvVar, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const StorageRef& rxRootStrg, + const OUString& rSysFileName ); + + virtual ~Config() override; + + Config(Config const &) = default; + Config(Config &&) = default; + Config & operator =(Config const &) = default; + Config & operator =(Config &&) = default; + + const css::uno::Reference< css::uno::XComponentContext >& getContext() const { return mxCfgData->getContext(); } + const StorageRef& getRootStorage() const { return mxCfgData->getRootStorage(); } + const OUString& getSysFileName() const { return mxCfgData->getSysFileName(); } + + const OUString& getStringOption( const String& rKey, const OUString& rDefault ) const; + bool getBoolOption( const String& rKey, bool bDefault ) const; + template< typename Type > + Type getIntOption( const String& rKey, Type nDefault ) const; + + bool isDumperEnabled() const; + bool isImportEnabled() const; + + template< typename ListType > + std::shared_ptr< ListType > createNameList( const String& rListName ); + void eraseNameList( const String& rListName ); + NameListRef getNameList( const String& rListName ) const; + + /** Returns the name for the passed key from the passed name list. */ + template< typename Type > + OUString getName( const NameListWrapper& rListWrp, Type nKey ) const; + /** Returns true, if the passed name list contains an entry for the passed key. */ + template< typename Type > + bool hasName( const NameListWrapper& rListWrp, Type nKey ) const; + +protected: + Config() {} + void construct( + const char* pcEnvVar, + const ::oox::core::FilterBase& rFilter ); + void construct( + const char* pcEnvVar, + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const StorageRef& rxRootStrg, + const OUString& rSysFileName ); + + virtual bool implIsValid() const override; + const OUString* implGetOption( const OUString& rKey ) const; + +private: + std::shared_ptr< SharedConfigData > mxCfgData; +}; + +typedef std::shared_ptr< Config > ConfigRef; + + +template< typename Type > +Type Config::getIntOption( const String& rKey, Type nDefault ) const +{ + sal_Int64 nRawData; + const OUString* pData = implGetOption( rKey ); + return (pData && StringHelper::convertStringToInt( nRawData, *pData )) ? + static_cast< Type >( nRawData ) : nDefault; +} + +template< typename ListType > +std::shared_ptr< ListType > Config::createNameList( const String& rListName ) +{ + return mxCfgData->createNameList< ListType >( rListName ); +} + +template< typename Type > +OUString Config::getName( const NameListWrapper& rListWrp, Type nKey ) const +{ + NameListRef xList = rListWrp.getNameList( *this ); + return xList ? xList->getName( *this, nKey ) : OOX_DUMP_ERR_NOMAP; +} + +template< typename Type > +bool Config::hasName( const NameListWrapper& rListWrp, Type nKey ) const +{ + NameListRef xList = rListWrp.getNameList( *this ); + return xList.get() && xList->hasName( nKey ); +} + + +class Output : public Base +{ +public: + explicit Output( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const OUString& rFileName ); + + + void newLine(); + void emptyLine( size_t nCount = 1 ); + + void incIndent(); + void decIndent(); + + void startTable( sal_Int32 nW1 ); + void startTable( sal_Int32 nW1, sal_Int32 nW2 ); + void startTable( sal_Int32 nW1, sal_Int32 nW2, sal_Int32 nW3, sal_Int32 nW4 ); + void startTable( size_t nColCount, const sal_Int32* pnColWidths ); + void tab(); + void tab( size_t nCol ); + void endTable(); + + void resetItemIndex( sal_Int64 nIdx = 0 ); + void startItem( const String& rItemName ); + void contItem(); + void endItem(); + + void startMultiItems(); + void endMultiItems(); + + void writeChar( sal_Unicode cChar, sal_Int32 nCount = 1 ); + void writeAscii( const char* pcStr ); + void writeString( const OUString& rStr ); + void writeArray( const sal_uInt8* pnData, std::size_t nSize, sal_Unicode cSep = OOX_DUMP_LISTSEP ); + void writeBool( bool bData ); + void writeDateTime( const css::util::DateTime& rDateTime ); + + template< typename Type > + void writeDec( Type nData, sal_Int32 nWidth = 0, sal_Unicode cFill = ' ' ) + { StringHelper::appendDec( maLine, nData, nWidth, cFill ); } + template< typename Type > + void writeHex( Type nData, bool bPrefix = true ) + { StringHelper::appendHex( maLine, nData, bPrefix ); } + template< typename Type > + void writeShortHex( Type nData, bool bPrefix = true ) + { StringHelper::appendShortHex( maLine, nData, bPrefix ); } + template< typename Type > + void writeBin( Type nData, bool bDots = true ) + { StringHelper::appendBin( maLine, nData, bDots ); } + template< typename Type > + void writeFix( Type nData, sal_Int32 nWidth ) + { StringHelper::appendFix( maLine, nData, nWidth ); } + template< typename Type > + void writeValue( Type nData, FormatType eFmtType ) + { StringHelper::appendValue( maLine, nData, eFmtType ); } + template< typename Type > + void writeName( const Config& rCfg, Type nData, const NameListWrapper& rListWrp ) + { writeString( rCfg.getName( rListWrp, nData ) ); } + + +protected: + virtual bool implIsValid() const override; + +private: + void writeItemName( const String& rItemName ); + +private: + css::uno::Reference< css::io::XTextOutputStream2 > mxStrm; + OUString maIndent; + OUStringBuffer maLine; + OUString maLastItem; + ::std::vector< sal_Int32 > + maColPos; + size_t mnCol; + size_t mnItemLevel; + size_t mnMultiLevel; + sal_Int64 mnItemIdx; + sal_Int32 mnLastItem; +}; + +typedef std::shared_ptr< Output > OutputRef; + + +class IndentGuard +{ +public: + explicit IndentGuard( const OutputRef& rxOut ) : mrOut( *rxOut ) { mrOut.incIndent(); } + ~IndentGuard() { mrOut.decIndent(); } +private: + IndentGuard( const IndentGuard& ) = delete; + IndentGuard& operator=( const IndentGuard& ) = delete; +private: + Output& mrOut; +}; + + +class TableGuard +{ +public: + explicit TableGuard( const OutputRef& rxOut, sal_Int32 nW1 ) : + mrOut( *rxOut ) { mrOut.startTable( nW1 ); } + explicit TableGuard( const OutputRef& rxOut, sal_Int32 nW1, sal_Int32 nW2 ) : + mrOut( *rxOut ) { mrOut.startTable( nW1, nW2 ); } + explicit TableGuard( const OutputRef& rxOut, sal_Int32 nW1, sal_Int32 nW2, sal_Int32 nW3, sal_Int32 nW4 ) : + mrOut( *rxOut ) { mrOut.startTable( nW1, nW2, nW3, nW4 ); } + explicit TableGuard( const OutputRef& rxOut, size_t nColCount, + const sal_Int32* pnColWidths ) : + mrOut( *rxOut ) { mrOut.startTable( nColCount, pnColWidths ); } + ~TableGuard() { mrOut.endTable(); } + void tab( size_t nCol ) { mrOut.tab( nCol ); } +private: + TableGuard( const TableGuard& ) = delete; + TableGuard& operator=( const TableGuard& ) = delete; +private: + Output& mrOut; +}; + + +class ItemGuard +{ +public: + explicit ItemGuard( const OutputRef& rxOut, const String& rName ) : + mrOut( *rxOut ) { mrOut.startItem( rName ); } + ~ItemGuard() { mrOut.endItem(); } + void cont() { mrOut.contItem(); } +private: + ItemGuard( const ItemGuard& ) = delete; + ItemGuard& operator=( const ItemGuard& ) = delete; +private: + Output& mrOut; +}; + + +class MultiItemsGuard +{ +public: + explicit MultiItemsGuard( const OutputRef& rxOut ) : mrOut( *rxOut ) { mrOut.startMultiItems(); } + ~MultiItemsGuard() { mrOut.endMultiItems(); } +private: + MultiItemsGuard( const MultiItemsGuard& ) = delete; + MultiItemsGuard& operator=( const MultiItemsGuard& ) = delete; +private: + Output& mrOut; +}; + + +class StorageIterator : public Base +{ +public: + explicit StorageIterator( const StorageRef& rxStrg ); + virtual ~StorageIterator() override; + + StorageIterator& operator++(); + + OUString getName() const; + bool isStream() const; + bool isStorage() const; + +private: + virtual bool implIsValid() const override; + +private: + StorageRef mxStrg; + OUStringVector maNames; + OUStringVector::const_iterator maIt; +}; + + +class ObjectBase : public Base +{ +public: + virtual ~ObjectBase() override; + + ObjectBase(ObjectBase const &) = default; + ObjectBase(ObjectBase &&) = default; + ObjectBase & operator =(ObjectBase const &) = default; + ObjectBase & operator =(ObjectBase &&) = default; + + const css::uno::Reference< css::uno::XComponentContext >& + getContext() const { return mxConfig->getContext(); } + + void dump(); + + +protected: + ObjectBase() {} + + void construct( const ConfigRef& rxConfig ); + void construct( const ObjectBase& rParent ); + + virtual bool implIsValid() const override; + virtual void implDump(); + + + Config& cfg() const { return *mxConfig; } + +private: + ConfigRef mxConfig; +}; + +typedef std::shared_ptr< ObjectBase > ObjectRef; + + +class StorageObjectBase : public ObjectBase +{ +protected: + StorageObjectBase() {} + +protected: + using ObjectBase::construct; + void construct( const ObjectBase& rParent, const StorageRef& rxStrg, const OUString& rSysPath ); + void construct( const ObjectBase& rParent ); + + virtual bool implIsValid() const override; + virtual void implDump() override; + + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ); + + virtual void implDumpStorage( + const StorageRef& rxStrg, + const OUString& rStrgPath, + const OUString& rSysPath ); + + virtual void implDumpBaseStream( + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName ); + + void addPreferredStream( const String& rStrmName ); + void addPreferredStorage( const String& rStrgPath ); + +private: + static OUString getSysFileName( + const OUString& rStrmName, + std::u16string_view rSysOutPath ); + + void extractStream( + StorageBase& rStrg, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ); + void extractStorage( + const StorageRef& rxStrg, + const OUString& rStrgPath, + const OUString& rSysPath ); + + void extractItem( + const StorageRef& rxStrg, + const OUString& rStrgPath, + const OUString& rItemName, + std::u16string_view rSysPath, + bool bIsStrg, bool bIsStrm ); + +private: + struct PreferredItem + { + OUString maName; + bool mbStorage; + + explicit PreferredItem( const OUString& rName, bool bStorage ) : + maName( rName ), mbStorage( bStorage ) {} + }; + typedef ::std::vector< PreferredItem > PreferredItemVector; + + StorageRef mxStrg; + OUString maSysPath; + PreferredItemVector maPreferred; +}; + + +class OutputObjectBase : public ObjectBase +{ +public: + virtual ~OutputObjectBase() override; + + OutputObjectBase(OutputObjectBase const &) = default; + OutputObjectBase(OutputObjectBase &&) = default; + OutputObjectBase & operator =(OutputObjectBase const &) = default; + OutputObjectBase & operator =(OutputObjectBase &&) = default; + +protected: + OutputObjectBase() {} + + using ObjectBase::construct; + void construct( const ObjectBase& rParent, const OUString& rSysFileName ); + void construct( const OutputObjectBase& rParent ); + + virtual bool implIsValid() const override; + + + void writeEmptyItem( const String& rName ); + void writeInfoItem( const String& rName, const String& rData ); + void writeCharItem( const String& rName, sal_Unicode cData ); + void writeStringItem( const String& rName, const OUString& rData ); + void writeArrayItem( const String& rName, const sal_uInt8* pnData, std::size_t nSize, sal_Unicode cSep = OOX_DUMP_LISTSEP ); + void writeDateTimeItem( const String& rName, const css::util::DateTime& rDateTime ); + void writeGuidItem( const String& rName, const OUString& rGuid ); + + template< typename Type > + void addNameToItem( Type nData, const NameListWrapper& rListWrp ); + + template< typename Type > + void writeNameItem( const String& rName, Type nData, const NameListWrapper& rListWrp ); + template< typename Type > + void writeDecItem( const String& rName, Type nData, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + void writeHexItem( const String& rName, Type nData, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + void writeShortHexItem( const String& rName, Type nData, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + void writeBinItem( const String& rName, Type nData, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + void writeFixItem( const String& rName, Type nData, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + void writeDecBoolItem( const String& rName, Type nData, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + void writeValueItem( const String& rName, Type nData, FormatType eFmtType, const NameListWrapper& rListWrp = NO_LIST ); + + template< typename Type > + void writeValueItem( const ItemFormat& rItemFmt, Type nData ); + + template< typename Type > + void writeDecPairItem( const String& rName, Type nData1, Type nData2, sal_Unicode cSep = ',' ); + template< typename Type > + void writeHexPairItem( const String& rName, Type nData1, Type nData2, sal_Unicode cSep = ',' ); + +protected: + OutputRef mxOut; + OUString maSysFileName; +}; + + +template< typename Type > +void OutputObjectBase::addNameToItem( Type nData, const NameListWrapper& rListWrp ) +{ + if( !rListWrp.isEmpty() ) + { + mxOut->contItem(); + mxOut->writeName( cfg(), nData, rListWrp ); + } +} + +template< typename Type > +void OutputObjectBase::writeNameItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeName( cfg(), nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeDecItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeDec( nData ); + addNameToItem( nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeHexItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeHex( nData ); + addNameToItem( nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeShortHexItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeShortHex( nData ); + addNameToItem( nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeBinItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeBin( nData ); + addNameToItem( nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeFixItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeFix( nData ); + addNameToItem( nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeDecBoolItem( const String& rName, Type nData, const NameListWrapper& rListWrp ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeDec( nData ); + aItem.cont(); + mxOut->writeBool( nData != 0 ); + addNameToItem( nData, rListWrp ); +} + +template< typename Type > +void OutputObjectBase::writeValueItem( const String& rName, Type nData, FormatType eFmtType, const NameListWrapper& rListWrp ) +{ + if( eFmtType == FORMATTYPE_BOOL ) + writeDecBoolItem( rName, nData, rListWrp ); + else + { + ItemGuard aItem( mxOut, rName ); + mxOut->writeValue( nData, eFmtType ); + addNameToItem( nData, rListWrp ); + } +} + +template< typename Type > +void OutputObjectBase::writeValueItem( const ItemFormat& rItemFmt, Type nData ) +{ + OString aNameUtf8 = StringHelper::convertToUtf8( rItemFmt.maItemName ); + writeValueItem( aNameUtf8.getStr(), nData, rItemFmt.meFmtType, rItemFmt.maListName ); +} + +template< typename Type > +void OutputObjectBase::writeDecPairItem( const String& rName, Type nData1, Type nData2, sal_Unicode cSep ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeDec( nData1 ); + mxOut->writeChar( cSep ); + mxOut->writeDec( nData2 ); +} + +template< typename Type > +void OutputObjectBase::writeHexPairItem( const String& rName, Type nData1, Type nData2, sal_Unicode cSep ) +{ + ItemGuard aItem( mxOut, rName ); + mxOut->writeHex( nData1 ); + mxOut->writeChar( cSep ); + mxOut->writeHex( nData2 ); +} + + +class InputObjectBase : public OutputObjectBase +{ +public: + virtual ~InputObjectBase() override; + + InputObjectBase(InputObjectBase const &) = default; + InputObjectBase(InputObjectBase &&) = default; + InputObjectBase & operator =(InputObjectBase const &) = default; + InputObjectBase & operator =(InputObjectBase &&) = default; + +protected: + InputObjectBase() {} + + using OutputObjectBase::construct; + void construct( const ObjectBase& rParent, const BinaryInputStreamRef& rxStrm, const OUString& rSysFileName ); + void construct( const OutputObjectBase& rParent, const BinaryInputStreamRef& rxStrm ); + void construct( const InputObjectBase& rParent ); + + virtual bool implIsValid() const override; + + void skipBlock( sal_Int64 nBytes, bool bShowSize = true ); + void dumpRawBinary( sal_Int64 nBytes, bool bShowOffset, bool bStream = false ); + + void dumpBinary( const String& rName, sal_Int64 nBytes, bool bShowOffset = true ); + void dumpRemaining( sal_Int64 nBytes ); + void dumpRemainingTo( sal_Int64 nPos ); + void dumpRemainingStream(); + + void dumpArray( const String& rName, sal_Int32 nBytes, sal_Unicode cSep = OOX_DUMP_LISTSEP ); + void dumpUnused( sal_Int32 nBytes ) { dumpArray( OUString(OOX_DUMP_UNUSED), nBytes ); } + void dumpUnknown( sal_Int32 nBytes ) { dumpArray( OUString(OOX_DUMP_UNKNOWN), nBytes ); } + + sal_Unicode dumpUnicode( const String& rName ); + + OUString dumpCharArray( const String& rName, sal_Int32 nLen, rtl_TextEncoding eTextEnc, bool bHideTrailingNul = false ); + OUString dumpUnicodeArray( const String& rName, sal_Int32 nLen, bool bHideTrailingNul = false ); + + css::util::DateTime dumpFileTime( const String& rName = EMPTY_STRING ); + OUString dumpGuid( const String& rName = EMPTY_STRING ); + + void dumpItem( const ItemFormat& rItemFmt ); + + template< typename Type > + Type dumpName( const String& rName, const NameListWrapper& rListWrp ); + template< typename Type > + Type dumpDec( const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + Type dumpHex( const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + Type dumpBin( const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + Type dumpFix( const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + Type dumpBool( const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + Type dumpValue( const ItemFormat& rItemFmt ); + + template< typename Type1, typename Type2 > + Type1 dumpName( bool bType1, const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type1, typename Type2 > + Type1 dumpDec( bool bType1, const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type1, typename Type2 > + Type1 dumpHex( bool bType1, const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type1, typename Type2 > + Type1 dumpBin( bool bType1, const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type1, typename Type2 > + Type1 dumpFix( bool bType1, const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type1, typename Type2 > + Type1 dumpBool( bool bType1, const String& rName, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type1, typename Type2 > + Type1 dumpValue( bool bType1, const ItemFormat& rItemFmt ); + + template< typename Type > + void dumpDecPair( const String& rName, sal_Unicode cSep = ',' ); + template< typename Type > + void dumpHexPair( const String& rName, sal_Unicode cSep = ',' ); + +protected: + BinaryInputStreamRef mxStrm; +}; + + +template< typename Type > +Type InputObjectBase::dumpName( const String& rName, const NameListWrapper& rListWrp ) +{ + Type nData = mxStrm->readValue(); + writeNameItem( rName, nData, rListWrp ); + return nData; +} + +template< typename Type > +Type InputObjectBase::dumpDec( const String& rName, const NameListWrapper& rListWrp ) +{ + Type nData = mxStrm->readValue(); + writeDecItem( rName, nData, rListWrp ); + return nData; +} + +template< typename Type > +Type InputObjectBase::dumpHex( const String& rName, const NameListWrapper& rListWrp ) +{ + Type nData = mxStrm->readValue(); + writeHexItem( rName, nData, rListWrp ); + return nData; +} + +template< typename Type > +Type InputObjectBase::dumpBin( const String& rName, const NameListWrapper& rListWrp ) +{ + Type nData = mxStrm->readValue(); + writeBinItem( rName, nData, rListWrp ); + return nData; +} + +template< typename Type > +Type InputObjectBase::dumpFix( const String& rName, const NameListWrapper& rListWrp ) +{ + Type nData = mxStrm->readValue(); + writeFixItem( rName, nData, rListWrp ); + return nData; +} + +template< typename Type > +Type InputObjectBase::dumpBool( const String& rName, const NameListWrapper& rListWrp ) +{ + Type nData = mxStrm->readValue(); + writeDecBoolItem( rName, nData, rListWrp ); + return nData; +} + +template< typename Type > +Type InputObjectBase::dumpValue( const ItemFormat& rItemFmt ) +{ + Type nData = mxStrm->readValue(); + writeValueItem( rItemFmt, nData ); + return nData; +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpName( bool bType1, const String& rName, const NameListWrapper& rListWrp ) +{ + return bType1 ? dumpName< Type1 >( rName, rListWrp ) : static_cast< Type1 >( dumpName< Type2 >( rName, rListWrp ) ); +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpDec( bool bType1, const String& rName, const NameListWrapper& rListWrp ) +{ + return bType1 ? dumpDec< Type1 >( rName, rListWrp ) : static_cast< Type1 >( dumpDec< Type2 >( rName, rListWrp ) ); +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpHex( bool bType1, const String& rName, const NameListWrapper& rListWrp ) +{ + return bType1 ? dumpHex< Type1 >( rName, rListWrp ) : static_cast< Type1 >( dumpHex< Type2 >( rName, rListWrp ) ); +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpBin( bool bType1, const String& rName, const NameListWrapper& rListWrp ) +{ + return bType1 ? dumpBin< Type1 >( rName, rListWrp ) : static_cast< Type1 >( dumpBin< Type2 >( rName, rListWrp ) ); +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpFix( bool bType1, const String& rName, const NameListWrapper& rListWrp ) +{ + return bType1 ? dumpFix< Type1 >( rName, rListWrp ) : static_cast< Type1 >( dumpFix< Type2 >( rName, rListWrp ) ); +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpBool( bool bType1, const String& rName, const NameListWrapper& rListWrp ) +{ + return bType1 ? dumpBool< Type1 >( rName, rListWrp ) : static_cast< Type1 >( dumpBool< Type2 >( rName, rListWrp ) ); +} + +template< typename Type1, typename Type2 > +Type1 InputObjectBase::dumpValue( bool bType1, const ItemFormat& rItemFmt ) +{ + return bType1 ? dumpValue< Type1 >( rItemFmt ) : static_cast< Type1 >( dumpValue< Type2 >( rItemFmt ) ); +} + +template< typename Type > +void InputObjectBase::dumpDecPair( const String& rName, sal_Unicode cSep ) +{ + Type nData1, nData2; + *mxStrm >> nData1 >> nData2; + writeDecPairItem( rName, nData1, nData2, cSep ); +} + +template< typename Type > +void InputObjectBase::dumpHexPair( const String& rName, sal_Unicode cSep ) +{ + Type nData1, nData2; + *mxStrm >> nData1 >> nData2; + writeHexPairItem( rName, nData1, nData2, cSep ); +} + + +class BinaryStreamObject final : public InputObjectBase +{ +public: + explicit BinaryStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName ); + +private: + void dumpBinaryStream( bool bShowOffset = true ); + + virtual void implDump() override; +}; + + +class TextStreamObjectBase : public InputObjectBase +{ +protected: + TextStreamObjectBase() {} + + using InputObjectBase::construct; + void construct( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + rtl_TextEncoding eTextEnc, + const OUString& rSysFileName ); + void construct( + const OutputObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + rtl_TextEncoding eTextEnc ); + + virtual bool implIsValid() const override; + virtual void implDump() override; + + virtual void implDumpText( TextInputStream& rTextStrm ) = 0; + +private: + void constructTextStrmObj( rtl_TextEncoding eTextEnc ); + + std::shared_ptr< TextInputStream > mxTextStrm; +}; + + +class TextLineStreamObject final : public TextStreamObjectBase +{ +public: + explicit TextLineStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + rtl_TextEncoding eTextEnc, + const OUString& rSysFileName ); + + explicit TextLineStreamObject( + const OutputObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + rtl_TextEncoding eTextEnc ); + +private: + virtual void implDumpText( TextInputStream& rTextStrm ) override; + void implDumpLine( const OUString& rLine, sal_uInt32 nLine ); +}; + + +class XmlStreamObject : public TextStreamObjectBase +{ +public: + explicit XmlStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName ); + +protected: + virtual void implDumpText( TextInputStream& rTextStrm ) override; +}; + + +class RecordObjectBase : public InputObjectBase +{ +protected: + RecordObjectBase() {} + + using InputObjectBase::construct; + void construct( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxBaseStrm, + const OUString& rSysFileName, + const BinaryInputStreamRef& rxRecStrm, + const String& rRecNames, + const String& rSimpleRecs ); + + sal_Int64 getRecId() const { return mnRecId; } + sal_Int64 getRecSize() const { return mnRecSize; } + + virtual bool implIsValid() const override; + virtual void implDump() override; + + virtual bool implStartRecord( BinaryInputStream& rBaseStrm, sal_Int64& ornRecPos, sal_Int64& ornRecId, sal_Int64& ornRecSize ) = 0; + virtual void implWriteExtHeader(); + virtual void implDumpRecordBody(); + +private: + void constructRecObjBase( + const BinaryInputStreamRef& rxBaseStrm, + const String& rRecNames, + const String& rSimpleRecs ); + + void writeHeader(); + +private: + BinaryInputStreamRef mxBaseStrm; + NameListWrapper maRecNames; + NameListWrapper maSimpleRecs; + sal_Int64 mnRecPos; + sal_Int64 mnRecId; + sal_Int64 mnRecSize; + bool mbShowRecPos; + bool mbBinaryOnly; +}; + + +class SequenceRecordObjectBase : public RecordObjectBase +{ +protected: + SequenceRecordObjectBase() : mxRecData( std::make_shared() ) {} + + using RecordObjectBase::construct; + void construct( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxBaseStrm, + const OUString& rSysFileName, + const String& rRecNames, + const String& rSimpleRecs ); + + virtual bool implStartRecord( BinaryInputStream& rBaseStrm, sal_Int64& ornRecPos, sal_Int64& ornRecId, sal_Int64& ornRecSize ) override; + virtual bool implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize ) = 0; + +private: + std::shared_ptr< StreamDataSequence > mxRecData; +}; + + +/** Base class for a file dumper. Derived classes implement the implDump() + function to add functionality. + */ +class DumperBase : public ObjectBase +{ +public: + virtual ~DumperBase() override; + + bool isImportEnabled() const; + +protected: + DumperBase() {} + + using ObjectBase::construct; + void construct( const ConfigRef& rxConfig ); +}; + + +} // namespace oox::dump + +#define OOX_DUMP_FILE( DumperClassName ) \ +do { \ + DumperClassName aDumper( *this ); \ + aDumper.dump(); \ + if( !aDumper.isImportEnabled() ) \ + return aDumper.isValid(); \ +} while( false ) + +#else // DBG_UTIL + +#define OOX_DUMP_FILE( DumperClassName ) (void)0 + +#endif // DBG_UTIL +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/dump/oledumper.hxx b/include/oox/dump/oledumper.hxx new file mode 100644 index 000000000..77b3ab14c --- /dev/null +++ b/include/oox/dump/oledumper.hxx @@ -0,0 +1,849 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DUMP_OLEDUMPER_HXX +#define INCLUDED_OOX_DUMP_OLEDUMPER_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef DBG_UTIL + +namespace com::sun::star { + namespace io { class XInputStream; } +} + +namespace oox::dump { + + +class OleInputObjectBase : public InputObjectBase +{ +protected: + OleInputObjectBase() {} + + OUString dumpAnsiString32( const String& rName ); + OUString dumpUniString32( const String& rName ); + + sal_Int32 dumpStdClipboardFormat( const String& rName ); + OUString dumpAnsiString32OrStdClip( const String& rName ); + OUString dumpUniString32OrStdClip( const String& rName ); + + void writeOleColorItem( const String& rName, sal_uInt32 nColor ); + sal_uInt32 dumpOleColor( const String& rName ); +}; + + +class StdFontObject : public OleInputObjectBase +{ +public: + explicit StdFontObject( const InputObjectBase& rParent ); + +protected: + virtual void implDump() override; +}; + + +class StdPicObject : public OleInputObjectBase +{ +public: + explicit StdPicObject( const InputObjectBase& rParent ); + +protected: + virtual void implDump() override; +}; + + +class OleStreamObject : public OleInputObjectBase +{ +public: + explicit OleStreamObject( const ObjectBase& rParent, const BinaryInputStreamRef& rxStrm, const OUString& rSysFileName ); +}; + + +class OleCompObjObject : public OleStreamObject +{ +public: + explicit OleCompObjObject( const ObjectBase& rParent, const BinaryInputStreamRef& rxStrm, const OUString& rSysFileName ); + +protected: + virtual void implDump() override; +}; + + +class OlePropertyStreamObject : public InputObjectBase +{ +public: + explicit OlePropertyStreamObject( const ObjectBase& rParent, const BinaryInputStreamRef& rxStrm, const OUString& rSysFileName ); + +protected: + virtual void implDump() override; + +private: + void dumpSection( const OUString& rGuid, sal_uInt32 nStartPos ); + + void dumpProperty( sal_Int32 nPropId, sal_uInt32 nStartPos ); + void dumpCodePageProperty( sal_uInt32 nStartPos ); + void dumpDictionaryProperty( sal_uInt32 nStartPos ); + + sal_uInt16 dumpPropertyContents( sal_Int32 nPropId ); + void dumpPropertyValue( sal_Int32 nPropId, sal_uInt16 nBaseType ); + void dumpPropertyVector( sal_Int32 nPropId, sal_uInt16 nBaseType ); + + sal_uInt16 dumpPropertyType(); + void dumpBlob( sal_Int32 nPropId, const String& rName ); + OUString dumpString8( const String& rName ); + OUString dumpCharArray8( const String& rName, sal_Int32 nLen ); + OUString dumpString16( const String& rName ); + OUString dumpCharArray16( const String& rName, sal_Int32 nLen ); + bool dumpTypedProperty( const String& rName, sal_uInt16 nExpectedType ); + void dumpHlinks( sal_Int32 nSize ); + + bool startElement( sal_uInt32 nStartPos ); + void writeSectionHeader( const OUString& rGuid, sal_uInt32 nStartPos ); + void writePropertyHeader( sal_Int32 nPropId, sal_uInt32 nStartPos ); + +private: + NameListRef mxPropIds; + rtl_TextEncoding meTextEnc; + bool mbIsUnicode; +}; + + +class OleStorageObject : public StorageObjectBase +{ +public: + explicit OleStorageObject( const ObjectBase& rParent, const StorageRef& rxStrg, const OUString& rSysPath ); + +protected: + OleStorageObject() {} + + using StorageObjectBase::construct; + + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; +}; + + +class ComCtlObjectBase : public OleInputObjectBase +{ +protected: + explicit ComCtlObjectBase( + const InputObjectBase& rParent, + sal_uInt32 nDataId5, sal_uInt32 nDataId6, sal_uInt16 nVersion, + bool bCommonPart, bool bComplexPart ); + + virtual void implDump() override; + virtual void implDumpProperties() = 0; + virtual void implDumpCommonExtra( sal_Int64 nEndPos ); + virtual void implDumpCommonTrailing(); + +private: + bool dumpComCtlHeader( sal_uInt32 nExpId, sal_uInt16 nExpMajor = SAL_MAX_UINT16, sal_uInt16 nExpMinor = SAL_MAX_UINT16 ); + bool dumpComCtlSize(); + bool dumpComCtlData( sal_uInt32& ornCommonPartSize ); + bool dumpComCtlCommon( sal_uInt32 nPartSize ); + bool dumpComCtlComplex(); + +protected: + sal_uInt32 mnDataId5; + sal_uInt32 mnDataId6; + sal_uInt16 mnVersion; + bool mbCommonPart; + bool mbComplexPart; +}; + + +class ComCtlScrollBarObject : public ComCtlObjectBase +{ +public: + explicit ComCtlScrollBarObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; +}; + + +class ComCtlProgressBarObject : public ComCtlObjectBase +{ +public: + explicit ComCtlProgressBarObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; +}; + + +class ComCtlSliderObject : public ComCtlObjectBase +{ +public: + explicit ComCtlSliderObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; +}; + + +class ComCtlUpDownObject : public ComCtlObjectBase +{ +public: + explicit ComCtlUpDownObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; +}; + + +class ComCtlImageListObject : public ComCtlObjectBase +{ +public: + explicit ComCtlImageListObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; + virtual void implDumpCommonExtra( sal_Int64 nEndPos ) override; + virtual void implDumpCommonTrailing() override; +}; + + +class ComCtlTabStripObject : public ComCtlObjectBase +{ +public: + explicit ComCtlTabStripObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; + virtual void implDumpCommonExtra( sal_Int64 nEndPos ) override; +}; + + +class ComCtlTreeViewObject : public ComCtlObjectBase +{ +public: + explicit ComCtlTreeViewObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; + virtual void implDumpCommonExtra( sal_Int64 nEndPos ) override; + +private: + sal_uInt32 mnStringFlags; +}; + + +class ComCtlStatusBarObject : public ComCtlObjectBase +{ +public: + explicit ComCtlStatusBarObject( const InputObjectBase& rParent, sal_uInt16 nVersion ); + +protected: + virtual void implDumpProperties() override; + virtual void implDumpCommonExtra( sal_Int64 nEndPos ) override; + virtual void implDumpCommonTrailing() override; +}; + + +class AxPropertyObjectBase : public OleInputObjectBase +{ +protected: + AxPropertyObjectBase() {} + + using OleInputObjectBase::construct; + void construct( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + const String& rPropNameList, + bool b64BitPropFlags = false ); + void construct( + const InputObjectBase& rParent, + const String& rPropNameList, + bool b64BitPropFlags = false ); + + virtual bool implIsValid() const override; + virtual void implDump() override; + + virtual void implDumpShortProperties(); + virtual void implDumpExtended(); + + bool ensureValid( bool bCondition = true ); + + template< typename Type > + void alignInput(); + + void setAlignAnchor(); + bool startNextProperty(); + OUString getPropertyName() const; + + template< typename Type > + Type dumpDecProperty( Type nDefault, const NameListWrapper& rListWrp = NO_LIST ); + template< typename Type > + Type dumpHexProperty( Type nDefault, const NameListWrapper& rListWrp = NO_LIST ); + + bool dumpBoolProperty() { return startNextProperty(); } + sal_Int32 dumpHmmProperty() { return dumpDecProperty< sal_Int32 >( 0, "CONV-HMM-TO-CM" ); } + sal_uInt8 dumpMousePtrProperty() { return dumpDecProperty< sal_uInt8 >( 0, "OLE-MOUSEPTR" ); } + template< typename Type > + Type dumpBorderStyleProperty( Type nDefault ) { return dumpDecProperty< Type >( nDefault, "AX-BORDERSTYLE" ); } + template< typename Type > + Type dumpSpecialEffectProperty( Type nDefault ) { return dumpDecProperty< Type >( nDefault, "AX-SPECIALEFFECT" ); } + sal_uInt32 dumpEnabledProperty() { return dumpDecProperty< sal_uInt32 >( 1, "AX-ENABLED" ); } + sal_Int32 dumpOrientationProperty() { return dumpDecProperty< sal_Int32 >( -1, "AX-ORIENTATION" ); } + sal_Int32 dumpDelayProperty() { return dumpDecProperty< sal_Int32 >( 50, "AX-CONV-MS" ); } + sal_uInt32 dumpImagePosProperty() { return dumpHexProperty< sal_uInt32 >( 0x00070001, "AX-IMAGEPOS" ); } + sal_uInt8 dumpImageSizeModeProperty() { return dumpDecProperty< sal_uInt8 >( 0, "AX-IMAGESIZEMODE" ); } + sal_uInt8 dumpImageAlignProperty() { return dumpDecProperty< sal_uInt8 >( 2, "AX-IMAGEALIGN" ); } + + sal_uInt32 dumpFlagsProperty( sal_uInt32 nDefault, const char* pcNameList = "AX-FLAGS" ); + sal_uInt32 dumpColorProperty( sal_uInt32 nDefault ); + sal_Unicode dumpUnicodeProperty(); + void dumpUnknownProperty(); + + void dumpPosProperty(); + void dumpSizeProperty(); + void dumpGuidProperty( OUString* pValue = nullptr ); + void dumpStringProperty( OUString* pValue = nullptr ); + void dumpStringArrayProperty(); + void dumpStreamProperty(); + + void dumpEmbeddedFont(); + void dumpToPosition( sal_Int64 nPos ); + +private: + void constructAxPropObj( const String& rPropNameList, bool b64BitPropFlags ); + + void dumpVersion(); + OUString dumpString( const String& rName, sal_uInt32 nSize, bool bArray ); + void dumpShortProperties(); + void dumpLargeProperties(); + +private: + struct LargeProperty + { + enum LargePropertyType { PROPTYPE_POS, PROPTYPE_SIZE, PROPTYPE_GUID, PROPTYPE_STRING, PROPTYPE_STRINGARRAY }; + + LargePropertyType mePropType; + OUString maItemName; + sal_uInt32 mnDataSize; + OUString* mpItemValue; + explicit LargeProperty( LargePropertyType ePropType, const String& rItemName, sal_uInt32 nDataSize, OUString* pItemValue = nullptr ) : + mePropType( ePropType ), maItemName( rItemName ), mnDataSize( nDataSize ), mpItemValue( pItemValue ) {} + }; + typedef ::std::vector< LargeProperty > LargePropertyVector; + + struct StreamProperty + { + OUString maItemName; + sal_uInt16 mnData; + explicit StreamProperty( const String& rItemName, sal_uInt16 nData ) : + maItemName( rItemName ), mnData( nData ) {} + }; + + LargePropertyVector maLargeProps; + std::vector< StreamProperty > + maStreamProps; + NameListRef mxPropNames; + sal_Int64 mnPropertiesStart; + sal_Int64 mnPropertiesEnd; + sal_Int64 mnPropFlags; + sal_Int64 mnCurrProp; + bool mb64BitPropFlags; + bool mbValid; +}; + + +template< typename Type > +void AxPropertyObjectBase::alignInput() +{ + mxStrm->skip( (sizeof( Type ) - ((mxStrm->tell() - mnPropertiesStart) % sizeof( Type ))) % sizeof( Type ) ); +} + +template< typename Type > +Type AxPropertyObjectBase::dumpDecProperty( Type nDefault, const NameListWrapper& rListWrp ) +{ + if( startNextProperty() ) + { + alignInput< Type >(); + return dumpDec< Type >( getPropertyName(), rListWrp ); + } + return nDefault; +} + +template< typename Type > +Type AxPropertyObjectBase::dumpHexProperty( Type nDefault, const NameListWrapper& rListWrp ) +{ + if( startNextProperty() ) + { + alignInput< Type >(); + return dumpHex< Type >( getPropertyName(), rListWrp ); + } + return nDefault; +} + + +class AxCFontNewObject : public AxPropertyObjectBase +{ +public: + explicit AxCFontNewObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class AxColumnInfoObject : public AxPropertyObjectBase +{ +public: + explicit AxColumnInfoObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class AxCommandButtonObject : public AxPropertyObjectBase +{ +public: + explicit AxCommandButtonObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; + virtual void implDumpExtended() override; +}; + + +class AxMorphControlObject : public AxPropertyObjectBase +{ +public: + explicit AxMorphControlObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; + virtual void implDumpExtended() override; + +private: + void dumpColumnInfos(); + +private: + sal_uInt16 mnColInfoCount; + sal_uInt8 mnCtrlType; +}; + + +class AxLabelObject : public AxPropertyObjectBase +{ +public: + explicit AxLabelObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; + virtual void implDumpExtended() override; +}; + + +class AxImageObject : public AxPropertyObjectBase +{ +public: + explicit AxImageObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class AxScrollBarObject : public AxPropertyObjectBase +{ +public: + explicit AxScrollBarObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class AxSpinButtonObject : public AxPropertyObjectBase +{ +public: + explicit AxSpinButtonObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class AxTabStripObject : public AxPropertyObjectBase +{ +public: + explicit AxTabStripObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; + virtual void implDumpExtended() override; + +private: + sal_Int32 mnTabFlagCount; +}; + + +class FormControlStreamObject : public OleInputObjectBase +{ +public: + explicit FormControlStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + const OUString* pProgId = nullptr ); + explicit FormControlStreamObject( + const OutputObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString* pProgId = nullptr ); + +protected: + virtual void implDump() override; + +private: + void constructFormCtrlStrmObj( const OUString* pProgId ); + +private: + OUString maProgId; + bool mbReadGuid; +}; + + +struct VbaFormSiteInfo +{ + OUString maProgId; + sal_Int32 mnId; + sal_uInt32 mnLength; + bool mbInStream; + + VbaFormSiteInfo() : mnId( 0 ), mnLength( 0 ), mbInStream( false ) {} +}; + + +struct VbaFormSharedData +{ + OUStringVector maClassInfoProgIds; + std::vector< VbaFormSiteInfo > maSiteInfos; +}; + + +class VbaFormClassInfoObject : public AxPropertyObjectBase +{ +public: + explicit VbaFormClassInfoObject( const InputObjectBase& rParent, VbaFormSharedData& rFormData ); + +protected: + virtual void implDumpShortProperties() override; + +private: + VbaFormSharedData& mrFormData; +}; + + +class VbaFormSiteObject : public AxPropertyObjectBase +{ +public: + explicit VbaFormSiteObject( const InputObjectBase& rParent, VbaFormSharedData& rFormData ); + +protected: + virtual void implDumpShortProperties() override; + +private: + VbaFormSharedData& mrFormData; +}; + + +class VbaFormDesignExtObject : public AxPropertyObjectBase +{ +public: + explicit VbaFormDesignExtObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class VbaFStreamObject : public AxPropertyObjectBase +{ +public: + explicit VbaFStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + VbaFormSharedData& rFormData ); + +protected: + virtual void implDumpShortProperties() override; + virtual void implDumpExtended() override; + +private: + void dumpClassInfos(); + void dumpFormSites( sal_uInt32 nCount ); + void dumpSiteData(); + void dumpDesignExtender(); + +private: + VbaFormSharedData& mrFormData; + sal_uInt32 mnFlags; +}; + + +class VbaOStreamObject : public OleInputObjectBase +{ +public: + explicit VbaOStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + VbaFormSharedData& rFormData ); + +protected: + virtual void implDump() override; + +private: + VbaFormSharedData& mrFormData; +}; + + +class VbaPageObject : public AxPropertyObjectBase +{ +public: + explicit VbaPageObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; +}; + + +class VbaMultiPageObject : public AxPropertyObjectBase +{ +public: + explicit VbaMultiPageObject( const InputObjectBase& rParent ); + +protected: + virtual void implDumpShortProperties() override; + virtual void implDumpExtended() override; + +private: + sal_Int32 mnPageCount; +}; + + +class VbaXStreamObject : public InputObjectBase +{ +public: + explicit VbaXStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + VbaFormSharedData& rFormData ); + +protected: + virtual void implDump() override; + +private: + VbaFormSharedData& mrFormData; +}; + + +class VbaContainerStorageObject : public OleStorageObject +{ +public: + explicit VbaContainerStorageObject( + const ObjectBase& rParent, + const StorageRef& rxStrg, + const OUString& rSysPath ); + +protected: + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; + + virtual void implDumpStorage( + const StorageRef& rxStrg, + const OUString& rStrgPath, + const OUString& rSysPath ) override; + +private: + bool isFormStorage( const OUString& rStrgPath ) const; + +private: + VbaFormSharedData maFormData; +}; + + +struct VbaSharedData +{ + typedef ::std::map< OUString, sal_Int32 > StreamOffsetMap; + + StreamOffsetMap maStrmOffsets; + rtl_TextEncoding meTextEnc; + + VbaSharedData(); + + bool isModuleStream( const OUString& rStrmName ) const; + sal_Int32 getStreamOffset( const OUString& rStrmName ) const; +}; + + +class VbaDirStreamObject : public SequenceRecordObjectBase +{ +public: + explicit VbaDirStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + VbaSharedData& rVbaData ); + +protected: + virtual bool implIsValid() const override; + virtual bool implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize ) override; + virtual void implDumpRecordBody() override; + +private: + OUString dumpByteString( const String& rName ); + OUString dumpUniString( const String& rName ); + OUString dumpByteStringWithLength( const String& rName ); + +private: + VbaSharedData& mrVbaData; + BinaryInputStreamRef mxInStrm; + OUString maCurrStream; + sal_Int32 mnCurrOffset; +}; + + +class VbaModuleStreamObject : public InputObjectBase +{ +public: + explicit VbaModuleStreamObject( + const ObjectBase& rParent, + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName, + VbaSharedData& rVbaData, + sal_Int32 nStrmOffset ); + +protected: + virtual void implDump() override; + +private: + VbaSharedData& mrVbaData; + sal_Int32 mnStrmOffset; +}; + + +class VbaStorageObject : public OleStorageObject +{ +public: + explicit VbaStorageObject( + const ObjectBase& rParent, + const StorageRef& rxStrg, + const OUString& rSysPath, + VbaSharedData& rVbaData ); + +protected: + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; + +private: + VbaSharedData& mrVbaData; +}; + + +class VbaFormStorageObject : public VbaContainerStorageObject +{ +public: + explicit VbaFormStorageObject( + const ObjectBase& rParent, + const StorageRef& rxStrg, + const OUString& rSysPath, + VbaSharedData& rVbaData ); + +protected: + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; + +private: + VbaSharedData& mrVbaData; +}; + + +class VbaProjectStorageObject : public OleStorageObject +{ +public: + explicit VbaProjectStorageObject( const ObjectBase& rParent, const StorageRef& rxStrg, const OUString& rSysPath ); + +protected: + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; + + virtual void implDumpStorage( + const StorageRef& rxStrg, + const OUString& rStrgPath, + const OUString& rSysPath ) override; + +private: + VbaSharedData maVbaData; +}; + + +class ActiveXStorageObject : public VbaContainerStorageObject +{ +public: + explicit ActiveXStorageObject( + const ObjectBase& rParent, + const StorageRef& rxStrg, + const OUString& rSysPath ); + +protected: + virtual void implDumpBaseStream( + const BinaryInputStreamRef& rxStrm, + const OUString& rSysFileName ) override; +}; + + +} // namespace oox::dump + +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/dump/pptxdumper.hxx b/include/oox/dump/pptxdumper.hxx new file mode 100644 index 000000000..9e12ecd48 --- /dev/null +++ b/include/oox/dump/pptxdumper.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DUMP_PPTXDUMPER_HXX +#define INCLUDED_OOX_DUMP_PPTXDUMPER_HXX + +#include +#include +#include + +#ifdef DBG_UTIL + +namespace com::sun::star { + namespace io { class XInputStream; } + namespace uno { class XComponentContext; } +} + +namespace oox::core { class FilterBase; } + +namespace oox::dump::pptx { + + +class RootStorageObject : public StorageObjectBase +{ +public: + explicit RootStorageObject( const DumperBase& rParent ); + +protected: + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; +}; + + +class Dumper : public DumperBase +{ +public: + explicit Dumper( const ::oox::core::FilterBase& rFilter ); + + explicit Dumper( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + const OUString& rSysFileName ); + +protected: + virtual void implDump() override; +}; + + +} // namespace oox::dump::pptx + +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/dump/xlsbdumper.hxx b/include/oox/dump/xlsbdumper.hxx new file mode 100644 index 000000000..96acd2616 --- /dev/null +++ b/include/oox/dump/xlsbdumper.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_DUMP_XLSBDUMPER_HXX +#define INCLUDED_OOX_DUMP_XLSBDUMPER_HXX + +#include +#include +#include +#include + +#ifdef DBG_UTIL + +namespace com::sun::star { + namespace io { class XInputStream; } + namespace uno { class XComponentContext; } +} + +namespace oox { + class BinaryInputStream; + class SequenceInputStream; +} + +namespace oox::core { class FilterBase; } + +namespace oox::dump::xlsb { + + +class RecordObjectBase final : public SequenceRecordObjectBase +{ + explicit RecordObjectBase(); + virtual ~RecordObjectBase() override; + + using SequenceRecordObjectBase::construct; + + virtual bool implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize ) override; +}; + + +class RootStorageObject : public StorageObjectBase +{ +public: + explicit RootStorageObject( const DumperBase& rParent ); + +protected: + virtual void implDumpStream( + const css::uno::Reference< css::io::XInputStream >& rxStrm, + const OUString& rStrgPath, + const OUString& rStrmName, + const OUString& rSysFileName ) override; +}; + + +class Dumper : public DumperBase +{ +public: + explicit Dumper( const ::oox::core::FilterBase& rFilter ); + + explicit Dumper( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + const OUString& rSysFileName ); + +protected: + virtual void implDump() override; +}; + + +} // namespace oox::dmp::xlsb + +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/export/DMLPresetShapeExport.hxx b/include/oox/export/DMLPresetShapeExport.hxx new file mode 100644 index 000000000..1f650f558 --- /dev/null +++ b/include/oox/export/DMLPresetShapeExport.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* +* This file is part of the LibreOffice project. +* +* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef INCLUDED_OOX_EXPORT_DMLPRESETSHAPEXPORT_HXX +#define INCLUDED_OOX_EXPORT_DMLPRESETSHAPEXPORT_HXX + +#include +#include +#include +#include + +#include +#include + +#include + +#include + +namespace com::sun::star::beans +{ +struct PropertyValue; +} + +namespace com::sun::star::drawing +{ +class XShape; +struct EnhancedCustomShapeAdjustmentValue; +} + +namespace oox::core +{ +class XmlFilterBase; +} + +namespace oox::drawingml +{ +/// Class for exporting the custom shapes to OOXML preset ones, if possible. +/// This functionality needed for keeping the information for the office programs +/// about the shape type, and geometry data. Before these shapes were exported +/// with custom geometry, and they kept their geometry but has no information +/// about the shape itself. This lead to lost textbox size/position/padding for +/// example. +class DMLPresetShapeExporter +{ +private: + // the shape to export + css::uno::Reference m_xShape; + // the DMLwriter + DrawingML* m_pDMLexporter; + // the type of the custom shape (diamond/rectangle/circle/triangle...) + OUString m_sPresetShapeType; + // True if the shape has points where its geometry can be modified + bool m_bHasHandleValues; + // The first the x the second the y coordinate, of flipping + std::pair m_bIsFlipped; + + // Custom Shape Geometry information for export: + + // The adjusting values stored in this sequence: + css::uno::Sequence m_AdjustmentValues; + // Shapes what have adjusting points, the range of these points + // and the index of the value stored in this sequence: + css::uno::Sequence> m_HandleValues; + + //TODO: + //css::awt::Rectangle m_ViewBox; + //css::uno::Sequence m_Path; + //css::uno::Sequence m_Equations; + +public: + DMLPresetShapeExporter() = delete; + ~DMLPresetShapeExporter(); + + DMLPresetShapeExporter(DrawingML* pDMLExporter, + css::uno::Reference xShape); + + // Writes the preset shape to the xml + bool WriteShape(); + +private: + struct AdjustmentPointValueBase + { + std::optional nMaxVal; + std::optional nMinVal; + std::optional nCurrVal; + }; + + typedef AdjustmentPointValueBase RadiusAdjustmentValue; + typedef AdjustmentPointValueBase AngleAdjustmentValue; + typedef AdjustmentPointValueBase XAdjustmentValue; + typedef AdjustmentPointValueBase YAdjustmentValue; + + // Returns true, if the shape has adjusting points + bool HasHandleValue() const; + + // Returns true if the shape flipped. + bool IsXFlipped() const { return m_bIsFlipped.first; }; + bool IsYFlipped() const { return m_bIsFlipped.second; }; + + // Returns with the shape type, like triangle for example + const OUString& GetShapeType() const; + // Returns with the handle points + const css::uno::Sequence>& + GetHandleValues() const; + // Returns with the adjustment values + const css::uno::Sequence& + GetAdjustmentValues() const; + // Returns with the raw value of the given property of the shape geometry. + css::uno::Any GetHandleValueOfModificationPoint(sal_Int32 nPoint, std::u16string_view sType); + // Returns with the appropriate value of the handle point. + RadiusAdjustmentValue GetAdjustmentPointRadiusValue(sal_Int32 nPoint); + AngleAdjustmentValue GetAdjustmentPointAngleValue(sal_Int32 nPoint); + XAdjustmentValue GetAdjustmentPointXValue(sal_Int32 nPoint); + YAdjustmentValue GetAdjustmentPointYValue(sal_Int32 nPoint); + + // Writes one adjustment point. + bool WriteAV(const OUString& sValName, const OUString& sVal); + // Opens/Closes the AVlist tag. + bool StartAVListWriting(); + bool EndAVListWriting(); + + // Finds the given value in the sequence + static css::uno::Any FindHandleValue(css::uno::Sequence aValues, + std::u16string_view sKey); + // Writes and converts the adjustment points from sdr to ooxml ones per shape type. + bool WriteShapeWithAVlist(); + +}; // end of DMLPresetShapeExporter class + +} // end of namespace oox::drawingml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/export/chartexport.hxx b/include/oox/export/chartexport.hxx new file mode 100644 index 000000000..6a40254f6 --- /dev/null +++ b/include/oox/export/chartexport.hxx @@ -0,0 +1,279 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_EXPORT_CHARTEXPORT_HXX +#define INCLUDED_OOX_EXPORT_CHARTEXPORT_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { + class XPropertySet; + } + namespace chart { + class XDiagram; + class XChartDocument; + } + namespace chart2 { + struct RelativePosition; + struct RelativeSize; + class XDiagram; + class XChartDocument; + class XDataSeries; + class XChartType; + namespace data + { + class XDataSequence; + class XLabeledDataSequence; + } + } + namespace drawing { + class XShape; + } + namespace frame { + class XModel; + } +} + +namespace oox { +namespace core { + class XmlFilterBase; +}} + +namespace oox::drawingml { + +enum AxesType +{ + AXIS_PRIMARY_X = 1, + AXIS_PRIMARY_Y = 2, + AXIS_PRIMARY_Z = 3, + AXIS_SECONDARY_X = 4, + AXIS_SECONDARY_Y = 5 +}; + +struct AxisIdPair{ + AxesType nAxisType; + sal_Int32 nAxisId; + sal_Int32 nCrossAx; + + AxisIdPair(AxesType nType, sal_Int32 nId, sal_Int32 nAx) + : nAxisType(nType) + , nAxisId(nId) + , nCrossAx(nAx) + {} +}; + +/** + A helper container class to collect the chart data point labels and the address + of the cell[range] from which the labels are sourced if that is the case. This + is then used to write the label texts under the extension tag . + + @since LibreOffice 7.3.0 + */ +class DataLabelsRange +{ +public: + + /// type of the internal container that stores the indexed label text. + typedef std::map LabelsRangeMap; + + /// Returns whether the container is empty or not. + bool empty() const; + /// Returns the count of labels stored. + size_t count() const; + /// Indicates whether the container has a label with index specified by nIndex. + bool hasLabel(sal_Int32 nIndex) const; + /// Returns the address of the cell[range] from which label contents are sourced. + const OUString & getRange() const; + + /// Sets the address of the cell[range] from which label contents are sourced. + void setRange(const OUString& rRange); + /// Adds a new indexed label text. + void setLabel(sal_Int32 nIndex, const OUString& rText); + + LabelsRangeMap::const_iterator begin() const; + LabelsRangeMap::const_iterator end() const; + +private: + OUString maRange; + LabelsRangeMap maLabels; +}; + + +class OOX_DLLPUBLIC ChartExport final : public DrawingML { + +public: + // first: data sequence for label, second: data sequence for values. + typedef ::std::vector< AxisIdPair > AxisVector; + +private: + sal_Int32 mnXmlNamespace; + sal_Int32 mnSeriesCount; + css::uno::Reference< css::frame::XModel > mxChartModel; + css::uno::Reference< css::chart::XDiagram > mxDiagram; + css::uno::Reference< css::chart2::XDiagram > mxNewDiagram; + std::shared_ptr mpURLTransformer; + + // members filled by InitRangeSegmentationProperties (retrieved from DataProvider) + bool mbHasCategoryLabels; //if the categories are only automatically generated this will be false + + //css::uno::Reference< css::drawing::XShapes > mxAdditionalShapes; + css::uno::Reference< css::chart2::data::XDataSequence > mxCategoriesValues; + + AxisVector maAxes; + bool mbHasZAxis; + bool mbIs3DChart; + bool mbStacked; + bool mbPercent; + bool mbHasDateCategories; + + std::set maExportedAxis; + +private: + sal_Int32 getChartType(); + + css::uno::Sequence< css::uno::Sequence< rtl::OUString > > getSplitCategoriesList(const OUString& rRange); + + OUString parseFormula( const OUString& rRange ); + void InitPlotArea(); + + void ExportContent_(); + void exportChartSpace( const css::uno::Reference< + css::chart::XChartDocument >& rChartDoc, + bool bIncludeTable ); + void exportChart( const css::uno::Reference< + css::chart::XChartDocument >& rChartDoc ); + void exportExternalData( const css::uno::Reference< + css::chart::XChartDocument >& rChartDoc ); + void exportLegend( const css::uno::Reference< + css::chart::XChartDocument >& rChartDoc ); + void exportTitle( const css::uno::Reference< css::drawing::XShape >& xShape, + const OUString* pSubText = nullptr ); + void exportPlotArea( const css::uno::Reference< + css::chart::XChartDocument >& rChartDoc ); + void exportAdditionalShapes( const css::uno::Reference& rChartDoc ); + void exportFill( const css::uno::Reference< css::beans::XPropertySet >& xPropSet ); + void exportSolidFill(const css::uno::Reference& xPropSet); + void exportGradientFill( const css::uno::Reference< css::beans::XPropertySet >& xPropSet ); + void exportBitmapFill( const css::uno::Reference< css::beans::XPropertySet >& xPropSet ); + void exportHatch(const css::uno::Reference& xPropSet); + void exportDataTable( ); + + void exportAreaChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportBarChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportBubbleChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportDoughnutChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportLineChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportPieChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportRadarChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportScatterChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportScatterChartSeries( const css::uno::Reference< css::chart2::XChartType >& xChartType, + const css::uno::Sequence>* pSeries); + void exportStockChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportSurfaceChart( const css::uno::Reference< css::chart2::XChartType >& xChartType ); + void exportHiLowLines(); + void exportUpDownBars(const css::uno::Reference< css::chart2::XChartType >& xChartType ); + + void exportAllSeries(const css::uno::Reference& xChartType, bool& rPrimaryAxes); + void exportSeries(const css::uno::Reference< css::chart2::XChartType >& xChartType, + const css::uno::Sequence >& rSeriesSeq, bool& rPrimaryAxes); + + void exportVaryColors(const css::uno::Reference& xChartType); + void exportCandleStickSeries( + const css::uno::Sequence< + css::uno::Reference< + css::chart2::XDataSeries > > & aSeriesSeq, + bool& rPrimaryAxes ); + void exportSeriesText( + const css::uno::Reference< css::chart2::data::XDataSequence >& xValueSeq ); + void exportSeriesCategory( + const css::uno::Reference< css::chart2::data::XDataSequence >& xValueSeq, sal_Int32 nValueType = XML_cat ); + void exportSeriesValues( + const css::uno::Reference< css::chart2::data::XDataSequence >& xValueSeq, sal_Int32 nValueType = XML_val ); + void exportShapeProps( const css::uno::Reference< css::beans::XPropertySet >& xPropSet ); + void exportDataPoints( + const css::uno::Reference< css::beans::XPropertySet >& xSeriesProperties, + sal_Int32 nSeriesLength, sal_Int32 eChartType ); + void exportDataLabels( const css::uno::Reference& xSeries, sal_Int32 nSeriesLength, + sal_Int32 eChartType, DataLabelsRange& rDLblsRange ); + void exportGrouping( bool isBar = false ); + void exportTrendlines( const css::uno::Reference< css::chart2::XDataSeries >& xSeries ); + void exportMarker( const css::uno::Reference< css::beans::XPropertySet >& xPropSet ); + void exportSmooth(); + void exportFirstSliceAng(); + + void exportErrorBar(const css::uno::Reference< css::beans::XPropertySet >& xErrorBarProps, + bool bYError); + + void exportManualLayout(const css::chart2::RelativePosition& rPos, const css::chart2::RelativeSize& rSize, const bool bIsExcludingDiagramPositioning); + + void exportAxes( ); + void exportAxis(const AxisIdPair& rAxisIdPair); + void _exportAxis( + const css::uno::Reference< css::beans::XPropertySet >& xAxisProp, + const css::uno::Reference< css::drawing::XShape >& xAxisTitle, + const css::uno::Reference< css::beans::XPropertySet >& xMajorGrid, + const css::uno::Reference< css::beans::XPropertySet >& xMinorGrid, + sal_Int32 nAxisType, + const char* sAxisPos, + const AxisIdPair& rAxisIdPair ); + void exportAxesId(bool bPrimaryAxes, bool bCheckCombinedAxes = false); + void exportView3D(); + bool isDeep3dChart(); + + void exportMissingValueTreatment(const css::uno::Reference& xPropSet); + + OUString getNumberFormatCode(sal_Int32 nKey) const; + +public: + + ChartExport( sal_Int32 nXmlNamespace, ::sax_fastparser::FSHelperPtr pFS, css::uno::Reference< css::frame::XModel > const & xModel, + ::oox::core::XmlFilterBase* pFB, DocumentType eDocumentType ); + virtual ~ChartExport() {} + + void SetURLTranslator(const std::shared_ptr& pTransformer); + + const css::uno::Reference< css::frame::XModel >& getModel() const { return mxChartModel; } + + void WriteChartObj( const css::uno::Reference< css::drawing::XShape >& xShape, sal_Int32 nID, sal_Int32 nChartCount ); + void exportTextProps(const css::uno::Reference< css::beans::XPropertySet >& xPropSet); + + void ExportContent(); + void InitRangeSegmentationProperties( + const css::uno::Reference< + css::chart2::XChartDocument > & xChartDoc ); +}; + +} + +#endif // INCLUDED_OOX_EXPORT_CHARTEXPORT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/export/drawingml.hxx b/include/oox/export/drawingml.hxx new file mode 100644 index 000000000..8b57523a5 --- /dev/null +++ b/include/oox/export/drawingml.hxx @@ -0,0 +1,382 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_EXPORT_DRAWINGML_HXX +#define INCLUDED_OOX_EXPORT_DRAWINGML_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Graphic; +class SdrObjCustomShape; +enum class SvxDateFormat; +enum class SvxTimeFormat; + +namespace com::sun::star { +namespace awt { + struct FontDescriptor; + struct Gradient; +} +namespace beans { + struct PropertyValue; + class XPropertySet; + class XPropertyState; +} +namespace drawing { + class XShape; + struct EnhancedCustomShapeParameterPair; + struct EnhancedCustomShapeParameter; +} +namespace graphic { + class XGraphic; +} +namespace style { + struct LineSpacing; +} +namespace text { + class XTextContent; + class XTextRange; + class XTextFrame; +} +namespace io { + class XOutputStream; +} +namespace uno { + class XInterface; +} +namespace frame { + class XModel; +} +} + +struct EscherConnectorListEntry; +class OutlinerParaObject; +namespace tools { class Rectangle; } + +namespace tools { + class PolyPolygon; +} + +namespace oox { +namespace core { + class XmlFilterBase; +} + +namespace drawingml { + +class OOX_DLLPUBLIC URLTransformer +{ +public: + virtual ~URLTransformer(); + + virtual OUString getTransformedString(const OUString& rURL) const; + + virtual bool isExternalURL(const OUString& rURL) const; +}; + +// Our rotation is counter-clockwise and is in 100ths of a degree. +// drawingML rotation is clockwise and is in 60000ths of a degree. +inline sal_Int32 ExportRotateClockwisify(Degree100 input) +{ + return ((21600000 - input.get() * 600) % 21600000); +} + +/// Interface to be implemented by the parent exporter that knows how to handle shape text. +class OOX_DLLPUBLIC DMLTextExport +{ +public: + virtual void WriteOutliner(const OutlinerParaObject& rParaObj) = 0; + /// Write the contents of the textbox that is associated to this shape. + virtual void WriteTextBox(css::uno::Reference xShape) = 0; + /// Get textbox which belongs to the shape. + virtual css::uno::Reference GetUnoTextFrame( + css::uno::Reference xShape) = 0; +protected: + DMLTextExport() {} + virtual ~DMLTextExport() {} +}; + +class OOX_DLLPUBLIC DrawingML +{ + +private: + static std::stack mnImageCounter; + static std::stack mnWdpImageCounter; + static std::stack> maWdpCache; + static sal_Int32 mnDrawingMLCount; + static sal_Int32 mnVmlCount; + static std::stack> maExportGraphics; + + /// To specify where write eg. the images to (like 'ppt', or 'word' - according to the OPC). + DocumentType meDocumentType; + /// Parent exporter, used for text callback. + DMLTextExport* mpTextExport; + + +protected: + css::uno::Any mAny; + ::sax_fastparser::FSHelperPtr mpFS; + ::oox::core::XmlFilterBase* mpFB; + /// If set, this is the parent of the currently handled shape. + css::uno::Reference m_xParent; + bool mbIsBackgroundDark; + + /// True when exporting presentation placeholder shape. + bool mbPlaceholder; + + bool GetProperty( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, const OUString& aName ); + bool GetPropertyAndState( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, + const css::uno::Reference< css::beans::XPropertyState >& rXPropState, + const OUString& aName, css::beans::PropertyState& eState ); + OUString GetFieldValue( const css::uno::Reference< css::text::XTextRange >& rRun, bool& bIsURLField ); + /** Gets OOXML datetime field type from LO Date format + + @param eDate LO Date format + */ + static OUString GetDatetimeTypeFromDate(SvxDateFormat eDate); + /** Gets OOXML datetime field type from LO Time format + + @param eTime LO Time format + */ + static OUString GetDatetimeTypeFromTime(SvxTimeFormat eTime); + /** Gets OOXML datetime field type from combination of LO Time and Date formats + + @param eDate LO Date format + @param eTime LO Time format + */ + static OUString GetDatetimeTypeFromDateTime(SvxDateFormat eDate, SvxTimeFormat eTime); + + /// Output the media (including copying a video from vnd.sun.star.Package: to the output if necessary). + void WriteMediaNonVisualProperties(const css::uno::Reference& xShape); + + void WriteStyleProperties( sal_Int32 nTokenId, const css::uno::Sequence< css::beans::PropertyValue >& aProperties ); + + const char* GetComponentDir() const; + const char* GetRelationCompPrefix() const; + + static bool EqualGradients( css::awt::Gradient aGradient1, css::awt::Gradient aGradient2 ); + bool IsFontworkShape(const css::uno::Reference< css::beans::XPropertySet >& rXShapePropSet); + + void WriteGlowEffect(const css::uno::Reference& rXPropSet); + void WriteSoftEdgeEffect(const css::uno::Reference& rXPropSet); + void WriteCustomGeometryPoint(const css::drawing::EnhancedCustomShapeParameterPair& rParamPair, + const EnhancedCustomShape2d& rCustomShape2d, + const bool bReplaceGeoWidth, const bool bReplaceGeoHeight); + bool WriteCustomGeometrySegment( + const sal_Int16 eCommand, const sal_Int32 nCount, + const css::uno::Sequence& rPairs, + sal_Int32& rnPairIndex, double& rfCurrentX, double& rfCurrentY, bool& rbCurrentValid, + const EnhancedCustomShape2d& rCustomShape2d, + const bool bReplaceGeoWidth, const bool bReplaceGeoHeight); + +public: + DrawingML( ::sax_fastparser::FSHelperPtr pFS, ::oox::core::XmlFilterBase* pFB, DocumentType eDocumentType = DOCUMENT_PPTX, DMLTextExport* pTextExport = nullptr ) + : meDocumentType( eDocumentType ), mpTextExport(pTextExport), mpFS( pFS ), mpFB( pFB ), mbIsBackgroundDark( false ), mbPlaceholder(false) {} + void SetFS( ::sax_fastparser::FSHelperPtr pFS ) { mpFS = pFS; } + const ::sax_fastparser::FSHelperPtr& GetFS() const { return mpFS; } + ::oox::core::XmlFilterBase* GetFB() { return mpFB; } + DocumentType GetDocumentType() const { return meDocumentType; } + /// The application-specific text exporter callback, if there is one. + DMLTextExport* GetTextExport() { return mpTextExport; } + + void SetBackgroundDark(bool bIsDark) { mbIsBackgroundDark = bIsDark; } + /// If bRelPathToMedia is true add "../" to image folder path while adding the image relationship + OUString WriteImage( const Graphic &rGraphic , bool bRelPathToMedia = false ); + + void WriteColor( ::Color nColor, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteColor( const OUString& sColorSchemeName, const css::uno::Sequence< css::beans::PropertyValue >& aTransformations, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteColor( const ::Color nColor, const css::uno::Sequence< css::beans::PropertyValue >& aTransformations, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteColorTransformations( const css::uno::Sequence< css::beans::PropertyValue >& aTransformations, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteGradientStop(sal_uInt16 nStop, ::Color nColor, sal_Int32 nAlpha = MAX_PERCENT); + void WriteLineArrow( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, bool bLineStart ); + void WriteConnectorConnections( sal_uInt32 nStartGlueId, sal_Int32 nEndGlueId, sal_Int32 nStartID, sal_Int32 nEndID ); + + bool WriteCharColor(const css::uno::Reference& xPropertySet); + bool WriteFillColor(const css::uno::Reference& xPropertySet); + + void WriteSolidFill( ::Color nColor, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteSolidFill( const OUString& sSchemeName, const css::uno::Sequence< css::beans::PropertyValue >& aTransformations, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteSolidFill( const ::Color nColor, const css::uno::Sequence< css::beans::PropertyValue >& aTransformations, sal_Int32 nAlpha = MAX_PERCENT ); + void WriteSolidFill( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet ); + void WriteGradientFill( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet ); + + void WriteGradientFill( css::awt::Gradient rGradient, css::awt::Gradient rTransparenceGradient, + const css::uno::Reference& rXPropSet = css::uno::Reference()); + + void WriteGrabBagGradientFill( const css::uno::Sequence< css::beans::PropertyValue >& aGradientStops, css::awt::Gradient rGradient); + + void WriteBlipOrNormalFill( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, + const OUString& rURLPropName ); + void WriteBlipFill( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, + const OUString& sURLPropName ); + void WriteBlipFill( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, + const OUString& sURLPropName, sal_Int32 nXmlNamespace ); + + void WriteXGraphicBlipFill(css::uno::Reference const & rXPropSet, + css::uno::Reference const & rxGraphic, + sal_Int32 nXmlNamespace, bool bWriteMode, bool bRelPathToMedia = false); + + void WritePattFill( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet ); + void WritePattFill(const css::uno::Reference& rXPropSet, + const css::drawing::Hatch& rHatch); + + void WriteGraphicCropProperties(css::uno::Reference const & rxPropertySet, + Size const & rOriginalSize, MapMode const & rMapMode); + + void WriteSrcRectXGraphic(css::uno::Reference const & rxPropertySet, + css::uno::Reference const & rxGraphic); + + void WriteOutline( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, + css::uno::Reference< css::frame::XModel> const & xModel = nullptr ); + + void WriteXGraphicStretch(css::uno::Reference const & rXPropSet, + css::uno::Reference const & rxGraphic); + + void WriteXGraphicTile(css::uno::Reference const& rXPropSet, + css::uno::Reference const& rxGraphic); + + void WriteLinespacing(const css::style::LineSpacing& rLineSpacing, float fFirstCharHeight); + + OUString WriteXGraphicBlip(css::uno::Reference const & rXPropSet, + css::uno::Reference const & rxGraphic, + bool bRelPathToMedia); + + void WriteImageBrightnessContrastTransparence(css::uno::Reference const & rXPropSet); + + void WriteXGraphicBlipMode(css::uno::Reference const & rXPropSet, + css::uno::Reference const & rxGraphic); + + void WriteShapeTransformation(const css::uno::Reference< css::drawing::XShape >& rXShape, + sal_Int32 nXmlNamespace, bool bFlipH = false, bool bFlipV = false, bool bSuppressRotation = false, bool bSuppressFlipping = false, bool bFlippedBeforeRotation = false); + void WriteTransformation(const css::uno::Reference< css::drawing::XShape >& xShape, const tools::Rectangle& rRectangle, + sal_Int32 nXmlNamespace, bool bFlipH = false, bool bFlipV = false, sal_Int32 nRotation = 0, bool bIsGroupShape = false); + + void WriteText( const css::uno::Reference< css::uno::XInterface >& rXIface, bool bBodyPr, bool bText = true, sal_Int32 nXmlNamespace = 0, bool bWritePropertiesAsLstStyles = false); + + /** Populates the lstStyle with the shape's text run and paragraph properties */ + void WriteLstStyles(const css::uno::Reference& rParagraph, + bool& rbOverridingCharHeight, sal_Int32& rnCharHeight, + const css::uno::Reference& rXShapePropSet); + void WriteParagraph( const css::uno::Reference< css::text::XTextContent >& rParagraph, + bool& rbOverridingCharHeight, sal_Int32& rnCharHeight, const css::uno::Reference< css::beans::XPropertySet >& rXShapePropSet); + /** Writes paragraph properties + + @returns true if any paragraph properties were written + */ + bool WriteParagraphProperties(const css::uno::Reference< css::text::XTextContent >& rParagraph, const css::uno::Reference& rXShapePropSet, float fFirstCharHeight, sal_Int32 nElement); + void WriteParagraphNumbering(const css::uno::Reference< css::beans::XPropertySet >& rXPropSet, float fFirstCharHeight, + sal_Int16 nLevel ); + void WriteParagraphTabStops(const css::uno::Reference& rXPropSet); + void WriteRun( const css::uno::Reference< css::text::XTextRange >& rRun, + bool& rbOverridingCharHeight, sal_Int32& rnCharHeight, + const css::uno::Reference< css::beans::XPropertySet >& rXShapePropSet); + void WriteRunProperties( const css::uno::Reference< css::beans::XPropertySet >& rRun, bool bIsField, sal_Int32 nElement, bool bCheckDirect, + bool& rbOverridingCharHeight, sal_Int32& rnCharHeight, + sal_Int16 nScriptType = css::i18n::ScriptType::LATIN, + const css::uno::Reference< css::beans::XPropertySet >& rXShapePropSet = {}); + + void WritePresetShape( const OString& pShape , std::vector< std::pair> & rAvList ); + void WritePresetShape( const OString& pShape ); + void WritePresetShape( const OString& pShape, MSO_SPT eShapeType, bool bPredefinedHandlesUsed, const css::beans::PropertyValue& rProp ); + bool WriteCustomGeometry( + const css::uno::Reference& rXShape, + const SdrObjCustomShape& rSdrObjCustomShape); + void WriteEmptyCustomGeometry(); + void WritePolyPolygon(const css::uno::Reference& rXShape, + const bool bClosed); + void WriteFill( const css::uno::Reference< css::beans::XPropertySet >& xPropSet ); + void WriteShapeStyle( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet ); + void WriteShapeEffects( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet ); + void WriteShapeEffect( std::u16string_view sName, const css::uno::Sequence< css::beans::PropertyValue >& aEffectProps ); + /** Populates scene3d tag + @param rXPropSet Prop set + @param bIsText True if the 3D effects are for a text body, false if it is for a shape + */ + void Write3DEffects(const css::uno::Reference& rXPropSet, bool bIsText); + void WriteArtisticEffect( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet ); + OString WriteWdpPicture( const OUString& rFileId, const css::uno::Sequence< sal_Int8 >& rPictureData ); + void WriteDiagram(const css::uno::Reference& rXShape, int nDiagramId); + void writeDiagramRels(const css::uno::Sequence>& xRelSeq, + const css::uno::Reference& xOutStream, + std::u16string_view sGrabBagProperyName, int nDiagramId); + static void WriteFromTo(const css::uno::Reference& rXShape, const css::awt::Size& aPageSize, + const sax_fastparser::FSHelperPtr& pDrawing); + + static bool IsGroupShape( const css::uno::Reference< css::drawing::XShape >& rXShape ); + sal_Int32 getBulletMarginIndentation (const css::uno::Reference< css::beans::XPropertySet >& rXPropSet,sal_Int16 nLevel, std::u16string_view propName); + + static void ResetMlCounters(); + + static void PushExportGraphics(); + static void PopExportGraphics(); + + static sal_Int32 getNewDrawingUniqueId() { return ++mnDrawingMLCount; } + static sal_Int32 getNewVMLUniqueId() { return ++mnVmlCount; } + + // A Helper to decide the script type for given text in order to call WriteRunProperties. + static sal_Int16 GetScriptType(const OUString& rStr); + + static sal_Unicode SubstituteBullet( sal_Unicode cBulletId, css::awt::FontDescriptor& rFontDesc ); + + static ::Color ColorWithIntensity( sal_uInt32 nColor, sal_uInt32 nIntensity ); + + static const char* GetAlignment( css::style::ParagraphAdjust nAlignment ); + + sax_fastparser::FSHelperPtr CreateOutputStream ( + const OUString& sFullStream, + std::u16string_view sRelativeStream, + const css::uno::Reference< css::io::XOutputStream >& xParentRelation, + const char* sContentType, + const char* sRelationshipType, + OUString* pRelationshipId ); + +}; + +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/export/shapes.hxx b/include/oox/export/shapes.hxx new file mode 100644 index 000000000..646d462e8 --- /dev/null +++ b/include/oox/export/shapes.hxx @@ -0,0 +1,213 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_EXPORT_SHAPES_HXX +#define INCLUDED_OOX_EXPORT_SHAPES_HXX + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { +namespace beans { + class XPropertySet; +} +namespace drawing { + class XShape; +} + +namespace embed { + class XEmbeddedObject; +} +namespace io { + class XInputStream; +} +namespace uno { + class XComponentContext; + class XInterface; +} +} + +namespace oox::core { + class XmlFilterBase; +} + +class Graphic; + +namespace oox { + +OOX_DLLPUBLIC css::uno::Reference GetOLEObjectStream( + css::uno::Reference const& xContext, + css::uno::Reference const& xObj, + std::u16string_view i_rProgID, + OUString & o_rMediaType, + OUString & o_rRelationType, + OUString & o_rSuffix, + const char *& o_rpProgID); + +} + +namespace oox::drawingml { + +class OOX_DLLPUBLIC ShapeExport : public DrawingML { + +private: + int m_nEmbeddedObjects; + +public: + typedef std::unordered_map< css::uno::Reference< css::drawing::XShape>, sal_Int32> ShapeHashMap; + +protected: + sal_Int32 mnShapeIdMax; + bool mbUserShapes; // for chart's embedded usershapes + + void WriteGraphicObjectShapePart( const css::uno::Reference< css::drawing::XShape >& xShape, const Graphic *pGraphic=nullptr ); + + OUString GetShapeName(const css::uno::Reference< css::drawing::XShape >& xShape); + +private: + sal_Int32 mnXmlNamespace; + MapMode maMapModeSrc, maMapModeDest; + std::shared_ptr mpURLTransformer; + + css::awt::Size MapSize( const css::awt::Size& ) const; + + ShapeHashMap maShapeMap; + ShapeHashMap* mpShapeMap; + +public: + + ShapeExport( sal_Int32 nXmlNamespace, ::sax_fastparser::FSHelperPtr pFS, + ShapeHashMap* pShapeMap, ::oox::core::XmlFilterBase* pFB, + DocumentType eDocumentType = DOCUMENT_PPTX, + DMLTextExport* pTextExport = nullptr, + bool bUserShapes = false ); + virtual ~ShapeExport() {} + + void SetURLTranslator(const std::shared_ptr& pTransformer); + + static bool NonEmptyText( const css::uno::Reference< css::uno::XInterface >& xIface ); + + ShapeExport& + WritePolyPolygonShape( const css::uno::Reference< css::drawing::XShape >& xShape, bool bClosed ); + ShapeExport& + WriteClosedPolyPolygonShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteConnectorShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteCustomShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteEllipseShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteGraphicObjectShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteGroupShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteLineShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteNonVisualDrawingProperties( const css::uno::Reference< css::drawing::XShape >& xShape, const char* sName ); + virtual ShapeExport& + WriteNonVisualProperties( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteOpenPolyPolygonShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteRectangleShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + + /** + * Write the DrawingML for a particular shape. + * + *

    This is the member function you want. It performs the type lookup and + * invokes the appropriate corresponding Write*() method for the specific + * type.

    + * + *

    To write an XShape, XShape::getShapeType() is called to determine + * the shape type, and the corresponding method in this table is + * invoked:

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Shape TypeMethod
    com.sun.star.drawing.ClosedBezierShape ShapeExport::WriteClosedPolyPolygonShape
    com.sun.star.drawing.CustomShape ShapeExport::WriteCustomShape
    com.sun.star.drawing.EllipseShape ShapeExport::WriteEllipseShape
    com.sun.star.drawing.GraphicObjectShape ShapeExport::WriteGraphicObjectShape
    com.sun.star.drawing.LineShape ShapeExport::WriteLineShape
    com.sun.star.drawing.OpenBezierShape ShapeExport::WriteOpenPolyPolygonShape
    com.sun.star.drawing.PolyPolygonShape ShapeExport::WriteClosedPolyPolygonShape
    com.sun.star.drawing.PolyLineShape ShapeExport::WriteOpenPolyPolygonShape
    com.sun.star.drawing.RectangleShape ShapeExport::WriteRectangleShape
    com.sun.star.drawing.TableShape ShapeExport::WriteTableShape
    com.sun.star.drawing.TextShape ShapeExport::WriteTextShape
    com.sun.star.presentation.DateTimeShape ShapeExport::WriteTextShape
    com.sun.star.presentation.FooterShape ShapeExport::WriteTextShape
    com.sun.star.presentation.HeaderShape ShapeExport::WriteTextShape
    com.sun.star.presentation.NotesShape ShapeExport::WriteTextShape
    com.sun.star.presentation.OutlinerShape ShapeExport::WriteTextShape
    com.sun.star.presentation.SlideNumberShapeShapeExport::WriteTextShape
    com.sun.star.presentation.TitleTextShape ShapeExport::WriteTextShape
    + * + *

    If the shape type is not recognized, then + * ShapeExport::WriteUnknownShape is called.

    + * + * @param xShape The shape to export as DrawingML. + * @return *this + */ + ShapeExport& WriteShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& WriteTextBox( const css::uno::Reference< css::uno::XInterface >& xIface, sal_Int32 nXmlNamespace, bool bWritePropertiesAsLstStyles = false ); + virtual ShapeExport& + WriteTextShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + ShapeExport& + WriteTableShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + void WriteMathShape(css::uno::Reference const& xShape); + ShapeExport& + WriteOLE2Shape( const css::uno::Reference< css::drawing::XShape >& xShape ); + virtual ShapeExport& + WriteUnknownShape( const css::uno::Reference< css::drawing::XShape >& xShape ); + + void WriteTable( const css::uno::Reference< css::drawing::XShape >& rXShape ); + + void WriteTableCellProperties(const css::uno::Reference< css::beans::XPropertySet >& rXPropSet); + + void WriteBorderLine(const sal_Int32 XML_line, const css::table::BorderLine2& rBorderLine); + void WriteTableCellBorders(const css::uno::Reference< css::beans::XPropertySet >& rXPropSet); + + sal_Int32 GetNewShapeID( const css::uno::Reference< css::drawing::XShape >& rShape ); + sal_Int32 GetNewShapeID( const css::uno::Reference< css::drawing::XShape >& rShape, ::oox::core::XmlFilterBase* pFB ); + sal_Int32 GetShapeID( const css::uno::Reference< css::drawing::XShape >& rShape ); + static sal_Int32 GetShapeID( const css::uno::Reference< css::drawing::XShape >& rShape, ShapeHashMap* pShapeMap ); +}; + +} + +#endif // INCLUDED_OOX_EXPORT_SHAPES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/export/utils.hxx b/include/oox/export/utils.hxx new file mode 100644 index 000000000..00fd953a0 --- /dev/null +++ b/include/oox/export/utils.hxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_EXPORT_UTILS_HXX +#define INCLUDED_OOX_EXPORT_UTILS_HXX + +#include + +#include +#include +#include + +#include + +inline OString I32SHEX(sal_Int32 x) +{ + OString aStr = OString::number(x, 16); + while (aStr.getLength() < 6) + aStr = "0" + aStr; + return aStr; +} + +/** + * @return const char* literal "true" for true value, or literal "false" + * for false value. + */ +static constexpr const char* ToPsz(bool b) +{ + return b ? "true" : "false"; +} + +/** + * @return literal "1" for true value, or literal "0" for false value. + */ +static constexpr const char* ToPsz10(bool b) +{ + // xlsx seems to use "1" or "0" for boolean values. I wonder it ever uses + // the "true" "false" variant. + return b ? "1" : "0"; +} + +static constexpr sal_Int64 PPTtoEMU( sal_Int32 nPPT ) +{ + return o3tl::convert(nPPT, o3tl::Length::master, o3tl::Length::emu); +} + +static constexpr sal_Int64 TwipsToEMU( sal_Int32 nTwips ) +{ + return o3tl::convert(nTwips, o3tl::Length::twip, o3tl::Length::emu); +} + +template +OString write1000thOfAPercent(T number) +{ + return OString::number( lround(number * 1000.0) ); +} + +namespace oox::drawingml { + enum DocumentType { DOCUMENT_DOCX, DOCUMENT_PPTX, DOCUMENT_XLSX }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/export/vmlexport.hxx b/include/oox/export/vmlexport.hxx new file mode 100644 index 000000000..fa54f27aa --- /dev/null +++ b/include/oox/export/vmlexport.hxx @@ -0,0 +1,209 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_EXPORT_VMLEXPORT_HXX +#define INCLUDED_OOX_EXPORT_VMLEXPORT_HXX + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace drawing { + class XShape; + } +} + +namespace oox::drawingml { + class DrawingML; +} + + +namespace sax_fastparser { + class FastAttributeList; +} + +class Point; +namespace tools { class Rectangle; } +class SdrObject; + +namespace oox::vml { + +/// Interface to be implemented by the parent exporter that knows how to handle shape text. +class OOX_DLLPUBLIC VMLTextExport +{ +public: + virtual void WriteOutliner(const OutlinerParaObject& rParaObj) = 0; + virtual oox::drawingml::DrawingML& GetDrawingML() = 0; + /// Write the contents of the textbox that is associated to this shape in VML format. + virtual void WriteVMLTextBox(css::uno::Reference xShape) = 0; +protected: + VMLTextExport() {} + virtual ~VMLTextExport() {} +}; + +class OOX_DLLPUBLIC VMLExport : public EscherEx +{ + /// Fast serializer to output the data + ::sax_fastparser::FSHelperPtr m_pSerializer; + + /// Parent exporter, used for text callback. + VMLTextExport* m_pTextExport; + + /// Anchoring - Writer specific properties + sal_Int16 m_eHOri, m_eVOri, m_eHRel, m_eVRel; + rtl::Reference m_pWrapAttrList; + bool m_bInline; // css::text::TextContentAnchorType_AS_CHARACTER + bool m_IsFollowingTextFlow = false; + + /// The object we're exporting. + const SdrObject* m_pSdrObject; + + /// Fill the shape attributes as they come. + rtl::Reference<::sax_fastparser::FastAttributeList> m_pShapeAttrList; + + /// Remember the shape type. + sal_uInt32 m_nShapeType; + + /// Remember the shape flags. + ShapeFlag m_nShapeFlags; + + /// Remember style, the most important shape attribute ;-) + OStringBuffer m_ShapeStyle; + + /// style for textbox + OStringBuffer m_TextboxStyle; + + /// Remember the generated shape id. + OString m_sShapeId; + + /// Remember which shape types we had already written. + std::vector m_aShapeTypeWritten; + + /// It seems useless to write out an XML_ID attribute next to XML_id which defines the actual shape id + bool m_bSkipwzName; + + /// Use '#' mark for type attribute (check Type Attribute of VML shape in OOXML documentation) + bool m_bUseHashMarkForType; + + /** There is a shapeid generation mechanism in EscherEx, but it does not seem to work + * so override the existing behavior to get actually unique ids. + */ + bool m_bOverrideShapeIdGeneration; + + /// Prefix for overridden shape id generation (used if m_bOverrideShapeIdGeneration is true) + OString m_sShapeIDPrefix; + + /// Counter for generating shape ids (used if m_bOverrideShapeIdGeneration is true) + sal_uInt64 m_nShapeIDCounter; + +public: + VMLExport( ::sax_fastparser::FSHelperPtr const & pSerializer, VMLTextExport* pTextExport = nullptr); + virtual ~VMLExport() override; + + const ::sax_fastparser::FSHelperPtr& + GetFS() const { return m_pSerializer; } + + void SetFS(const ::sax_fastparser::FSHelperPtr& pSerializer); + + /// Export the sdr object as VML. + /// + /// Call this when you need to export the object as VML. + OString const & AddSdrObject( const SdrObject& rObj, + bool const bIsFollowingTextFlow = false, + sal_Int16 eHOri = -1, sal_Int16 eVOri = -1, sal_Int16 eHRel = -1, + sal_Int16 eVRel = -1, + sax_fastparser::FastAttributeList* pWrapAttrList = nullptr, + const bool bOOxmlExport = false ); + OString const & AddInlineSdrObject( const SdrObject& rObj, const bool bOOxmlExport ); + virtual void AddSdrObjectVMLObject( const SdrObject& rObj) override; + static bool IsWaterMarkShape(std::u16string_view rStr); + + void SetSkipwzName(bool bSkipwzName) { m_bSkipwzName = bSkipwzName; } + void SetHashMarkForType(bool bUseHashMarkForType) { m_bUseHashMarkForType = bUseHashMarkForType; } + void OverrideShapeIDGen(bool bOverrideShapeIdGeneration, + const OString& sShapeIDPrefix = OString()); + static OString GetVMLShapeTypeDefinition(std::string_view sShapeID, const bool bIsPictureFrame); + +protected: + /// Add an attribute to the generated element. + /// + /// This should be called from within StartShape() to ensure that the + /// added attribute is preserved. + void AddShapeAttribute( sal_Int32 nAttribute, const OString& sValue ); + + using EscherEx::StartShape; + using EscherEx::EndShape; + + /// Override shape ID generation when m_bOverrideShapeIdGeneration is set to true + virtual sal_uInt32 GenerateShapeId() override; + + /// Start the shape for which we just collected the information. + /// + /// Returns the element's tag number, -1 means we wrote nothing. + virtual sal_Int32 StartShape(); + + /// End the shape. + /// + /// The parameter is just what we got from StartShape(). + virtual void EndShape( sal_Int32 nShapeElement ); + virtual void Commit( EscherPropertyContainer& rProps, const tools::Rectangle& rRect ) override; + +private: + + virtual void OpenContainer( sal_uInt16 nEscherContainer, int nRecInstance = 0 ) override; + virtual void CloseContainer() override; + + virtual sal_uInt32 EnterGroup( const OUString& rShapeName, const tools::Rectangle* pBoundRect ) override; + virtual void LeaveGroup() override; + + virtual void AddShape( sal_uInt32 nShapeType, ShapeFlag nShapeFlags, sal_uInt32 nShapeId = 0 ) override; + +private: + /// Create an OString representing the id from a numerical id. + OString ShapeIdString( sal_uInt32 nId ); + + /// Add flip X and\or flip Y + void AddFlipXY( ); + + /// Add starting and ending point of a line to the m_pShapeAttrList. + void AddLineDimensions( const tools::Rectangle& rRectangle ); + + /// Add position and size to the OStringBuffer. + void AddRectangleDimensions( OStringBuffer& rBuffer, const tools::Rectangle& rRectangle, bool rbAbsolutePos = true ); +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/addtosequence.hxx b/include/oox/helper/addtosequence.hxx new file mode 100644 index 000000000..dbb271ca0 --- /dev/null +++ b/include/oox/helper/addtosequence.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_ADDTOSEQUENCE_HXX +#define INCLUDED_OOX_HELPER_ADDTOSEQUENCE_HXX + +#include +#include + +namespace oox +{ + +/** this adds an any to another any. + if rNewValue is empty, rOldValue is returned. + if rOldValue is empty, rNewValue is returned. + if rOldValue contains a value, a sequence with rOldValue and rNewValue is returned. + if rOldValue contains a sequence, a new sequence with the old sequence and rNewValue is returned. +*/ +OOX_DLLPUBLIC css::uno::Any addToSequence( const css::uno::Any& rOldValue, const css::uno::Any& rNewValue ); + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/attributelist.hxx b/include/oox/helper/attributelist.hxx new file mode 100644 index 000000000..27101657f --- /dev/null +++ b/include/oox/helper/attributelist.hxx @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_ATTRIBUTELIST_HXX +#define INCLUDED_OOX_HELPER_ATTRIBUTELIST_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace xml::sax { class XFastAttributeList; } +} + +namespace sax_fastparser { + class FastAttributeList; +}; + +namespace oox { + + /* Get the color tokens from their string representatives. */ + sal_Int32 getHighlightColorTokenFromString(std::u16string_view sColorName); + +/** Static helpers for conversion of strings to attribute values of various + different data types. + */ +class OOX_DLLPUBLIC AttributeConversion +{ +public: + /** Returns the XML token identifier from the passed string. */ + static sal_Int32 decodeToken( std::u16string_view rValue ); + + /** Returns the decoded string value. All characters in the format + '_xHHHH_' (H being a hexadecimal digit), will be decoded. */ + static OUString decodeXString( const OUString& rValue ); + + /** Returns the 32-bit signed integer value from the passed string (decimal). */ + static sal_Int32 decodeInteger( std::u16string_view rValue ); + + /** Returns the 32-bit unsigned integer value from the passed string (decimal). */ + static sal_uInt32 decodeUnsigned( std::u16string_view rValue ); + + /** Returns the 64-bit signed integer value from the passed string (decimal). */ + static sal_Int64 decodeHyper( std::u16string_view rValue ); + + /** Returns the 32-bit signed integer value from the passed string (hexadecimal). */ + static sal_Int32 decodeIntegerHex( std::u16string_view rValue ); +}; + + +/** Provides access to attribute values of an element. + + Wraps a com.sun.star.xml.sax.XFastAttributeList object. Provides + convenience functions that convert the string value of an attribute to + various other data types. + */ +class OOX_DLLPUBLIC AttributeList +{ +public: + explicit AttributeList( + const css::uno::Reference< css::xml::sax::XFastAttributeList >& rxAttribs ); + + /** Returns the wrapped com.sun.star.xml.sax.XFastAttributeList object. */ + const css::uno::Reference< css::xml::sax::XFastAttributeList >& + getFastAttributeList() const { return mxAttribs; } + + /** Returns true, if the specified attribute is present. */ + bool hasAttribute( sal_Int32 nAttrToken ) const; + + // optional return values ------------------------------------------------- + + /** Returns the token identifier of the value of the specified attribute. */ + OptValue< sal_Int32 > getToken( sal_Int32 nAttrToken ) const; + + /** Returns the Color object of highlight of the text. */ + oox::drawingml::Color getHighlightColor(sal_Int32 nAttrToken) const; + + /** Returns the string value of the specified attribute. */ + OptValue< OUString > getString( sal_Int32 nAttrToken ) const; + + /** Returns the string value of the specified attribute. All characters in + the format '_xHHHH_' (H being a hexadecimal digit), will be decoded. */ + OptValue< OUString > getXString( sal_Int32 nAttrToken ) const; + + /** Returns the double value of the specified attribute. */ + OptValue< double > getDouble( sal_Int32 nAttrToken ) const; + + /** Returns the 32-bit signed integer value of the specified attribute (decimal). */ + OptValue< sal_Int32 > getInteger( sal_Int32 nAttrToken ) const; + + /** Returns the 32-bit unsigned integer value of the specified attribute (decimal). */ + OptValue< sal_uInt32 > getUnsigned( sal_Int32 nAttrToken ) const; + + /** Returns the 64-bit signed integer value of the specified attribute (decimal). */ + OptValue< sal_Int64 > getHyper( sal_Int32 nAttrToken ) const; + + /** Returns the 32-bit signed integer value of the specified attribute (hexadecimal). */ + OptValue< sal_Int32 > getIntegerHex( sal_Int32 nAttrToken ) const; + + /** Returns the boolean value of the specified attribute. */ + OptValue< bool > getBool( sal_Int32 nAttrToken ) const; + + /** Returns the date/time value of the specified attribute. */ + OptValue< css::util::DateTime > getDateTime( sal_Int32 nAttrToken ) const; + + // defaulted return values ------------------------------------------------ + + /** Returns the token identifier of the value of the specified attribute, + or the passed default identifier if the attribute is missing. */ + sal_Int32 getToken( sal_Int32 nAttrToken, sal_Int32 nDefault ) const; + + /** Returns the string value of the specified attribute, or the passed + default string if the attribute is missing. */ + OUString getString( sal_Int32 nAttrToken, const OUString& rDefault ) const; + + /** Returns the decoded string value of the specified attribute, or the + passed default string if the attribute is missing. */ + OUString getXString( sal_Int32 nAttrToken, const OUString& rDefault ) const; + + const char* getChar( sal_Int32 nAttrToken ) const; + + + /** Returns the double value of the specified attribute, or the passed + default value if the attribute is missing or not convertible to a double. */ + double getDouble( sal_Int32 nAttrToken, double fDefault ) const; + + /** Returns the 32-bit signed integer value of the specified attribute, or the + passed default value if the attribute is missing or not convertible to integer. */ + sal_Int32 getInteger( sal_Int32 nAttrToken, sal_Int32 nDefault ) const; + + /** Returns the 32-bit unsigned integer value of the specified attribute, or the + passed default value if the attribute is missing or not convertible to unsigned. */ + sal_uInt32 getUnsigned( sal_Int32 nAttrToken, sal_uInt32 nDefault ) const; + + /** Returns the 64-bit signed integer value of the specified attribute, or the + passed default value if the attribute is missing or not convertible to integer. */ + sal_Int64 getHyper( sal_Int32 nAttrToken, sal_Int64 nDefault ) const; + + /** Returns the 32-bit signed integer value of the specified attribute (hexadecimal), + or the passed default value if the attribute is missing or not convertible. */ + sal_Int32 getIntegerHex( sal_Int32 nAttrToken, sal_Int32 nDefault ) const; + + sal_uInt32 getUnsignedHex( sal_Int32 nAttrToken, sal_uInt32 nDefault ) const; + + /** Returns the boolean value of the specified attribute, or the passed + default value if the attribute is missing or not convertible to bool. */ + bool getBool( sal_Int32 nAttrToken, bool bDefault ) const; + + /** Returns the date/time value of the specified attribute, or the default + value if the attribute is missing or not convertible to a date/time value. */ + css::util::DateTime getDateTime( sal_Int32 nAttrToken, const css::util::DateTime& rDefault ) const; + + std::vector getTokenList(sal_Int32 nAttrToken) const; + +private: + css::uno::Reference< css::xml::sax::XFastAttributeList > + mxAttribs; + mutable sax_fastparser::FastAttributeList *mpAttribList; + sax_fastparser::FastAttributeList *getAttribList() const; +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/binaryinputstream.hxx b/include/oox/helper/binaryinputstream.hxx new file mode 100644 index 000000000..e27b2def9 --- /dev/null +++ b/include/oox/helper/binaryinputstream.hxx @@ -0,0 +1,385 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_BINARYINPUTSTREAM_HXX +#define INCLUDED_OOX_HELPER_BINARYINPUTSTREAM_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XInputStream; } +} + +namespace oox { + +class BinaryOutputStream; + + +/** Interface for binary input stream classes. + + The binary data in the stream is assumed to be in little-endian format. + */ +class OOX_DLLPUBLIC BinaryInputStream : public virtual BinaryStreamBase +{ +public: + /** Derived classes implement reading nBytes bytes to the passed sequence. + The sequence will be reallocated internally. + + @param nAtomSize + The size of the elements in the memory block, if available. Derived + classes may be interested in this information. + + @return + Number of bytes really read. + */ + virtual sal_Int32 readData( StreamDataSequence& orData, sal_Int32 nBytes, size_t nAtomSize = 1 ) = 0; + + /** Derived classes implement reading nBytes bytes to the (preallocated!) + memory buffer opMem. + + @param nAtomSize + The size of the elements in the memory block, if available. Derived + classes may be interested in this information. + + @return + Number of bytes really read. + */ + virtual sal_Int32 readMemory( void* opMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) = 0; + + /** Derived classes implement seeking the stream forward by the passed + number of bytes. This should work for non-seekable streams too. + + @param nAtomSize + The size of the elements in the memory block, if available. Derived + classes may be interested in this information. + */ + virtual void skip( sal_Int32 nBytes, size_t nAtomSize = 1 ) = 0; + + /** Reads a value from the stream and converts it to platform byte order. + All data types supported by the ByteOrderConverter class can be used. + */ + template< typename Type > + [[nodiscard]] + Type readValue(); + + [[nodiscard]] + sal_Int8 readInt8() { return readValue(); } + [[nodiscard]] + sal_uInt8 readuInt8() { return readValue(); } + [[nodiscard]] + sal_Int16 readInt16() { return readValue(); } + [[nodiscard]] + sal_uInt16 readuInt16() { return readValue(); } + [[nodiscard]] + sal_Int32 readInt32() { return readValue(); } + [[nodiscard]] + sal_uInt32 readuInt32() { return readValue(); } + [[nodiscard]] + sal_Int64 readInt64() { return readValue(); } + [[nodiscard]] + float readFloat() { return readValue(); } + [[nodiscard]] + double readDouble() { return readValue(); } + [[nodiscard]] + unsigned char readuChar() { return readValue(); } + + /** Reads a (preallocated!) C array of values from the stream. + + Converts all values in the array to platform byte order. All data types + supported by the ByteOrderConverter class can be used. + + @param nElemCount + Number of array elements to read (NOT byte count). + + @return + Number of array elements really read (NOT byte count). + */ + template< typename Type > + sal_Int32 readArray( Type* opnArray, sal_Int32 nElemCount ); + + /** Reads a vector of values from the stream. + + The vector will be resized internally. Converts all values in the + vector to platform byte order. All data types supported by the + ByteOrderConverter class can be used. + + @param nElemCount + Number of elements to put into the vector (NOT byte count). + + @return + Number of vector elements really read (NOT byte count). + */ + template< typename Type > + sal_Int32 readArray( ::std::vector< Type >& orVector, sal_Int32 nElemCount ); + + /** Reads a NUL-terminated Unicode character array and returns the string. + */ + OUString readNulUnicodeArray(); + + /** Reads a byte character array and returns the string. + NUL characters are replaced by question marks. + + @param nChars + Number of characters (bytes) to read from the stream. + */ + OString readCharArray( sal_Int32 nChars ); + + /** Reads a byte character array and returns a Unicode string. + NUL characters are replaced by question marks. + + @param nChars + Number of characters (bytes) to read from the stream. + + @param eTextEnc + The text encoding used to create the Unicode string. + */ + OUString readCharArrayUC( sal_Int32 nChars, rtl_TextEncoding eTextEnc ); + + /** Reads a Unicode character array and returns the string. + NUL characters are replaced by question marks (default). + + @param nChars + Number of 16-bit characters to read from the stream. + */ + OUString readUnicodeArray( sal_Int32 nChars ); + + /** Reads a Unicode character array (may be compressed) and returns the + string. + NUL characters are replaced by question marks (default). + + @param nChars + Number of 8-bit or 16-bit characters to read from the stream. + + @param bCompressed + True = Character array is compressed (stored as 8-bit characters). + False = Character array is not compressed (stored as 16-bit characters). + */ + OUString readCompressedUnicodeArray( sal_Int32 nChars, bool bCompressed ); + + /** Copies bytes from the current position to the passed output stream. + */ + void copyToStream( BinaryOutputStream& rOutStrm ); + +protected: + /** This dummy default c'tor will never call the c'tor of the virtual base + class BinaryStreamBase as this class cannot be instantiated directly. */ + BinaryInputStream() : BinaryStreamBase( false ) {} + +private: + BinaryInputStream( BinaryInputStream const& ) = delete; + BinaryInputStream& operator=( BinaryInputStream const& ) = delete; +}; + +typedef std::shared_ptr< BinaryInputStream > BinaryInputStreamRef; + + +template< typename Type > +Type BinaryInputStream::readValue() +{ + Type ornValue = Type(); + readMemory( &ornValue, static_cast< sal_Int32 >( sizeof( Type ) ), sizeof( Type ) ); + ByteOrderConverter::convertLittleEndian( ornValue ); + return ornValue; +} + +template< typename Type > +sal_Int32 BinaryInputStream::readArray( Type* opnArray, sal_Int32 nElemCount ) +{ + sal_Int32 nRet = 0; + if( !mbEof ) + { + sal_Int32 nReadSize = getLimitedValue< sal_Int32, sal_Int32 >( nElemCount, 0, SAL_MAX_INT32 / sizeof( Type ) ) * sizeof( Type ); + nRet = readMemory( opnArray, nReadSize, sizeof( Type ) ) / sizeof( Type ); + ByteOrderConverter::convertLittleEndianArray( opnArray, static_cast< size_t >( nRet ) ); + } + return nRet; +} + +template< typename Type > +sal_Int32 BinaryInputStream::readArray( ::std::vector< Type >& orVector, sal_Int32 nElemCount ) +{ + orVector.resize( static_cast< size_t >( nElemCount ) ); + return orVector.empty() ? 0 : readArray(orVector.data(), nElemCount); +} + + +/** Wraps a UNO input stream and provides convenient access functions. + + The binary data in the stream is assumed to be in little-endian format. + */ +class OOX_DLLPUBLIC BinaryXInputStream final : public BinaryXSeekableStream, public BinaryInputStream +{ +public: + /** Constructs the wrapper object for the passed input stream. + + @param rxInStream + The com.sun.star.io.XInputStream interface of the UNO input stream + to be wrapped. + + @param bAutoClose + True = automatically close the wrapped input stream on destruction + of this wrapper or when close() is called. + */ + explicit BinaryXInputStream( + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + bool bAutoClose ); + + virtual ~BinaryXInputStream() override; + + /** Closes the input stream. Does also close the wrapped UNO input stream + if bAutoClose has been set to true in the constructor. */ + virtual void close() override; + + /** Reads nBytes bytes to the passed sequence. + @return Number of bytes really read. */ + virtual sal_Int32 readData( StreamDataSequence& orData, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Reads nBytes bytes to the (existing) buffer opMem. + @return Number of bytes really read. */ + virtual sal_Int32 readMemory( void* opMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Seeks the stream forward by the passed number of bytes. This works for + non-seekable streams too. */ + virtual void skip( sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + +private: + StreamDataSequence maBuffer; ///< Data buffer used in readMemory() function. + css::uno::Reference< css::io::XInputStream > + mxInStrm; ///< Reference to the input stream. + bool mbAutoClose; ///< True = automatically close stream on destruction. +}; + + +/** Wraps a StreamDataSequence and provides convenient access functions. + + The binary data in the stream is assumed to be in little-endian format. + */ +class OOX_DLLPUBLIC SequenceInputStream final : public SequenceSeekableStream, public BinaryInputStream +{ +public: + /** Constructs the wrapper object for the passed data sequence. + + @attention + The passed data sequence MUST live at least as long as this stream + wrapper. The data sequence MUST NOT be changed from outside as long + as this stream wrapper is used to read from it. + */ + explicit SequenceInputStream( const StreamDataSequence& rData ); + + /** Reads nBytes bytes to the passed sequence. + @return Number of bytes really read. */ + virtual sal_Int32 readData( StreamDataSequence& orData, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Reads nBytes bytes to the (existing) buffer opMem. + @return Number of bytes really read. */ + virtual sal_Int32 readMemory( void* opMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Seeks the stream forward by the passed number of bytes. This works for + non-seekable streams too. */ + virtual void skip( sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + +private: + /** Returns the number of bytes available in the sequence for the passed byte count. */ + sal_Int32 getMaxBytes( sal_Int32 nBytes ) const + { return getLimitedValue< sal_Int32, sal_Int32 >( nBytes, 0, mpData->getLength() - mnPos ); } +}; + + +/** Wraps a BinaryInputStream and provides access to a specific part of the + stream data. + + Provides access to the stream data block starting at the current position + of the stream, and with a specific length. If the wrapped stream is + seekable, this wrapper will treat the position of the wrapped stream at + construction time as position "0" (therefore the class name). + + The passed input stream MUST live at least as long as this stream wrapper. + The stream MUST NOT be changed from outside as long as this stream wrapper + is used to read from it. + */ +class RelativeInputStream final : public BinaryInputStream +{ +public: + /** Constructs the wrapper object for the passed stream. + + @param nSize + If specified, restricts the amount of data that can be read from + the passed input stream. + */ + explicit RelativeInputStream( + BinaryInputStream& rInStrm, + sal_Int64 nSize ); + + /** Returns the size of the data block in the wrapped stream offered by + this wrapper. */ + virtual sal_Int64 size() const override; + + /** Returns the current relative stream position. */ + virtual sal_Int64 tell() const override; + + /** Seeks the stream to the passed relative position, if the wrapped stream + is seekable. */ + virtual void seek( sal_Int64 nPos ) override; + + /** Closes the input stream but not the wrapped stream. */ + virtual void close() override; + + /** Reads nBytes bytes to the passed sequence. Does not read out of the + data block whose size has been specified on construction. + @return Number of bytes really read. */ + virtual sal_Int32 readData( StreamDataSequence& orData, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Reads nBytes bytes to the (existing) buffer opMem. Does not read out of + the data block whose size has been specified on construction. + @return Number of bytes really read. */ + virtual sal_Int32 readMemory( void* opMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Seeks the stream forward by the passed number of bytes. This works for + non-seekable streams too. Does not seek out of the data block. */ + virtual void skip( sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + +private: + /** Returns the number of bytes available in the sequence for the passed byte count. */ + sal_Int32 getMaxBytes( sal_Int32 nBytes ) const + { return getLimitedValue< sal_Int32, sal_Int64 >( nBytes, 0, mnSize - mnRelPos ); } + +private: + BinaryInputStream* mpInStrm; + sal_Int64 mnStartPos; + sal_Int64 mnRelPos; + sal_Int64 mnSize; +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/binaryoutputstream.hxx b/include/oox/helper/binaryoutputstream.hxx new file mode 100644 index 000000000..c1dc8ebb0 --- /dev/null +++ b/include/oox/helper/binaryoutputstream.hxx @@ -0,0 +1,208 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_BINARYOUTPUTSTREAM_HXX +#define INCLUDED_OOX_HELPER_BINARYOUTPUTSTREAM_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XOutputStream; } +} + +namespace oox { + + +/** Interface for binary output stream classes. + + The binary data in the stream is written in little-endian format. + */ +class BinaryOutputStream : public virtual BinaryStreamBase +{ +public: + /** Derived classes implement writing the contents of the passed data + sequence. + + @param nAtomSize + The size of the elements in the memory block, if available. Derived + classes may be interested in this information. + */ + virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) = 0; + + /** Derived classes implement writing the contents of the (preallocated!) + memory buffer pMem. + + @param nAtomSize + The size of the elements in the memory block, if available. Derived + classes may be interested in this information. + */ + virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) = 0; + + template< typename Type > + void writeArray( Type* opnArray, sal_Int32 nElemCount ); + + template< typename Type > + void writeArray( const Type* opnArray, sal_Int32 nElemCount ); + + /** Writes a value to the stream and converts it to platform byte order. + All data types supported by the ByteOrderConverter class can be used. + */ + template< typename Type > + void writeValue( Type nValue ); + + BinaryOutputStream& WriteInt16(sal_Int16 x) { writeValue(x); return *this; } + BinaryOutputStream& WriteUInt16(sal_uInt16 x) { writeValue(x); return *this; } + BinaryOutputStream& WriteInt32(sal_Int32 x) { writeValue(x); return *this; } + BinaryOutputStream& WriteUInt32(sal_uInt32 x) { writeValue(x); return *this; } + BinaryOutputStream& WriteInt64(sal_Int64 x) { writeValue(x); return *this; } + + void writeCompressedUnicodeArray( const OUString& rString, bool bCompressed ); + + void writeCharArrayUC( std::u16string_view rString, rtl_TextEncoding eTextEnc ); + + void writeUnicodeArray( const OUString& rString ); + +protected: + /** This dummy default c'tor will never call the c'tor of the virtual base + class BinaryStreamBase as this class cannot be instantiated directly. */ + BinaryOutputStream() : BinaryStreamBase( false ) {} + +private: + BinaryOutputStream( BinaryOutputStream const& ) = delete; + BinaryOutputStream& operator=( BinaryOutputStream const& ) = delete; +}; + +template< typename Type > +void BinaryOutputStream::writeArray( Type* opnArray, sal_Int32 nElemCount ) +{ + sal_Int32 nWriteSize = getLimitedValue< sal_Int32, sal_Int32 >( nElemCount, 0, SAL_MAX_INT32 / sizeof( Type ) ) * sizeof( Type ); + ByteOrderConverter::convertLittleEndianArray( opnArray, static_cast< size_t >( nElemCount ) ); + writeMemory( opnArray, nWriteSize, sizeof( Type ) ); +} + +template< typename Type > +void BinaryOutputStream::writeArray( const Type* opnArray, sal_Int32 nElemCount ) +{ + std::unique_ptr xArray(new Type[nElemCount]); + std::uninitialized_copy(opnArray, opnArray + nElemCount, xArray.get()); + writeArray(xArray.get(), nElemCount); +} + +template< typename Type > +void BinaryOutputStream::writeValue( Type nValue ) +{ + ByteOrderConverter::convertLittleEndian( nValue ); + writeMemory( &nValue, static_cast< sal_Int32 >( sizeof( Type ) ), sizeof( Type ) ); +} + + +/** Wraps a UNO output stream and provides convenient access functions. + + The binary data in the stream is written in little-endian format. + */ +class OOX_DLLPUBLIC BinaryXOutputStream final : public BinaryXSeekableStream, public BinaryOutputStream +{ +public: + /** Constructs the wrapper object for the passed output stream. + + @param rxOutStream + The com.sun.star.io.XOutputStream interface of the output stream to + be wrapped. + + @param bAutoClose + True = automatically close the wrapped output stream on destruction + of this wrapper or when close() is called. + */ + explicit BinaryXOutputStream( + const css::uno::Reference< css::io::XOutputStream >& rxOutStrm, + bool bAutoClose ); + + virtual ~BinaryXOutputStream() override; + + /** Flushes and closes the output stream. Does also close the wrapped UNO + output stream if bAutoClose has been set to true in the constructor. */ + void close() override; + + /** Writes the passed data sequence. */ + virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) override; + + /** Write nBytes bytes from the (preallocated!) buffer pMem. */ + virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + +private: + StreamDataSequence maBuffer; ///< Data buffer used in writeMemory() function. + css::uno::Reference< css::io::XOutputStream > + mxOutStrm; ///< Reference to the output stream. + bool mbAutoClose; ///< True = automatically close stream on destruction. +}; + + +/** Wraps a StreamDataSequence and provides convenient access functions. + + The binary data in the stream is written in little-endian format. After + construction, the stream points to the beginning of the passed data + sequence. The data sequence is expanded automatically while writing to it. + */ +class SequenceOutputStream final : public BinaryOutputStream +{ +public: + /** Constructs the wrapper object for the passed data sequence. + + @attention + The passed data sequence MUST live at least as long as this stream + wrapper. The data sequence MUST NOT be changed from outside as long + as this stream wrapper is used to write to it. + */ + explicit SequenceOutputStream( StreamDataSequence & rData ); + + /** Writes the passed data sequence. */ + virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) override; + + /** Write nBytes bytes from the (preallocated!) buffer pMem. */ + virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Returns the size of the wrapped data sequence. */ + virtual sal_Int64 size() const override; + /** Returns the current stream position. */ + virtual sal_Int64 tell() const override; + /** Seeks the stream to the passed position. */ + virtual void seek( sal_Int64 nPos ) override; + /** Releases the reference to the data sequence. */ + virtual void close() override; + +private: + StreamDataSequence* mpData; ///< Wrapped data sequence. + sal_Int32 mnPos; ///< Current position in the sequence. +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/binarystreambase.hxx b/include/oox/helper/binarystreambase.hxx new file mode 100644 index 000000000..8e93d1458 --- /dev/null +++ b/include/oox/helper/binarystreambase.hxx @@ -0,0 +1,179 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_BINARYSTREAMBASE_HXX +#define INCLUDED_OOX_HELPER_BINARYSTREAMBASE_HXX + +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XSeekable; } +} + +namespace oox { + +typedef css::uno::Sequence< sal_Int8 > StreamDataSequence; + + +/** Base class for binary stream classes. + */ +class OOX_DLLPUBLIC BinaryStreamBase +{ +public: + virtual ~BinaryStreamBase(); + + /** Implementations return the size of the stream, if possible. + + This function may be implemented for some types of unseekable streams, + and MUST be implemented for all seekable streams. + + @return + The size of the stream in bytes, or -1, if not implemented. + */ + virtual sal_Int64 size() const = 0; + + /** Implementations return the current stream position, if possible. + + This function may be implemented for some types of unseekable streams, + and MUST be implemented for all seekable streams. + + @return + The current position in the stream, or -1, if not implemented. + */ + virtual sal_Int64 tell() const = 0; + + /** Implementations seek the stream to the passed position, if + the stream is seekable. + */ + virtual void seek( sal_Int64 nPos ) = 0; + + /** Implementations close the stream. + */ + virtual void close() = 0; + + /** Returns true, if the implementation supports the seek() operation. + + Implementations may still implement size() and tell() even if the + stream is not seekable. + */ + bool isSeekable() const { return mbSeekable; } + + /** Returns true, if the stream position is invalid (EOF). This flag turns + true *after* the first attempt to seek/read beyond the stream end. + */ + bool isEof() const { return mbEof; } + + /** Returns the size of the remaining data available in the stream, if + stream supports size() and tell(), otherwise -1. + */ + sal_Int64 getRemaining() const; + + /** Seeks the stream to the beginning, if stream is seekable. + */ + void seekToStart() { seek( 0 ); } + + /** Seeks the stream forward to a position that is a multiple of the passed + block size, if stream is seekable. + + @param nBlockSize + The size of the data blocks the streams needs to be aligned to. + + @param nAnchorPos + Position in the stream the data blocks are aligned to. + */ + void alignToBlock( sal_Int32 nBlockSize, sal_Int64 nAnchorPos ); + +protected: + explicit BinaryStreamBase( bool bSeekable ) : mbEof( false ), mbSeekable( bSeekable ) {} + +private: + BinaryStreamBase( const BinaryStreamBase& ) = delete; + BinaryStreamBase& operator=( const BinaryStreamBase& ) = delete; + +protected: + bool mbEof; ///< End of stream flag. + +private: + const bool mbSeekable; ///< True = implementation supports seeking. +}; + + +/** Base class for binary input and output streams wrapping a UNO stream, + seekable via the com.sun.star.io.XSeekable interface. + */ +class BinaryXSeekableStream : public virtual BinaryStreamBase +{ +public: + virtual ~BinaryXSeekableStream() override; + + /** Returns the size of the stream, if wrapped stream is seekable, otherwise -1. */ + virtual sal_Int64 size() const override; + /** Returns the current stream position, if wrapped stream is seekable, otherwise -1. */ + virtual sal_Int64 tell() const override; + /** Seeks the stream to the passed position, if wrapped stream is seekable. */ + virtual void seek( sal_Int64 nPos ) override; + /** Releases the reference to the UNO XSeekable interface. */ + virtual void close() override; + +protected: + explicit BinaryXSeekableStream( + const css::uno::Reference< css::io::XSeekable >& rxSeekable ); + +private: + css::uno::Reference< css::io::XSeekable > + mxSeekable; ///< Stream seeking interface. +}; + + +/** Base class for binary input and output streams wrapping a + StreamDataSequence, which is always seekable. + + The wrapped data sequence MUST live at least as long as this stream + wrapper. The data sequence MUST NOT be changed from outside as long as this + stream wrapper is used to modify it. + */ +class OOX_DLLPUBLIC SequenceSeekableStream : public virtual BinaryStreamBase +{ +public: + /** Returns the size of the wrapped data sequence. */ + virtual sal_Int64 size() const override; + /** Returns the current stream position. */ + virtual sal_Int64 tell() const override; + /** Seeks the stream to the passed position. */ + virtual void seek( sal_Int64 nPos ) override; + /** Releases the reference to the data sequence. */ + virtual void close() override; + +protected: + explicit SequenceSeekableStream( const StreamDataSequence& rData ); + +protected: + const StreamDataSequence* mpData; ///< Wrapped data sequence. + sal_Int32 mnPos; ///< Current position in the sequence. +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/containerhelper.hxx b/include/oox/helper/containerhelper.hxx new file mode 100644 index 000000000..3b725d509 --- /dev/null +++ b/include/oox/helper/containerhelper.hxx @@ -0,0 +1,298 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_CONTAINERHELPER_HXX +#define INCLUDED_OOX_HELPER_CONTAINERHELPER_HXX + +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace container { class XNameAccess; } + namespace container { class XNameContainer; } + namespace uno { class Any; } +} + +namespace oox { + + +/** A range of signed 32-bit integer values. */ +struct ValueRange +{ + sal_Int32 mnFirst; + sal_Int32 mnLast; + + explicit ValueRange( sal_Int32 nValue ) : mnFirst( nValue ), mnLast( nValue ) {} + explicit ValueRange( sal_Int32 nFirst, sal_Int32 nLast ) : mnFirst( nFirst ), mnLast( nLast ) {} + + bool operator==( const ValueRange& rRange ) const { return (mnFirst == rRange.mnFirst) && (mnLast == rRange.mnLast); } + bool operator!=( const ValueRange& rRange ) const { return !(*this == rRange); } + bool contains( const ValueRange& rRange ) const { return (mnFirst <= rRange.mnFirst) && (rRange.mnLast <= mnLast); } + bool intersects( const ValueRange& rRange ) const { return (mnFirst <= rRange.mnLast) && (rRange.mnFirst <= mnLast); } +}; + + +typedef ::std::vector< ValueRange > ValueRangeVector; + + +/** An ordered list of value ranges. The insertion operation will merge + consecutive value ranges. + */ +class OOX_DLLPUBLIC ValueRangeSet +{ +public: + ValueRangeSet() {} + + /** Inserts the passed value range into the range list. */ + void insert( const ValueRange& rRange ); + + /** Returns the ordered list of all value ranges. */ + const ValueRangeVector& getRanges() const { return maRanges; } + +private: + ValueRangeVector maRanges; +}; + + +/** Template for a 2-dimensional array of objects. + + This class template provides a similar interface to the ::std::vector + template. + */ +template< typename Type > +class Matrix +{ +public: + typedef ::std::vector< Type > container_type; + typedef typename container_type::value_type value_type; + typedef typename container_type::pointer pointer; + typedef typename container_type::reference reference; + typedef typename container_type::const_reference const_reference; + typedef typename container_type::size_type size_type; + typedef typename container_type::iterator iterator; + typedef typename container_type::const_iterator const_iterator; + + Matrix() : mnWidth( 0 ) {} + explicit Matrix( size_type nWidth, size_type nHeight ) { resize( nWidth, nHeight ); } + explicit Matrix( size_type nWidth, size_type nHeight, const_reference rData ) { resize( nWidth, nHeight, rData ); } + + bool empty() const { return maData.empty(); } + size_type size() const { return maData.size(); } + size_type width() const { return mnWidth; } + size_type height() const { return empty() ? 0 : (size() / width()); } + + void clear() { resize( 0, 0 ); } + void resize( size_type nWidth, size_type nHeight ) { mnWidth = nWidth; maData.resize( nWidth * nHeight ); } + void resize( size_type nWidth, size_type nHeight, const_reference rData ) { mnWidth = nWidth; maData.resize( nWidth * nHeight, rData ); } + + iterator at( size_type nX, size_type nY ) { return maData.begin() + mnWidth * nY + nX; } + const_iterator at( size_type nX, size_type nY ) const { return maData.begin() + mnWidth * nY + nX; } + + reference operator()( size_type nX, size_type nY ) { return *at( nX, nY ); } + const_reference operator()( size_type nX, size_type nY ) const { return *at( nX, nY ); } + + iterator begin() { return maData.begin(); } + const_iterator begin() const { return maData.begin(); } + iterator end() { return maData.end(); } + const_iterator end() const { return maData.end(); } + + iterator row_begin( size_type nY ) { return at( 0, nY ); } + const_iterator row_begin( size_type nY ) const { return at( 0, nY ); } + iterator row_end( size_type nY ) { return at( mnWidth, nY ); } + const_iterator row_end( size_type nY ) const { return at( mnWidth, nY ); } + + reference row_front( size_type nY ) { return (*this)( 0, nY ); } + const_reference row_front( size_type nY ) const { return (*this)( 0, nY ); } + +private: + container_type maData; + size_type mnWidth; +}; + + +/** Static helper functions for improved API container handling. */ +class OOX_DLLPUBLIC ContainerHelper +{ +public: + + /** Returns a name that is not used in the passed name container. + + @param rxNameAccess com.sun.star.container.XNameAccess interface of + the name container. + + @param rSuggestedName Suggested name for the object. + + @return An unused name. Will be equal to the suggested name, if not + contained, otherwise a numerical index will be appended. + */ + static OUString getUnusedName( + const css::uno::Reference< css::container::XNameAccess >& rxNameAccess, + const OUString& rSuggestedName, + sal_Unicode cSeparator ); + + /** Inserts an object into a name container. + + @param rxNameContainer com.sun.star.container.XNameContainer interface + of the name container. + + @param rName Exact name for the object. + + @param rObject The object to be inserted. + + @return True = object successfully inserted. + */ + static bool insertByName( + const css::uno::Reference< css::container::XNameContainer >& rxNameContainer, + const OUString& rName, + const css::uno::Any& rObject ); + + /** Inserts an object into a name container. + + The function will use an unused name to insert the object, based on the + suggested object name. It is possible to specify whether the existing + object or the new inserted object will be renamed, if the container + already has an object with the name suggested for the new object. + + @param rxNameContainer com.sun.star.container.XNameContainer interface + of the name container. + + @param rSuggestedName Suggested name for the object. + + @param rObject The object to be inserted. + + The new object + will be inserted with a name not yet extant in the container (this + is done by appending a numerical index to the suggested name). + + @return The final name the object is inserted with. Will always be + equal to the suggested name, if parameter bRenameOldExisting is + true. + */ + static OUString insertByUnusedName( + const css::uno::Reference< css::container::XNameContainer >& rxNameContainer, + const OUString& rSuggestedName, + sal_Unicode cSeparator, + const css::uno::Any& rObject ); + + // std::vector and std::map element access -------------------------------- + + /** Returns the pointer to an existing element of the passed vector, or a + null pointer, if the passed index is out of bounds. */ + template< typename VectorType > + static const typename VectorType::value_type* + getVectorElement( const VectorType& rVector, sal_Int32 nIndex ); + + /** Returns the pointer to an existing element of the passed vector, or a + null pointer, if the passed index is out of bounds. */ + template< typename VectorType > + static typename VectorType::value_type* + getVectorElementAccess( VectorType& rVector, sal_Int32 nIndex ); + + /** Returns the reference to an existing element of the passed vector, or + the passed default value, if the passed index is out of bounds. */ + template< typename VectorType > + static const typename VectorType::value_type& + getVectorElement( const VectorType& rVector, sal_Int32 nIndex, const typename VectorType::value_type& rDefault ); + + /** Returns the pointer to an existing element of the passed map, or a null + pointer, if an element with the passed key does not exist. */ + template< typename MapType > + static const typename MapType::mapped_type* + getMapElement( const MapType& rMap, const typename MapType::key_type& rKey ); + + /** Returns the reference to an existing element of the passed map, or the + passed default value, if an element with the passed key does not exist. */ + template< typename MapType > + static const typename MapType::mapped_type& + getMapElement( const MapType& rMap, const typename MapType::key_type& rKey, const typename MapType::mapped_type& rDefault ); + + /** Creates a UNO sequence of sequences from a matrix with copies of all elements. + + @param rMatrix The matrix to be converted to a sequence of sequences. + + @return A com.sun.star.uno.Sequence object containing + com.sun.star.uno.Sequence objects with copies of all objects + contained in the passed matrix. + */ + template< typename MatrixType > + static css::uno::Sequence< css::uno::Sequence< typename MatrixType::value_type > > + matrixToSequenceSequence( const MatrixType& rMatrix ); +}; + + +template< typename VectorType > +/*static*/ const typename VectorType::value_type* ContainerHelper::getVectorElement( const VectorType& rVector, sal_Int32 nIndex ) +{ + return ((0 <= nIndex) && (static_cast< size_t >( nIndex ) < rVector.size())) ? &rVector[ static_cast< size_t >( nIndex ) ] : nullptr; +} + +template< typename VectorType > +/*static*/ typename VectorType::value_type* ContainerHelper::getVectorElementAccess( VectorType& rVector, sal_Int32 nIndex ) +{ + return ((0 <= nIndex) && (static_cast< size_t >( nIndex ) < rVector.size())) ? &rVector[ static_cast< size_t >( nIndex ) ] : nullptr; +} + +template< typename VectorType > +/*static*/ const typename VectorType::value_type& ContainerHelper::getVectorElement( const VectorType& rVector, sal_Int32 nIndex, const typename VectorType::value_type& rDefault ) +{ + return ((0 <= nIndex) && (static_cast< size_t >( nIndex ) < rVector.size())) ? rVector[ static_cast< size_t >( nIndex ) ] : rDefault; +} + +template< typename MapType > +/*static*/ const typename MapType::mapped_type* ContainerHelper::getMapElement( const MapType& rMap, const typename MapType::key_type& rKey ) +{ + typename MapType::const_iterator aIt = rMap.find( rKey ); + return (aIt == rMap.end()) ? nullptr : &aIt->second; +} + +template< typename MapType > +/*static*/ const typename MapType::mapped_type& ContainerHelper::getMapElement( const MapType& rMap, const typename MapType::key_type& rKey, const typename MapType::mapped_type& rDefault ) +{ + typename MapType::const_iterator aIt = rMap.find( rKey ); + return (aIt == rMap.end()) ? rDefault : aIt->second; +} + +template< typename MatrixType > +/*static*/ css::uno::Sequence< css::uno::Sequence< typename MatrixType::value_type > > ContainerHelper::matrixToSequenceSequence( const MatrixType& rMatrix ) +{ + typedef typename MatrixType::value_type ValueType; + css::uno::Sequence< css::uno::Sequence< ValueType > > aSeq; + if( !rMatrix.empty() ) + { + aSeq.realloc( static_cast< sal_Int32 >( rMatrix.height() ) ); + auto pSeq = aSeq.getArray(); + for( size_t nRow = 0, nHeight = rMatrix.height(); nRow < nHeight; ++nRow ) + pSeq[ static_cast< sal_Int32 >( nRow ) ] = + css::uno::Sequence< ValueType >( &rMatrix.row_front( nRow ), static_cast< sal_Int32 >( rMatrix.width() ) ); + } + return aSeq; +} + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/grabbagstack.hxx b/include/oox/helper/grabbagstack.hxx new file mode 100644 index 000000000..bd03535c9 --- /dev/null +++ b/include/oox/helper/grabbagstack.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_OOX_HELPER_GRABBAGSTACK_HXX +#define INCLUDED_OOX_HELPER_GRABBAGSTACK_HXX + +#include +#include + +#include +#include +#include +#include + +namespace com::sun::star { + namespace uno { class Any; } +} + +namespace oox { + +struct GrabBagStackElement +{ + OUString maElementName; + std::vector maPropertyList; +}; + +/// Tool that is useful for construction of a nested Sequence/PropertyValue hierarchy +class OOX_DLLPUBLIC GrabBagStack final +{ +private: + std::stack mStack; + GrabBagStackElement mCurrentElement; + +public: + GrabBagStack(const OUString& aElementName); + ~GrabBagStack(); + + const OUString& getCurrentName() const { return mCurrentElement.maElementName;} + + css::beans::PropertyValue getRootProperty(); + + void appendElement(const OUString& aName, const css::uno::Any& aAny); + void push(const OUString& aKey); + void pop(); + void addInt32(const OUString& aElementName, sal_Int32 aIntValue); + void addString(const OUString& aElementName, const OUString& aStringValue); + bool isStackEmpty() const; +}; + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/graphichelper.hxx b/include/oox/helper/graphichelper.hxx new file mode 100644 index 000000000..eab39beff --- /dev/null +++ b/include/oox/helper/graphichelper.hxx @@ -0,0 +1,161 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_GRAPHICHELPER_HXX +#define INCLUDED_OOX_HELPER_GRAPHICHELPER_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct WmfExternal; +class OutputDevice; + +namespace com::sun::star { + namespace awt { struct Point; } + namespace awt { struct Size; } + namespace awt { class XUnitConversion; } + namespace io { class XInputStream; } + namespace frame { class XFrame; } + namespace graphic { class XGraphic; } + namespace graphic { class XGraphicObject; } + namespace graphic { class XGraphicProvider; } + namespace uno { class XComponentContext; } +} + +namespace oox { + + +/** Provides helper functions for colors, device measurement conversion, + graphics, and graphic objects handling. + */ +class OOX_DLLPUBLIC GraphicHelper +{ +public: + explicit GraphicHelper( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XFrame >& rxTargetFrame, + const StorageRef& rxStorage ); + virtual ~GraphicHelper(); + + // Avoid implicitly defined copy constructors/assignments for the DLLPUBLIC class (they may + // require forward-declared classes used internally to be defined in places using GraphicHelper) + GraphicHelper(const GraphicHelper&) = delete; + GraphicHelper(GraphicHelper&&) = delete; + GraphicHelper& operator=(const GraphicHelper&) = delete; + GraphicHelper& operator=(GraphicHelper&&) = delete; + + // System colors and predefined colors ------------------------------------ + + /** Returns a system color specified by the passed XML token identifier. */ + ::Color getSystemColor( sal_Int32 nToken, ::Color nDefaultRgb = API_RGB_TRANSPARENT ) const; + /** Derived classes may implement to resolve a scheme color from the passed XML token identifier. */ + virtual ::Color getSchemeColor( sal_Int32 nToken ) const; + /** Derived classes may implement to resolve a palette index to an RGB color. */ + virtual ::Color getPaletteColor( sal_Int32 nPaletteIdx ) const; + + virtual sal_Int32 getDefaultChartAreaFillStyle() const; + + /** Returns chartspace automatic default border style */ + static sal_Int32 getDefaultChartAreaLineStyle(); + + /** Returns chartspace automatic default border width in Emu */ + static sal_Int16 getDefaultChartAreaLineWidth(); + + // Device info and device dependent unit conversion ----------------------- + + /** Returns information about the output device. */ + const css::awt::DeviceInfo& getDeviceInfo() const { return maDeviceInfo;} + + /** Converts the passed value from horizontal screen pixels to 1/100 mm. */ + sal_Int32 convertScreenPixelXToHmm( double fPixelX ) const; + /** Converts the passed value from vertical screen pixels to 1/100 mm. */ + sal_Int32 convertScreenPixelYToHmm( double fPixelY ) const; + /** Converts the passed size from screen pixels to 1/100 mm. */ + css::awt::Size convertScreenPixelToHmm( const css::awt::Size& rPixel ) const; + + /** Converts the passed value from 1/100 mm to horizontal screen pixels. */ + double convertHmmToScreenPixelX( sal_Int32 nHmmX ) const; + /** Converts the passed value from 1/100 mm to vertical screen pixels. */ + double convertHmmToScreenPixelY( sal_Int32 nHmmY ) const; + /** Converts the passed point from 1/100 mm to screen pixels. */ + css::awt::Point convertHmmToScreenPixel( const css::awt::Point& rHmm ) const; + /** Converts the passed size from 1/100 mm to screen pixels. */ + css::awt::Size convertHmmToScreenPixel( const css::awt::Size& rHmm ) const; + + /** Converts the passed point from 1/100 mm to AppFont units. */ + css::awt::Point convertHmmToAppFont( const css::awt::Point& rHmm ) const; + /** Converts the passed size from 1/100 mm to AppFont units. */ + css::awt::Size convertHmmToAppFont( const css::awt::Size& rHmm ) const; + + + // Graphics and graphic objects ------------------------------------------ + + /** Imports a graphic from the passed input stream. */ + css::uno::Reference< css::graphic::XGraphic > + importGraphic( + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + const WmfExternal* pExtHeader = nullptr ) const; + + /** Imports a graphic from the passed binary memory block. */ + css::uno::Reference< css::graphic::XGraphic > + importGraphic( const StreamDataSequence& rGraphicData ) const; + + /** Imports a graphic from the storage stream with the passed path and name. */ + css::uno::Reference< css::graphic::XGraphic > + importEmbeddedGraphic( + const OUString& rStreamName, + const WmfExternal* pExtHeader = nullptr ) const; + + /** calculates the original size of a graphic which is necessary to be able to calculate cropping values + @return The original Graphic size in 100thmm */ + css::awt::Size getOriginalSize( const css::uno::Reference< css::graphic::XGraphic >& rxGraphic ) const; + + void setGraphicMapper(css::uno::Reference const & rxGraphicMapper); + + void initializeGraphicMapperIfNeeded() const; +private: + + css::uno::Reference< css::uno::XComponentContext > mxContext; + css::uno::Reference< css::graphic::XGraphicProvider2 > mxGraphicProvider; + VclPtr mxDefaultOutputDevice; + css::awt::DeviceInfo maDeviceInfo; ///< Current output device info. + ::std::map< sal_Int32, ::Color > maSystemPalette; ///< Maps system colors (XML tokens) to RGB color values. + StorageRef mxStorage; ///< Storage containing embedded graphics. + double mfPixelPerHmmX; ///< Number of screen pixels per 1/100 mm in X direction. + double mfPixelPerHmmY; ///< Number of screen pixels per 1/100 mm in Y direction. + css::uno::Reference mxGraphicMapper; +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/helper.hxx b/include/oox/helper/helper.hxx new file mode 100644 index 000000000..63718ca0e --- /dev/null +++ b/include/oox/helper/helper.hxx @@ -0,0 +1,301 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_HELPER_HXX +#define INCLUDED_OOX_HELPER_HELPER_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace oox { + +// Helper macros ============================================================== + +namespace detail { + +//TODO: Temporary helper for STATIC_ARRAY_SELECT; ultimately, the latter should be replaced by a +// proper function (template): +template constexpr std::make_unsigned_t make_unsigned(T value) { + if constexpr (std::is_signed_v) { + return o3tl::make_unsigned(value); + } else { + return value; + } +} + +} + +/** Expands to the 'index'-th element of a STATIC data array, or to 'def', if + 'index' is out of the array limits. */ +#define STATIC_ARRAY_SELECT( array, index, def ) \ + ((detail::make_unsigned(index) < SAL_N_ELEMENTS(array)) ? ((array)[static_cast(index)]) : (def)) + +// Common constants =========================================================== + +const sal_uInt8 WINDOWS_CHARSET_ANSI = 0; +const sal_uInt8 WINDOWS_CHARSET_DEFAULT = 1; +const sal_uInt8 WINDOWS_CHARSET_SYMBOL = 2; +const sal_uInt8 WINDOWS_CHARSET_APPLE_ROMAN = 77; +const sal_uInt8 WINDOWS_CHARSET_SHIFTJIS = 128; +const sal_uInt8 WINDOWS_CHARSET_HANGEUL = 129; +const sal_uInt8 WINDOWS_CHARSET_JOHAB = 130; +const sal_uInt8 WINDOWS_CHARSET_GB2312 = 134; +const sal_uInt8 WINDOWS_CHARSET_BIG5 = 136; +const sal_uInt8 WINDOWS_CHARSET_GREEK = 161; +const sal_uInt8 WINDOWS_CHARSET_TURKISH = 162; +const sal_uInt8 WINDOWS_CHARSET_VIETNAMESE = 163; +const sal_uInt8 WINDOWS_CHARSET_HEBREW = 177; +const sal_uInt8 WINDOWS_CHARSET_ARABIC = 178; +const sal_uInt8 WINDOWS_CHARSET_BALTIC = 186; +const sal_uInt8 WINDOWS_CHARSET_RUSSIAN = 204; +const sal_uInt8 WINDOWS_CHARSET_THAI = 222; +const sal_uInt8 WINDOWS_CHARSET_EASTERN = 238; +const sal_uInt8 WINDOWS_CHARSET_OEM = 255; + + +const ::Color API_RGB_TRANSPARENT (ColorTransparency, 0xffffffff); ///< Transparent color for API calls. +const sal_uInt32 UNSIGNED_RGB_TRANSPARENT = static_cast(-1); ///< Transparent color for unsigned int32 places. +const ::Color API_RGB_BLACK (0x000000); ///< Black color for API calls. +const ::Color API_RGB_GRAY (0x808080); ///< Gray color for API calls. +const ::Color API_RGB_WHITE (0xFFFFFF); ///< White color for API calls. + +const sal_Int16 API_LINE_SOLID = 0; +const sal_Int16 API_LINE_DOTTED = 1; +const sal_Int16 API_LINE_DASHED = 2; +const sal_Int16 API_FINE_LINE_DASHED = 14; + +const sal_Int16 API_LINE_NONE = 0; +const sal_Int16 API_LINE_HAIR = 2; +const sal_Int16 API_LINE_THIN = 35; +const sal_Int16 API_LINE_MEDIUM = 88; +const sal_Int16 API_LINE_THICK = 141; + +const sal_Int16 API_ESCAPE_NONE = 0; ///< No escapement. +const sal_Int16 API_ESCAPE_SUPERSCRIPT = 101; ///< Superscript: raise characters automatically (magic value 101). +const sal_Int16 API_ESCAPE_SUBSCRIPT = -101; ///< Subscript: lower characters automatically (magic value -101). + +const sal_Int8 API_ESCAPEHEIGHT_NONE = 100; ///< Relative character height if not escaped. +const sal_Int8 API_ESCAPEHEIGHT_DEFAULT = 58; ///< Relative character height if escaped. + + +// Limitate values ------------------------------------------------------------ + +template< typename ReturnType, typename Type > +inline ReturnType getLimitedValue( Type nValue, Type nMin, Type nMax ) +{ + return static_cast< ReturnType >( ::std::clamp( nValue, nMin, nMax ) ); +} + +template< typename ReturnType, typename Type > +inline ReturnType getIntervalValue( Type nValue, Type nBegin, Type nEnd ) +{ + static_assert(::std::numeric_limits< Type >::is_integer, "is integer"); + Type nInterval = nEnd - nBegin; + Type nCount = (nValue < nBegin) ? -((nBegin - nValue - 1) / nInterval + 1) : ((nValue - nBegin) / nInterval); + return static_cast< ReturnType >( nValue - nCount * nInterval ); +} + +template< typename ReturnType > +inline ReturnType getDoubleIntervalValue( double fValue, double fBegin, double fEnd ) +{ + double fInterval = fEnd - fBegin; + double fCount = (fValue < fBegin) ? -(::rtl::math::approxFloor( (fBegin - fValue - 1.0) / fInterval ) + 1.0) : ::rtl::math::approxFloor( (fValue - fBegin) / fInterval ); + return static_cast< ReturnType >( fValue - fCount * fInterval ); +} + +// Read from bitfields -------------------------------------------------------- + +/** Returns true, if at least one of the bits set in nMask is set in nBitField. */ +template< typename Type > +inline bool getFlag( Type nBitField, Type nMask ) +{ + return (nBitField & nMask) != 0; +} + +/** Returns nSet, if at least one bit of nMask is set in nBitField, otherwise nUnset. */ +template< typename ReturnType, typename Type > +inline ReturnType getFlagValue( Type nBitField, Type nMask, ReturnType nSet, ReturnType nUnset ) +{ + return getFlag( nBitField, nMask ) ? nSet : nUnset; +} + +/** Extracts a value from a bit field. + + Returns the data fragment from nBitField, that starts at bit nStartBit + (0-based, bit 0 is rightmost) with the width of nBitCount. The returned + value will be right-aligned (normalized). + For instance: extractValue(0x4321,8,4) returns 3 (value in bits 8-11). + */ +template< typename ReturnType, typename Type > +inline ReturnType extractValue( Type nBitField, sal_uInt8 nStartBit, sal_uInt8 nBitCount ) +{ + sal_uInt64 nMask = 1; nMask <<= nBitCount; --nMask; + return static_cast< ReturnType >( nMask & (nBitField >> nStartBit) ); +} + +// Write to bitfields --------------------------------------------------------- + +/** Sets or clears (according to bSet) all set bits of nMask in ornBitField. */ +template< typename Type > +inline void setFlag( Type& ornBitField, Type nMask, bool bSet = true ) +{ + if( bSet ) ornBitField |= nMask; else ornBitField &= ~nMask; +} + + +/** Optional value, similar to ::std::optional<>, with convenience accessors. + */ +template< typename Type > +class OptValue +{ +public: + OptValue() : maValue(), mbHasValue( false ) {} + explicit OptValue( const Type& rValue ) : maValue( rValue ), mbHasValue( true ) {} + explicit OptValue( bool bHasValue, const Type& rValue ) : maValue( rValue ), mbHasValue( bHasValue ) {} + + bool has() const { return mbHasValue; } + bool operator!() const { return !mbHasValue; } + bool differsFrom( const Type& rValue ) const { return mbHasValue && (maValue != rValue); } + + const Type& get() const { return maValue; } + const Type& get( const Type& rDefValue ) const { return mbHasValue ? maValue : rDefValue; } + + void set( const Type& rValue ) { maValue = rValue; mbHasValue = true; } + Type& use() { mbHasValue = true; return maValue; } + + OptValue& operator=( const Type& rValue ) { set( rValue ); return *this; } + bool operator==( const OptValue& rValue ) const { + return ( ( !mbHasValue && rValue.mbHasValue == false ) || + ( mbHasValue == rValue.mbHasValue && maValue == rValue.maValue ) ); + } + void assignIfUsed( const OptValue& rValue ) { if( rValue.mbHasValue ) set( rValue.maValue ); } + +private: + Type maValue; + bool mbHasValue; +}; + + +/** Provides platform independent functions to convert from or to little-endian + byte order, e.g. for reading data from or writing data to memory or a + binary stream. + + On big-endian platforms, the byte order in the passed values is swapped, + this can be used for converting big-endian to and from little-endian data. + + On little-endian platforms, the conversion functions are implemented empty, + thus compilers should completely optimize away the function call. + */ +class ByteOrderConverter +{ +public: +#ifdef OSL_BIGENDIAN + static void convertLittleEndian( sal_Int8& ) {} // present for usage in templates + static void convertLittleEndian( sal_uInt8& ) {} // present for usage in templates + static void convertLittleEndian( char16_t& rnValue ) { swap2( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( sal_Int16& rnValue ) { swap2( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( sal_uInt16& rnValue ) { swap2( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( sal_Int32& rnValue ) { swap4( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( sal_uInt32& rnValue ) { swap4( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( sal_Int64& rnValue ) { swap8( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( sal_uInt64& rnValue ) { swap8( reinterpret_cast< sal_uInt8* >( &rnValue ) ); } + static void convertLittleEndian( float& rfValue ) { swap4( reinterpret_cast< sal_uInt8* >( &rfValue ) ); } + static void convertLittleEndian( double& rfValue ) { swap8( reinterpret_cast< sal_uInt8* >( &rfValue ) ); } + + template< typename Type > + inline static void convertLittleEndianArray( Type* pnArray, size_t nElemCount ); + + static void convertLittleEndianArray( sal_Int8*, size_t ) {} + static void convertLittleEndianArray( sal_uInt8*, size_t ) {} + +#else + template< typename Type > + static void convertLittleEndian( Type& ) {} + + template< typename Type > + static void convertLittleEndianArray( Type*, size_t ) {} + +#endif + + /** Writes a value to memory, while converting it to little-endian. + @param pDstBuffer The memory buffer to write the value to. + @param nValue The value to be written to memory in little-endian. + */ + template< typename Type > + inline static void writeLittleEndian( void* pDstBuffer, Type nValue ); + +#ifdef OSL_BIGENDIAN +private: + inline static void swap2( sal_uInt8* pnData ); + inline static void swap4( sal_uInt8* pnData ); + inline static void swap8( sal_uInt8* pnData ); +#endif +}; + + +template< typename Type > +inline void ByteOrderConverter::writeLittleEndian( void* pDstBuffer, Type nValue ) +{ + convertLittleEndian( nValue ); + memcpy( pDstBuffer, &nValue, sizeof( Type ) ); +} + +#ifdef OSL_BIGENDIAN +template< typename Type > +inline void ByteOrderConverter::convertLittleEndianArray( Type* pnArray, size_t nElemCount ) +{ + for( Type* pnArrayEnd = pnArray + nElemCount; pnArray != pnArrayEnd; ++pnArray ) + convertLittleEndian( *pnArray ); +} + +inline void ByteOrderConverter::swap2( sal_uInt8* pnData ) +{ + ::std::swap( pnData[ 0 ], pnData[ 1 ] ); +} + +inline void ByteOrderConverter::swap4( sal_uInt8* pnData ) +{ + ::std::swap( pnData[ 0 ], pnData[ 3 ] ); + ::std::swap( pnData[ 1 ], pnData[ 2 ] ); +} + +inline void ByteOrderConverter::swap8( sal_uInt8* pnData ) +{ + ::std::swap( pnData[ 0 ], pnData[ 7 ] ); + ::std::swap( pnData[ 1 ], pnData[ 6 ] ); + ::std::swap( pnData[ 2 ], pnData[ 5 ] ); + ::std::swap( pnData[ 3 ], pnData[ 4 ] ); +} +#endif + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/modelobjecthelper.hxx b/include/oox/helper/modelobjecthelper.hxx new file mode 100644 index 000000000..dd6100b33 --- /dev/null +++ b/include/oox/helper/modelobjecthelper.hxx @@ -0,0 +1,131 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_MODELOBJECTHELPER_HXX +#define INCLUDED_OOX_HELPER_MODELOBJECTHELPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Gradient; + class XBitmap; } + namespace graphic { class XGraphic; } + namespace container { class XNameContainer; } + namespace drawing { struct LineDash; } + namespace drawing { struct Hatch; } + namespace drawing { struct PolyPolygonBezierCoords; } + namespace lang { class XMultiServiceFactory; } +} + +namespace oox { + + +/** This helper manages named objects in a container, which is created on demand. + */ +class OOX_DLLPUBLIC ObjectContainer +{ +public: + explicit ObjectContainer( + const css::uno::Reference< css::lang::XMultiServiceFactory >& rxModelFactory, + const OUString& rServiceName ); + ~ObjectContainer(); + + /** Returns true, if the object with the passed name exists in the container. */ + bool hasObject( const OUString& rObjName ) const; + + css::uno::Any getObject( const OUString& rObjName ) const; + + /** Inserts the passed object into the container, returns its final name. */ + OUString insertObject( + const OUString& rObjName, + const css::uno::Any& rObj, + bool bInsertByUnusedName ); + +private: + void createContainer() const; + +private: + mutable css::uno::Reference< css::lang::XMultiServiceFactory > + mxModelFactory; ///< Factory to create the container. + mutable css::uno::Reference< css::container::XNameContainer > + mxContainer; ///< Container for the objects. + OUString maServiceName; ///< Service name to create the container. + sal_Int32 mnIndex; ///< Index to create unique identifiers. +}; + + +/** Contains tables for named drawing objects for a document model. + + Contains tables for named line markers, line dashes, fill gradients, and + fill bitmap URLs. The class is needed to handle different document models + in the same filter (e.g. embedded charts) which carry their own drawing + object tables. + */ +class OOX_DLLPUBLIC ModelObjectHelper +{ +public: + explicit ModelObjectHelper( + const css::uno::Reference< css::lang::XMultiServiceFactory >& rxModelFactory ); + + /** Returns true, if the model contains a line marker with the passed name. */ + bool hasLineMarker( const OUString& rMarkerName ) const; + + /** Inserts a new named line marker, overwrites an existing line marker + with the same name. Returns true, if the marker could be inserted. */ + bool insertLineMarker( + const OUString& rMarkerName, + const css::drawing::PolyPolygonBezierCoords& rMarker ); + + /** Inserts a new named line dash, returns the line dash name, based on an + internal constant name with a new unused index appended. */ + OUString insertLineDash( const css::drawing::LineDash& rDash ); + + /** Inserts a new named fill gradient, returns the gradient name, based on + an internal constant name with a new unused index appended. */ + OUString insertFillGradient( const css::awt::Gradient& rGradient ); + + OUString insertTransGrandient( const css::awt::Gradient& rGradient ); + + OUString insertFillHatch( const css::drawing::Hatch& rHatch ); + + /** Inserts a new named fill graphic, returns the bitmap name, based on + an internal constant name with a new unused index appended. */ + OUString insertFillBitmapXGraphic(css::uno::Reference const & rxGraphic); + + css::uno::Reference getFillBitmap(OUString const & rGraphicName); + +private: + ObjectContainer maMarkerContainer; ///< Contains all named line markers (line end polygons). + ObjectContainer maDashContainer; ///< Contains all named line dashes. + ObjectContainer maGradientContainer; ///< Contains all named fill gradients. + ObjectContainer maTransGradContainer; ///< Contains all named transparency Gradients. + ObjectContainer maBitmapUrlContainer; ///< Contains all named fill bitmap URLs. + ObjectContainer maHatchContainer; ///< Contains all named fill hatches. +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/progressbar.hxx b/include/oox/helper/progressbar.hxx new file mode 100644 index 000000000..e1c5c0a99 --- /dev/null +++ b/include/oox/helper/progressbar.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_PROGRESSBAR_HXX +#define INCLUDED_OOX_HELPER_PROGRESSBAR_HXX + +#include + +#include +#include +#include + +namespace com::sun::star { + namespace task { class XStatusIndicator; } +} + +namespace oox { + +// Interfaces ================================================================= + +/** Interface for progress bar classes. + */ +class OOX_DLLPUBLIC IProgressBar +{ +public: + virtual ~IProgressBar(); + + /** Returns the current position of the progress bar. + + @return Position of the progress bar, in the range from 0.0 (beginning + of the progress bar) to 1.0 (end of the progress bar) inclusive. + */ + virtual double getPosition() const = 0; + + /** Sets the current position of the progress bar. + + @param fPosition New position of the progress bar, in the range from + 0.0 (beginning of the progress bar) to 1.0 (end of the progress bar) + inclusive. + */ + virtual void setPosition( double fPosition ) = 0; +}; + + +class ISegmentProgressBar; +typedef std::shared_ptr< ISegmentProgressBar > ISegmentProgressBarRef; + +/** Interface for a segment in a progress bar, that is able to create sub + segments from itself. + */ +class OOX_DLLPUBLIC ISegmentProgressBar : public IProgressBar +{ +public: + virtual ~ISegmentProgressBar() override; + + /** Returns the length that is still free for creating sub segments. */ + virtual double getFreeLength() const = 0; + + /** Adds a new segment with the specified length. */ + virtual ISegmentProgressBarRef createSegment( double fLength ) = 0; +}; + + +/** A simple progress bar. + */ +class OOX_DLLPUBLIC ProgressBar final : public IProgressBar +{ +public: + explicit ProgressBar( + const css::uno::Reference< css::task::XStatusIndicator >& rxIndicator, + const OUString& rText ); + + virtual ~ProgressBar() override; + + /** Returns the current position of the progress bar. */ + virtual double getPosition() const override; + /** Sets the current position of the progress bar. */ + virtual void setPosition( double fPosition ) override; + +private: + css::uno::Reference< css::task::XStatusIndicator > + mxIndicator; + double mfPosition; +}; + + +/** A progress bar containing several independent segments. + */ +class OOX_DLLPUBLIC SegmentProgressBar final : public ISegmentProgressBar +{ +public: + explicit SegmentProgressBar( + const css::uno::Reference< css::task::XStatusIndicator >& rxIndicator, + const OUString& rText ); + + /** Returns the current position of the progress bar segment. */ + virtual double getPosition() const override; + /** Sets the current position of the progress bar segment. */ + virtual void setPosition( double fPosition ) override; + + /** Returns the length that is still free for creating sub segments. */ + virtual double getFreeLength() const override; + /** Adds a new segment with the specified length. */ + virtual ISegmentProgressBarRef createSegment( double fLength ) override; + +private: + ProgressBar maProgress; + double mfFreeStart; +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/propertymap.hxx b/include/oox/helper/propertymap.hxx new file mode 100644 index 000000000..423bb11fc --- /dev/null +++ b/include/oox/helper/propertymap.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_PROPERTYMAP_HXX +#define INCLUDED_OOX_HELPER_PROPERTYMAP_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { + struct PropertyValue; + class XPropertySet; +} + +namespace oox { + + +typedef ::std::map< OUString, css::uno::Any > PropertyNameMap; + +/** A helper that maps property identifiers to property values. + + The property identifiers are generated on compile time and refer to the + property name strings that are held by a static vector. The identifier to + name mapping is done internally while the properties are written to + property sets. + */ +class OOX_DLLPUBLIC PropertyMap +{ +public: + PropertyMap(); + + /** Returns the name of the passed property identifier. */ + static const OUString& getPropertyName( sal_Int32 nPropId ); + + /** Returns the property identifier of the passed name. */ + static sal_Int32 getPropertyId( std::u16string_view sPropName ); + + /** Returns true, if the map contains a property with the passed identifier. */ + bool hasProperty( sal_Int32 nPropId ) const; + + /** Sets the specified property to the passed value. Does nothing, if the + identifier is invalid. */ + bool setAnyProperty( sal_Int32 nPropId, const css::uno::Any& rValue ); + + /** Sets the specified property to the passed value. Does nothing, if the + identifier is invalid. */ + template< typename Type > + bool setProperty( sal_Int32 nPropId, Type&& rValue ) + { + if( nPropId < 0 ) + return false; + + maProperties[ nPropId ] <<= std::forward(rValue); + return true; + } + + /** setAnyProperty should be used */ + bool setProperty( sal_Int32, const css::uno::Any& ) = delete; + + css::uno::Any getProperty( sal_Int32 nPropId ); + + void erase( sal_Int32 nPropId ); + + bool empty() const; + + /** Inserts all properties contained in the passed property map. */ + void assignUsed( const PropertyMap& rPropMap ); + + /** Inserts all properties contained in the passed property map */ + void assignAll( const PropertyMap& rPropMap ); + + /** Returns a sequence of property values, filled with all contained properties. */ + css::uno::Sequence< css::beans::PropertyValue > + makePropertyValueSequence() const; + + /** Fills the passed sequences of names and anys with all contained properties. */ + void fillSequences( + css::uno::Sequence< OUString >& rNames, + css::uno::Sequence< css::uno::Any >& rValues ) const; + + void fillPropertyNameMap(PropertyNameMap& rMap) const; + + /** Creates a property set supporting the XPropertySet interface and inserts all properties. */ + css::uno::Reference< css::beans::XPropertySet > + makePropertySet() const; + +#if OSL_DEBUG_LEVEL > 0 +#ifdef DBG_UTIL + static void dump( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet); +#endif + static void dumpCode( const css::uno::Reference< css::beans::XPropertySet >& rXPropSet); + static void dumpData( const css::uno::Reference& rXPropSet); +#endif +private: + const std::vector* mpPropNames; + +protected: + std::map< sal_Int32, css::uno::Any > maProperties; +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/propertyset.hxx b/include/oox/helper/propertyset.hxx new file mode 100644 index 000000000..676ec4ceb --- /dev/null +++ b/include/oox/helper/propertyset.hxx @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_PROPERTYSET_HXX +#define INCLUDED_OOX_HELPER_PROPERTYSET_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { class XMultiPropertySet; } + namespace beans { class XPropertySet; } + namespace beans { class XPropertySetInfo; } +} + +namespace oox { + +class PropertyMap; + + +/** A wrapper for a UNO property set. + + This class provides functions to silently get and set properties (without + exceptions, without the need to check validity of the UNO property set). + + An instance is constructed with the reference to a UNO property set or any + other interface (the constructor will query for the + com.sun.star.beans.XPropertySet interface then). The reference to the + property set will be kept as long as the instance of this class is alive. + + The functions setProperties() tries to handle all passed values at once, + using the com.sun.star.beans.XMultiPropertySet interface. If the + implementation does not support the XMultiPropertySet interface, all + properties are handled separately in a loop. + */ +class OOX_DLLPUBLIC PropertySet +{ +public: + PropertySet() {} + + /** Constructs a property set wrapper with the passed UNO property set. */ + explicit PropertySet( + const css::uno::Reference< css::beans::XPropertySet >& rxPropSet ) + { set( rxPropSet ); } + + /** Constructs a property set wrapper after querying the XPropertySet interface. */ + template< typename Type > + explicit PropertySet( const Type& rObject ) { set( rObject ); } + + /** Sets the passed UNO property set and releases the old UNO property set. */ + void set( const css::uno::Reference< css::beans::XPropertySet >& rxPropSet ); + + /** Queries the passed object (interface or any) for an XPropertySet and releases the old UNO property set. */ + template< typename Type > + void set( const Type& rObject ) + { set( css::uno::Reference< css::beans::XPropertySet >( rObject, css::uno::UNO_QUERY ) ); } + + /** Returns true, if the contained XPropertySet interface is valid. */ + bool is() const { return mxPropSet.is(); } + + /** Returns true, if the specified property is supported by the property set. */ + bool hasProperty( sal_Int32 nPropId ) const; + + // Get properties --------------------------------------------------------- + + /** Gets the specified property from the property set. + @return the property value, or an empty Any, if the property is missing. */ + css::uno::Any getAnyProperty( sal_Int32 nPropId ) const; + + /** Gets the specified property from the property set. + @return true, if the passed variable could be filled with the property value. */ + template< typename Type > + bool getProperty( Type& orValue, sal_Int32 nPropId ) const + { return getAnyProperty( nPropId ) >>= orValue; } + + /** Gets the specified boolean property from the property set. + @return true = property contains true; false = property contains false or error occurred. */ + bool getBoolProperty( sal_Int32 nPropId ) const + { bool bValue = false; return getProperty( bValue, nPropId ) && bValue; } + // Set properties --------------------------------------------------------- + + /** Puts the passed any into the property set. */ + bool setAnyProperty( sal_Int32 nPropId, const css::uno::Any& rValue ); + + /** Puts the passed value into the property set. */ + template< typename Type > + bool setProperty( sal_Int32 nPropId, const Type& rValue ) + { return setAnyProperty( nPropId, css::uno::Any( rValue ) ); } + bool setProperty( sal_Int32 nPropId, ::Color rValue ) + { return setAnyProperty( nPropId, css::uno::Any( rValue ) ); } + + /** Puts the passed properties into the property set. Tries to use the XMultiPropertySet interface. + @param rPropNames The property names. MUST be ordered alphabetically. + @param rValues The related property values. */ + void setProperties( + const css::uno::Sequence< OUString >& rPropNames, + const css::uno::Sequence< css::uno::Any >& rValues ); + + /** Puts the passed property map into the property set. Tries to use the XMultiPropertySet interface. + @param rPropertyMap The property map. */ + void setProperties( const PropertyMap& rPropertyMap ); + +#ifdef DBG_UTIL + void dump(); +#endif + + +private: + /** Gets the specified property from the property set. + @return true, if the any could be filled with the property value. */ + bool implGetPropertyValue( css::uno::Any& orValue, const OUString& rPropName ) const; + + /** Puts the passed any into the property set. */ + bool implSetPropertyValue( const OUString& rPropName, const css::uno::Any& rValue ); + +private: + css::uno::Reference< css::beans::XPropertySet > + mxPropSet; ///< The mandatory property set interface. + css::uno::Reference< css::beans::XMultiPropertySet > + mxMultiPropSet; ///< The optional multi property set interface. + css::uno::Reference< css::beans::XPropertySetInfo > + mxPropSetInfo; ///< Property information. +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/refmap.hxx b/include/oox/helper/refmap.hxx new file mode 100644 index 000000000..2e63af512 --- /dev/null +++ b/include/oox/helper/refmap.hxx @@ -0,0 +1,144 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_REFMAP_HXX +#define INCLUDED_OOX_HELPER_REFMAP_HXX + +#include +#include +#include +#include + +namespace oox { + + +/** Template for a map of ref-counted objects with additional accessor functions. + + An instance of the class RefMap< Type > stores elements of the type + std::shared_ptr< Type >. The new accessor functions has() and get() + work correctly for nonexisting keys, there is no need to check the passed + key before. + */ +template< typename KeyType, typename ObjType, typename CompType = std::less< KeyType > > +class RefMap : public std::map< KeyType, std::shared_ptr< ObjType >, CompType > +{ +public: + typedef std::map< KeyType, std::shared_ptr< ObjType >, CompType > container_type; + typedef typename container_type::key_type key_type; + typedef typename container_type::mapped_type mapped_type; + typedef typename container_type::value_type value_type; + typedef typename container_type::key_compare key_compare; + +public: + /** Returns true, if the object associated to the passed key exists. + Returns false, if the key exists but points to an empty reference. */ + bool has( key_type nKey ) const + { + const mapped_type* pxRef = getRef( nKey ); + return pxRef && pxRef->get(); + } + + /** Returns a reference to the object associated to the passed key, or an + empty reference on error. */ + mapped_type get( key_type nKey ) const + { + if( const mapped_type* pxRef = getRef( nKey ) ) return *pxRef; + return mapped_type(); + } + + /** Calls the passed functor for every contained object, automatically + skips all elements that are empty references. */ + template< typename FunctorType > + void forEach( const FunctorType& rFunctor ) const + { + std::for_each( this->begin(), this->end(), ForEachFunctor< FunctorType >( rFunctor ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType > + void forEachMem( FuncType pFunc ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1 ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType, typename ParamType1, typename ParamType2 > + void forEachMem( FuncType pFunc, ParamType1 aParam1, ParamType2 aParam2 ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1, aParam1, aParam2 ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType, typename ParamType1, typename ParamType2, typename ParamType3 > + void forEachMem( FuncType pFunc, ParamType1 aParam1, ParamType2 aParam2, ParamType3 aParam3 ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1, aParam1, aParam2, aParam3 ) ); + } + + + /** Calls the passed functor for every contained object. Passes the key as + first argument and the object reference as second argument to rFunctor. */ + template< typename FunctorType > + void forEachWithKey( const FunctorType& rFunctor ) const + { + std::for_each( this->begin(), this->end(), ForEachFunctorWithKey< FunctorType >( rFunctor ) ); + } + + /** Calls the passed member function of ObjType on every contained object. + Passes the object key as argument to the member function. */ + template< typename FuncType > + void forEachMemWithKey( FuncType pFunc ) const + { + forEachWithKey( ::std::bind( pFunc, std::placeholders::_2, std::placeholders::_1 ) ); + } + + +private: + template< typename FunctorType > + struct ForEachFunctor + { + FunctorType maFunctor; + explicit ForEachFunctor( const FunctorType& rFunctor ) : maFunctor( rFunctor ) {} + void operator()( const value_type& rValue ) { if( rValue.second.get() ) maFunctor( *rValue.second ); } + }; + + template< typename FunctorType > + struct ForEachFunctorWithKey + { + FunctorType maFunctor; + explicit ForEachFunctorWithKey( const FunctorType& rFunctor ) : maFunctor( rFunctor ) {} + void operator()( const value_type& rValue ) { if( rValue.second.get() ) maFunctor( rValue.first, *rValue.second ); } + }; + + const mapped_type* getRef( key_type nKey ) const + { + typename container_type::const_iterator aIt = this->find( nKey ); + return (aIt == this->end()) ? nullptr : &aIt->second; + } +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/refvector.hxx b/include/oox/helper/refvector.hxx new file mode 100644 index 000000000..018940836 --- /dev/null +++ b/include/oox/helper/refvector.hxx @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_REFVECTOR_HXX +#define INCLUDED_OOX_HELPER_REFVECTOR_HXX + +#include +#include +#include +#include + +#include + +namespace oox { + + +/** Template for a vector of ref-counted objects with additional accessor functions. + + An instance of the class RefVector< Type > stores elements of the type + std::shared_ptr< Type >. The new accessor functions has() and get() + work correctly for indexes out of the current range, there is no need to + check the passed index before. + */ +template< typename ObjType > +class RefVector : public ::std::vector< std::shared_ptr< ObjType > > +{ +public: + typedef ::std::vector< std::shared_ptr< ObjType > > container_type; + typedef typename container_type::value_type value_type; + typedef typename container_type::size_type size_type; + +public: + + /** Returns a reference to the object with the passed index, or 0 on error. */ + value_type get( sal_Int32 nIndex ) const + { + if( const value_type* pxRef = getRef( nIndex ) ) return *pxRef; + return value_type(); + } + + /** Calls the passed functor for every contained object, automatically + skips all elements that are empty references. */ + template< typename FunctorType > + void forEach( FunctorType aFunctor ) const + { + ::std::for_each( this->begin(), this->end(), ForEachFunctor< FunctorType >( aFunctor ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType > + void forEachMem( FuncType pFunc ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1 ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType, typename ParamType > + void forEachMem( FuncType pFunc, ParamType aParam ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1, aParam ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType, typename ParamType1, typename ParamType2 > + void forEachMem( FuncType pFunc, ParamType1 aParam1, ParamType2 aParam2 ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1, aParam1, aParam2 ) ); + } + + /** Calls the passed member function of ObjType on every contained object, + automatically skips all elements that are empty references. */ + template< typename FuncType, typename ParamType1, typename ParamType2, typename ParamType3 > + void forEachMem( FuncType pFunc, ParamType1 aParam1, ParamType2 aParam2, ParamType3 aParam3 ) const + { + forEach( ::std::bind( pFunc, std::placeholders::_1, aParam1, aParam2, aParam3 ) ); + } + + /** Calls the passed functor for every contained object. Passes the index as + first argument and the object reference as second argument to rFunctor. */ + template< typename FunctorType > + void forEachWithIndex( const FunctorType& rFunctor ) const + { + ::std::for_each( this->begin(), this->end(), ForEachFunctorWithIndex< FunctorType >( rFunctor ) ); + } + + /** Calls the passed member function of ObjType on every contained object. + Passes the vector index as first argument to the member function. */ + template< typename FuncType, typename ParamType1, typename ParamType2 > + void forEachMemWithIndex( FuncType pFunc, ParamType1 aParam1, ParamType2 aParam2 ) const + { + forEachWithIndex( ::std::bind( pFunc, std::placeholders::_2, std::placeholders::_1, aParam1, aParam2 ) ); + } + + /** Searches for an element by using the passed functor that takes a + constant reference of the object type (const ObjType&). */ + template< typename FunctorType > + value_type findIf( const FunctorType& rFunctor ) const + { + typename container_type::const_iterator aIt = ::std::find_if( this->begin(), this->end(), FindFunctor< FunctorType >( rFunctor ) ); + return (aIt == this->end()) ? value_type() : *aIt; + } + +private: + template< typename FunctorType > + struct ForEachFunctor + { + FunctorType maFunctor; + explicit ForEachFunctor( const FunctorType& rFunctor ) : maFunctor( rFunctor ) {} + void operator()( const value_type& rxValue ) { if( rxValue.get() ) maFunctor( *rxValue ); } + }; + + template< typename FunctorType > + struct ForEachFunctorWithIndex + { + FunctorType maFunctor; + sal_Int32 mnIndex; + explicit ForEachFunctorWithIndex( const FunctorType& rFunctor ) : maFunctor( rFunctor ), mnIndex( 0 ) {} + void operator()( const value_type& rxValue ) { + if( rxValue.get() ) maFunctor( mnIndex, *rxValue ); + ++mnIndex; + } + }; + + template< typename FunctorType > + struct FindFunctor + { + FunctorType maFunctor; + explicit FindFunctor( const FunctorType& rFunctor ) : maFunctor( rFunctor ) {} + bool operator()( const value_type& rxValue ) { return rxValue.get() && maFunctor( *rxValue ); } + }; + + const value_type* getRef( sal_Int32 nIndex ) const + { + return ((0 <= nIndex) && (static_cast< size_type >( nIndex ) < this->size())) ? + &(*this)[ static_cast< size_type >( nIndex ) ] : nullptr; + } +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/storagebase.hxx b/include/oox/helper/storagebase.hxx new file mode 100644 index 000000000..2722ed80b --- /dev/null +++ b/include/oox/helper/storagebase.hxx @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_STORAGEBASE_HXX +#define INCLUDED_OOX_HELPER_STORAGEBASE_HXX + +#include +#include +#include + +#include +#include +#include +#include + +namespace com::sun::star { + namespace embed { class XStorage; } + namespace io { class XInputStream; } + namespace io { class XOutputStream; } + namespace io { class XStream; } +} + +namespace oox { + + +class StorageBase; +typedef std::shared_ptr< StorageBase > StorageRef; + +/** Base class for storage access implementations. + + Derived classes will be used to encapsulate storage access implementations + for ZIP storages containing XML streams, and OLE storages containing binary + data streams. + */ +class OOX_DLLPUBLIC StorageBase +{ +public: + explicit StorageBase( + const css::uno::Reference< css::io::XInputStream >& rxInStream, + bool bBaseStreamAccess ); + + explicit StorageBase( + const css::uno::Reference< css::io::XStream >& rxOutStream, + bool bBaseStreamAccess ); + + virtual ~StorageBase(); + + /** Returns true, if the object represents a valid storage. */ + bool isStorage() const; + + /** Returns true, if the object represents the root storage. */ + bool isRootStorage() const; + + /** Returns true, if the storage operates in read-only mode (based on an + input stream). */ + bool isReadOnly() const { return mbReadOnly;} + + /** Returns the com.sun.star.embed.XStorage interface of the current storage. */ + css::uno::Reference< css::embed::XStorage > + getXStorage() const; + + /** Returns the element name of this storage. */ + const OUString& getName() const { return maStorageName;} + + /** Returns the full path of this storage. */ + OUString getPath() const; + + /** Fills the passed vector with the names of all direct elements of this + storage. */ + void getElementNames( ::std::vector< OUString >& orElementNames ) const; + + /** Opens and returns the specified sub storage from the storage. + + @param rStorageName + The name of the embedded storage. The name may contain slashes to + open storages from embedded substorages. + @param bCreateMissing + True = create missing sub storages (for export filters). Must be + false for storages based on input streams. + */ + StorageRef openSubStorage( const OUString& rStorageName, bool bCreateMissing ); + + /** Opens and returns the specified input stream from the storage. + + @param rStreamName + The name of the embedded storage stream. The name may contain + slashes to open streams from embedded substorages. If base stream + access has been enabled in the constructor, the base stream can be + accessed by passing an empty string as stream name. + */ + css::uno::Reference< css::io::XInputStream > + openInputStream( const OUString& rStreamName ); + + /** Opens and returns the specified output stream from the storage. + + @param rStreamName + The name of the embedded storage stream. The name may contain + slashes to create and open streams in embedded substorages. If base + stream access has been enabled in the constructor, the base stream + can be accessed by passing an empty string as stream name. + */ + css::uno::Reference< css::io::XOutputStream > + openOutputStream( const OUString& rStreamName ); + + /** Copies the specified element from this storage to the passed + destination storage. + + @param rElementName + The name of the embedded storage or stream. The name may contain + slashes to specify an element in an embedded substorage. In this + case, the element will be copied to the same substorage in the + destination storage. + */ + void copyToStorage( StorageBase& rDestStrg, const OUString& rElementName ); + + /** Copies all streams of this storage and of all substorages to the passed + destination. */ + void copyStorageToStorage( StorageBase& rDestStrg ); + + /** Commits the changes to the storage and all substorages. */ + void commit(); + +protected: + /** Special constructor for sub storage objects. */ + explicit StorageBase( const StorageBase& rParentStorage, const OUString& rStorageName, bool bReadOnly ); + +private: + StorageBase( const StorageBase& ) = delete; + StorageBase& operator=( const StorageBase& ) = delete; + + /** Returns true, if the object represents a valid storage. */ + virtual bool implIsStorage() const = 0; + + /** Returns the com.sun.star.embed.XStorage interface of the current storage. */ + virtual css::uno::Reference< css::embed::XStorage > + implGetXStorage() const = 0; + + /** Returns the names of all elements of this storage. */ + virtual void implGetElementNames( ::std::vector< OUString >& orElementNames ) const = 0; + + /** Implementation of opening a storage element. */ + virtual StorageRef implOpenSubStorage( const OUString& rElementName, bool bCreate ) = 0; + + /** Implementation of opening an input stream element. */ + virtual css::uno::Reference< css::io::XInputStream > + implOpenInputStream( const OUString& rElementName ) = 0; + + /** Implementation of opening an output stream element. */ + virtual css::uno::Reference< css::io::XOutputStream > + implOpenOutputStream( const OUString& rElementName ) = 0; + + /** Commits the current storage. */ + virtual void implCommit() const = 0; + + /** Helper that opens and caches the specified direct substorage. */ + StorageRef getSubStorage( const OUString& rElementName, bool bCreateMissing ); + +private: + RefMap< OUString, StorageBase > + maSubStorages; ///< Map of direct sub storages. + css::uno::Reference< css::io::XInputStream > + mxInStream; ///< Cached base input stream (to keep it alive). + css::uno::Reference< css::io::XStream > + mxOutStream; ///< Cached base output stream (to keep it alive). + OUString maParentPath; ///< Full path of parent storage. + OUString maStorageName; ///< Name of this storage, if it is a substorage. + bool mbBaseStreamAccess; ///< True = access base streams with empty stream name. + bool mbReadOnly; ///< True = storage opened read-only (based on input stream). +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/textinputstream.hxx b/include/oox/helper/textinputstream.hxx new file mode 100644 index 000000000..4a5bcdbfe --- /dev/null +++ b/include/oox/helper/textinputstream.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_TEXTINPUTSTREAM_HXX +#define INCLUDED_OOX_HELPER_TEXTINPUTSTREAM_HXX + +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XInputStream; } + namespace io { class XTextInputStream2; } + namespace uno { class XComponentContext; } +} + +namespace oox { + +class BinaryInputStream; + + +class TextInputStream +{ +public: + explicit TextInputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + rtl_TextEncoding eTextEnc ); + + explicit TextInputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + BinaryInputStream& rInStrm, + rtl_TextEncoding eTextEnc ); + + ~TextInputStream(); + + /** Returns true, if no more text is available in the stream. + */ + bool isEof() const; + + /** Reads a text line from the stream. + + If the last line in the stream is not terminated with line-end + character(s), the stream will immediately go into EOF state and return + the text line. Otherwise, if the last character in the stream is a + line-end character, the next call to this function will turn the stream + into EOF state and return an empty string. + */ + OUString readLine(); + + /** Reads a text portion from the stream until the specified character is + found. + + If the end of the stream is not terminated with the specified + character, the stream will immediately go into EOF state and return the + remaining text portion. Otherwise, if the last character in the stream + is the specified character (and caller specifies to read and return it, + see parameter bIncludeChar), the next call to this function will turn + the stream into EOF state and return an empty string. + + @param cChar + The separator character to be read to. + + @param bIncludeChar + True = if found, the specified character will be read from stream + and included in the returned string. + False = the specified character will neither be read from the + stream nor included in the returned string, but will be + returned as first character in the next call of this function + or readLine(). + */ + OUString readToChar( sal_Unicode cChar, bool bIncludeChar ); + + + /** Creates a UNO text input stream object from the passed UNO input stream. + */ + static css::uno::Reference< css::io::XTextInputStream2 > + createXTextInputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + rtl_TextEncoding eTextEnc ); + + +private: + void init( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStrm, + rtl_TextEncoding eTextEnc ); + + /** Adds the pending character in front of the passed string, if existing. */ + OUString createFinalString( const OUString& rString ); + +private: + css::uno::Reference< css::io::XTextInputStream2 > + mxTextStrm; + sal_Unicode mcPendingChar; +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/helper/zipstorage.hxx b/include/oox/helper/zipstorage.hxx new file mode 100644 index 000000000..dec4b483e --- /dev/null +++ b/include/oox/helper/zipstorage.hxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_HELPER_ZIPSTORAGE_HXX +#define INCLUDED_OOX_HELPER_ZIPSTORAGE_HXX + +#include + +#include +#include +#include + +namespace com::sun::star { + namespace embed { class XStorage; } + namespace io { class XInputStream; } + namespace io { class XOutputStream; } + namespace io { class XStream; } + namespace uno { class XComponentContext; } +} + +namespace oox { + + +/** Implements stream access for ZIP storages containing XML streams. */ +class ZipStorage final : public StorageBase +{ +public: + explicit ZipStorage( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStream ); + + explicit ZipStorage( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XStream >& rxStream ); + + virtual ~ZipStorage() override; + +private: + explicit ZipStorage( + const ZipStorage& rParentStorage, + const css::uno::Reference< css::embed::XStorage >& rxStorage, + const OUString& rElementName ); + + /** Returns true, if the object represents a valid storage. */ + virtual bool implIsStorage() const override; + + /** Returns the com.sun.star.embed.XStorage interface of the current storage. */ + virtual css::uno::Reference< css::embed::XStorage > + implGetXStorage() const override; + + /** Returns the names of all elements of this storage. */ + virtual void implGetElementNames( ::std::vector< OUString >& orElementNames ) const override; + + /** Opens and returns the specified sub storage from the storage. */ + virtual StorageRef implOpenSubStorage( const OUString& rElementName, bool bCreateMissing ) override; + + /** Opens and returns the specified input stream from the storage. */ + virtual css::uno::Reference< css::io::XInputStream > + implOpenInputStream( const OUString& rElementName ) override; + + /** Opens and returns the specified output stream from the storage. */ + virtual css::uno::Reference< css::io::XOutputStream > + implOpenOutputStream( const OUString& rElementName ) override; + + /** Commits the current storage. */ + virtual void implCommit() const override; + +private: + css::uno::Reference< css::embed::XStorage > + mxStorage; ///< Storage based on input or output stream. +}; + + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/mathml/export.hxx b/include/oox/mathml/export.hxx new file mode 100644 index 000000000..e9589a0d1 --- /dev/null +++ b/include/oox/mathml/export.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_OOX_MATHML_EXPORT_HXX +#define INCLUDED_OOX_MATHML_EXPORT_HXX + +#include +#include +#include +#include +#include +#include + +namespace oox +{ + +/** + Interface class, StarMath will implement writeFormula*() to write out markup + representing the formula. + */ +class OOX_DLLPUBLIC FormulaExportBase +{ +public: + virtual void writeFormulaOoxml(::sax_fastparser::FSHelperPtr pSerializer, + oox::core::OoxmlVersion version, + oox::drawingml::DocumentType documentType, sal_Int8 nAlign) = 0; + virtual void writeFormulaRtf( OStringBuffer& rBuffer, rtl_TextEncoding nEncoding ) = 0; + enum eFormulaAlign { INLINE, CENTER, GROUPEDCENTER, LEFT, RIGHT }; + +protected: + FormulaExportBase(); + + ~FormulaExportBase() {} +}; + +} // namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/mathml/import.hxx b/include/oox/mathml/import.hxx new file mode 100644 index 000000000..92db9a837 --- /dev/null +++ b/include/oox/mathml/import.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_OOX_MATHML_IMPORT_HXX +#define INCLUDED_OOX_MATHML_IMPORT_HXX + +#include +#include +#include + +namespace oox +{ + +namespace formulaimport +{ +class XmlStream; +} + +/** + Interface class, StarMath will implement readFormulaOoxml() to read OOXML + representing the formula and getFormulaSize() to provide the size of the resulting + formula. + */ +class OOX_DLLPUBLIC FormulaImportBase +{ +public: + virtual void readFormulaOoxml( oox::formulaimport::XmlStream& stream ) = 0; + virtual Size getFormulaSize() const = 0; + +protected: + FormulaImportBase(); + + ~FormulaImportBase() {} +}; + +namespace core { class ContextHandler; } +namespace drawingml { class TextParagraph; } + +::rtl::Reference CreateLazyMathBufferingContext( + core::ContextHandler const& rParent, drawingml::TextParagraph & rPara); + +} // namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/mathml/importutils.hxx b/include/oox/mathml/importutils.hxx new file mode 100644 index 000000000..9ab79a6f0 --- /dev/null +++ b/include/oox/mathml/importutils.hxx @@ -0,0 +1,255 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_OOX_MATHML_IMPORTUTILS_HXX +#define INCLUDED_OOX_MATHML_IMPORTUTILS_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star +{ +namespace xml::sax +{ +class XFastAttributeList; +} +} + +namespace oox::formulaimport +{ +// used to differentiate between tags that opening or closing +const int TAG_OPENING = 1 << 29; +const int TAG_CLOSING = 1 << 30; + +// you probably want to #define these to something shorter in the .cxx file, +// but they must be done as macros, otherwise they wouldn't be usable for case values, +// and macros cannot be namespaced +#define XML_STREAM_OPENING(token) (TAG_OPENING | token) +#define XML_STREAM_CLOSING(token) (TAG_CLOSING | token) + +/** + Class for storing a stream of xml tokens. + + A part of an XML file can be parsed and stored in this stream, from which it can be read + as if parsed linearly. The purpose of this class is to allow simpler handling of XML + files, unlike the usual LO way of using callbacks, context handlers and similar needlessly + complicated stuff (YMMV). + + The advantages of this approach is easy to read and debug code (as it is just functions + reading tokens one by one and calling other functions, compared to having to use callbacks + and temporary storage). The disadvantage is that the XML structure needs to be handled + manually by the code. + + Note that tag identifiers are simply int values and the API does not care besides matching + their values to XML stream contents and requiring that the values are not as high as TAG_OPENING. + Be prepared for the fact that some of the functions may throw exceptions if the input + stream does not match the required token (TBD). + + The API tries to make the common idioms as simple as possible, see the following examples. + + Parse text , where tagtwo is optional: + @code +XmlStream::Tag tagoneTag = stream.ensureOpeningTag( tagone ); +if( attributeTag.hasAttribute( attr )) + ... = attributeTag.attribute( attr, defaultValueOfTheRightType ); +if( XmlStream::Tag tagtwoTag = stream.checkOpeningTag( tagtwo )) +{ + ... = tagtwoTag.text; + stream.ensureClosingTag( tagtwo ); +} +stream.ensureClosingTag( tagone ); + @endcode + + Parse an element that may contain several sub-elements of different types in random order: + @code +stream.ensureOpeningTag( element ); +while( !stream.atEnd() && stream.currentToken() != CLOSING( element )) + { + switch( stream.currentToken()) + { + case OPENING( subelement1 ): + handleSubElement1(); + break; + case OPENING( subelement2 ): + ... process subelement2; + break; + default: + stream.handleUnexpectedTag(); + break; + } +stream.ensureClosingTag( element ); + @endcode + + If there may not be a zero number of sub-elements, use a helper bool variable or use a do-while loop. + + Parse an element that may contain an unknown number of sub-elements of the same type: + @code +stream.ensureOpeningTag( element ); +while( !stream.atEnd() && stream.findTag( OPENING( subelement ))) + { + handleSubelement(); + } +stream.ensureClosingTag( element ); + @endcode + + If there may not be a zero number of sub-elements, use a helper bool variable or use a do-while loop. + + @since 3.5 +*/ +class OOX_DLLPUBLIC XmlStream +{ +public: + XmlStream(); + /** + Structure representing a list of attributes. + */ + // One could theoretically use oox::AttributeList, but that complains if the passed reference is empty, + // which would be complicated to avoid here. Also, parsers apparently reuse the same instance of XFastAttributeList, + // which means using oox::AttributeList would make them all point to the one instance. + struct OOX_DLLPUBLIC AttributeList + { + OUString& operator[](int token); + OUString attribute(int token, const OUString& def) const; + bool attribute(int token, bool def) const; + sal_Unicode attribute(int token, sal_Unicode def) const; + // when adding more attribute() overloads, add also to XmlStream itself + protected: + std::map attrs; + }; + /** + Structure representing a tag, including its attributes and content text immediately following it. + */ + struct OOX_DLLPUBLIC Tag + { + Tag(int token = XML_TOKEN_INVALID, + const css::uno::Reference& attributes + = css::uno::Reference()); + Tag(int token, const AttributeList& attribs); + int token; ///< tag type, or XML_TOKEN_INVALID + AttributeList attributes; + OUString text; + /** + This function returns value of the given attribute, or the passed default value if not found. + The type of the default value selects the return type (OUString here). + */ + OUString attribute(int token, const OUString& def = OUString()) const; + /** + @overload + */ + bool attribute(int token, bool def) const; + /** + @overload + */ + sal_Unicode attribute(int token, sal_Unicode def) const; + // when adding more attribute() overloads, add also to XmlStream::AttributeList and inline below + /** + Converts to true if the tag has a valid token, false otherwise. Allows simple + usage in if(), for example 'if( XmlStream::Tag foo = stream.checkOpeningTag( footoken ))'. + */ + operator bool() const; + }; + /** + @return true if current position is at the end of the XML stream + */ + bool atEnd() const; + /** + @return data about the current tag + */ + Tag currentTag() const; + /** + @return the token for the current tag + */ + int currentToken() const; + /** + Moves position to the next tag. + */ + void moveToNextTag(); + /** + Ensures that an opening tag with the given token is read. If the current tag does not match, + writes out a warning and tries to recover by skipping tags until found (or until the current element would end). + If found, the position in the stream is afterwards moved to the next tag. + @return the matching found opening tag, or empty tag if not found + */ + Tag ensureOpeningTag(int token); + /** + Tries to find an opening tag with the given token. Works similarly like ensureOpeningTag(), + but if a matching tag is not found, the position in the stream is not altered. The primary + use of this function is to check for optional elements. + @return the matching found opening tag, or empty tag if not found + */ + Tag checkOpeningTag(int token); + /** + Ensures that a closing tag with the given token is read. Like ensureOpeningTag(), + if not, writes out a warning and tries to recover by skipping tags until found (or until the current element would end). + If found, the position in the stream is afterwards moved to the next tag. + */ + void ensureClosingTag(int token); + /** + Tries to find the given token, until either found (returns true) or end of current element. + Position in the stream is set to make the tag current (i.e. it will be the next one read). + */ + bool findTag(int token); + /** + Handle the current (unexpected) tag. + */ + void handleUnexpectedTag(); + +protected: + Tag checkTag(int token, bool optional); + bool findTagInternal(int token, bool silent); + void skipElementInternal(int token, bool silent); + std::vector tags; + unsigned int pos; +}; + +/** + This class is used for creating XmlStream. + + Simply use this class and then pass it as XmlStream to the consumer. + + @since 3.5.0 +*/ +class OOX_DLLPUBLIC XmlStreamBuilder : public XmlStream +{ +public: + void appendOpeningTag(int token, + const css::uno::Reference& attributes + = css::uno::Reference()); + void appendOpeningTag(int token, const AttributeList& attribs); + void appendClosingTag(int token); + // appends the characters after the last appended token + void appendCharacters(std::u16string_view characters); +}; + +inline OUString XmlStream::Tag::attribute(int t, const OUString& def) const +{ + return attributes.attribute(t, def); +} + +inline bool XmlStream::Tag::attribute(int t, bool def) const +{ + return attributes.attribute(t, def); +} + +inline sal_Unicode XmlStream::Tag::attribute(int t, sal_Unicode def) const +{ + return attributes.attribute(t, def); +} + +} // namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/axbinaryreader.hxx b/include/oox/ole/axbinaryreader.hxx new file mode 100644 index 000000000..eb185f235 --- /dev/null +++ b/include/oox/ole/axbinaryreader.hxx @@ -0,0 +1,251 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_AXBINARYREADER_HXX +#define INCLUDED_OOX_OLE_AXBINARYREADER_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace oox::ole { struct AxFontData; } + +namespace oox::ole { + + +/** A wrapper for a binary input stream that supports aligned read operations. + + The implementation does not support seeking back the wrapped stream. All + seeking operations (tell, seekTo, align) are performed relative to the + position of the wrapped stream at construction time of this wrapper. It is + possible to construct this wrapper with an unseekable input stream without + losing any functionality. + */ +class AxAlignedInputStream final : public BinaryInputStream +{ +public: + explicit AxAlignedInputStream( BinaryInputStream& rInStrm ); + + /** Returns the size of the data this stream represents, if the wrapped + stream supports the size() operation. */ + virtual sal_Int64 size() const override; + /** Return the current relative stream position (relative to position of + the wrapped stream at construction time). */ + virtual sal_Int64 tell() const override; + /** Seeks the stream to the passed relative position, if it is behind the + current position. */ + virtual void seek( sal_Int64 nPos ) override; + /** Closes the input stream but not the wrapped stream. */ + virtual void close() override; + + /** Reads nBytes bytes to the passed sequence. + @return Number of bytes really read. */ + virtual sal_Int32 readData( StreamDataSequence& orData, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + /** Reads nBytes bytes to the (existing) buffer opMem. + @return Number of bytes really read. */ + virtual sal_Int32 readMemory( void* opMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + /** Seeks the stream forward by the passed number of bytes. */ + virtual void skip( sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Aligns the stream to a multiple of the passed size (relative to the + position of the wrapped stream at construction time). */ + void align( size_t nSize ); + + /** Aligns the stream according to the passed type and reads a value. */ + template< typename Type > + [[nodiscard]] + Type readAligned() { align( sizeof( Type ) ); return readValue< Type >(); } + /** Aligns the stream according to the passed type and skips the size of the type. */ + template< typename Type > + void skipAligned() { align( sizeof( Type ) ); skip( sizeof( Type ) ); } + +private: + BinaryInputStream* mpInStrm; ///< The wrapped input stream. + sal_Int64 mnStrmPos; ///< Tracks relative position in the stream. + sal_Int64 mnStrmSize; ///< Size of the wrapped stream data. +}; + + +/** A pair of integer values as a property. */ +typedef ::std::pair< sal_Int32, sal_Int32 > AxPairData; + +/** An array of string values as a property. */ +typedef ::std::vector< OUString > AxArrayString; + + +/** Import helper to read simple and complex ActiveX form control properties + from a binary input stream. */ +class AxBinaryPropertyReader +{ +public: + explicit AxBinaryPropertyReader( BinaryInputStream& rInStrm, bool b64BitPropFlags = false ); + + /** Reads the next integer property value from the stream, if the + respective flag in the property mask is set. */ + template< typename StreamType, typename DataType > + void readIntProperty( DataType& ornValue ) + { if( startNextProperty() ) ornValue = maInStrm.readAligned< StreamType >(); } + /** Reads the next boolean property value from the stream, if the + respective flag in the property mask is set. */ + void readBoolProperty( bool& orbValue, bool bReverse = false ); + /** Reads the next pair property from the stream, if the respective flag in + the property mask is set. */ + void readPairProperty( AxPairData& orPairData ); + /** Reads the next string property from the stream, if the respective flag + in the property mask is set. */ + void readStringProperty( OUString& orValue ); + /** Reads ArrayString, an array of fmString ( compressed or uncompressed ) + is read from the stream and inserted into rStrings */ + void readArrayStringProperty( std::vector< OUString >& rStrings ); + /** Reads the next GUID property from the stream, if the respective flag + in the property mask is set. The GUID will be enclosed in braces. */ + void readGuidProperty( OUString& orGuid ); + /** Reads the next font property from the stream, if the respective flag in + the property mask is set. */ + void readFontProperty( AxFontData& orFontData ); + /** Reads the next picture property from the stream, if the respective flag + in the property mask is set. */ + void readPictureProperty( StreamDataSequence& orPicData ); + + /** Skips the next integer property value in the stream, if the respective + flag in the property mask is set. */ + template< typename StreamType > + void skipIntProperty() { if( startNextProperty() ) maInStrm.skipAligned< StreamType >(); } + /** Skips the next boolean property value in the stream, if the respective + flag in the property mask is set. */ + void skipBoolProperty() { (void)startNextProperty(); } + /** Skips the next string property in the stream, if the respective flag in + the property mask is set. */ + void skipStringProperty() { readStringProperty( maDummyString ); } + /** Skips the next ArrayString property in the stream, if the respective flag in + the property mask is set. */ + void skipArrayStringProperty() { readArrayStringProperty( maDummyArrayString ); } + /** Skips the next GUID property in the stream, if the respective flag in + the property mask is set. */ + void skipGuidProperty() { readGuidProperty( maDummyString ); } + /** Skips the next picture property in the stream, if the respective flag + in the property mask is set. */ + void skipPictureProperty() { readPictureProperty( maDummyPicData ); } + /** Has to be called for undefined properties. If the respective flag in + the mask is set, the property import cannot be finished successfully. */ + void skipUndefinedProperty() { ensureValid( !startNextProperty() ); } + + /** Final processing, reads contents of all complex properties. */ + bool finalizeImport(); + +private: + bool ensureValid( bool bCondition = true ); + bool startNextProperty(); + +private: + /** Base class for complex properties such as string, point, size, GUID, picture. */ + struct ComplexProperty + { + virtual ~ComplexProperty(); + virtual bool readProperty( AxAlignedInputStream& rInStrm ) = 0; + }; + + /** Complex property for a 32-bit value pair, e.g. point or size. */ + struct PairProperty final : public ComplexProperty + { + AxPairData& mrPairData; + + explicit PairProperty( AxPairData& rPairData ) : + mrPairData( rPairData ) {} + virtual bool readProperty( AxAlignedInputStream& rInStrm ) override; + }; + + /** Complex property for a string value. */ + struct StringProperty final : public ComplexProperty + { + OUString& mrValue; + sal_uInt32 mnSize; + + explicit StringProperty( OUString& rValue, sal_uInt32 nSize ) : + mrValue( rValue ), mnSize( nSize ) {} + virtual bool readProperty( AxAlignedInputStream& rInStrm ) override; + }; + + /** Complex property for an array of strings. */ + struct ArrayStringProperty final : public ComplexProperty + { + AxArrayString& mrArray; + sal_uInt32 mnSize; + explicit ArrayStringProperty( AxArrayString& rArray, sal_uInt32 nSize ) : + mrArray( rArray ), mnSize( nSize ) {} + virtual bool readProperty( AxAlignedInputStream& rInStrm ) override; + }; + + /** Complex property for a GUID value. */ + struct GuidProperty final : public ComplexProperty + { + OUString& mrGuid; + + explicit GuidProperty( OUString& rGuid ) : + mrGuid( rGuid ) {} + virtual bool readProperty( AxAlignedInputStream& rInStrm ) override; + }; + + /** Stream property for a font structure. */ + struct FontProperty final : public ComplexProperty + { + AxFontData& mrFontData; + + explicit FontProperty( AxFontData& rFontData ) : + mrFontData( rFontData ) {} + virtual bool readProperty( AxAlignedInputStream& rInStrm ) override; + }; + + /** Stream property for a picture or mouse icon. */ + struct PictureProperty final : public ComplexProperty + { + StreamDataSequence& mrPicData; + + explicit PictureProperty( StreamDataSequence& rPicData ) : + mrPicData( rPicData ) {} + virtual bool readProperty( AxAlignedInputStream& rInStrm ) override; + }; + + typedef RefVector< ComplexProperty > ComplexPropVector; + +private: + AxAlignedInputStream maInStrm; ///< The input stream to read from. + ComplexPropVector maLargeProps; ///< Stores info for all used large properties. + ComplexPropVector maStreamProps; ///< Stores info for all used stream data properties. + StreamDataSequence maDummyPicData; ///< Dummy picture for unsupported properties. + OUString maDummyString; ///< Dummy string for unsupported properties. + AxArrayString maDummyArrayString; ///< Dummy strings for unsupported ArrayString properties. + sal_Int64 mnPropFlags; ///< Flags specifying existing properties. + sal_Int64 mnNextProp; ///< Next property to read. + sal_Int64 mnPropsEnd; ///< End position of simple/large properties. + bool mbValid; ///< True = stream still valid. +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/axbinarywriter.hxx b/include/oox/ole/axbinarywriter.hxx new file mode 100644 index 000000000..eb370473a --- /dev/null +++ b/include/oox/ole/axbinarywriter.hxx @@ -0,0 +1,164 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OOX_OLE_AXBINARYWRITER_HXX +#define INCLUDED_OOX_OLE_AXBINARYWRITER_HXX + +#include +#include + +#include +#include +#include +#include +#include + +namespace oox::ole { + + +/** A wrapper for a binary output stream that supports aligned write operations. + + The implementation does support seeking back the wrapped stream. All + seeking operations (tell, seekTo, align) are performed relative to the + position of the wrapped stream at construction time of this wrapper. + Unlike it's reader class counterpart it is NOT possible to construct this + wrapper with an unseekable output stream. + */ +class AxAlignedOutputStream final : public BinaryOutputStream +{ +public: + explicit AxAlignedOutputStream( BinaryOutputStream& rOutStrm ); + + /** Returns the size of the data this stream represents, if the wrapped + stream supports the size() operation. */ + virtual sal_Int64 size() const override; + /** Return the current relative stream position (relative to position of + the wrapped stream at construction time). */ + virtual sal_Int64 tell() const override; + /** Seeks the stream to the passed relative position, if it is behind the + current position. */ + virtual void seek( sal_Int64 nPos ) override; + /** Closes the input stream but not the wrapped stream. */ + virtual void close() override; + + /** Reads nBytes bytes to the passed sequence. + @return Number of bytes really read. */ + virtual void writeData( const StreamDataSequence& orData, size_t nAtomSize = 1 ) override; + /** Reads nBytes bytes to the (existing) buffer opMem. + @return Number of bytes really read. */ + virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + + /** Aligns the stream to a multiple of the passed size (relative to the + position of the wrapped stream at construction time). */ + void align( size_t nSize ); + + void pad( sal_Int32 nBytes ); + + /** Aligns the stream according to the passed type and reads a value. */ + template< typename Type > + void writeAligned( Type nVal ) { align( sizeof( Type ) ); writeValue( nVal ); } + +private: + BinaryOutputStream* mpOutStrm; ///< The wrapped input stream. + sal_Int64 mnStrmPos; ///< Tracks relative position in the stream. + sal_Int64 mnStrmSize; ///< Size of the wrapped stream data. + sal_Int64 mnWrappedBeginPos; ///< starting pos or wrapped stream +}; + +/** A pair of integer values as a property. */ +typedef ::std::pair< sal_Int32, sal_Int32 > AxPairData; + +/** Export helper to write simple and complex ActiveX form control properties + to a binary input stream. */ +class AxBinaryPropertyWriter +{ +public: + explicit AxBinaryPropertyWriter( BinaryOutputStream& rOutStrm, bool b64BitPropFlags = false ); + + /** Write an integer property value to the stream, the + respective flag in the property mask is set. */ + template< typename StreamType, typename DataType > + void writeIntProperty( DataType ornValue ) + { startNextProperty(); maOutStrm.writeAligned< StreamType >( ornValue ); } + /** Write a boolean property value to the stream, the + respective flag in the property mask is set. */ + void writeBoolProperty( bool orbValue ); + /** Write a pair property the stream, the respective flag in + the property mask is set. */ + void writePairProperty( AxPairData& orPairData ); + /** Write a string property to the stream, the respective flag + in the property mask is set. */ + void writeStringProperty( OUString& orValue ); + + /** Skips the next property clears the respective + flag in the property mask. */ + void skipProperty() { startNextProperty( true ); } + + /** Final processing, write contents of all complex properties, writes record size */ + void finalizeExport(); + +private: + bool ensureValid(); + void startNextProperty( bool bSkip = false ); + +private: + /** Base class for complex properties such as string, point, size, GUID, picture. */ + struct ComplexProperty + { + virtual ~ComplexProperty(); + virtual bool writeProperty( AxAlignedOutputStream& rOutStrm ) = 0; + }; + + /** Complex property for a 32-bit value pair, e.g. point or size. */ + struct PairProperty final : public ComplexProperty + { + AxPairData& mrPairData; + + explicit PairProperty( AxPairData& rPairData ) : + mrPairData( rPairData ) {} + virtual bool writeProperty( AxAlignedOutputStream& rOutStrm ) override; + }; + + /** Complex property for a string value. */ + struct StringProperty final : public ComplexProperty + { + OUString& mrValue; + sal_uInt32 mnSize; + + explicit StringProperty( OUString& rValue, sal_uInt32 nSize ) : + mrValue( rValue ), mnSize( nSize ) {} + virtual bool writeProperty( AxAlignedOutputStream& rOutStrm ) override; + }; + + /** Stream property for a picture or mouse icon. */ + struct PictureProperty final : public ComplexProperty + { + virtual bool writeProperty( AxAlignedOutputStream& rOutStrm ) override; + }; + + typedef RefVector< ComplexProperty > ComplexPropVector; + +private: + AxAlignedOutputStream maOutStrm; ///< The input stream to read from. + ComplexPropVector maLargeProps; ///< Stores info for all used large properties. + ComplexPropVector maStreamProps; ///< Stores info for all used stream data properties. + sal_Int16 mnBlockSize; + sal_Int64 mnPropFlagsStart; ///< pos of Prop flags + sal_Int64 mnPropFlags; ///< Flags specifying existing properties. + sal_Int64 mnNextProp; ///< Next property to read. + bool mbValid; ///< True = stream still valid. + bool mb64BitPropFlags; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/axcontrol.hxx b/include/oox/ole/axcontrol.hxx new file mode 100644 index 000000000..f4fd7b6a7 --- /dev/null +++ b/include/oox/ole/axcontrol.hxx @@ -0,0 +1,993 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_AXCONTROL_HXX +#define INCLUDED_OOX_OLE_AXCONTROL_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { class XControlModel; } + namespace container { class XIndexContainer; } + namespace drawing { class XDrawPage; } + namespace frame { class XModel; } + namespace form { class XFormsSupplier; } + namespace lang { class XMultiServiceFactory; } +} + +namespace oox { + class BinaryInputStream; + class BinaryOutputStream; + class GraphicHelper; + class PropertyMap; +} + +namespace oox::ole { + + +#define COMCTL_GUID_SCROLLBAR_60 "{FE38753A-44A3-11D1-B5B7-0000C09000C4}" +#define COMCTL_GUID_PROGRESSBAR_50 "{0713E8D2-850A-101B-AFC0-4210102A8DA7}" +#define COMCTL_GUID_PROGRESSBAR_60 "{35053A22-8589-11D1-B16A-00C0F0283628}" + +const sal_uInt16 COMCTL_VERSION_50 = 5; +const sal_uInt16 COMCTL_VERSION_60 = 6; + + +#define AX_GUID_COMMANDBUTTON "{D7053240-CE69-11CD-a777-00dd01143c57}" +#define AX_GUID_LABEL "{978C9E23-D4B0-11CE-bf2d-00aa003f40d0}" +#define AX_GUID_IMAGE "{4C599241-6926-101B-9992-00000b65c6f9}" +#define AX_GUID_TOGGLEBUTTON "{8BD21D60-EC42-11CE-9e0d-00aa006002f3}" +#define AX_GUID_CHECKBOX "{8BD21D40-EC42-11CE-9e0d-00aa006002f3}" +#define AX_GUID_OPTIONBUTTON "{8BD21D50-EC42-11CE-9e0d-00aa006002f3}" +#define AX_GUID_TEXTBOX "{8BD21D10-EC42-11CE-9e0d-00aa006002f3}" +#define AX_GUID_LISTBOX "{8BD21D20-EC42-11CE-9e0d-00aa006002f3}" +#define AX_GUID_COMBOBOX "{8BD21D30-EC42-11CE-9e0d-00aa006002f3}" +#define AX_GUID_SPINBUTTON "{79176FB0-B7F2-11CE-97ef-00aa006d2776}" +#define AX_GUID_SCROLLBAR "{DFD181E0-5E2F-11CE-a449-00aa004a803d}" +#define AX_GUID_FRAME "{6E182020-F460-11CE-9bcd-00aa00608e01}" + +// Html control GUID(s) + +#define HTML_GUID_SELECT "{5512D122-5CC6-11CF-8d67-00aa00bdce1d}" +#define HTML_GUID_TEXTBOX "{5512D124-5CC6-11CF-8d67-00aa00bdce1d}" + +const sal_uInt32 AX_SYSCOLOR_WINDOWBACK = 0x80000005; +const sal_uInt32 AX_SYSCOLOR_WINDOWFRAME = 0x80000006; +const sal_uInt32 AX_SYSCOLOR_WINDOWTEXT = 0x80000008; +const sal_uInt32 AX_SYSCOLOR_BUTTONFACE = 0x8000000F; +const sal_uInt32 AX_SYSCOLOR_BUTTONTEXT = 0x80000012; + +const sal_uInt32 AX_FLAGS_ENABLED = 0x00000002; +const sal_uInt32 AX_FLAGS_LOCKED = 0x00000004; +const sal_uInt32 AX_FLAGS_OPAQUE = 0x00000008; +const sal_uInt32 AX_FLAGS_COLUMNHEADS = 0x00000400; +const sal_uInt32 AX_FLAGS_ENTIREROWS = 0x00000800; +const sal_uInt32 AX_FLAGS_EXISTINGENTRIES = 0x00001000; +const sal_uInt32 AX_FLAGS_CAPTIONLEFT = 0x00002000; +const sal_uInt32 AX_FLAGS_EDITABLE = 0x00004000; +const sal_uInt32 AX_FLAGS_IMEMODE_MASK = 0x00078000; +const sal_uInt32 AX_FLAGS_DRAGENABLED = 0x00080000; +const sal_uInt32 AX_FLAGS_ENTERASNEWLINE = 0x00100000; +const sal_uInt32 AX_FLAGS_KEEPSELECTION = 0x00200000; +const sal_uInt32 AX_FLAGS_TABASCHARACTER = 0x00400000; +const sal_uInt32 AX_FLAGS_WORDWRAP = 0x00800000; +const sal_uInt32 AX_FLAGS_BORDERSSUPPRESSED = 0x02000000; +const sal_uInt32 AX_FLAGS_SELECTLINE = 0x04000000; +const sal_uInt32 AX_FLAGS_SINGLECHARSELECT = 0x08000000; +const sal_uInt32 AX_FLAGS_AUTOSIZE = 0x10000000; +const sal_uInt32 AX_FLAGS_HIDESELECTION = 0x20000000; +const sal_uInt32 AX_FLAGS_MAXLENAUTOTAB = 0x40000000; +const sal_uInt32 AX_FLAGS_MULTILINE = 0x80000000; + +const sal_Int32 AX_BORDERSTYLE_NONE = 0; +const sal_Int32 AX_BORDERSTYLE_SINGLE = 1; + +const sal_Int32 AX_SPECIALEFFECT_FLAT = 0; +const sal_Int32 AX_SPECIALEFFECT_RAISED = 1; +const sal_Int32 AX_SPECIALEFFECT_SUNKEN = 2; +const sal_Int32 AX_SPECIALEFFECT_ETCHED = 3; +const sal_Int32 AX_SPECIALEFFECT_BUMPED = 6; + +const sal_Int32 AX_PICSIZE_CLIP = 0; +const sal_Int32 AX_PICSIZE_STRETCH = 1; +const sal_Int32 AX_PICSIZE_ZOOM = 3; + +const sal_Int32 AX_PICALIGN_TOPLEFT = 0; +const sal_Int32 AX_PICALIGN_TOPRIGHT = 1; +const sal_Int32 AX_PICALIGN_CENTER = 2; +const sal_Int32 AX_PICALIGN_BOTTOMLEFT = 3; +const sal_Int32 AX_PICALIGN_BOTTOMRIGHT = 4; + +const sal_Int32 AX_DISPLAYSTYLE_TEXT = 1; +const sal_Int32 AX_DISPLAYSTYLE_LISTBOX = 2; +const sal_Int32 AX_DISPLAYSTYLE_COMBOBOX = 3; +const sal_Int32 AX_DISPLAYSTYLE_CHECKBOX = 4; +const sal_Int32 AX_DISPLAYSTYLE_OPTBUTTON = 5; +const sal_Int32 AX_DISPLAYSTYLE_TOGGLE = 6; +const sal_Int32 AX_DISPLAYSTYLE_DROPDOWN = 7; + +const sal_Int32 AX_SELECTION_SINGLE = 0; +const sal_Int32 AX_SELECTION_MULTI = 1; +const sal_Int32 AX_SELECTION_EXTENDED = 2; + +const sal_Int32 AX_SHOWDROPBUTTON_NEVER = 0; +const sal_Int32 AX_SHOWDROPBUTTON_FOCUS = 1; +const sal_Int32 AX_SHOWDROPBUTTON_ALWAYS = 2; + +const sal_Int32 AX_SCROLLBAR_NONE = 0x00; +const sal_Int32 AX_SCROLLBAR_HORIZONTAL = 0x01; +const sal_Int32 AX_SCROLLBAR_VERTICAL = 0x02; + + +/** Enumerates all UNO API control types supported by these filters. */ +enum ApiControlType +{ + API_CONTROL_BUTTON, + API_CONTROL_FIXEDTEXT, + API_CONTROL_IMAGE, + API_CONTROL_CHECKBOX, + API_CONTROL_RADIOBUTTON, + API_CONTROL_EDIT, + API_CONTROL_NUMERIC, + API_CONTROL_LISTBOX, + API_CONTROL_COMBOBOX, + API_CONTROL_SPINBUTTON, + API_CONTROL_SCROLLBAR, + API_CONTROL_TABSTRIP, //11 + API_CONTROL_PROGRESSBAR, + API_CONTROL_GROUPBOX, + API_CONTROL_FRAME, // 14 + API_CONTROL_PAGE, // 15 + API_CONTROL_MULTIPAGE, // 16 + API_CONTROL_DIALOG // 17 +}; + + +/** Specifies how a form control supports transparent background. */ +enum class ApiTransparencyMode +{ + NotSupported, ///< Control does not support transparency. + Void, ///< Transparency is enabled by missing fill color. +}; + +/** Specifies how a form control supports the DefaultState property. */ +enum ApiDefaultStateMode +{ + API_DEFAULTSTATE_BOOLEAN, ///< Control does not support tri-state, state is given as boolean. + API_DEFAULTSTATE_SHORT, ///< Control does not support tri-state, state is given as short. + API_DEFAULTSTATE_TRISTATE ///< Control supports tri-state, state is given as short. +}; + + +/** A base class with useful helper functions for something that is able to + convert ActiveX and ComCtl form controls. + */ +class OOX_DLLPUBLIC ControlConverter final +{ +public: + explicit ControlConverter( + const css::uno::Reference< css::frame::XModel >& rxDocModel, + const GraphicHelper& rGraphicHelper, + bool bDefaultColorBgr = true ); + ~ControlConverter(); + + // Generic conversion ----------------------------------------------------- + + /** Converts the passed position in 1/100 mm to UNO properties. */ + void convertPosition( + PropertyMap& rPropMap, + const AxPairData& rPos ) const; + + /** Converts the passed size in 1/100 mm to UNO properties. */ + void convertSize( + PropertyMap& rPropMap, + const AxPairData& rSize ) const; + + /** Converts the passed encoded OLE color to UNO properties. */ + void convertColor( + PropertyMap& rPropMap, + sal_Int32 nPropId, + sal_uInt32 nOleColor ) const; + + static void convertToMSColor( + PropertySet const & rPropSet, + sal_Int32 nPropId, + sal_uInt32& nOleColor, + sal_uInt32 nDefault = 0 ); + + + /** Converts the passed StdPic picture stream to UNO properties. */ + void convertPicture( + PropertyMap& rPropMap, + const StreamDataSequence& rPicData ) const; + + /** Converts the control orientation to UNO properties. */ + static void convertOrientation( + PropertyMap& rPropMap, + bool bHorizontal ); + + static void convertToMSOrientation( + PropertySet const & rPropMap, + bool& bHorizontal ); + + /** Converts the vertical alignment to UNO properties. */ + static void convertVerticalAlign( + PropertyMap& rPropMap, + sal_Int32 nVerticalAlign ); + + /** Converts common scrollbar settings to UNO properties. */ + static void convertScrollBar( + PropertyMap& rPropMap, + sal_Int32 nMin, sal_Int32 nMax, sal_Int32 nPosition, + sal_Int32 nSmallChange, sal_Int32 nLargeChange, bool bAwtModel ); + + /** Converts scrollability settings to UNO properties. */ + void convertScrollabilitySettings( + PropertyMap& rPropMap, + const AxPairData& rScrollPos, const AxPairData& rScrollArea, + sal_Int32 nScrollBars ) const; + + /** Binds the passed control model to the passed data sources. The + implementation will check which source types are supported. */ + void bindToSources( + const css::uno::Reference< css::awt::XControlModel >& rxCtrlModel, + const OUString& rCtrlSource, + const OUString& rRowSource, + sal_Int32 nRefSheet = 0 ) const; + + // ActiveX (Forms 2.0) specific conversion -------------------------------- + + /** Converts the Forms 2.0 background formatting to UNO properties. */ + void convertAxBackground( + PropertyMap& rPropMap, + sal_uInt32 nBackColor, + sal_uInt32 nFlags, + ApiTransparencyMode eTranspMode ) const; + + /** Converts the Forms 2.0 border formatting to UNO properties. */ + void convertAxBorder( + PropertyMap& rPropMap, + sal_uInt32 nBorderColor, + sal_Int32 nBorderStyle, + sal_Int32 nSpecialEffect ) const; + + static void convertToAxBorder( + PropertySet const & rPropSet, + sal_uInt32& nBorderColor, + sal_Int32& nBorderStyle, + sal_Int32& nSpecialEffect ); + + /** Converts the Forms 2.0 special effect to UNO properties. */ + static void convertAxVisualEffect( + PropertyMap& rPropMap, + sal_Int32 nSpecialEffect ); + + static void convertToAxVisualEffect( + PropertySet const & rPropSet, + sal_Int32& nSpecialEffect ); + + /** Converts the passed picture stream and Forms 2.0 position to UNO + properties. */ + void convertAxPicture( + PropertyMap& rPropMap, + const StreamDataSequence& rPicData, + sal_uInt32 nPicPos ) const; + + /** Converts the passed picture stream and Forms 2.0 position to UNO + properties. */ + void convertAxPicture( + PropertyMap& rPropMap, + const StreamDataSequence& rPicData, + sal_Int32 nPicSizeMode ) const; + + /** Converts the Forms 2.0 value for checked/unchecked/dontknow to UNO + properties. */ + static void convertAxState( + PropertyMap& rPropMap, + const OUString& rValue, + sal_Int32 nMultiSelect, + ApiDefaultStateMode eDefStateMode, + bool bAwtModel ); + + static void convertToAxState( + PropertySet const & rPropSet, + OUString& rValue, + sal_Int32& nMultiSelect, + ApiDefaultStateMode eDefStateMode ); + + /** Converts the Forms 2.0 control orientation to UNO properties. */ + static void convertAxOrientation( + PropertyMap& rPropMap, + const AxPairData& rSize, + sal_Int32 nOrientation ); + + static void convertToAxOrientation( + PropertySet const & rPropSet, + sal_Int32& nOrientation ); + +private: + css::uno::Reference< css::frame::XModel > mxDocModel; + const GraphicHelper& mrGraphicHelper; + mutable PropertySet maAddressConverter; + mutable PropertySet maRangeConverter; + bool mbDefaultColorBgr; +}; + + +/** Base class for all models of form controls. */ +class OOX_DLLPUBLIC ControlModelBase +{ +public: + explicit ControlModelBase(); + virtual ~ControlModelBase(); + + /** Sets this control model to AWT model mode. */ + void setAwtModelMode() { mbAwtModel = true; } + /** Sets this control model to form component mode. */ + void setFormComponentMode() { mbAwtModel = false; } + + /** Returns the UNO service name used to construct the AWT control model, + or the control form component. */ + OUString getServiceName() const; + + /** Derived classes set specific OOXML properties at the model structure. */ + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ); + /** Derived classes set binary data (picture, mouse icon) at the model structure. */ + virtual void importPictureData( sal_Int32 nPropId, BinaryInputStream& rInStrm ); + /** Derived classes import a form control model from the passed input stream. */ + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) = 0; + /** Derived classes export a form control model to the passed output stream. */ + virtual void exportBinaryModel( BinaryOutputStream& /*rOutStrm*/ ) {} + /** Derived classes export CompObjStream contents. */ + virtual void exportCompObj( BinaryOutputStream& /*rOutStrm*/ ) {} + /** Derived classes return the UNO control type enum value. */ + virtual ApiControlType getControlType() const = 0; + /** Derived classes convert all control properties. */ + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const; + /** Derived classes convert from uno control properties to equiv. MS values. */ + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ); + + /** Converts the control size to UNO properties. */ + void convertSize( PropertyMap& rPropMap, const ControlConverter& rConv ) const; + +public: // direct access needed for legacy VML drawing controls + AxPairData maSize; ///< Size of the control in 1/100 mm. + +protected: + bool mbAwtModel; ///< True = AWT control model, false = form component. +}; + +typedef std::shared_ptr< ControlModelBase > ControlModelRef; + + +/** Base class for all models of ComCtl form controls. */ +class ComCtlModelBase : public ControlModelBase +{ +public: + explicit ComCtlModelBase( + sal_uInt32 nDataPartId5, sal_uInt32 nDataPartId6, sal_uInt16 nVersion ); + + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + +protected: + virtual void importControlData( BinaryInputStream& rInStrm ) = 0; + +private: + /** Returns the data part identifier according to the model version. */ + sal_uInt32 getDataPartId() const; + + static bool readPartHeader( BinaryInputStream& rInStrm, + sal_uInt32 nExpPartId, + sal_uInt16 nExpMajor = SAL_MAX_UINT16, + sal_uInt16 nExpMinor = SAL_MAX_UINT16 ); + + bool importSizePart( BinaryInputStream& rInStrm ); + bool importCommonPart( BinaryInputStream& rInStrm, sal_uInt32 nPartSize ); + bool importComplexPart( BinaryInputStream& rInStrm ); + +protected: + StdFontInfo maFontData; ///< Font formatting. + StreamDataSequence maMouseIcon; ///< Binary picture stream for mouse icon. + sal_uInt32 mnFlags; ///< Common flags for ComCtl controls. + const sal_uInt16 mnVersion; ///< Current version of the ComCtl control model. + +private: + sal_uInt32 mnDataPartId5; ///< Identifier for version 5.0 control data. + sal_uInt32 mnDataPartId6; ///< Identifier for version 6.0 control data. + bool mbCommonPart; ///< True = the COMCTL_COMMONDATA part exists. + bool mbComplexPart; ///< True = the COMCTL_COMPLEXDATA part exists. +}; + + +/** Model for a ComCtl scroll bar. */ +class ComCtlScrollBarModel final : public ComCtlModelBase +{ +public: + explicit ComCtlScrollBarModel( sal_uInt16 nVersion ); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + +private: + virtual void importControlData( BinaryInputStream& rInStrm ) override; + + sal_uInt32 mnScrollBarFlags; ///< Special flags for scroll bar model. + sal_Int32 mnLargeChange; ///< Increment step size (thumb). + sal_Int32 mnSmallChange; ///< Increment step size (buttons). + sal_Int32 mnMin; ///< Minimum of the value range. + sal_Int32 mnMax; ///< Maximum of the value range. + sal_Int32 mnPosition; ///< Value of the spin button. +}; + + +/** Model for a ComCtl progress bar. */ +class ComCtlProgressBarModel final : public ComCtlModelBase +{ +public: + explicit ComCtlProgressBarModel( sal_uInt16 nVersion ); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + +private: + virtual void importControlData( BinaryInputStream& rInStrm ) override; + + float mfMin; ///< Minimum of the value range. + float mfMax; ///< Maximum of the value range. + sal_uInt16 mnVertical; ///< 0 = horizontal, 1 = vertical. + sal_uInt16 mnSmooth; ///< 0 = progress blocks, 1 = pixel resolution. +}; + + +/** Base class for all models of Form 2.0 form controls. */ +class OOX_DLLPUBLIC AxControlModelBase : public ControlModelBase +{ +public: + explicit AxControlModelBase(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; +}; + + +/** Base class for Forms 2.0 controls supporting text formatting. */ +class OOX_DLLPUBLIC AxFontDataModel : public AxControlModelBase +{ +public: + explicit AxFontDataModel( bool bSupportsAlign = true ); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + + /** Returns the font height in points. */ + sal_Int16 getFontHeight() const { return maFontData.getHeightPoints(); } + +public: // direct access needed for legacy VML drawing controls + AxFontData maFontData; ///< The font settings. + +private: + bool mbSupportsAlign; ///< True = UNO model supports Align property. +}; + + +/** Model for a Forms 2.0 command button. */ +class OOX_DLLPUBLIC AxCommandButtonModel final : public AxFontDataModel +{ +public: + explicit AxCommandButtonModel(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual void importPictureData( sal_Int32 nPropId, BinaryInputStream& rInStrm ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + +public: // direct access needed for legacy VML drawing controls + StreamDataSequence maPictureData; ///< Binary picture stream. + OUString maCaption; ///< Visible caption of the button. + sal_uInt32 mnTextColor; ///< Text color. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnFlags; ///< Various flags. + sal_uInt32 mnPicturePos; ///< Position of the picture relative to text. + sal_Int32 mnVerticalAlign; ///< Vertical alignment (legacy VML drawing controls only). + bool mbFocusOnClick; ///< True = take focus on click. +}; + + +/** Model for a Forms 2.0 label. */ +class OOX_DLLPUBLIC AxLabelModel final : public AxFontDataModel +{ +public: + explicit AxLabelModel(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + +public: // direct access needed for legacy VML drawing controls + OUString maCaption; ///< Visible caption of the button. + sal_uInt32 mnTextColor; ///< Text color. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnFlags; ///< Various flags. + sal_uInt32 mnBorderColor; ///< Flat border color. + sal_Int32 mnBorderStyle; ///< Flat border style. + sal_Int32 mnSpecialEffect; ///< 3D border effect. + sal_Int32 mnVerticalAlign; ///< Vertical alignment (legacy VML drawing controls only). +}; + + +/** Model for a Forms 2.0 image. */ +class OOX_DLLPUBLIC AxImageModel final : public AxControlModelBase +{ +public: + explicit AxImageModel(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual void importPictureData( sal_Int32 nPropId, BinaryInputStream& rInStrm ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + +private: + StreamDataSequence maPictureData; ///< Binary picture stream. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnFlags; ///< Various flags. + sal_uInt32 mnBorderColor; ///< Flat border color. + sal_Int32 mnBorderStyle; ///< Flat border style. + sal_Int32 mnSpecialEffect; ///< 3D border effect. + sal_Int32 mnPicSizeMode; ///< Clip, stretch, zoom. + sal_Int32 mnPicAlign; ///< Anchor position of the picture. + bool mbPicTiling; ///< True = picture is repeated. +}; + +class OOX_DLLPUBLIC AxTabStripModel final : public AxFontDataModel +{ +public: + explicit AxTabStripModel(); + + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + + virtual ApiControlType getControlType() const override; + +public: + sal_uInt32 mnListIndex; + sal_uInt32 mnTabStyle; + sal_uInt32 mnTabData; + sal_uInt32 mnVariousPropertyBits; + std::vector< OUString > maItems; // captions for each tab + std::vector< OUString > maTabNames; // names for each tab +}; + + +/** Base class for a Forms 2.0 morph data control. */ +class OOX_DLLPUBLIC AxMorphDataModelBase : public AxFontDataModel +{ +public: + explicit AxMorphDataModelBase(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual void importPictureData( sal_Int32 nPropId, BinaryInputStream& rInStrm ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + +public: // direct access needed for legacy VML drawing controls + StreamDataSequence maPictureData; ///< Binary picture stream. + OUString maCaption; ///< Visible caption of the button. + OUString maValue; ///< Current value of the control. + OUString maGroupName; ///< Group name for option buttons. + sal_uInt32 mnTextColor; ///< Text color. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnFlags; ///< Various flags. + sal_uInt32 mnPicturePos; ///< Position of the picture relative to text. + sal_uInt32 mnBorderColor; ///< Flat border color. + sal_Int32 mnBorderStyle; ///< Flat border style. + sal_Int32 mnSpecialEffect; ///< 3D border effect. + sal_Int32 mnDisplayStyle; ///< Type of the morph control. + sal_Int32 mnMultiSelect; ///< Selection mode. + sal_Int32 mnScrollBars; ///< Horizontal/vertical scroll bar. + sal_Int32 mnMatchEntry; ///< Auto completion mode. + sal_Int32 mnShowDropButton; ///< When to show the dropdown button. + sal_Int32 mnMaxLength; ///< Maximum character count. + sal_Int32 mnPasswordChar; ///< Password character in edit fields. + sal_Int32 mnListRows; ///< Number of rows in dropdown box. + sal_Int32 mnVerticalAlign; ///< Vertical alignment (legacy VML drawing controls only). +}; + + +/** Model for a Forms 2.0 toggle button. */ +class OOX_DLLPUBLIC AxToggleButtonModel final : public AxMorphDataModelBase +{ +public: + explicit AxToggleButtonModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a Forms 2.0 check box. */ +class OOX_DLLPUBLIC AxCheckBoxModel final : public AxMorphDataModelBase +{ +public: + explicit AxCheckBoxModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a Forms 2.0 option button. */ +class OOX_DLLPUBLIC AxOptionButtonModel final : public AxMorphDataModelBase +{ +public: + explicit AxOptionButtonModel(); + + /** Returns the group name used to goup several option buttons together. */ + const OUString& getGroupName() const { return maGroupName; } + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a Forms 2.0 text box. */ +class OOX_DLLPUBLIC AxTextBoxModel : public AxMorphDataModelBase +{ +public: + explicit AxTextBoxModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a numeric field (legacy drawing controls only). */ +class OOX_DLLPUBLIC AxNumericFieldModel final : public AxMorphDataModelBase +{ +public: + explicit AxNumericFieldModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a Forms 2.0 list box. */ +class OOX_DLLPUBLIC AxListBoxModel : public AxMorphDataModelBase +{ +public: + explicit AxListBoxModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a Forms 2.0 combo box. */ +class OOX_DLLPUBLIC AxComboBoxModel final : public AxMorphDataModelBase +{ +public: + explicit AxComboBoxModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; +}; + + +/** Model for a Forms 2.0 spin button. */ +class OOX_DLLPUBLIC AxSpinButtonModel final : public AxControlModelBase +{ +public: + explicit AxSpinButtonModel(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; + +public: // direct access needed for legacy VML drawing controls + sal_uInt32 mnArrowColor; ///< Button arrow color. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnFlags; ///< Various flags. + sal_Int32 mnOrientation; ///< Orientation of the buttons. + sal_Int32 mnMin; ///< Minimum of the value range. + sal_Int32 mnMax; ///< Maximum of the value range. + sal_Int32 mnPosition; ///< Value of the spin button. + sal_Int32 mnSmallChange; ///< Increment step size. + sal_Int32 mnDelay; ///< Repeat delay in milliseconds. +}; + + +/** Model for a Forms 2.0 scroll bar. */ +class OOX_DLLPUBLIC AxScrollBarModel final : public AxControlModelBase +{ +public: + explicit AxScrollBarModel(); + + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void exportBinaryModel( BinaryOutputStream& rOutStrm ) override; + virtual void exportCompObj( BinaryOutputStream& rOutStrm ) override; + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + virtual void convertFromProperties( PropertySet& rPropSet, const ControlConverter& rConv ) override; + +public: // direct access needed for legacy VML drawing controls + sal_uInt32 mnArrowColor; ///< Button arrow color. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnFlags; ///< Various flags. + sal_Int32 mnOrientation; ///< Orientation of the buttons. + sal_Int32 mnPropThumb; ///< Proportional thumb size. + sal_Int32 mnMin; ///< Minimum of the value range. + sal_Int32 mnMax; ///< Maximum of the value range. + sal_Int32 mnPosition; ///< Value of the spin button. + sal_Int32 mnSmallChange; ///< Increment step size (buttons). + sal_Int32 mnLargeChange; ///< Increment step size (thumb). + sal_Int32 mnDelay; ///< Repeat delay in milliseconds. +}; + + +typedef ::std::vector< OUString > AxClassTable; + +/** Base class for ActiveX container controls. */ +class OOX_DLLPUBLIC AxContainerModelBase : public AxFontDataModel +{ +public: + explicit AxContainerModelBase( bool bFontSupport = false ); + + /** Allows to set single properties specified by XML token identifier. */ + virtual void importProperty( sal_Int32 nPropId, const OUString& rValue ) override; + /** Reads the leading structure in the 'f' stream containing the model for + this control. */ + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + /** Converts font settings if supported. */ + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + + /** Reads the class table structure for embedded controls following the own + model from the 'f' stream. */ + bool importClassTable( BinaryInputStream& rInStrm, AxClassTable& orClassTable ); + +public: // direct access needed for legacy VML drawing controls + StreamDataSequence maPictureData; ///< Binary picture stream. + OUString maCaption; ///< Visible caption of the form. + AxPairData maLogicalSize; ///< Logical form size (scroll area). + AxPairData maScrollPos; ///< Scroll position. + sal_uInt32 mnBackColor; ///< Fill color. + sal_uInt32 mnTextColor; ///< Text color. + sal_uInt32 mnFlags; ///< Various flags. + sal_uInt32 mnBorderColor; ///< Flat border color. + sal_Int32 mnBorderStyle; ///< Flat border style. + sal_Int32 mnScrollBars; ///< Horizontal/vertical scroll bar. + sal_Int32 mnCycleType; ///< Cycle in all forms or in this form. + sal_Int32 mnSpecialEffect; ///< 3D border effect. + sal_Int32 mnPicAlign; ///< Anchor position of the picture. + sal_Int32 mnPicSizeMode; ///< Clip, stretch, zoom. + bool mbPicTiling; ///< True = picture is repeated. + bool mbFontSupport; ///< True = control supports the font property. +}; + + +/** Model for a Forms 2.0 frame control. */ +class OOX_DLLPUBLIC AxFrameModel final : public AxContainerModelBase +{ +public: + explicit AxFrameModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; +}; + +class OOX_DLLPUBLIC AxPageModel final : public AxContainerModelBase +{ +public: + explicit AxPageModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; +}; + +class OOX_DLLPUBLIC AxMultiPageModel final : public AxContainerModelBase +{ +public: + explicit AxMultiPageModel(); + + virtual ApiControlType getControlType() const override; + void importPageAndMultiPageProperties( BinaryInputStream& rInStrm, sal_Int32 nPages ); + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; + std::vector mnIDs; + sal_uInt32 mnActiveTab; + sal_uInt32 mnTabStyle; +}; + + +/** Model for a Forms 2.0 user form. */ +class OOX_DLLPUBLIC AxUserFormModel final : public AxContainerModelBase +{ +public: + explicit AxUserFormModel(); + + virtual ApiControlType getControlType() const override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; +}; + +class HtmlSelectModel final : public AxListBoxModel +{ + css::uno::Sequence< OUString > msListData; + css::uno::Sequence< sal_Int16 > msIndices; +public: + HtmlSelectModel(); + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; + virtual void convertProperties( PropertyMap& rPropMap, const ControlConverter& rConv ) const override; +}; + +class HtmlTextBoxModel final : public AxTextBoxModel +{ +public: + explicit HtmlTextBoxModel(); + virtual bool importBinaryModel( BinaryInputStream& rInStrm ) override; +}; + + +/** A form control embedded in a document draw page. Contains a specific model + structure according to the type of the control. */ +class OOX_DLLPUBLIC EmbeddedControl +{ +public: + explicit EmbeddedControl( const OUString& rName ); + + /** Creates and returns the internal control model of the specified type. */ + template< typename ModelType > + inline ModelType& createModel(); + + /** Creates and returns the internal control model of the specified type. */ + template< typename ModelType, typename ParamType > + inline ModelType& createModel( const ParamType& rParam ); + + /** Creates and returns the internal control model according to the passed + MS class identifier. */ + ControlModelBase* createModelFromGuid( std::u16string_view rClassId ); + + /** Returns true, if the internal control model exists. */ + bool hasModel() const { return bool(mxModel); } + /** Returns read-only access to the internal control model. */ + const ControlModelBase* getModel() const { return mxModel.get(); } + /** Returns read/write access to the internal control model. */ + ControlModelBase* getModel() { return mxModel.get(); } + + /** Returns the UNO service name needed to construct the control model. */ + OUString getServiceName() const; + + /** Converts all control properties and inserts them into the passed model. */ + bool convertProperties( + const css::uno::Reference< css::awt::XControlModel >& rxCtrlModel, + const ControlConverter& rConv ) const; + + void convertFromProperties( + const css::uno::Reference< css::awt::XControlModel >& rxCtrlModel, + const ControlConverter& rConv ); + +private: + ControlModelRef mxModel; ///< Control model containing the properties. + OUString maName; ///< Name of the control. +}; + + +template< typename ModelType > +inline ModelType& EmbeddedControl::createModel() +{ + auto xModel = std::make_shared(); + mxModel = xModel; + xModel->setFormComponentMode(); + return *xModel; +} + +template< typename ModelType, typename ParamType > +inline ModelType& EmbeddedControl::createModel( const ParamType& rParam ) +{ + auto xModel = std::make_shared( rParam ); + mxModel = xModel; + xModel->setFormComponentMode(); + return *xModel; +} + + +/** A wrapper for a control form embedded directly in a draw page. */ +class EmbeddedForm +{ +public: + explicit EmbeddedForm( + const css::uno::Reference< css::frame::XModel >& rxDocModel, + const css::uno::Reference< css::drawing::XDrawPage >& rxDrawPage, + const GraphicHelper& rGraphicHelper ); + + /** Converts the passed control and inserts the control model into the form. + @return The API control model, if conversion was successful. */ + css::uno::Reference< css::awt::XControlModel > + convertAndInsert( const EmbeddedControl& rControl, sal_Int32& rnCtrlIndex ); + + /** Returns the XIndexContainer interface of the UNO control form, if existing. */ + const css::uno::Reference< css::container::XIndexContainer >& + getXForm() const { return mxFormIC; } + +private: + /** Creates the form that will hold the form controls. */ + css::uno::Reference< css::container::XIndexContainer > const & + createXForm(); + +private: + ControlConverter maControlConv; + css::uno::Reference< css::lang::XMultiServiceFactory > mxModelFactory; + css::uno::Reference< css::form::XFormsSupplier > mxFormsSupp; + css::uno::Reference< css::container::XIndexContainer > mxFormIC; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/axcontrolfragment.hxx b/include/oox/ole/axcontrolfragment.hxx new file mode 100644 index 000000000..e6b87b416 --- /dev/null +++ b/include/oox/ole/axcontrolfragment.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_AXCONTROLFRAGMENT_HXX +#define INCLUDED_OOX_OLE_AXCONTROLFRAGMENT_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class XmlFilterBase; } + +namespace oox::ole { + +class ControlModelBase; +class EmbeddedControl; + + +/** Context handler for ActiveX form control model properties. */ +class AxControlPropertyContext final : public ::oox::core::ContextHandler2 +{ +public: + explicit AxControlPropertyContext( + ::oox::core::FragmentHandler2 const & rFragment, + ControlModelBase& rModel ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + ControlModelBase& mrModel; + sal_Int32 mnPropId; ///< Identifier of currently processed property. +}; + + +/** Fragment handler for an embedded ActiveX form control fragment. */ +class AxControlFragment final : public ::oox::core::FragmentHandler2 +{ +public: + explicit AxControlFragment( + ::oox::core::XmlFilterBase& rFilter, + const OUString& rFragmentPath, + EmbeddedControl& rControl ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + EmbeddedControl& mrControl; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/axfontdata.hxx b/include/oox/ole/axfontdata.hxx new file mode 100644 index 000000000..df3503247 --- /dev/null +++ b/include/oox/ole/axfontdata.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_AXFONTDATA_HXX +#define INCLUDED_OOX_OLE_AXFONTDATA_HXX + +#include +#include +#include +#include + +namespace oox { + class BinaryInputStream; + class BinaryOutputStream; +} + +enum class AxFontFlags { + NONE = 0x00000000, + Bold = 0x00000001, + Italic = 0x00000002, + Underline = 0x00000004, + Strikeout = 0x00000008, + Disabled = 0x00002000, + AutoColor = 0x40000000, +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +namespace oox::ole { + +enum class AxHorizontalAlign { + Left = 1, Right = 2, Center = 3 +}; + +/** All entries of a font property. */ +struct OOX_DLLPUBLIC AxFontData +{ + OUString maFontName; ///< Name of the used font. + AxFontFlags mnFontEffects; ///< Font effect flags. + sal_Int32 mnFontHeight; ///< Height of the font (not really twips, see code). + sal_Int32 mnFontCharSet; ///< Windows character set of the font. + AxHorizontalAlign mnHorAlign; ///< Horizontal text alignment. + bool mbDblUnderline; ///< True = double underline style (legacy VML drawing controls only). + + explicit AxFontData(); + + /** Converts the internal representation of the font height to points. */ + sal_Int16 getHeightPoints() const; + /** Converts the passed font height from points to the internal representation. */ + void setHeightPoints( sal_Int16 nPoints ); + + /** Reads the font data settings from the passed input stream. */ + bool importBinaryModel( BinaryInputStream& rInStrm ); + + void exportBinaryModel( BinaryOutputStream& rOutStrm ); + /** Reads the font data settings from the passed input stream that contains + an OLE StdFont structure. */ + bool importStdFont( BinaryInputStream& rInStrm ); + /** Reads the font data settings from the passed input stream depending on + the GUID preceding the actual font data. */ + bool importGuidAndFont( BinaryInputStream& rInStrm ); +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/olehelper.hxx b/include/oox/ole/olehelper.hxx new file mode 100644 index 000000000..e01e60257 --- /dev/null +++ b/include/oox/ole/olehelper.hxx @@ -0,0 +1,198 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_OLEHELPER_HXX +#define INCLUDED_OOX_OLE_OLEHELPER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { class XControlModel; } + namespace awt { struct Size; } + namespace form { class XFormComponent; } + namespace frame { class XModel; } + namespace io { class XOutputStream; } + namespace uno { class XComponentContext; } +} + +class SotStorage; +class SotStorageStream; +class SvGlobalName; + +namespace oox { + class BinaryInputStream; + class BinaryOutputStream; +} + +namespace oox::ole { + class ControlModelBase; + class EmbeddedControl; + + +#define OLE_GUID_STDFONT "{0BE35203-8F91-11CE-9DE3-00AA004BB851}" +#define OLE_GUID_STDPIC "{0BE35204-8F91-11CE-9DE3-00AA004BB851}" + + +const sal_uInt16 OLE_STDFONT_NORMAL = 400; +const sal_uInt16 OLE_STDFONT_BOLD = 700; + +const sal_uInt8 OLE_STDFONT_ITALIC = 0x02; +const sal_uInt8 OLE_STDFONT_UNDERLINE = 0x04; +const sal_uInt8 OLE_STDFONT_STRIKE = 0x08; + +/** Stores data about a StdFont font structure. */ +struct StdFontInfo +{ + OUString maName; ///< Font name. + sal_uInt32 mnHeight; ///< Font height (1/10,000 points). + sal_uInt16 mnWeight; ///< Font weight (normal/bold). + sal_uInt16 mnCharSet; ///< Font charset. + sal_uInt8 mnFlags; ///< Font flags. + + explicit StdFontInfo(); + explicit StdFontInfo( + const OUString& rName, + sal_uInt32 nHeight ); +}; + + +/** Stores data about a StdHlink hyperlink. */ +struct StdHlinkInfo +{ + OUString maTarget; + OUString maLocation; + OUString maDisplay; +}; + + +/** Static helper functions for OLE import/export. */ +namespace OleHelper +{ + /** Returns the UNO RGB color from the passed encoded OLE color. + + @param bDefaultColorBgr + True = OLE default color type is treated as BGR color. + False = OLE default color type is treated as palette color. + */ + OOX_DLLPUBLIC ::Color decodeOleColor( + const GraphicHelper& rGraphicHelper, + sal_uInt32 nOleColor, + bool bDefaultColorBgr ); + + /** Returns the OLE color from the passed UNO RGB color. + */ + OOX_DLLPUBLIC sal_uInt32 encodeOleColor( sal_Int32 nRgbColor ); + inline sal_uInt32 encodeOleColor( Color nRgbColor ) { return encodeOleColor(sal_Int32(nRgbColor)); } + + /** Imports a GUID from the passed binary stream and returns its string + representation (in uppercase characters). + */ + OOX_DLLPUBLIC OUString importGuid( BinaryInputStream& rInStrm ); + OOX_DLLPUBLIC void exportGuid( BinaryOutputStream& rOutStrm, const SvGlobalName& rId ); + + /** Imports an OLE StdFont font structure from the current position of the + passed binary stream. + */ + OOX_DLLPUBLIC bool importStdFont( + StdFontInfo& orFontInfo, + BinaryInputStream& rInStrm, + bool bWithGuid ); + + /** Imports an OLE StdPic picture from the current position of the passed + binary stream. + */ + OOX_DLLPUBLIC bool importStdPic( + StreamDataSequence& orGraphicData, + BinaryInputStream& rInStrm ); +} + +class OOX_DLLPUBLIC OleFormCtrlExportHelper final +{ + std::unique_ptr<::oox::ole::EmbeddedControl> mpControl; + ::oox::ole::ControlModelBase* mpModel; + ::oox::GraphicHelper maGrfHelper; + css::uno::Reference< css::frame::XModel > mxDocModel; + css::uno::Reference< css::awt::XControlModel > mxControlModel; + + OUString maName; + OUString maTypeName; + OUString maFullName; + OUString maGUID; +public: + OleFormCtrlExportHelper( const css::uno::Reference< css::uno::XComponentContext >& rxCtx, const css::uno::Reference< css::frame::XModel >& xDocModel, const css::uno::Reference< css::awt::XControlModel >& xModel ); + ~OleFormCtrlExportHelper(); + + std::u16string_view getGUID() const + { + std::u16string_view sResult; + if ( maGUID.getLength() > 2 ) + sResult = maGUID.subView(1, maGUID.getLength() - 2 ); + return sResult; + } + const OUString& getFullName() const { return maFullName; } + const OUString& getTypeName() const { return maTypeName; } + const OUString& getName() const { return maName; } + bool isValid() const { return mpModel != nullptr; } + void exportName( const css::uno::Reference< css::io::XOutputStream >& rxOut ); + void exportCompObj( const css::uno::Reference< css::io::XOutputStream >& rxOut ); + void exportControl( const css::uno::Reference< css::io::XOutputStream >& rxOut, const css::awt::Size& rSize, bool bAutoClose = false ); +}; + +// ideally it would be great to get rid of SvxMSConvertOCXControls +// however msfilter/source/msfilter/svdfppt.cxx still uses +// SvxMSConvertOCXControls as a base class, unfortunately oox depends on +// msfilter. Probably the solution would be to move the svdfppt.cxx +// implementation into the sd module itself. +class OOX_DLLPUBLIC MSConvertOCXControls : public SvxMSConvertOCXControls +{ +protected: + css::uno::Reference< css::uno::XComponentContext > mxCtx; + ::oox::GraphicHelper maGrfHelper; + + bool importControlFromStream( ::oox::BinaryInputStream& rInStrm, + css::uno::Reference< css::form::XFormComponent > & rxFormComp, + std::u16string_view rGuidString ); + bool importControlFromStream( ::oox::BinaryInputStream& rInStrm, + css::uno::Reference< css::form::XFormComponent > & rxFormComp, + const OUString& rGuidString, + sal_Int32 nSize ); +public: + MSConvertOCXControls( const css::uno::Reference< css::frame::XModel >& rxModel ); + virtual ~MSConvertOCXControls() override; + bool ReadOCXStorage( tools::SvRef const & rSrc1, css::uno::Reference< css::form::XFormComponent > & rxFormComp ); + bool ReadOCXCtlsStream(tools::SvRef const & rSrc1, css::uno::Reference< css::form::XFormComponent > & rxFormComp, + sal_Int32 nPos, sal_Int32 nSize ); + static bool WriteOCXStream( const css::uno::Reference< css::frame::XModel >& rxModel, tools::SvRef const &rSrc1, const css::uno::Reference< css::awt::XControlModel > &rControlModel, const css::awt::Size& rSize,OUString &rName); + static bool WriteOCXExcelKludgeStream( const css::uno::Reference< css::frame::XModel >& rxModel, const css::uno::Reference< css::io::XOutputStream >& xOutStrm, const css::uno::Reference< css::awt::XControlModel > &rControlModel, const css::awt::Size& rSize,OUString &rName); +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/oleobjecthelper.hxx b/include/oox/ole/oleobjecthelper.hxx new file mode 100644 index 000000000..5b792f204 --- /dev/null +++ b/include/oox/ole/oleobjecthelper.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_OLEOBJECTHELPER_HXX +#define INCLUDED_OOX_OLE_OLEOBJECTHELPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Size; } + namespace document { class XEmbeddedObjectResolver; } + namespace frame { class XModel; } + namespace lang { class XMultiServiceFactory; } +} + +namespace oox { class PropertyMap; } + +namespace oox::ole { + + +/** Contains generic information about an OLE object. */ +struct OleObjectInfo +{ + StreamDataSequence maEmbeddedData; ///< Data of an embedded OLE object. + OUString maTargetLink; ///< Path to external data for linked OLE object. + OUString maProgId; + bool mbLinked; ///< True = linked OLE object, false = embedded OLE object. + bool mbShowAsIcon; ///< True = show as icon, false = show contents. + bool mbAutoUpdate; + bool mbHasPicture; /// + + explicit OleObjectInfo(); +}; + + +/** Helper for OLE object handling. */ +class OleObjectHelper +{ +public: + explicit OleObjectHelper( + const css::uno::Reference& rxModelFactory, + const css::uno::Reference& xModel); + ~OleObjectHelper(); + + bool importOleObject( + PropertyMap& rPropMap, + const OleObjectInfo& rOleObject, + const css::awt::Size& rObjSize ); + +private: + css::uno::Reference m_xModel; + css::uno::Reference< css::document::XEmbeddedObjectResolver > mxResolver; + sal_Int32 mnObjectId; +}; + + +OOX_DLLPUBLIC void SaveInteropProperties( + css::uno::Reference const& xModel, + OUString const& rObjectName, OUString const* pOldObjectName, + OUString const& rProgId); + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/olestorage.hxx b/include/oox/ole/olestorage.hxx new file mode 100644 index 000000000..b7ac512f1 --- /dev/null +++ b/include/oox/ole/olestorage.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_OLESTORAGE_HXX +#define INCLUDED_OOX_OLE_OLESTORAGE_HXX + +#include + +#include +#include +#include +#include + +namespace com::sun::star { + namespace container { class XNameContainer; } + namespace embed { class XStorage; } + namespace io { class XInputStream; } + namespace io { class XOutputStream; } + namespace io { class XStream; } + namespace uno { class XComponentContext; } +} + +namespace oox::ole { + + +/** Implements stream access for binary OLE storages. */ +class OOX_DLLPUBLIC OleStorage final : public StorageBase +{ +public: + explicit OleStorage( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStream, + bool bBaseStreamAccess ); + + explicit OleStorage( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XStream >& rxOutStream, + bool bBaseStreamAccess ); + + virtual ~OleStorage() override; + +private: + explicit OleStorage( + const OleStorage& rParentStorage, + const css::uno::Reference< css::container::XNameContainer >& rxStorage, + const OUString& rElementName, + bool bReadOnly ); + explicit OleStorage( + const OleStorage& rParentStorage, + const css::uno::Reference< css::io::XStream >& rxOutStream, + const OUString& rElementName ); + + /** Initializes the API storage object for input. */ + void initStorage( const css::uno::Reference< css::io::XInputStream >& rxInStream ); + /** Initializes the API storage object for input/output. */ + void initStorage( const css::uno::Reference< css::io::XStream >& rxOutStream ); + + /** Returns true, if the object represents a valid storage. */ + virtual bool implIsStorage() const override; + + /** Returns the com.sun.star.embed.XStorage interface of the current storage. + + @attention + This function is not implemented for binary OLE storages. + */ + virtual css::uno::Reference< css::embed::XStorage > + implGetXStorage() const override; + + /** Returns the names of all elements of this storage. */ + virtual void implGetElementNames( ::std::vector< OUString >& orElementNames ) const override; + + /** Opens and returns the specified sub storage from the storage. */ + virtual StorageRef implOpenSubStorage( const OUString& rElementName, bool bCreateMissing ) override; + + /** Opens and returns the specified input stream from the storage. */ + virtual css::uno::Reference< css::io::XInputStream > + implOpenInputStream( const OUString& rElementName ) override; + + /** Opens and returns the specified output stream from the storage. */ + virtual css::uno::Reference< css::io::XOutputStream > + implOpenOutputStream( const OUString& rElementName ) override; + + /** Commits the current storage. */ + virtual void implCommit() const override; + +private: + css::uno::Reference< css::uno::XComponentContext > + mxContext; ///< Component context with service manager. + css::uno::Reference< css::container::XNameContainer > + mxStorage; ///< Access to elements of this sub storage. + const OleStorage* mpParentStorage; ///< Parent OLE storage that contains this storage. +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/vbacontrol.hxx b/include/oox/ole/vbacontrol.hxx new file mode 100644 index 000000000..c0afd6ae7 --- /dev/null +++ b/include/oox/ole/vbacontrol.hxx @@ -0,0 +1,214 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_VBACONTROL_HXX +#define INCLUDED_OOX_OLE_VBACONTROL_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { class XControlModel; } + namespace container { class XNameContainer; } + namespace frame { class XModel; } + namespace uno { class XComponentContext; } +} + +namespace oox { + class BinaryInputStream; + class GraphicHelper; + class PropertyMap; + class StorageBase; +} + +namespace oox::ole { + + +/** Common properties for all controls that are part of a VBA user form or of + another container control in a VBA user form. */ +class VbaSiteModel final +{ +public: + explicit VbaSiteModel(); + ~VbaSiteModel(); + + /** Allows to set single properties specified by XML token identifier. */ + void importProperty( sal_Int32 nPropId, const OUString& rValue ); + /** Imports the site model data from the passed input stream. */ + bool importBinaryModel( BinaryInputStream& rInStrm ); + /** Moves the control relative to its current position by the passed distance. */ + void moveRelative( const AxPairData& rDistance ); + + /** Returns the programmatical name of the control. */ + const OUString& getName() const { return maName; } + /** Returns the position of the control in its parent. */ + const AxPairData& getPosition() const { return maPos; } + /** Returns the unique identifier of this control. */ + sal_Int32 getId() const { return mnId; } + /** Returns true, if this control is a container control. */ + bool isContainer() const; + /** Returns the length of the stream data for stream based controls. */ + sal_uInt32 getStreamLength() const; + /** Returns the name of the substorage for the container control data. */ + OUString getSubStorageName() const; + /** Returns the tab index of the control. */ + sal_Int16 getTabIndex() const { return mnTabIndex; } + + /** Tries to create the control model according to the site model. */ + ControlModelRef createControlModel( const AxClassTable& rClassTable ) const; + /** Converts all form site properties. */ + void convertProperties( + PropertyMap& rPropMap, + const ControlConverter& rConv, + ApiControlType eCtrlType, + sal_Int32 nCtrlIndex ) const; + const OUString& getControlSource() const { return maControlSource; } + const OUString& getRowSource() const { return maRowSource; } +private: + OUString maName; ///< Name of the control. + OUString maTag; ///< User defined tag. + OUString maToolTip; ///< Tool tip for the control. + OUString maControlSource; ///< Linked cell for the control value in a spreadsheet. + OUString maRowSource; ///< Source data for the control in a spreadsheet. + + AxPairData maPos; ///< Position in parent container. + sal_Int32 mnId; ///< Control identifier. + sal_Int32 mnHelpContextId; ///< Help context identifier. + sal_uInt32 mnFlags; ///< Various flags. + sal_uInt32 mnStreamLen; ///< Size of control stream data. + sal_Int16 mnTabIndex; ///< Tab order index. + sal_uInt16 mnClassIdOrCache; ///< Class name identifier or GUID cache index. + sal_uInt16 mnGroupId; ///< Group identifier for grouped controls. +}; + +typedef std::shared_ptr< VbaSiteModel > VbaSiteModelRef; + + +/** A control that is embedded in a VBA user form or in another container + control in a VBA user form. + + The control may be a 'simple' control with its data stored in the 'o' + stream, or it may be a container control with its data stored in an own + substorage. + */ +class VbaFormControl +{ +public: + explicit VbaFormControl(); + virtual ~VbaFormControl(); + + /** Imports the model from the passed stream or storage, depending on the + control's type. Imports all embedded controls, if this is a container. */ + void importModelOrStorage( + BinaryInputStream& rInStrm, + StorageBase& rStrg, + const AxClassTable& rClassTable ); + + /** Returns the programmatical name of the control. */ + OUString getControlName() const; + + /** Creates the UNO control model, inserts it into the passed container, + and converts all control properties. */ + void createAndConvert( + sal_Int32 nCtrlIndex, + const css::uno::Reference< css::container::XNameContainer >& rxParentNC, + const ControlConverter& rConv ) const; + +protected: + /** Creates and imports the control model containing properties of the control. */ + void importControlModel( BinaryInputStream& rInStrm, const AxClassTable& rClassTable ); + /** Creates and imports the control model, and imports all embedded + controls from the passed substorage. */ + void importStorage( StorageBase& rStrg, const AxClassTable& rClassTable ); + + /** Converts all control properties, and inserts and converts embedded controls. */ + bool convertProperties( + const css::uno::Reference< css::awt::XControlModel >& rxCtrlModel, + const ControlConverter& rConv, + sal_Int32 nCtrlIndex ) const; + +private: + typedef RefVector< VbaFormControl > VbaFormControlVector; + typedef VbaFormControlVector::value_type VbaFormControlRef; + + /** Creates the control model according to the current site model. */ + void createControlModel( const AxClassTable& rClassTable ); + /** Imports the site model data containing common properties of the control. */ + bool importSiteModel( BinaryInputStream& rInStrm ); + + /** Imports the site models of all embedded controls from the 'f' stream. */ + void importEmbeddedSiteModels( BinaryInputStream& rInStrm ); + /* Final processing of all embedded controls after import. */ + void finalizeEmbeddedControls(); + + /** Moves the control relative to its current position by the passed distance. */ + void moveRelative( const AxPairData& rDistance ); + /** Moves all embedded controls from their relative position in this + control to an absolute position in the parent of this control. */ + void moveEmbeddedToAbsoluteParent(); + + /** Functor for comparing controls by their tab index. */ + static bool compareByTabIndex( const VbaFormControlRef& rxLeft, const VbaFormControlRef& rxRight ); + +protected: + VbaSiteModelRef mxSiteModel; ///< Common control properties. + ControlModelRef mxCtrlModel; ///< Specific control properties. + +private: + VbaFormControlVector maControls; ///< All embedded form controls. + AxClassTable maClassTable; ///< Class identifiers for exotic embedded controls. +}; + + +class VbaUserForm final : public VbaFormControl +{ +public: + explicit VbaUserForm( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XModel >& rxDocModel, + const GraphicHelper& rGraphicHelper, + bool bDefaultColorBgr ); + + /** Imports the form and its embedded controls, and inserts the form with + all its controls into the passed dialog library. */ + void importForm( + const css::uno::Reference< css::container::XNameContainer >& rxDialogLib, + StorageBase& rVbaFormStrg, + const OUString& rModuleName, + rtl_TextEncoding eTextEnc ); + +private: + css::uno::Reference< css::uno::XComponentContext > mxContext; + css::uno::Reference< css::frame::XModel > mxDocModel; + ControlConverter maConverter; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/vbaexport.hxx b/include/oox/ole/vbaexport.hxx new file mode 100644 index 000000000..04d9f7512 --- /dev/null +++ b/include/oox/ole/vbaexport.hxx @@ -0,0 +1,155 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OOX_OLE_VBAEXPORT_HXX +#define INCLUDED_OOX_OLE_VBAEXPORT_HXX + +#include + +#include +#include +#include +#include + +class SotStorage; +class SvStream; +class SvMemoryStream; + +namespace com::sun::star { + namespace container { class XNameContainer; } + namespace frame { class XModel; } + namespace script { class XLibraryContainer; } +} + +class OOX_DLLPUBLIC VbaExport +{ +public: + VbaExport(css::uno::Reference const & xModel); + + void exportVBA(SotStorage* pRootStorage); + + bool containsVBAProject(); + +private: + + css::uno::Reference + getBasicLibrary() const; + + css::uno::Reference + getLibraryContainer() const; + + OUString getProjectName() const; + rtl_TextEncoding getVBATextEncoding() const; + + css::uno::Reference mxModel; +}; + +class VBACompressionChunk +{ +public: + + VBACompressionChunk(SvStream& rCompressedStream, const sal_uInt8* pData, std::size_t nChunkSize); + + void write(); + +private: + SvStream& mrCompressedStream; + const sal_uInt8* mpUncompressedData; + sal_uInt8* mpCompressedChunkStream; + + // same as DecompressedChunkEnd in the spec + std::size_t mnChunkSize; + + // CompressedCurrent according to the spec + sal_uInt64 mnCompressedCurrent; + + // CompressedEnd according to the spec + sal_uInt64 mnCompressedEnd; + + // DecompressedCurrent according to the spec + sal_uInt64 mnDecompressedCurrent; + + // DecompressedEnd according to the spec + sal_uInt64 mnDecompressedEnd; + + static void PackCompressedChunkSize(size_t nSize, sal_uInt16& rHeader); + + static void PackCompressedChunkFlag(bool bCompressed, sal_uInt16& rHeader); + + static void PackCompressedChunkSignature(sal_uInt16& rHeader); + + void compressTokenSequence(); + + void compressToken(size_t index, sal_uInt8& nFlagByte); + + static void SetFlagBit(size_t index, bool bVal, sal_uInt8& rFlag); + + sal_uInt16 CopyToken(size_t nLength, size_t nOffset); + + void match(size_t& rLength, size_t& rOffset); + + void CopyTokenHelp(sal_uInt16& rLengthMask, sal_uInt16& rOffsetMask, + sal_uInt16& rBitCount, sal_uInt16& rMaximumLength); + + void writeRawChunk(); + + sal_uInt16 handleHeader(bool bCompressed); +}; + +class OOX_DLLPUBLIC VBACompression +{ +public: + VBACompression(SvStream& rCompressedStream, + SvMemoryStream& rUncompressedStream); + + void write(); + +private: + SvStream& mrCompressedStream; + SvMemoryStream& mrUncompressedStream; +}; + +class OOX_DLLPUBLIC VBAEncryption +{ +public: + VBAEncryption(const sal_uInt8* pData, + const sal_uInt16 nLength, + SvStream& rEncryptedData, + sal_uInt8 nProjKey, + rtl_TextEncoding eTextEncoding); + + void write(); + + static sal_uInt8 calculateProjKey(const OUString& rString); + +private: + const sal_uInt8* mpData; // an array of bytes to be obfuscated + const sal_uInt16 mnLength; // the length of Data + SvStream& mrEncryptedData; // Encrypted Data Structure + sal_uInt8 mnUnencryptedByte1; // the last unencrypted byte read or written + sal_uInt8 mnEncryptedByte1; // the last encrypted byte read or written + sal_uInt8 mnEncryptedByte2; // the next-to-last encrypted byte read or written + sal_Unicode mnProjKey; // a project-specific encryption key + sal_uInt8 mnIgnoredLength; // the length in bytes of IgnoredEnc + + sal_uInt8 mnSeed; // the seed value + sal_uInt8 mnVersionEnc; // the version encoding + rtl_TextEncoding meTextEncoding; // the VBA text encoding on export + + void writeSeed(); + void writeVersionEnc(); + void writeProjKeyEnc(); + void writeIgnoredEnc(); + void writeDataLengthEnc(); + void writeDataEnc(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/vbahelper.hxx b/include/oox/ole/vbahelper.hxx new file mode 100644 index 000000000..248d09810 --- /dev/null +++ b/include/oox/ole/vbahelper.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_VBAHELPER_HXX +#define INCLUDED_OOX_OLE_VBAHELPER_HXX + +#include +#include +#include + +namespace oox { class BinaryInputStream; } + +namespace oox::ole { + +// Directory stream record identifiers ======================================== + +const sal_uInt16 VBA_ID_MODULECOOKIE = 0x002C; +const sal_uInt16 VBA_ID_MODULEDOCSTRING = 0x001C; +const sal_uInt16 VBA_ID_MODULEDOCSTRINGUNICODE = 0x0048; +const sal_uInt16 VBA_ID_MODULEEND = 0x002B; +const sal_uInt16 VBA_ID_MODULEHELPCONTEXT = 0x001E; +const sal_uInt16 VBA_ID_MODULENAME = 0x0019; +const sal_uInt16 VBA_ID_MODULENAMEUNICODE = 0x0047; +const sal_uInt16 VBA_ID_MODULEOFFSET = 0x0031; +const sal_uInt16 VBA_ID_MODULEPRIVATE = 0x0028; +const sal_uInt16 VBA_ID_MODULEREADONLY = 0x0025; +const sal_uInt16 VBA_ID_MODULESTREAMNAME = 0x001A; +const sal_uInt16 VBA_ID_MODULESTREAMNAMEUNICODE = 0x0032; +const sal_uInt16 VBA_ID_MODULETYPEDOCUMENT = 0x0022; +const sal_uInt16 VBA_ID_MODULETYPEPROCEDURAL = 0x0021; +const sal_uInt16 VBA_ID_PROJECTCODEPAGE = 0x0003; +const sal_uInt16 VBA_ID_PROJECTEND = 0x0010; +const sal_uInt16 VBA_ID_PROJECTMODULES = 0x000F; +const sal_uInt16 VBA_ID_PROJECTNAME = 0x0004; +const sal_uInt16 VBA_ID_PROJECTVERSION = 0x0009; + + +/** Static helper functions for the VBA filters. */ +namespace VbaHelper +{ + /** Reads the next record from the VBA directory stream 'dir'. + + @param rnRecId (out parameter) The record identifier of the new record. + @param rRecData (out parameter) The contents of the new record. + @param rInStrm The 'dir' stream. + + @return True = next record successfully read. False on any error, or + if the stream is EOF. + */ + bool readDirRecord( + sal_uInt16& rnRecId, + StreamDataSequence& rRecData, + BinaryInputStream& rInStrm ); + + /** Extracts a key/value pair from a string separated by an equality sign. + + @param rKey (out parameter) The key before the separator. + @param rValue (out parameter) The value following the separator. + @param rCodeLine The source key/value pair. + + @return True = Equality sign separator found, and the returned key and + value are not empty. False otherwise. + */ + bool extractKeyValue( + OUString& rKey, + OUString& rValue, + std::u16string_view rKeyValue ); +} + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/vbainputstream.hxx b/include/oox/ole/vbainputstream.hxx new file mode 100644 index 000000000..4f2f78d81 --- /dev/null +++ b/include/oox/ole/vbainputstream.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_VBAINPUTSTREAM_HXX +#define INCLUDED_OOX_OLE_VBAINPUTSTREAM_HXX + +#include +#include + +#include +#include +#include + +namespace oox::ole { + + +/** A non-seekable input stream that implements run-length decompression. */ +class VbaInputStream final : public BinaryInputStream +{ +public: + explicit VbaInputStream( BinaryInputStream& rInStrm ); + + /** Returns -1, stream size is not determinable. */ + virtual sal_Int64 size() const override; + /** Returns -1, stream position is not tracked. */ + virtual sal_Int64 tell() const override; + /** Does nothing, stream is not seekable. */ + virtual void seek( sal_Int64 nPos ) override; + /** Closes the input stream but not the wrapped stream. */ + virtual void close() override; + + /** Reads nBytes bytes to the passed sequence. + @return Number of bytes really read. */ + virtual sal_Int32 readData( StreamDataSequence& orData, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + /** Reads nBytes bytes to the (existing) buffer opMem. + @return Number of bytes really read. */ + virtual sal_Int32 readMemory( void* opMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + /** Seeks the stream forward by the passed number of bytes. */ + virtual void skip( sal_Int32 nBytes, size_t nAtomSize = 1 ) override; + +private: + /** If no data left in chunk buffer, reads the next chunk from stream. */ + bool updateChunk(); + +private: + typedef ::std::vector< sal_uInt8 > ChunkBuffer; + + BinaryInputStream* mpInStrm; + ChunkBuffer maChunk; + size_t mnChunkPos; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/vbamodule.hxx b/include/oox/ole/vbamodule.hxx new file mode 100644 index 000000000..573552766 --- /dev/null +++ b/include/oox/ole/vbamodule.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_VBAMODULE_HXX +#define INCLUDED_OOX_OLE_VBAMODULE_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace container { class XNameAccess; } + namespace container { class XNameContainer; } + namespace frame { class XModel; } + namespace uno { class XComponentContext; } +} + +namespace oox { + class BinaryInputStream; + class StorageBase; +} + +namespace oox::ole { + +/** Stores, which key shortcut maps to which VBA macro method. */ +struct VbaMacroKeyAndMethodBinding +{ + // This describes a key combination in "raw" VBA Macro form, that + // still needs translated to a key event that can be used in + // LibreOffice. + OUString msApiKey; + // The name of the macro method + OUString msMethodName; +}; + +class VbaModule +{ +public: + explicit VbaModule( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XModel >& rxDocModel, + const OUString& rName, + rtl_TextEncoding eTextEnc, + bool bExecutable ); + + /** Returns the module type (com.sun.star.script.ModuleType constant). */ + sal_Int32 getType() const { return mnType; } + /** Sets the passed module type. */ + void setType( sal_Int32 nType ) { mnType = nType; } + + /** Returns the name of the module. */ + const OUString& getName() const { return maName; } + /** Returns the stream name of the module. */ + const OUString& getStreamName() const { return maStreamName; } + + /** Imports all records for this module until the MODULEEND record. */ + void importDirRecords( BinaryInputStream& rDirStrm ); + + /** Imports the VBA source code into the passed Basic library. */ + void createAndImportModule( + StorageBase& rVbaStrg, + const css::uno::Reference< css::container::XNameContainer >& rxBasicLib, + const css::uno::Reference< css::container::XNameAccess >& rxDocObjectNA ); + /** Creates an empty Basic module in the passed Basic library. */ + void createEmptyModule( + const css::uno::Reference< css::container::XNameContainer >& rxBasicLib, + const css::uno::Reference< css::container::XNameAccess >& rxDocObjectNA ) const; + + void registerShortcutKeys(); + +private: + /** Reads and returns the VBA source code from the passed storage. */ + OUString readSourceCode( StorageBase& rVbaStrg ); + + /** Creates a new Basic module and inserts it into the passed Basic library. */ + void createModule( + std::u16string_view rVBASourceCode, + const css::uno::Reference< css::container::XNameContainer >& rxBasicLib, + const css::uno::Reference< css::container::XNameAccess >& rxDocObjectNA ) const; + +private: + css::uno::Reference< css::uno::XComponentContext > + mxContext; ///< Component context with service manager. + css::uno::Reference< css::frame::XModel > + mxDocModel; ///< Document model used to import/export the VBA project. + OUString maName; + OUString maStreamName; + OUString maDocString; + rtl_TextEncoding meTextEnc; + sal_Int32 mnType; + sal_uInt32 mnOffset; + bool mbReadOnly; + bool mbPrivate; + bool mbExecutable; + + /** Keys and VBA macro method bindings */ + std::vector maKeyBindings; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ole/vbaproject.hxx b/include/oox/ole/vbaproject.hxx new file mode 100644 index 000000000..4a9b3e1a4 --- /dev/null +++ b/include/oox/ole/vbaproject.hxx @@ -0,0 +1,211 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_OLE_VBAPROJECT_HXX +#define INCLUDED_OOX_OLE_VBAPROJECT_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace container { class XNameContainer; } + namespace frame { class XModel; } + namespace script { class XLibraryContainer; } + namespace script::vba { class XVBAMacroResolver; } + namespace uno { class XComponentContext; } + namespace uno { class XInterface; } + namespace io { class XInputStream; } +} + +namespace oox { + class GraphicHelper; + class StorageBase; +} + +namespace oox::ole { + +class VbaModule; + +class VbaFilterConfig +{ +public: + explicit VbaFilterConfig( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + std::u16string_view rConfigCompName ); + ~VbaFilterConfig(); + + /** Returns true, if the VBA source code and forms should be imported. */ + bool isImportVba() const; + /** Returns true, if the VBA source code should be imported executable. */ + bool isImportVbaExecutable() const; + /** Returns true, if the VBA source code and forms should be exported. */ + bool isExportVba() const; + +private: + css::uno::Reference< css::uno::XInterface > + mxConfigAccess; +}; + + +/** Base class for objects that attach a macro to a specific action. + + Purpose is to collect objects that need to attach a VBA macro to an action. + The VBA project will be loaded at a very late point of the document import + process, because it depends on an initialized core document model (e.g. + spreadsheet codenames). Some objects that want to attach a VBA macro to an + action (e.g. mouse click action for drawing shapes) are loaded long before + the VBA project. The drawback is that in most cases macros are specified + without module name, or the VBA project name is part of the macro name. + In the former case, all code modules have to be scanned for the macro to be + able to create a valid script URL. + + The import code will register these requests to attach a VBA macro with an + instance of a class derived from this base class. The derived class will + store all information needed to finally attach the macro to the action, + once the VBA project has been imported. + */ +class OOX_DLLPUBLIC VbaMacroAttacherBase +{ +public: + explicit VbaMacroAttacherBase( const OUString& rMacroName ); + virtual ~VbaMacroAttacherBase(); + + /** Resolves the internal macro name to the related macro URL, and attaches + the macro to the object. */ + void resolveAndAttachMacro( + const css::uno::Reference< css::script::vba::XVBAMacroResolver >& rxResolver ); + +private: + /** Called after the VBA project has been imported. Derived classes will + attach the passed script to the object represented by this instance. */ + virtual void attachMacro( const OUString& rScriptUrl ) = 0; + +private: + OUString maMacroName; +}; + +typedef std::shared_ptr< VbaMacroAttacherBase > VbaMacroAttacherRef; + + +class OOX_DLLPUBLIC VbaProject : public VbaFilterConfig +{ +public: + explicit VbaProject( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XModel >& rxDocModel, + std::u16string_view rConfigCompName ); + virtual ~VbaProject(); + + /** Imports the entire VBA project from the passed storage. + + @param rVbaPrjStrg The root storage of the entire VBA project. + */ + void importVbaProject( + StorageBase& rVbaPrjStrg, + const GraphicHelper& rGraphicHelper ); + + bool importVbaProject( + StorageBase& rVbaPrjStrg ); + + /// Imports VBA data for a VBA project, e.g. word/vbaData.xml. + void importVbaData(const css::uno::Reference& xInputStream); + + /** Reads vba module related information from the project streams */ + void readVbaModules( StorageBase& rVbaPrjStrg ); + /** Imports (and creates) vba modules and user forms from the vba project records previously read. + Note: ( expects that readVbaModules was already called ) */ + void importModulesAndForms( StorageBase& rVbaPrjStrg, const GraphicHelper& rGraphicHelper ); + /** Registers a macro attacher object. For details, see description of the + VbaMacroAttacherBase class. */ + void registerMacroAttacher( const VbaMacroAttacherRef& rxAttacher ); + + /** Attaches VBA macros to objects registered via registerMacroAttacher(). */ + void attachMacros(); + + void setOleOverridesSink( css::uno::Reference< css::container::XNameContainer > const & rxOleOverridesSink ){ mxOleOverridesSink = rxOleOverridesSink; } + +protected: + /** Registers a dummy module that will be created when the VBA project is + imported. */ + void addDummyModule( const OUString& rName, sal_Int32 nType ); + + /** Called when the import process of the VBA project has been started. */ + virtual void prepareImport(); + +private: + VbaProject( const VbaProject& ) = delete; + VbaProject& operator=( const VbaProject& ) = delete; + + /** Returns the Basic or dialog library container. */ + css::uno::Reference< css::script::XLibraryContainer > + getLibraryContainer( sal_Int32 nPropId ); + /** Opens a Basic or dialog library, creates missing if not found. */ + css::uno::Reference< css::container::XNameContainer > + openLibrary( sal_Int32 nPropId ); + /** Creates and returns the Basic library of the document used for import. */ + css::uno::Reference< css::container::XNameContainer > const & + createBasicLibrary(); + /** Creates and returns the dialog library of the document used for import. */ + css::uno::Reference< css::container::XNameContainer > const & + createDialogLibrary(); + + /** Imports the VBA code modules and forms. */ + void importVba( + StorageBase& rVbaPrjStrg, + const GraphicHelper& rGraphicHelper ); + + /** Copies the entire VBA project storage to the passed document model. */ + void copyStorage( StorageBase& rVbaPrjStrg ); + +private: + typedef RefVector< VbaMacroAttacherBase > MacroAttacherVector; + typedef ::std::map< OUString, sal_Int32 > DummyModuleMap; + + css::uno::Reference< css::uno::XComponentContext > + mxContext; ///< Component context with service manager. + css::uno::Reference< css::frame::XModel > + mxDocModel; ///< Document model used to import/export the VBA project. + css::uno::Reference< css::container::XNameContainer > + mxBasicLib; ///< The Basic library of the document used for import. + css::uno::Reference< css::container::XNameContainer > + mxDialogLib; ///< The dialog library of the document used for import. + MacroAttacherVector maMacroAttachers; ///< Objects that want to attach a VBA macro to an action. + DummyModuleMap maDummyModules; ///< Additional empty modules created on import. + OUString maPrjName; ///< Name of the VBA project. + css::uno::Reference< css::container::XNameContainer > + mxOleOverridesSink; + typedef RefMap< OUString, VbaModule > VbaModuleMap; + VbaModuleMap maModules; + VbaModuleMap maModulesByStrm; +}; + + +} // namespace oox::ole + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/animationspersist.hxx b/include/oox/ppt/animationspersist.hxx new file mode 100644 index 000000000..8c8bb766d --- /dev/null +++ b/include/oox/ppt/animationspersist.hxx @@ -0,0 +1,125 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef INCLUDED_OOX_PPT_ANIMATIONSPERSIST_HXX +#define INCLUDED_OOX_PPT_ANIMATIONSPERSIST_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace oox::ppt { + + enum { + NP_TO = 0, + NP_FROM, NP_BY, NP_USERDATA, NP_ATTRIBUTENAME, + NP_ACCELERATION, NP_AUTOREVERSE, NP_DECELERATE, NP_DURATION, NP_FILL, + NP_REPEATCOUNT, NP_REPEATDURATION, NP_RESTART, + NP_DIRECTION, NP_COLORINTERPOLATION, NP_CALCMODE, NP_TRANSFORMTYPE, + NP_PATH, + NP_ENDSYNC, NP_ITERATETYPE, NP_ITERATEINTERVAL, + NP_SUBITEM, NP_TARGET, NP_COMMAND, NP_PARAMETER, + NP_VALUES, NP_FORMULA, NP_KEYTIMES, NP_DISPLAY, + NP_HIDEDURINGSHOW, + NP_ISNARRATION, + NP_SIZE_ + }; + + typedef std::array< css::uno::Any, NP_SIZE_ > NodePropertyMap; + + + /** data for CT_TLShapeTargetElement */ + struct ShapeTargetElement + { + ShapeTargetElement() + : mnType(0) + , mnRangeType(0) + { + maRange.start = maRange.end = 0; + } + void convert( css::uno::Any & aAny, sal_Int16 & rSubType ) const; + + sal_Int32 mnType; + sal_Int32 mnRangeType; + drawingml::IndexRange maRange; + OUString msSubShapeId; + }; + + + /** data for CT_TLTimeTargetElement */ + struct AnimTargetElement + { + AnimTargetElement() + : mnType( 0 ) + {} + /** convert to a set of properties */ + css::uno::Any convert(const SlidePersistPtr & pSlide, sal_Int16 & nSubType) const; + + sal_Int32 mnType; + OUString msValue; + ShapeTargetElement maShapeTarget; + }; + + typedef std::shared_ptr< AnimTargetElement > AnimTargetElementPtr; + + struct AnimationCondition; + + typedef std::vector< AnimationCondition > AnimationConditionList; + + /** data for CT_TLTimeCondition */ + struct AnimationCondition + { + AnimationCondition() + : mnType( 0 ) + {} + + css::uno::Any convert(const SlidePersistPtr & pSlide) const; + static css::uno::Any convertList(const SlidePersistPtr & pSlide, const AnimationConditionList & l); + + AnimTargetElementPtr & getTarget() + { if(!mpTarget) mpTarget = std::make_shared(); return mpTarget; } + css::uno::Any maValue; + sal_Int32 mnType; + private: + AnimTargetElementPtr mpTarget; + }; + + + struct TimeAnimationValue + { + OUString msFormula; + OUString msTime; + css::uno::Any maValue; + }; + + typedef ::std::vector< TimeAnimationValue > TimeAnimationValueList; + +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/backgroundproperties.hxx b/include/oox/ppt/backgroundproperties.hxx new file mode 100644 index 000000000..35a209b30 --- /dev/null +++ b/include/oox/ppt/backgroundproperties.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_BACKGROUNDPROPERTIES_HXX +#define INCLUDED_OOX_PPT_BACKGROUNDPROPERTIES_HXX + +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::drawingml { struct FillProperties; } + +namespace oox::ppt { + + +class BackgroundPropertiesContext final : public ::oox::core::FragmentHandler2 +{ +public: + BackgroundPropertiesContext( ::oox::core::FragmentHandler2 const & rParent, ::oox::drawingml::FillProperties& rFillProperties ); + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + +private: + ::oox::drawingml::FillProperties& mrFillProperties; +}; + +} + +#endif // INCLUDED_OOX_PPT_BACKGROUNDPROPERTIES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/comments.hxx b/include/oox/ppt/comments.hxx new file mode 100644 index 000000000..10cad1270 --- /dev/null +++ b/include/oox/ppt/comments.hxx @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + + +#ifndef INCLUDED_OOX_PPT_COMMENTS_HXX +#define INCLUDED_OOX_PPT_COMMENTS_HXX + +#include + +#include +#include +#include + +namespace oox::ppt { + +struct CommentAuthor +{ + OUString clrIdx; + OUString id; + OUString initials; + OUString lastIdx; + OUString name; +}; + +class CommentAuthorList +{ + private: + std::vector cmAuthorLst; + + public: + void setValues(const CommentAuthorList& list); + + void addAuthor(const CommentAuthor& _author) + { + cmAuthorLst.push_back(_author); + } + + friend class Comment; +}; + +class Comment +{ + private: + OUString authorId; + OUString dt; + OUString idx; + OUString x; + OUString y; + OUString text; + css::util::DateTime aDateTime; + + void setDateTime (const OUString& datetime); + + public: + void setAuthorId(const OUString& _aId) + { + authorId = _aId; + } + void setdt(const OUString& _dt) + { + dt=_dt; + setDateTime(_dt); + } + void setidx(const OUString& _idx) + { + idx=_idx; + } + void setPoint(const OUString& _x, const OUString& _y) + { + x=_x; + y=_y; + } + void setText(const OUString& _text) + { + text = _text; + } + const OUString& get_text() const + { + return text; + } + const css::util::DateTime& getDateTime() const + { + return aDateTime; + } + sal_Int32 getIntX() const + { + return x.toInt32(); + } + sal_Int32 getIntY() const + { + return y.toInt32(); + } + OUString getAuthor ( const CommentAuthorList& list ); +}; + +class CommentList +{ + public: + std::vector cmLst; + int getSize () const + { + return static_cast(cmLst.size()); + } + const Comment& getCommentAtIndex (int index); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/customshowlistcontext.hxx b/include/oox/ppt/customshowlistcontext.hxx new file mode 100644 index 000000000..d79cfc637 --- /dev/null +++ b/include/oox/ppt/customshowlistcontext.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_CUSTOMSHOWLISTCONTEXT_HXX +#define INCLUDED_OOX_PPT_CUSTOMSHOWLISTCONTEXT_HXX + +#include + +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::ppt { + + + struct CustomShow + { + OUString maCustomShowName; + OUString mnId; + std::vector< OUString >maSldLst; + }; + + /** CT_ */ + class CustomShowListContext final : public ::oox::core::FragmentHandler2 + { + std::vector< CustomShow >& mrCustomShowList; + + public: + CustomShowListContext( ::oox::core::FragmentHandler2 const & rParent, + std::vector< CustomShow >& rCustomShowList ); + + virtual ~CustomShowListContext( ) override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + }; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/headerfooter.hxx b/include/oox/ppt/headerfooter.hxx new file mode 100644 index 000000000..e304f3c6e --- /dev/null +++ b/include/oox/ppt/headerfooter.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_HEADERFOOTER_HXX +#define INCLUDED_OOX_PPT_HEADERFOOTER_HXX + +namespace oox::ppt { + + struct HeaderFooter + { + bool mbSlideNumber; + bool mbHeader; + bool mbFooter; + bool mbDateTime; + + HeaderFooter() + : mbSlideNumber( true ) + , mbHeader( true ) + , mbFooter( true ) + , mbDateTime( true ) {}; + }; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/layoutfragmenthandler.hxx b/include/oox/ppt/layoutfragmenthandler.hxx new file mode 100644 index 000000000..41fb7a85b --- /dev/null +++ b/include/oox/ppt/layoutfragmenthandler.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_LAYOUTFRAGMENTHANDLER_HXX +#define INCLUDED_OOX_PPT_LAYOUTFRAGMENTHANDLER_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class XmlFilterBase; } + +namespace oox::ppt { + +class LayoutFragmentHandler final : public SlideFragmentHandler +{ +public: + LayoutFragmentHandler(::oox::core::XmlFilterBase& rFilter, const OUString& rFragmentPath, + const SlidePersistPtr& pMasterPersistPtr); + virtual ~LayoutFragmentHandler() override; + + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; +}; + +} + +#endif // INCLUDED_OOX_PPT_LAYOUTFRAGMENTHANDLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptfilterhelpers.hxx b/include/oox/ppt/pptfilterhelpers.hxx new file mode 100644 index 000000000..58547d9e7 --- /dev/null +++ b/include/oox/ppt/pptfilterhelpers.hxx @@ -0,0 +1,99 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTFILTERHELPERS_HXX +#define INCLUDED_OOX_PPT_PPTFILTERHELPERS_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace animations { class XAnimationNode; } +} + +namespace oox::ppt { + + // conversion of MS to OOo attributes. + enum class AnimationAttributeEnum + { + PPT_X, PPT_Y, PPT_W, PPT_H, PPT_C, R, XSHEAR, FILLCOLOR, FILLTYPE, + FILLON, STROKECOLOR, STROKEON, STYLECOLOR, STYLEROTATION, FONTWEIGHT, + STYLEUNDERLINE, STYLEFONTFAMILY, STYLEFONTSIZE, STYLEFONTSTYLE, + STYLEVISIBILITY, STYLEOPACITY, UNKNOWN + }; + + struct ImplAttributeNameConversion + { + AnimationAttributeEnum meAttribute; + const char* mpMSName; + const char* mpAPIName; + }; + + OOX_DLLPUBLIC const ImplAttributeNameConversion *getAttributeConversionList(); + + struct OOX_DLLPUBLIC transition + { + const char* mpName; + sal_Int16 mnType; + sal_Int16 mnSubType; + bool mbDirection; // true: default geometric direction + + static const transition* getList(); + static const transition* find( std::u16string_view rName ); + }; + + struct OOX_DLLPUBLIC convert_subtype + { + sal_Int32 mnID; + const char* mpStrSubType; + + static const convert_subtype* getList(); + }; + + struct OOX_DLLPUBLIC preset_mapping + { + sal_Int32 mnPresetClass; + sal_Int32 mnPresetId; + const char* mpStrPresetId; + + static const preset_mapping* getList(); + }; + + OOX_DLLPUBLIC OUString getConvertedSubType( sal_Int16 nPresetClass, sal_Int32 nPresetId, sal_Int32 nPresetSubType ); + + OOX_DLLPUBLIC void fixMainSequenceTiming( const css::uno::Reference< css::animations::XAnimationNode >& xNode ); + + OOX_DLLPUBLIC void fixInteractiveSequenceTiming( const css::uno::Reference< css::animations::XAnimationNode >& xNode ); + + /** convert attribute values of the animation target so that LibreOffice understand. + */ + OOX_DLLPUBLIC bool convertAnimationValue(AnimationAttributeEnum eAttribute, css::uno::Any& rValue); + + /** convert the measure string to LibreOffice format. + * i.e. convert occurrence of #{0,1}ppt_[xywh] to x,y, width, height. + */ + OOX_DLLPUBLIC bool convertMeasure(OUString& rString); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptgraphicshapecontext.hxx b/include/oox/ppt/pptgraphicshapecontext.hxx new file mode 100644 index 000000000..bdc1f7d77 --- /dev/null +++ b/include/oox/ppt/pptgraphicshapecontext.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTGRAPHICSHAPECONTEXT_HXX +#define INCLUDED_OOX_PPT_PPTGRAPHICSHAPECONTEXT_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class ContextHandler2Helper; } + +namespace oox::ppt { + +class PPTGraphicShapeContext final : public ::oox::drawingml::GraphicShapeContext +{ + SlidePersistPtr mpSlidePersistPtr; + +public: + PPTGraphicShapeContext( ::oox::core::ContextHandler2Helper const & rParent, const SlidePersistPtr& rSlidePersistPtr, const oox::drawingml::ShapePtr& pMasterShapePtr, const oox::drawingml::ShapePtr& pShapePtr ); + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; +}; + +} + +#endif // OOX_PPT_PPTGRAPHICSHAPEGROUPCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptimport.hxx b/include/oox/ppt/pptimport.hxx new file mode 100644 index 000000000..2d7367c4c --- /dev/null +++ b/include/oox/ppt/pptimport.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTIMPORT_HXX +#define INCLUDED_OOX_PPT_PPTIMPORT_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace beans { struct PropertyValue; } + namespace uno { class XComponentContext; } +} + +namespace oox { + class GraphicHelper; + namespace drawingml::chart { class ChartConverter; } + namespace ole { class VbaProject; } + namespace vml { class Drawing; } +} + +namespace oox::ppt { + + +class PowerPointImport final : public oox::core::XmlFilterBase +{ +public: + /// @throws css::uno::RuntimeException + PowerPointImport( const css::uno::Reference< css::uno::XComponentContext >& rxContext ); + virtual ~PowerPointImport() override; + + // from FilterBase + virtual bool importDocument() override; + virtual bool exportDocument() noexcept override; + + virtual const ::oox::drawingml::Theme* getCurrentTheme() const override; + virtual ::oox::vml::Drawing* getVmlDrawing() override; + virtual oox::drawingml::table::TableStyleListPtr getTableStyles() override; + virtual ::oox::drawingml::chart::ChartConverter* getChartConverter() override; + + const SlidePersistPtr& getActualSlidePersist() const { return mpActualSlidePersist; }; + void setActualSlidePersist( SlidePersistPtr pActualSlidePersist ){ mpActualSlidePersist = pActualSlidePersist; }; + std::map< OUString, oox::drawingml::ThemePtr >& getThemes(){ return maThemes; }; + std::vector< SlidePersistPtr >& getDrawPages(){ return maDrawPages; }; + std::vector< SlidePersistPtr >& getMasterPages(){ return maMasterPages; }; + std::vector< SlidePersistPtr >& getNotesPages(){ return maNotesPages; }; + + virtual sal_Bool SAL_CALL filter( const css::uno::Sequence< css::beans::PropertyValue >& rDescriptor ) override; + + ::Color getSchemeColor( sal_Int32 nToken ) const; + virtual std::shared_ptr<::oox::drawingml::Theme> getCurrentThemePtr() const override; + +#if OSL_DEBUG_LEVEL > 0 + static XmlFilterBase* mpDebugFilterBase; +#endif + +private: + virtual GraphicHelper* implCreateGraphicHelper() const override; + virtual ::oox::ole::VbaProject* implCreateVbaProject() const override; + virtual OUString SAL_CALL getImplementationName() override; + +private: + OUString maTableStyleListPath; + oox::drawingml::table::TableStyleListPtr mpTableStyleList; + + SlidePersistPtr mpActualSlidePersist; + std::map< OUString, oox::drawingml::ThemePtr > maThemes; + + std::vector< SlidePersistPtr > maDrawPages; + std::vector< SlidePersistPtr > maMasterPages; + std::vector< SlidePersistPtr > maNotesPages; + + std::shared_ptr< ::oox::drawingml::chart::ChartConverter > mxChartConv; +}; + +} + +#endif // INCLUDED_OOX_PPT_PPTIMPORT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptshape.hxx b/include/oox/ppt/pptshape.hxx new file mode 100644 index 000000000..ead382b52 --- /dev/null +++ b/include/oox/ppt/pptshape.hxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTSHAPE_HXX +#define INCLUDED_OOX_PPT_PPTSHAPE_HXX + +#include + +#include +#include +#include +#include +#include +#include + +namespace basegfx { class B2DHomMatrix; } + +namespace com::sun::star { + namespace awt { struct Rectangle; } + namespace drawing { class XShapes; } +} + +namespace oox { + namespace core { class XmlFilterBase; } + namespace drawingml { class Theme; } + template class OptValue; +} + +namespace oox::ppt { + +class PPTShape final : public oox::drawingml::Shape +{ + OUString msModelId; // fallback dgs smartart shape reference + ShapeLocation meShapeLocation; // placeholdershapes (mnSubType != 0) on Master are never displayed + bool mbReferenced; // placeholdershapes on Layout are displayed only, if they are not referenced + // placeholdershapes on Slide are displayed always + oox::drawingml::ShapePtr mpPlaceholder; + /// Set if spPr tag is non empty for the shape + bool mbHasNoninheritedShapeProperties; + + bool IsPlaceHolderCandidate(const SlidePersist& rSlidePersist) const; + +public: + + PPTShape( const oox::ppt::ShapeLocation eShapeLocation, + const char* pServiceType ); + virtual ~PPTShape() override; + + using oox::drawingml::Shape::addShape; + // addShape is creating and inserting the corresponding XShape. + void addShape( + oox::core::XmlFilterBase& rFilterBase, + const SlidePersist& rPersist, + const oox::drawingml::Theme* pTheme, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + basegfx::B2DHomMatrix& aTransformation, + ::oox::drawingml::ShapeIdMap* pShapeMap ); + + ShapeLocation getShapeLocation() const { return meShapeLocation; }; + void setReferenced( bool bReferenced ){ mbReferenced = bReferenced; }; + void setPlaceholder( oox::drawingml::ShapePtr pPlaceholder ) { mpPlaceholder = pPlaceholder; } + void setModelId( const OUString& rId ) { msModelId = rId; } + + /// Flags shape as having a non-empty spPr tag + void setHasNoninheritedShapeProperties() { mbHasNoninheritedShapeProperties = true; } + /// Returns whether or not the shape had a non-empty spPr tag + bool hasNonInheritedShapeProperties() const { return mbHasNoninheritedShapeProperties; } + + static oox::drawingml::ShapePtr findPlaceholder( const sal_Int32 nFirstSubType, + const sal_Int32 nSecondSubType, const OptValue< sal_Int32 >& oSubTypeIndex, + std::vector< oox::drawingml::ShapePtr >& rShapes, bool bMasterOnly = false ); + static oox::drawingml::ShapePtr findPlaceholderByIndex( const sal_Int32 nIdx, + std::vector< oox::drawingml::ShapePtr >& rShapes, bool bMasterOnly = false ); + + static oox::drawingml::TextListStylePtr getSubTypeTextListStyle( const SlidePersist& rSlidePersist, sal_Int32 nSubType ); +}; + +} + +#endif // INCLUDED_OOX_PPT_PPTSHAPE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptshapecontext.hxx b/include/oox/ppt/pptshapecontext.hxx new file mode 100644 index 000000000..5d5277502 --- /dev/null +++ b/include/oox/ppt/pptshapecontext.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTSHAPECONTEXT_HXX +#define INCLUDED_OOX_PPT_PPTSHAPECONTEXT_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class ContextHandler2Helper; } + +namespace oox::ppt { + +class PPTShapeContext final : public ::oox::drawingml::ShapeContext +{ + SlidePersistPtr mpSlidePersistPtr; + +public: + PPTShapeContext( ::oox::core::ContextHandler2Helper const & rParent, const SlidePersistPtr& rSlidePersistPtr, const oox::drawingml::ShapePtr& pMasterShapePtr, const oox::drawingml::ShapePtr& pShapePtr ); + virtual ::oox::core::ContextHandlerRef onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; +}; + +} + +#endif // INCLUDED_OOX_PPT_PPTSHAPECONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptshapegroupcontext.hxx b/include/oox/ppt/pptshapegroupcontext.hxx new file mode 100644 index 000000000..89f8ca65d --- /dev/null +++ b/include/oox/ppt/pptshapegroupcontext.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTSHAPEGROUPCONTEXT_HXX +#define INCLUDED_OOX_PPT_PPTSHAPEGROUPCONTEXT_HXX + +#include +#include +#include +#include +#include + +namespace oox { + class AttributeList; + namespace core { class ContextHandler2Helper; } + namespace drawingml { class Color; } +} + +namespace oox::ppt { + +class PPTShapeGroupContext final : public ::oox::drawingml::ShapeGroupContext +{ + SlidePersistPtr mpSlidePersistPtr; + ShapeLocation meShapeLocation; + oox::drawingml::ShapePtr pGraphicShape; + + void applyFontRefColor(const oox::drawingml::ShapePtr& pShape, const oox::drawingml::Color& rFontRefColor); + +public: + PPTShapeGroupContext( + ::oox::core::FragmentHandler2 const & rParent, + const oox::ppt::SlidePersistPtr& rSlidePersistPtr, + const oox::ppt::ShapeLocation eShapeLocation, + const oox::drawingml::ShapePtr& pMasterShapePtr, + const oox::drawingml::ShapePtr& pGroupShapePtr ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; + + void importExtDrawings(); + +protected: + +}; + +} + +#endif // INCLUDED_OOX_PPT_PPTSHAPEGROUPCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/pptshapepropertiescontext.hxx b/include/oox/ppt/pptshapepropertiescontext.hxx new file mode 100644 index 000000000..124d7545d --- /dev/null +++ b/include/oox/ppt/pptshapepropertiescontext.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PPTSHAPEPROPERTIESCONTEXT_HXX +#define INCLUDED_OOX_PPT_PPTSHAPEPROPERTIESCONTEXT_HXX + +#include +#include +#include + +namespace oox { + class AttributeList; + namespace core { class ContextHandler2Helper; } + namespace drawingml { class Shape; } +} + +namespace oox::ppt { + +class PPTShapePropertiesContext final : public ::oox::drawingml::ShapePropertiesContext +{ +public: + PPTShapePropertiesContext( ::oox::core::ContextHandler2Helper const & rParent, ::oox::drawingml::Shape& rShape ); + virtual ::oox::core::ContextHandlerRef + onCreateContext( ::sal_Int32 Element, const ::oox::AttributeList& rAttribs ) override; +}; + +} + +#endif // INCLUDED_OOX_PPT_PPTSHAPEPROPERTIESCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/presPropsfragmenthandler.hxx b/include/oox/ppt/presPropsfragmenthandler.hxx new file mode 100644 index 000000000..18a2a97aa --- /dev/null +++ b/include/oox/ppt/presPropsfragmenthandler.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OOX_PPT_PRESPROPSFRAGMENTHANDLER_HXX +#define INCLUDED_OOX_PPT_PRESPROPSFRAGMENTHANDLER_HXX + +#include + +namespace oox +{ +namespace core +{ +class XmlFilterBase; +} + +namespace ppt +{ +class PresPropsFragmentHandler final : public core::FragmentHandler2 +{ +public: + PresPropsFragmentHandler(core::XmlFilterBase& rFilter, const OUString& rFragmentPath); + virtual ~PresPropsFragmentHandler() override; + virtual void finalizeImport() override; + virtual core::ContextHandlerRef onCreateContext(sal_Int32 aElementToken, + const AttributeList& rAttribs) override; + +private: + bool m_bLoop = false; + bool m_bTiming = true; + OUString m_sId; + OUString m_sSt; +}; +} // namespace ppt +} // namespace oox + +#endif // INCLUDED_OOX_PPT_PRESPROPSFRAGMENTHANDLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/oox/ppt/presentationfragmenthandler.hxx b/include/oox/ppt/presentationfragmenthandler.hxx new file mode 100644 index 000000000..a9bb5bb67 --- /dev/null +++ b/include/oox/ppt/presentationfragmenthandler.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_PRESENTATIONFRAGMENTHANDLER_HXX +#define INCLUDED_OOX_PPT_PRESENTATIONFRAGMENTHANDLER_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class XmlFilterBase; } + +namespace oox::ppt { + +class PresentationFragmentHandler final : public ::oox::core::FragmentHandler2 +{ +public: + PresentationFragmentHandler(::oox::core::XmlFilterBase& rFilter, const OUString& rFragmentPath); + virtual ~PresentationFragmentHandler() noexcept override; + virtual void finalizeImport() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + +private: + void importSlide( const ::oox::core::FragmentHandlerRef& rSlideFragmentHandler, + const oox::ppt::SlidePersistPtr& rPersist ); + void importSlide(sal_uInt32 nSlide, bool bFirstSlide, bool bImportNotes); + void saveThemeToGrabBag(const oox::drawingml::ThemePtr& pThemePtr, sal_Int32 nThemeIdx); + void importCustomSlideShow(std::vector& rCustomShowList); + + std::vector< OUString > maSlideMasterVector; + std::vector< OUString > maSlidesVector; + std::vector< OUString > maNotesMasterVector; + ::oox::drawingml::TextListStylePtr mpTextListStyle; + + css::awt::Size maSlideSize; + css::awt::Size maNotesSize; + + std::vector< CustomShow > maCustomShowList; + + CommentAuthorList maAuthorList; + bool mbCommentAuthorsRead; // read commentAuthors.xml only once +}; + +} + +#endif // INCLUDED_OOX_PPT_PRESENTATIONFRAGMENTHANDLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/slidefragmenthandler.hxx b/include/oox/ppt/slidefragmenthandler.hxx new file mode 100644 index 000000000..b7d1d59b3 --- /dev/null +++ b/include/oox/ppt/slidefragmenthandler.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_SLIDEFRAGMENTHANDLER_HXX +#define INCLUDED_OOX_PPT_SLIDEFRAGMENTHANDLER_HXX + +#include + +#include +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } +namespace oox::core { class XmlFilterBase; } + +namespace oox::ppt { + +class SlideFragmentHandler : public ::oox::core::FragmentHandler2 +{ +public: + SlideFragmentHandler( ::oox::core::XmlFilterBase& rFilter, const OUString& rFragmentPath, const SlidePersistPtr& pPersistPtr, const ShapeLocation eShapeLocation ); + virtual ~SlideFragmentHandler() override; + + virtual void finalizeImport() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + virtual void onCharacters( const OUString& rChars ) override; + + const ::std::vector< OUString>& getCharVector() const { return maCharVector; } + +protected: + SlidePersistPtr mpSlidePersistPtr; + ShapeLocation meShapeLocation; + +private: + OUString maSlideName; + PropertyMap maSlideProperties; + ::std::vector< OUString> maCharVector; // handle char in OnCharacters +}; + +} + +#endif // INCLUDED_OOX_PPT_SLIDEFRAGMENTHANDLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/slidemastertextstylescontext.hxx b/include/oox/ppt/slidemastertextstylescontext.hxx new file mode 100644 index 000000000..4d051ab8e --- /dev/null +++ b/include/oox/ppt/slidemastertextstylescontext.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_SLIDEMASTERTEXTSTYLESCONTEXT_HXX +#define INCLUDED_OOX_PPT_SLIDEMASTERTEXTSTYLESCONTEXT_HXX + +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::ppt { + +class SlideMasterTextStylesContext final : public oox::core::FragmentHandler2 +{ +public: + SlideMasterTextStylesContext( ::oox::core::FragmentHandler2 const & rParent, SlidePersistPtr const & pSlidePersistPtr ); + virtual ~SlideMasterTextStylesContext() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + +private: + SlidePersistPtr mpSlidePersistPtr; +}; + +} + +#endif // INCLUDED_OOX_PPT_SLIDEMASTERTEXTSTYLESCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/slidepersist.hxx b/include/oox/ppt/slidepersist.hxx new file mode 100644 index 000000000..4ba48637c --- /dev/null +++ b/include/oox/ppt/slidepersist.hxx @@ -0,0 +1,173 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_SLIDEPERSIST_HXX +#define INCLUDED_OOX_PPT_SLIDEPERSIST_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace animations { class XAnimationNode; } + namespace drawing { class XDrawPage; } +} + +namespace oox::core { class XmlFilterBase; } +namespace oox::vml { class Drawing; } + +namespace oox::ppt { + +enum ShapeLocation +{ + Master, + Layout, + Slide +}; + + +class TimeNode; +class SlidePersist; + +typedef std::shared_ptr< SlidePersist > SlidePersistPtr; + +class SlidePersist : public std::enable_shared_from_this< SlidePersist > +{ + +public: + SlidePersist( oox::core::XmlFilterBase& rFilter, bool bMaster, bool bNotes, + const css::uno::Reference< css::drawing::XDrawPage >&, + oox::drawingml::ShapePtr const & pShapesPtr, const ::oox::drawingml::TextListStylePtr & ); + ~SlidePersist(); + + + const css::uno::Reference< css::drawing::XDrawPage >& getPage() const { return mxPage; }; + +#if OSL_DEBUG_LEVEL > 0 + static css::uno::WeakReference< css::drawing::XDrawPage > mxDebugPage; +#endif + + void setMasterPersist( SlidePersistPtr pMasterPersistPtr ){ mpMasterPagePtr = pMasterPersistPtr; } + const SlidePersistPtr& getMasterPersist() const { return mpMasterPagePtr; } + + void setPath( const OUString& rPath ) { maPath = rPath; } + const OUString& getPath() const { return maPath; } + + void setLayoutPath( const OUString& rLayoutPath ) { maLayoutPath = rLayoutPath; } + const OUString& getLayoutPath() const { return maLayoutPath; } + + void setTheme( const oox::drawingml::ThemePtr& rThemePtr ){ mpThemePtr = rThemePtr; } + const oox::drawingml::ThemePtr& getTheme() const { return mpThemePtr; } + + void setClrMap( const oox::drawingml::ClrMapPtr pClrMapPtr ){ mpClrMapPtr = pClrMapPtr; } + const oox::drawingml::ClrMapPtr& getClrMap() const { return mpClrMapPtr; } + + void setBackgroundProperties( const oox::drawingml::FillPropertiesPtr& rFillPropertiesPtr ){ mpBackgroundPropertiesPtr = rFillPropertiesPtr; } + const oox::drawingml::FillPropertiesPtr& getBackgroundProperties() const { return mpBackgroundPropertiesPtr; } + oox::drawingml::Color& getBackgroundColor() { return maBackgroundColor; } + + bool isMasterPage() const { return mbMaster; } + bool isNotesPage() const { return mbNotes; } + + void setLayoutValueToken( sal_Int32 nLayoutValueToken ) { mnLayoutValueToken = nLayoutValueToken; } + sal_Int16 getLayoutFromValueToken() const; + + + const oox::drawingml::TextListStylePtr& getDefaultTextStyle() const { return maDefaultTextStylePtr; } + const oox::drawingml::TextListStylePtr& getTitleTextStyle() const { return maTitleTextStylePtr; } + const oox::drawingml::TextListStylePtr& getBodyTextStyle() const { return maBodyTextStylePtr; } + const oox::drawingml::TextListStylePtr& getNotesTextStyle() const { return maNotesTextStylePtr; } + const oox::drawingml::TextListStylePtr& getOtherTextStyle() const { return maOtherTextStylePtr; } + + const oox::drawingml::ShapePtr& getShapes() const { return maShapesPtr; } + void hideShapesAsMasterShapes(); + ::std::vector< std::shared_ptr< TimeNode > >& getTimeNodeList() { return maTimeNodeList; } + oox::ppt::HeaderFooter& getHeaderFooter(){ return maHeaderFooter; }; + + oox::vml::Drawing* getDrawing() { return mpDrawingPtr.get(); } + + void createXShapes( oox::core::XmlFilterBase& rFilterBase ); + void createBackground( const oox::core::XmlFilterBase& rFilterBase ); + void applyTextStyles( const oox::core::XmlFilterBase& rFilterBase ); + + std::map< OUString, css::uno::Reference< css::animations::XAnimationNode > >& getAnimNodesMap() { return maAnimNodesMap; }; + css::uno::Reference getAnimationNode(const OUString& sId) const; + ::oox::drawingml::ShapePtr getShape( const OUString & id ) { return maShapeMap[ id ]; } + ::oox::drawingml::ShapeIdMap& getShapeMap() { return maShapeMap; } + + CommentList& getCommentsList() { return maCommentsList; } + CommentAuthorList& getCommentAuthors() { return maCommentAuthors; } + + void createConnectorShapeConnection(); + + void addURLShapeId(const OUString& rShapeId) { maURLShapeId.push_back(rShapeId); } + std::vector& getURLShapeId() { return maURLShapeId; } + +private: + OUString maPath; + OUString maLayoutPath; + std::shared_ptr< oox::vml::Drawing > mpDrawingPtr; + css::uno::Reference< css::drawing::XDrawPage > mxPage; + oox::drawingml::ThemePtr mpThemePtr; // the theme that is used + oox::drawingml::ClrMapPtr mpClrMapPtr; // color mapping (if any) + SlidePersistPtr mpMasterPagePtr; + + oox::drawingml::ShapePtr maShapesPtr; + oox::drawingml::Color maBackgroundColor; + oox::drawingml::FillPropertiesPtr mpBackgroundPropertiesPtr; + ::std::vector< std::shared_ptr< TimeNode > > maTimeNodeList; + + oox::ppt::HeaderFooter maHeaderFooter; + sal_Int32 mnLayoutValueToken; + bool mbMaster; + bool mbNotes; + + oox::drawingml::TextListStylePtr maDefaultTextStylePtr; + oox::drawingml::TextListStylePtr maTitleTextStylePtr; + oox::drawingml::TextListStylePtr maBodyTextStylePtr; + oox::drawingml::TextListStylePtr maNotesTextStylePtr; + oox::drawingml::TextListStylePtr maOtherTextStylePtr; + + std::map< OUString, css::uno::Reference< css::animations::XAnimationNode > > maAnimNodesMap; + std::map< OUString, ::oox::drawingml::ShapePtr > maShapeMap; + + // slide comments + CommentList maCommentsList; + CommentAuthorList maCommentAuthors; + + std::vector maConnectorShapeId; + std::vector maURLShapeId; +}; + +} + +#endif // INCLUDED_OOX_PPT_SLIDEPERSIST_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/slidetimingcontext.hxx b/include/oox/ppt/slidetimingcontext.hxx new file mode 100644 index 000000000..7b147ab85 --- /dev/null +++ b/include/oox/ppt/slidetimingcontext.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_SLIDETIMINGCONTEXT_HXX +#define INCLUDED_OOX_PPT_SLIDETIMINGCONTEXT_HXX + +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::ppt { + +class SlideTimingContext final : public ::oox::core::FragmentHandler2 +{ +public: + SlideTimingContext( ::oox::core::FragmentHandler2 const & rParent, TimeNodePtrList & aTimeNodeList ) noexcept; + virtual ~SlideTimingContext() noexcept override; + + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + +private: + TimeNodePtrList & maTimeNodeList; +}; + +} + +#endif // INCLUDED_OOX_PPT_SLIDETIMINGCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/slidetransition.hxx b/include/oox/ppt/slidetransition.hxx new file mode 100644 index 000000000..01603b9fa --- /dev/null +++ b/include/oox/ppt/slidetransition.hxx @@ -0,0 +1,82 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef INCLUDED_OOX_PPT_SLIDETRANSITION_HXX +#define INCLUDED_OOX_PPT_SLIDETRANSITION_HXX + +#include +#include +#include +#include + +namespace com::sun::star { + namespace animations { class XTransitionFilter; } +} + +namespace oox { class PropertyMap; } + +namespace oox::ppt { + + class SlideTransition + { + public: + SlideTransition(); + explicit SlideTransition(std::u16string_view ); + + void setSlideProperties( PropertyMap& props ); + void setTransitionFilterProperties( const css::uno::Reference< css::animations::XTransitionFilter > & xFilter ); + + /// Set one of standard values for slide transition duration + void setOoxTransitionSpeed( sal_Int32 nToken ); + /// Set slide transition time directly + void setOoxTransitionSpeed( double fDuration ); + void setMode( bool bMode ) + { mbMode = bMode; } + void setOoxAdvanceTime( sal_Int32 nAdvanceTime ) + { mnAdvanceTime = nAdvanceTime; } + + static sal_Int16 ooxToOdpDirection( ::sal_Int32 nOoxType ); + static sal_Int16 ooxToOdpEightDirections( ::sal_Int32 nOoxType ); + static sal_Int16 ooxToOdpCornerDirections( ::sal_Int32 nOoxType ); + static sal_Int16 ooxToOdpBorderDirections( ::sal_Int32 nOoxType ); + static sal_Int16 ooxToOdpSideDirections( ::sal_Int32 nOoxType ); + static bool ooxToOdpSideDirectionsDirectionNormal( ::sal_Int32 nOoxType ); + + void setOoxTransitionType( ::sal_Int32 OoxType, + ::sal_Int32 param1, ::sal_Int32 param2 ); + + void setPresetTransition(std::u16string_view sPresetTransition); + + private: + ::sal_Int16 mnTransitionType; + ::sal_Int16 mnTransitionSubType; + bool mbTransitionDirectionNormal; + css::presentation::AnimationSpeed mnAnimationSpeed; + double mfTransitionDurationInSeconds; + bool mbMode; /**< https://api.libreoffice.org/docs/common/ref/com/sun/star/animations/XTransitionFilter.html Mode property */ + ::sal_Int32 mnAdvanceTime; + ::sal_Int32 mnTransitionFadeColor; + }; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/slidetransitioncontext.hxx b/include/oox/ppt/slidetransitioncontext.hxx new file mode 100644 index 000000000..f28b763c6 --- /dev/null +++ b/include/oox/ppt/slidetransitioncontext.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_SLIDETRANSITIONCONTEXT_HXX +#define INCLUDED_OOX_PPT_SLIDETRANSITIONCONTEXT_HXX + +#include +#include +#include +#include + +namespace oox { + class AttributeList; + class PropertyMap; +} + +namespace oox::ppt { + + class SlideTransitionContext final : public ::oox::core::FragmentHandler2 + { + public: + SlideTransitionContext( ::oox::core::FragmentHandler2 const & rParent, + const AttributeList& rAttributes, + PropertyMap & aProperties ) noexcept; + virtual ~SlideTransitionContext() noexcept override; + + virtual void onEndElement() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + + + private: + PropertyMap& maSlideProperties; + bool mbHasTransition; + bool mbHasTransitionDuration; + SlideTransition maTransition; + }; + +} + +#endif // INCLUDED_OOX_PPT_SLIDETRANSITIONCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/soundactioncontext.hxx b/include/oox/ppt/soundactioncontext.hxx new file mode 100644 index 000000000..4bf66a5f7 --- /dev/null +++ b/include/oox/ppt/soundactioncontext.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef INCLUDED_OOX_PPT_SOUNDACTIONCONTEXT_HXX +#define INCLUDED_OOX_PPT_SOUNDACTIONCONTEXT_HXX + +#include +#include +#include +#include + +namespace oox { + class AttributeList; + class PropertyMap; +} + +namespace oox::ppt { + +class SoundActionContext final : public ::oox::core::FragmentHandler2 +{ +public: + SoundActionContext( ::oox::core::FragmentHandler2 const & rParent, PropertyMap & aProperties ) noexcept; + virtual ~SoundActionContext() noexcept override; + + virtual void onEndElement() override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + +private: + PropertyMap& maSlideProperties; + bool mbHasStartSound; + bool mbLoopSound; + bool mbStopSound; + OUString msSndName; +}; + +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/timenode.hxx b/include/oox/ppt/timenode.hxx new file mode 100644 index 000000000..195e4472e --- /dev/null +++ b/include/oox/ppt/timenode.hxx @@ -0,0 +1,128 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#ifndef INCLUDED_OOX_PPT_TIMENODE_HXX +#define INCLUDED_OOX_PPT_TIMENODE_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace animations { class XAnimationNode; } +} + +namespace oox::core { class XmlFilterBase; } + +namespace oox::ppt { + + class TimeNode; + + typedef std::shared_ptr< TimeNode > TimeNodePtr; + typedef std::vector< TimeNodePtr > TimeNodePtrList; + + class TimeNode final + { + public: + typedef ::std::map< OUString, css::uno::Any > UserDataMap; + + TimeNode( sal_Int16 nNodeType ); + ~TimeNode(); + + NodePropertyMap & getNodeProperties() { return maNodeProperties; } + UserDataMap & getUserData() { return maUserData; } + TimeNodePtrList & getChildren() + { return maChildren; } + + void setId( sal_Int32 nId ); + + void addNode( + const ::oox::core::XmlFilterBase& rFilter, + const css::uno::Reference< css::animations::XAnimationNode >& rxNode, + const SlidePersistPtr & slide); + // data setters + void setTo( const css::uno::Any & aTo ); + void setFrom( const css::uno::Any & aFrom ); + void setBy( const css::uno::Any & aBy ); + void setTransitionFilter( const SlideTransition & aTransition) + { maTransitionFilter = aTransition; } + + void setNode( + const ::oox::core::XmlFilterBase& rFilter, + const css::uno::Reference< css::animations::XAnimationNode >& xNode, + const SlidePersistPtr & pSlide, + const css::uno::Reference< css::animations::XAnimationNode >& xParent); + + AnimTargetElementPtr const & getTarget() + { + if( !mpTarget ) + mpTarget = std::make_shared(); + return mpTarget; + } + + AnimationConditionList &getStartCondition() + { return maStCondList; } + AnimationConditionList &getEndCondition() + { return maEndCondList; } + AnimationConditionList &getNextCondition() + { return maNextCondList; } + AnimationConditionList &getPrevCondition() + { return maPrevCondList; } + AnimationCondition & getEndSyncValue() + { mbHasEndSyncValue = true; return maEndSyncValue; } + private: + + static OUString getServiceName( sal_Int16 nNodeType ); + + static css::uno::Reference< css::animations::XAnimationNode > + createAndInsert( + const ::oox::core::XmlFilterBase& rFilter, + const OUString& rServiceName, + const css::uno::Reference< css::animations::XAnimationNode >& rxNode ); + + const sal_Int16 mnNodeType; + + TimeNodePtrList maChildren; + + OUString msId; + NodePropertyMap maNodeProperties; + UserDataMap maUserData; // a sequence to be stored as "UserData" property + SlideTransition maTransitionFilter; + AnimTargetElementPtr mpTarget; + bool mbHasEndSyncValue; // set to true if we try to get the endSync. + AnimationCondition maEndSyncValue; + AnimationConditionList maStCondList, maEndCondList; + AnimationConditionList maPrevCondList, maNextCondList; + }; + +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/ppt/timenodelistcontext.hxx b/include/oox/ppt/timenodelistcontext.hxx new file mode 100644 index 000000000..82e7e67b9 --- /dev/null +++ b/include/oox/ppt/timenodelistcontext.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_PPT_TIMENODELISTCONTEXT_HXX +#define INCLUDED_OOX_PPT_TIMENODELISTCONTEXT_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace xml::sax { class XFastAttributeList; } +} + +namespace oox { class AttributeList; } + +namespace oox::ppt { + + + class TimeNodeContext : public ::oox::core::FragmentHandler2 + { + public: + virtual ~TimeNodeContext() noexcept override; + + static rtl::Reference makeContext( ::oox::core::FragmentHandler2 const & rParent, sal_Int32 aElement, const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttribs, const TimeNodePtr & pNode ); + + protected: + TimeNodeContext( ::oox::core::FragmentHandler2 const & rParent, sal_Int32 aElement, const TimeNodePtr & pNode ) noexcept; + + sal_Int32 mnElement; + TimeNodePtr mpNode; + }; + + +/** FastParser context for XML_tnLst, XML_subTnLst and XML_childTnLst */ +class TimeNodeListContext final : public ::oox::core::FragmentHandler2 +{ +public: + TimeNodeListContext( ::oox::core::FragmentHandler2 const & rParent, TimeNodePtrList & aList ) noexcept; + + virtual ~TimeNodeListContext() noexcept override; + virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs ) override; + + +private: + TimeNodePtrList & maList; +}; + +} + +#endif // INCLUDED_OOX_PPT_TIMENODELISTCONTEXT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/shape/ShapeContextHandler.hxx b/include/oox/shape/ShapeContextHandler.hxx new file mode 100644 index 000000000..2e108d8cd --- /dev/null +++ b/include/oox/shape/ShapeContextHandler.hxx @@ -0,0 +1,156 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace oox::shape { + +class ShapeFilterBase; + +class ShapeFragmentHandler final : public core::FragmentHandler2 +{ +public: + typedef rtl::Reference Pointer_t; + + explicit ShapeFragmentHandler(core::XmlFilterBase& rFilter, + const OUString& rFragmentPath ) + : FragmentHandler2(rFilter, rFragmentPath) + { + } +}; + +class OOX_DLLPUBLIC ShapeContextHandler final : + public ::cppu::WeakImplHelper< css::xml::sax::XFastContextHandler > +{ +public: + explicit ShapeContextHandler(const rtl::Reference& xFilterBase); + + virtual ~ShapeContextHandler() override; + + // css::xml::sax::XFastContextHandler: + virtual void SAL_CALL startFastElement + (::sal_Int32 Element, + const css::uno::Reference< css::xml::sax::XFastAttributeList > & Attribs) override; + + virtual void SAL_CALL startUnknownElement + (const OUString & Namespace, + const OUString & Name, + const css::uno::Reference< css::xml::sax::XFastAttributeList > & Attribs) override; + + virtual void SAL_CALL endFastElement(::sal_Int32 Element) override; + + virtual void SAL_CALL endUnknownElement + (const OUString & Namespace, + const OUString & Name) override; + + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL + createFastChildContext + (::sal_Int32 Element, + const css::uno::Reference< css::xml::sax::XFastAttributeList > & Attribs) override; + + virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL + createUnknownChildContext + (const OUString & Namespace, + const OUString & Name, + const css::uno::Reference< css::xml::sax::XFastAttributeList > & Attribs) override; + + virtual void SAL_CALL characters(const OUString & aChars) override; + + css::uno::Reference< css::drawing::XShape > getShape(); + + void setDrawPage(const css::uno::Reference< css::drawing::XDrawPage > & the_value); + + void setModel(const css::uno::Reference< css::frame::XModel > & the_value); + + void setRelationFragmentPath(const OUString & the_value); + + sal_Int32 getStartToken() const; + void popStartToken(); + void pushStartToken( sal_Int32 _starttoken ); + + void setPosition(const css::awt::Point& rPosition); + + const bool& getFullWPGSupport() { return m_bFullWPGSUpport; } + void setFullWPGSupport(bool bUse) { m_bFullWPGSUpport = bUse; } + + bool isWordProcessingGroupShape() const { return mxWpgContext ? true : false; } + + void setDocumentProperties(const css::uno::Reference& xDocProps); + void setMediaDescriptor(const css::uno::Sequence& rMediaDescriptor); + + void setGraphicMapper(css::uno::Reference const & rGraphicMapper); + + void setTheme(const oox::drawingml::ThemePtr& pTheme) { mpThemePtr = pTheme; } + const oox::drawingml::ThemePtr& getTheme() const { return mpThemePtr; } + +private: + ShapeContextHandler(ShapeContextHandler const &) = delete; + void operator =(ShapeContextHandler const &) = delete; + + // Special stack which always has at least one element. + // In case of group shapes with embedded content it will have more element than one. + std::stack mnStartTokenStack; + + css::awt::Point maPosition; + bool m_bFullWPGSUpport; // Is this DrawingML shape supposed to be processed as WPG? + + drawingml::ShapePtr mpShape; + std::shared_ptr< vml::Drawing > mpDrawing; + + typedef rtl::Reference + GraphicShapeContextPtr; + css::uno::Reference mxDrawingFragmentHandler; + css::uno::Reference mxGraphicShapeContext; + css::uno::Reference mxDiagramShapeContext; + css::uno::Reference mxLockedCanvasContext; + css::uno::Reference mxWpsContext; + css::uno::Reference mxSavedShape; + css::uno::Reference mxWpgContext; + css::uno::Reference mxChartShapeContext; + css::uno::Reference mxDocumentProperties; + css::uno::Sequence maMediaDescriptor; + + ::rtl::Reference< ShapeFilterBase > mxShapeFilterBase; + drawingml::ThemePtr mpThemePtr; + css::uno::Reference mxDrawPage; + OUString msRelationFragmentPath; + + css::uno::Reference const & getGraphicShapeContext(::sal_Int32 Element); + css::uno::Reference const & getChartShapeContext(::sal_Int32 Element); + css::uno::Reference const & getDrawingShapeContext(); + css::uno::Reference const & getDiagramShapeContext(); + css::uno::Reference const & getLockedCanvasContext(sal_Int32 nElement); + css::uno::Reference const & getWpsContext(sal_Int32 nStartElement, sal_Int32 nElement); + css::uno::Reference const & getWpgContext(sal_Int32 nElement); + css::uno::Reference getContextHandler(sal_Int32 nElement = 0); +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/shape/ShapeFilterBase.hxx b/include/oox/shape/ShapeFilterBase.hxx new file mode 100644 index 000000000..477060fa6 --- /dev/null +++ b/include/oox/shape/ShapeFilterBase.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_SHAPE_SHAPEFILTERBASE_HXX +#define INCLUDED_OOX_SHAPE_SHAPEFILTERBASE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace oox::drawingml::table { + +class TableStyleList; +typedef std::shared_ptr< TableStyleList > TableStyleListPtr; + +} + +namespace oox::shape { + +class OOX_DLLPUBLIC ShapeFilterBase final : public core::XmlFilterBase +{ +public: + typedef rtl::Reference Pointer_t; + + /// @throws css::uno::RuntimeException + explicit ShapeFilterBase( + const css::uno::Reference< css::uno::XComponentContext >& rxContext ); + + virtual ~ShapeFilterBase() override; + + /** Has to be implemented by each filter, returns the current theme. */ + virtual const ::oox::drawingml::Theme* getCurrentTheme() const override; + + /** May be implemented by filters which handle Diagrams, default returns empty ptr */ + virtual std::shared_ptr<::oox::drawingml::Theme> getCurrentThemePtr() const override; + + void setCurrentTheme(const ::oox::drawingml::ThemePtr& pTheme); + + /** Has to be implemented by each filter to return the collection of VML shapes. */ + virtual ::oox::vml::Drawing* getVmlDrawing() override; + + /** Has to be implemented by each filter to return TableStyles. */ + virtual ::oox::drawingml::table::TableStyleListPtr getTableStyles() override; + + virtual ::oox::drawingml::chart::ChartConverter* getChartConverter() override; + + virtual bool importDocument() override { return true; } + virtual bool exportDocument() override { return true; } + + ::Color getSchemeColor( sal_Int32 nToken ) const; + + void setGraphicMapper(css::uno::Reference const & rxGraphicMapper) + { + mxGraphicMapper = rxGraphicMapper; + } + +private: + virtual ::oox::ole::VbaProject* implCreateVbaProject() const override; + virtual OUString SAL_CALL getImplementationName() override; + virtual GraphicHelper* implCreateGraphicHelper() const override; + + std::shared_ptr< ::oox::drawingml::chart::ChartConverter > mxChartConv; + ::oox::drawingml::ThemePtr mpTheme; + css::uno::Reference mxGraphicMapper; +}; + +} // namespace oox::shape + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/token/namespacemap.hxx b/include/oox/token/namespacemap.hxx new file mode 100644 index 000000000..c02a39ba7 --- /dev/null +++ b/include/oox/token/namespacemap.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_TOKEN_NAMESPACEMAP_HXX +#define INCLUDED_OOX_TOKEN_NAMESPACEMAP_HXX + +#include + +#include +#include + +namespace oox +{ +/** A map that contains all XML namespace URLs used in the filters. */ +struct NamespaceMap +{ + std::map maTransitionalNamespaceMap; + std::map maStrictNamespaceMap; + + NamespaceMap(); + + typedef std::map::iterator iterator; + typedef std::map::const_iterator const_iterator; +}; + +/** Thread-safe singleton of a map of all supported XML namespace URLs. */ +NamespaceMap& StaticNamespaceMap(); + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/token/propertynames.hxx b/include/oox/token/propertynames.hxx new file mode 100644 index 000000000..91e07cbdd --- /dev/null +++ b/include/oox/token/propertynames.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +namespace oox +{ +/** A vector that contains all predefined property names used in the filters. */ +/** Thread-safe singleton of a vector of all supported property names. */ +const std::vector& GetPropertyNameVector(); + +} // namespace oox + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/token/relationship.hxx b/include/oox/token/relationship.hxx new file mode 100644 index 000000000..3c3a4336f --- /dev/null +++ b/include/oox/token/relationship.hxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OOX_TOKEN_RELATIONSHIP_HXX +#define INCLUDED_OOX_TOKEN_RELATIONSHIP_HXX + +#include + +#include + +namespace oox +{ +enum class Relationship +{ + ACTIVEXCONTROLBINARY, + CHART, + CHARTUSERSHAPES, + COMMENTS, + COMMENTAUTHORS, + COMMENTSEXTENDED, + CONTROL, + CTRLPROP, + CUSTOMXML, + CUSTOMXMLPROPS, + DIAGRAMCOLORS, + DIAGRAMDATA, + DIAGRAMDRAWING, + DIAGRAMLAYOUT, + DIAGRAMQUICKSTYLE, + DRAWING, + ENDNOTES, + EXTERNALLINKPATH, + FONT, + FONTTABLE, + FOOTER, + FOOTNOTES, + GLOSSARYDOCUMENT, + HDPHOTO, + HEADER, + HYPERLINK, + IMAGE, + MEDIA, + NOTESMASTER, + NOTESSLIDE, + NUMBERING, + OFFICEDOCUMENT, + OLEOBJECT, + PACKAGE, + PRESPROPS, + SETTINGS, + SHAREDSTRINGS, + SLIDE, + SLIDELAYOUT, + SLIDEMASTER, + STYLES, + THEME, + VBAPROJECT, + VIDEO, + AUDIO, + VMLDRAWING, + WORDVBADATA, + WORKSHEET +}; + +OUString OOX_DLLPUBLIC getRelationship(Relationship eRelationship); +} + +#endif // INCLUDED_OOX_TOKEN_RELATIONSHIP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/token/tokenmap.hxx b/include/oox/token/tokenmap.hxx new file mode 100644 index 000000000..db71c24c2 --- /dev/null +++ b/include/oox/token/tokenmap.hxx @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_TOKEN_TOKENMAP_HXX +#define INCLUDED_OOX_TOKEN_TOKENMAP_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace oox { + + +class TokenMap +{ +public: + explicit TokenMap(); + ~TokenMap(); + + /** Returns the token identifier for the passed Unicode token name. */ + static sal_Int32 getTokenFromUnicode( std::u16string_view rUnicodeName ); + + /** Returns the UTF8 name of the passed token identifier as byte sequence. */ + css::uno::Sequence< sal_Int8 > const & + getUtf8TokenName( sal_Int32 nToken ) const + { + SAL_WARN_IF(nToken < 0 || nToken >= XML_TOKEN_COUNT, "oox", "Wrong nToken parameter"); + if (0 <= nToken && nToken < XML_TOKEN_COUNT) + return maTokenNames[ nToken ]; + return EMPTY_BYTE_SEQ; + } + + /** Returns the token identifier for the passed UTF8 token name. */ + sal_Int32 getTokenFromUtf8( + const css::uno::Sequence< sal_Int8 >& rUtf8Name ) const + { + return getTokenFromUTF8( reinterpret_cast< const char * >( + rUtf8Name.getConstArray() ), + rUtf8Name.getLength() ); + } + + /** Returns the token identifier for a UTF8 string passed in pToken */ + sal_Int32 getTokenFromUTF8( const char *pToken, sal_Int32 nLength ) const + { + // 50% of OOXML tokens are primarily 1 lower-case character, a-z + if( nLength == 1) + { + char c = pToken[0]; + if (c >= 'a' && c <= 'z') + return mnAlphaTokens[ c - 'a' ]; + } + return getTokenPerfectHash( pToken, nLength ); + } + +private: + static sal_Int32 getTokenPerfectHash( const char *pToken, sal_Int32 nLength ); + static const css::uno::Sequence< sal_Int8 > EMPTY_BYTE_SEQ; + + std::vector< css::uno::Sequence< sal_Int8 > > + maTokenNames; + sal_Int32 mnAlphaTokens[26]; +}; + + +TokenMap& StaticTokenMap(); + +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmldrawing.hxx b/include/oox/vml/vmldrawing.hxx new file mode 100644 index 000000000..a11bfef0d --- /dev/null +++ b/include/oox/vml/vmldrawing.hxx @@ -0,0 +1,206 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLDRAWING_HXX +#define INCLUDED_OOX_VML_VMLDRAWING_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Rectangle; } + namespace drawing { class XDrawPage; } + namespace drawing { class XShape; } + namespace drawing { class XShapes; } +} + +namespace oox { + namespace core { class XmlFilterBase; } + namespace ole { class EmbeddedControl; } + namespace ole { class EmbeddedForm; } + namespace vml { class ShapeContainer; } +} + +namespace oox::vml { + +class ShapeBase; + + +/** Enumerates different types of VML drawings. */ +enum DrawingType +{ + VMLDRAWING_WORD, ///< Word: One shape per drawing. + VMLDRAWING_EXCEL, ///< Excel: OLE objects are part of VML. + VMLDRAWING_POWERPOINT ///< PowerPoint: OLE objects are part of DrawingML. +}; + + +/** Contains information about an OLE object embedded in a draw page. */ +struct OOX_DLLPUBLIC OleObjectInfo : public ::oox::ole::OleObjectInfo +{ + OUString maShapeId; ///< Shape identifier for shape lookup. + OUString maName; ///< Programmatical name of the OLE object. + bool mbAutoLoad; + const bool mbDmlShape; ///< True = DrawingML shape (PowerPoint), false = VML shape (Excel/Word). + + explicit OleObjectInfo( bool bDmlShape = false ); + + /** Sets the string representation of the passed numeric shape identifier. */ + void setShapeId( sal_Int32 nShapeId ); +}; + +// =========================================/=================================== + +/** Contains information about a form control embedded in a draw page. */ +struct OOX_DLLPUBLIC ControlInfo +{ + OUString maShapeId; ///< Shape identifier for shape lookup. + OUString maFragmentPath; ///< Path to the fragment describing the form control properties. + OUString maName; ///< Programmatical name of the form control. + bool mbTextContentShape; ///< Whether this control shape will be imported to Writer or not (has AnchorType property or not). + + explicit ControlInfo(); + + /** Sets the string representation of the passed numeric shape identifier. */ + void setShapeId( sal_Int32 nShapeId ); +}; + + +/** Represents the collection of VML shapes for a complete draw page. */ +class OOX_DLLPUBLIC Drawing +{ +public: + explicit Drawing( + ::oox::core::XmlFilterBase& rFilter, + const css::uno::Reference< css::drawing::XDrawPage >& rxDrawPage, + DrawingType eType ); + + virtual ~Drawing(); + + /** Returns the filter object that imports/exports this VML drawing. */ + ::oox::core::XmlFilterBase& getFilter() const { return mrFilter; } + /** Returns the application type containing the drawing. */ + DrawingType getType() const { return meType; } + /** Returns read/write access to the container of shapes and templates. */ + ShapeContainer& getShapes() { return *mxShapes; } + /** Returns read access to the container of shapes and templates. */ + const ShapeContainer& getShapes() const { return *mxShapes; } + /** Returns the form object used to process ActiveX form controls. */ + ::oox::ole::EmbeddedForm& getControlForm() const; + + /** Registers a block of shape identifiers reserved by this drawing. Block + size is 1024, shape identifiers are one-based (block 1 => 1025-2048). */ + void registerBlockId( sal_Int32 nBlockId ); + /** Registers the passed embedded OLE object. The related shape will then + load the OLE object data from the specified fragment. */ + void registerOleObject( const OleObjectInfo& rOleObject ); + /** Registers the passed embedded form control. The related shape will then + load the control properties from the specified fragment. */ + void registerControl( const ControlInfo& rControl ); + + /** Final processing after import of the fragment. */ + void finalizeFragmentImport(); + + /** Creates and inserts all UNO shapes into the draw page. The virtual + function notifyXShapeInserted() will be called for each new shape. */ + void convertAndInsert() const; + + /** Returns the local shape index from the passed global shape identifier. */ + sal_Int32 getLocalShapeIndex( const OUString& rShapeId ) const; + /** Returns the registered info structure for an OLE object, if extant. */ + const OleObjectInfo* getOleObjectInfo( const OUString& rShapeId ) const; + /** Returns the registered info structure for a form control, if extant. */ + const ControlInfo* getControlInfo( const OUString& rShapeId ) const; + + /** Creates a new UNO shape object, inserts it into the passed UNO shape + container, and sets the shape position and size. */ + css::uno::Reference< css::drawing::XShape > + createAndInsertXShape( + const OUString& rService, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const; + + /** Creates a new UNO shape object for a form control, inserts the control + model into the form, and the shape into the passed UNO shape container. */ + css::uno::Reference< css::drawing::XShape > + createAndInsertXControlShape( + const ::oox::ole::EmbeddedControl& rControl, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect, + sal_Int32& rnCtrlIndex ) const; + + /** Derived classes may disable conversion of specific shapes. */ + virtual bool isShapeSupported( const ShapeBase& rShape ) const; + + /** Derived classes may return additional base names for automatic shape + name creation. */ + virtual OUString getShapeBaseName( const ShapeBase& rShape ) const; + + /** Derived classes may calculate the shape rectangle from a non-standard + anchor information string. */ + virtual bool convertClientAnchor( + css::awt::Rectangle& orShapeRect, + const OUString& rShapeAnchor ) const; + + /** Derived classes create a UNO shape according to the passed shape model. + Called for shape models that specify being under host control. */ + virtual css::uno::Reference< css::drawing::XShape > + createAndInsertClientXShape( + const ShapeBase& rShape, + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const; + + /** Derived classes may want to know that a UNO shape has been inserted. + Will be called from the convertAndInsert() implementation. + @param bGroupChild True = inserted into a group shape, + false = inserted directly into this drawing. */ + virtual void notifyXShapeInserted( + const css::uno::Reference< css::drawing::XShape >& rxShape, + const css::awt::Rectangle& rShapeRect, + const ShapeBase& rShape, bool bGroupChild ); + +private: + typedef ::std::vector< sal_Int32 > BlockIdVector; + typedef ::std::map< OUString, OleObjectInfo > OleObjectInfoMap; + typedef ::std::map< OUString, ControlInfo > ControlInfoMap; + + ::oox::core::XmlFilterBase& mrFilter; ///< Filter object that imports/exports the VML drawing. + css::uno::Reference< css::drawing::XDrawPage > + mxDrawPage; ///< UNO draw page used to insert the shapes. + mutable std::unique_ptr<::oox::ole::EmbeddedForm> mxCtrlForm; ///< The control form used to process embedded controls. + mutable BlockIdVector maBlockIds; ///< Block identifiers used by this drawing. + std::unique_ptr mxShapes; ///< All shapes and shape templates. + OleObjectInfoMap maOleObjects; ///< Info about all embedded OLE objects, mapped by shape id. + ControlInfoMap maControls; ///< Info about all embedded form controls, mapped by control name. + const DrawingType meType; ///< Application type containing the drawing. +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmldrawingfragment.hxx b/include/oox/vml/vmldrawingfragment.hxx new file mode 100644 index 000000000..f7fa4d0bd --- /dev/null +++ b/include/oox/vml/vmldrawingfragment.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLDRAWINGFRAGMENT_HXX +#define INCLUDED_OOX_VML_VMLDRAWINGFRAGMENT_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XInputStream; } +} + +namespace oox { class AttributeList; } +namespace oox::core { class XmlFilterBase; } + +namespace oox::vml { + +class Drawing; + + +class OOX_DLLPUBLIC DrawingFragment : public ::oox::core::FragmentHandler2 +{ +public: + explicit DrawingFragment( + ::oox::core::XmlFilterBase& rFilter, + const OUString& rFragmentPath, + Drawing& rDrawing ); + + virtual css::uno::Reference< css::io::XInputStream > + openFragmentStream() const override; + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + + virtual void finalizeImport() override; + +private: + Drawing& mrDrawing; +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmlformatting.hxx b/include/oox/vml/vmlformatting.hxx new file mode 100644 index 000000000..3f7bbe60a --- /dev/null +++ b/include/oox/vml/vmlformatting.hxx @@ -0,0 +1,285 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLFORMATTING_HXX +#define INCLUDED_OOX_VML_VMLFORMATTING_HXX + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Point; } + namespace drawing { class XShape; } +} + +namespace oox { + class GraphicHelper; + namespace drawingml { class Color; } + namespace drawingml { class ShapePropertyMap; } +} + +namespace oox::vml { + + +typedef ::std::pair< sal_Int32, sal_Int32 > Int32Pair; +typedef ::std::pair< double, double > DoublePair; + + +namespace ConversionHelper +{ + /** Returns two values contained in rValue separated by cSep. + */ + OOX_DLLPUBLIC bool separatePair( + std::u16string_view& orValue1, std::u16string_view& orValue2, + std::u16string_view rValue, sal_Unicode cSep ); + + /** Returns the boolean value from the passed string of a VML attribute. + Supported values: 'f', 't', 'false', 'true'. False for anything else. + */ + OOX_DLLPUBLIC bool decodeBool( std::u16string_view rValue ); + + /** Converts the passed VML percentage measure string to a normalized + floating-point value. + + @param rValue The VML percentage value. This is a floating-point value + with optional following '%' or 'f' sign. If the sign is missing, the + floating point value will be returned unmodified. If the '%' sign + is present, the value will be divided by 100. If the 'f' sign is present, + the value will be divided by 65536. + */ + OOX_DLLPUBLIC double decodePercent( + std::u16string_view rValue, + double fDefValue ); + + /** Converts the passed VML rotation value to degrees. + See DffPropertyReader::Fix16ToAngle(): in VML, positive rotation + angles are clockwise, we have them as counter-clockwise. + Additionally, VML type is 0..360, our is 0..36000. + + @param rValue The VML rotation value. This is a floating-point value + with optional 'fd' suffix. If the suffix is missing, the floating + point value will be returned unmodified. If the 'fd' suffix is + present, the value will be divided by 65536. + */ + OOX_DLLPUBLIC Degree100 decodeRotation( std::u16string_view rValue ); + + /** Converts the passed VML measure string to EMU (English Metric Units). + + @param rGraphicHelper The graphic helper needed to perform pixel + conversion according to the current output device. + + @param rValue The VML measure value. This is a floating-point value + with optional measure string following the value. + + @param nRefValue Reference value needed for percentage measure. + + @param bPixelX Set to true if the value is oriented horizontally (e.g. + X coordinates, widths). Set to false if the value is oriented + vertically (e.g. Y coordinates, heights). This is needed because + output devices may specify different width and height for a pixel. + + @param bDefaultAsPixel Set to true if omitted measure unit means + pixel. Set to false if omitted measure unit means EMU. + */ + OOX_DLLPUBLIC sal_Int64 decodeMeasureToEmu( + const GraphicHelper& rGraphicHelper, + std::u16string_view rValue, + sal_Int32 nRefValue, + bool bPixelX, + bool bDefaultAsPixel ); + + /** Converts the passed VML measure string to 1/100 mm. + + @param rGraphicHelper See above. + @param rValue See above. + @param nRefValue See above. + @param bPixelX See above. + @param bDefaultAsPixel See above. + */ + OOX_DLLPUBLIC sal_Int32 decodeMeasureToHmm( + const GraphicHelper& rGraphicHelper, + std::u16string_view rValue, + sal_Int32 nRefValue, + bool bPixelX, + bool bDefaultAsPixel ); + +/** Converts the passed VML measure string to Twip. + + @param rGraphicHelper See above. + @param rValue See above. + @param nRefValue See above. + @param bPixelX See above. + @param bDefaultAsPixel See above. + */ +OOX_DLLPUBLIC sal_Int32 decodeMeasureToTwip(const GraphicHelper& rGraphicHelper, + std::u16string_view rValue, sal_Int32 nRefValue, + bool bPixelX, bool bDefaultAsPixel); + + /** Converts VML color attributes to a DrawingML color. + + @param roVmlColor The VML string representation of the color. If + existing, this can be a 3-digit or 6-digit hexadecimal RGB value + with leading '#' character, a predefined color name (e.g. 'black', + 'red', etc.), the index into an application defined color palette + in brackets with leading color name (e.g. 'red [9]' or + 'windowColor [64]'), or a color modifier used in one-color + gradients (e.g. 'fill darken(128)' or 'fill lighten(0)'). + + @param roVmlOpacity The opacity of the color. If existing, this should + be a floating-point value in the range [0.0;1.0]. + + @param nDefaultRgb Default RGB color used if the parameter roVmlColor + is empty. + + @param nPrimaryRgb If set to something else than API_RGB_TRANSPARENT, + specifies the color to be used to resolve the color modifiers used + in one-color gradients. + + @return The resulting DrawingML color. + */ + OOX_DLLPUBLIC ::oox::drawingml::Color decodeColor( + const GraphicHelper& rGraphicHelper, + const OptValue< OUString >& roVmlColor, + const OptValue< double >& roVmlOpacity, + ::Color nDefaultRgb, + ::Color nPrimaryRgb = API_RGB_TRANSPARENT ); + + /** Converts VML path string into point and flag vectors. + + @param rPoints The point vector to fill with coordinates. + + @param rFlags The flag vector to fill. PolygonFlags_NORMAL indicates + a corresponding plain shape coordinate in rPoints and + PolygonFlags_CONTROL indicates a bezier curve control point. + + @param rPath The VML path string. + + @param rGraphicHelper See above. + */ + OOX_DLLPUBLIC void decodeVmlPath( + ::std::vector< ::std::vector< css::awt::Point > >& rPoints, + ::std::vector< ::std::vector< css::drawing::PolygonFlags > >& rFlags, + const OUString& rPath ); +} + + +/** The stroke arrow model structure contains all properties for a line end arrow. */ +struct StrokeArrowModel +{ + OptValue< sal_Int32 > moArrowType; + OptValue< sal_Int32 > moArrowWidth; + OptValue< sal_Int32 > moArrowLength; + + void assignUsed( const StrokeArrowModel& rSource ); +}; + + +/** The stroke model structure contains all shape border properties. */ +struct StrokeModel +{ + OptValue< bool > moStroked; ///< Shape border line on/off. + StrokeArrowModel maStartArrow; ///< Start line arrow style. + StrokeArrowModel maEndArrow; ///< End line arrow style. + OptValue< OUString > moColor; ///< Solid line color. + OptValue< double > moOpacity; ///< Solid line color opacity. + OptValue< OUString > moWeight; ///< Line width. + OptValue< OUString > moDashStyle; ///< Line dash (predefined or manually). + OptValue< sal_Int32 > moLineStyle; ///< Line style (single, double, ...). + OptValue< sal_Int32 > moEndCap; ///< Type of line end cap. + OptValue< sal_Int32 > moJoinStyle; ///< Type of line join. + + void assignUsed( const StrokeModel& rSource ); + + /** Writes the properties to the passed property map. */ + void pushToPropMap( + ::oox::drawingml::ShapePropertyMap& rPropMap, + const GraphicHelper& rGraphicHelper ) const; +}; + + +/** The fill model structure contains all shape fill properties. */ +struct OOX_DLLPUBLIC FillModel +{ + OptValue< bool > moFilled; ///< Shape fill on/off. + OptValue< OUString > moColor; ///< Solid fill color. + OptValue< double > moOpacity; ///< Solid fill color opacity. + OptValue< OUString > moColor2; ///< End color of gradient. + OptValue< double > moOpacity2; ///< End color opacity of gradient. + OptValue< sal_Int32 > moType; ///< Fill type. + OptValue< sal_Int32 > moAngle; ///< Gradient rotation angle. + OptValue< double > moFocus; ///< Linear gradient focus of second color. + OptValue< DoublePair > moFocusPos; ///< Rectangular gradient focus position of second color. + OptValue< DoublePair > moFocusSize; ///< Rectangular gradient focus size of second color. + OptValue< OUString > moBitmapPath; ///< Path to fill bitmap fragment. + OptValue< bool > moRotate; ///< True = rotate gradient/bitmap with shape. + + void assignUsed( const FillModel& rSource ); + + /** Writes the properties to the passed property map. */ + void pushToPropMap( + ::oox::drawingml::ShapePropertyMap& rPropMap, + const GraphicHelper& rGraphicHelper ) const; +}; + + +/** The shadow model structure contains all shape shadow properties. */ +struct OOX_DLLPUBLIC ShadowModel +{ + bool mbHasShadow; ///< Is a v:shadow element seen? + OptValue moShadowOn; ///< Is the element turned on? + OptValue moColor; ///< Specifies the color of the shadow. + OptValue moOffset; ///< Specifies the shadow's offset from the shape's location. + OptValue moOpacity; ///< Specifies the opacity of the shadow. + + ShadowModel(); + + /** Writes the properties to the passed property map. */ + void pushToPropMap(oox::drawingml::ShapePropertyMap& rPropMap, const GraphicHelper& rGraphicHelper) const; +}; + +/** The shadow model structure contains all shape textpath properties. */ +struct TextpathModel +{ + OptValue moString; ///< Specifies the string of the textpath. + OptValue moStyle; ///< Specifies the style of the textpath. + OptValue moTrim; ///< Specifies whether extra space is removed above and below the text + + TextpathModel(); + + /** Writes the properties to the passed property map. */ + void pushToPropMap(oox::drawingml::ShapePropertyMap& rPropMap, const css::uno::Reference& xShape, + const GraphicHelper& rGraphicHelper) const; +}; + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmlinputstream.hxx b/include/oox/vml/vmlinputstream.hxx new file mode 100644 index 000000000..df074834f --- /dev/null +++ b/include/oox/vml/vmlinputstream.hxx @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLINPUTSTREAM_HXX +#define INCLUDED_OOX_VML_VMLINPUTSTREAM_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace io { class XTextInputStream2; } + namespace uno { class XComponentContext; } +} + +namespace oox::vml { + + +/** An input stream class for VML streams, implementing the UNO interface + com.sun.star.io.XInputStream needed by the Expat XML parsers. + + This stream reads the data from the input stream passed to the constructor, + and parses all XML elements for features unsupported by the current Expat + XML parser: + + 1) All elements that have the form '' where 'inst' is any string + not containing the characters '<' and '>' are stripped from the input + stream. + + 2) Multiple occurrences of the same attribute in an element but the last + are removed. + + 3) Line breaks represented by a single
    element (without matching +
    element) are replaced by a literal LF character. + */ +class InputStream final : public ::cppu::WeakImplHelper< css::io::XInputStream > +{ +public: + explicit InputStream( + const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::io::XInputStream >& rxInStrm ); + virtual ~InputStream() override; + + virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& rData, sal_Int32 nBytesToRead ) override; + virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& rData, sal_Int32 nMaxBytesToRead ) override; + virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override; + virtual sal_Int32 SAL_CALL available() override; + virtual void SAL_CALL closeInput() override; + +private: + /// @throws css::io::IOException + /// @throws css::uno::RuntimeException + void updateBuffer(); + /// @throws css::io::IOException + /// @throws css::uno::RuntimeException + OString readToElementBegin(); + /// @throws css::io::IOException + /// @throws css::uno::RuntimeException + OString readToElementEnd(); + +private: + css::uno::Reference< css::io::XTextInputStream2 > + mxTextStrm; + css::uno::Sequence< sal_Unicode > maOpeningBracket; + css::uno::Sequence< sal_Unicode > maClosingBracket; + OString maBuffer; + sal_Int32 mnBufferPos; +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmlshape.hxx b/include/oox/vml/vmlshape.hxx new file mode 100644 index 000000000..7a17bda51 --- /dev/null +++ b/include/oox/vml/vmlshape.hxx @@ -0,0 +1,476 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLSHAPE_HXX +#define INCLUDED_OOX_VML_VMLSHAPE_HXX + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace awt { struct Rectangle; } + namespace drawing { class XShape; } + namespace drawing { class XShapes; } + namespace graphic { class XGraphic; } +} + +namespace oox::vml { + +class Drawing; +struct ShapeParentAnchor; +class ShapeContainer; +class TextBox; + +const sal_Int32 VML_CLIENTDATA_UNCHECKED = 0; +const sal_Int32 VML_CLIENTDATA_CHECKED = 1; +const sal_Int32 VML_CLIENTDATA_MIXED = 2; + +const sal_Int32 VML_CLIENTDATA_TEXT = 0; +const sal_Int32 VML_CLIENTDATA_INTEGER = 1; +const sal_Int32 VML_CLIENTDATA_NUMBER = 2; +const sal_Int32 VML_CLIENTDATA_REFERENCE = 3; +const sal_Int32 VML_CLIENTDATA_FORMULA = 4; + + +/** The shape model structure contains all properties shared by all types of shapes. */ +struct ShapeTypeModel +{ + OUString maShapeId; ///< Unique identifier of the shape. + OUString maLegacyId; ///< Plaintext identifier of the shape. + OUString maShapeName; ///< Name of the shape, if present. + OptValue< sal_Int32 > moShapeType; ///< Builtin shape type identifier. + + OptValue< Int32Pair > moCoordPos; ///< Top-left position of coordinate system for children scaling. + OptValue< Int32Pair > moCoordSize; ///< Size of coordinate system for children scaling. + OUString maPosition; ///< Position type of the shape. + OUString maZIndex; ///< ZIndex of the shape + OUString maLeft; ///< X position of the shape bounding box (number with unit). + OUString maTop; ///< Y position of the shape bounding box (number with unit). + OUString maWidth; ///< Width of the shape bounding box (number with unit). + OUString maHeight; ///< Height of the shape bounding box (number with unit). + OUString maMarginLeft; ///< X position of the shape bounding box to shape anchor (number with unit). + OUString maMarginTop; ///< Y position of the shape bounding box to shape anchor (number with unit). + OUString maPositionHorizontalRelative; ///< The X position is relative to this. + OUString maPositionVerticalRelative; ///< The Y position is relative to this. + OUString maPositionHorizontal; ///< The X position orientation (default: absolute). + OUString maPositionVertical; ///< The Y position orientation. + OUString maWidthPercent; ///< The width in percents of the WidthRelative + OUString maHeightPercent; ///< The height in percents of the HeightRelative + OUString maWidthRelative; ///< To what the width is relative + OUString maHeightRelative; ///< To what the height is relative + OUString maRotation; ///< Rotation of the shape, in degrees. + OUString maFlip; ///< Flip type of the shape (can be "x" or "y"). + bool mbAutoHeight; ///< If true, the height value is a minimum value (mostly used for textboxes) + bool mbVisible; ///< Visible or Hidden + OUString maWrapStyle; ///< Wrapping mode for text. + OUString maArcsize; ///< round rectangles arc size + OUString maEditAs; ///< Edit As type (e.g. "canvas" etc) + OUString maAdjustments; ///< Shape adjustment values + + StrokeModel maStrokeModel; ///< Border line formatting. + FillModel maFillModel; ///< Shape fill formatting. + ShadowModel maShadowModel; ///< Shape shadow formatting. + TextpathModel maTextpathModel; ///< Shape textpath formatting. + + OptValue< OUString > moGraphicPath; ///< Path to a graphic for this shape. + OptValue< OUString > moGraphicTitle; ///< Title of the graphic. + OptValue< OUString > moWrapAnchorX; ///< The base object from which our horizontal positioning should be calculated. + OptValue< OUString > moWrapAnchorY; ///< The base object from which our vertical positioning should be calculated. + OptValue< OUString > moWrapType; ///< How to wrap the text around the object + OptValue< OUString > moWrapSide; ///< On which side to wrap the text around the object + OUString maVTextAnchor; ///< How the text inside the shape is anchored vertically. + OUString maWrapDistanceLeft; ///< Distance from the left side of the shape to the text that wraps around it. + OUString maWrapDistanceRight; ///< Distance from the right side of the shape to the text that wraps around it. + OUString maWrapDistanceTop; ///< Distance from the top of the shape to the text that wraps around it. + OUString maWrapDistanceBottom; ///< Distance from the bottom of the shape to the text that wraps around it. + OptValue moCropBottom; ///< Specifies the how much to crop the image from the bottom up as a fraction of picture size. + OptValue moCropLeft; ///< Specifies how much to crop the image from the left in as a fraction of picture size. + OptValue moCropRight; ///< Specifies how much to crop the image from the right in as a fraction of picture size. + OptValue moCropTop; ///< Specifies how much to crop the image from the top down as a fraction of picture size. + OUString maLayoutFlowAlt; ///< Specifies the alternate layout flow for text in textboxes. + + /// An adjustment for the intensity of all colors, i.e. contrast, on a 0..0x10000 scale. + sal_Int32 mnGain = 0x10000; + + /// The image brightness, on a 0..0x10000 scale. + sal_Int16 mnBlacklevel = 0; + + explicit ShapeTypeModel(); + + void assignUsed( const ShapeTypeModel& rSource ); +}; + + +/** A shape template contains all formatting properties of shapes and can serve + as templates for several shapes in a drawing. */ +class SAL_DLLPUBLIC_RTTI ShapeType +{ +public: + explicit ShapeType( Drawing& rDrawing ); + virtual ~ShapeType(); + + /** Returns read/write access to the shape template model structure. */ + ShapeTypeModel& getTypeModel() { return maTypeModel; } + /** Returns read access to the shape template model structure. */ + const ShapeTypeModel& getTypeModel() const { return maTypeModel; } + + /** Returns the shape identifier (which is unique through the containing drawing). */ + const OUString& getShapeId() const { return maTypeModel.maShapeId; } + /** Returns the application defined shape type. */ + sal_Int32 getShapeType() const; + /** Returns the fragment path to the embedded graphic used by this shape. */ + OUString getGraphicPath() const; + + const Drawing& getDrawing() const { return mrDrawing; } + +protected: + /** Returns the coordinate system of this shape. */ + css::awt::Rectangle getCoordSystem() const; + /** Returns the absolute shape rectangle according to the passed anchor. */ + css::awt::Rectangle getRectangle( const ShapeParentAnchor* pParentAnchor ) const; + /** Returns the absolute shape rectangle. */ + virtual css::awt::Rectangle getAbsRectangle() const; + /** Returns the rectangle relative to the parent coordinate system. */ + virtual css::awt::Rectangle getRelRectangle() const; + +protected: + Drawing& mrDrawing; ///< The VML drawing page that contains this shape. + ShapeTypeModel maTypeModel; ///< The model structure containing shape type data. +}; + + +/** Excel specific shape client data (such as cell anchor). */ +struct ClientData +{ + OUString maAnchor; ///< Cell anchor as comma-separated string. + OUString maFmlaMacro; ///< Link to macro associated to the control. + OUString maFmlaPict; ///< Target cell range of picture links. + OUString maFmlaLink; ///< Link to value cell associated to the control. + OUString maFmlaRange; ///< Link to cell range used as data source for the control. + OUString maFmlaGroup; ///< Link to value cell associated to a group of option buttons. + sal_Int32 mnObjType; ///< Type of the shape. + sal_Int32 mnTextHAlign; ///< Horizontal text alignment. + sal_Int32 mnTextVAlign; ///< Vertical text alignment. + sal_Int32 mnCol; ///< Column index for spreadsheet cell note. + sal_Int32 mnRow; ///< Row index for spreadsheet cell note. + sal_Int32 mnChecked; ///< State for checkboxes and option buttons. + sal_Int32 mnDropStyle; ///< Drop down box style (read-only or editable). + sal_Int32 mnDropLines; ///< Number of lines in drop down box. + sal_Int32 mnVal; ///< Current value of spin buttons and scroll bars. + sal_Int32 mnMin; ///< Minimum value of spin buttons and scroll bars. + sal_Int32 mnMax; ///< Maximum value of spin buttons and scroll bars. + sal_Int32 mnInc; ///< Small increment of spin buttons and scroll bars. + sal_Int32 mnPage; ///< Large increment of spin buttons and scroll bars. + sal_Int32 mnSelType; ///< Listbox selection type. + sal_Int32 mnVTEdit; ///< Data type of the textbox. + bool mbPrintObject; ///< True = print the object. + bool mbVisible; ///< True = cell note is visible. + bool mbDde; ///< True = object is linked through DDE. + bool mbNo3D; ///< True = flat style, false = 3D style. + bool mbNo3D2; ///< True = flat style, false = 3D style (listboxes and dropdowns). + bool mbMultiLine; ///< True = textbox allows line breaks. + bool mbVScroll; ///< True = textbox has a vertical scrollbar. + bool mbSecretEdit; ///< True = textbox is a password edit field. + + explicit ClientData(); +}; + + +struct ShapeModel +{ + typedef ::std::vector< css::awt::Point > PointVector; + + OUString maType; ///< Shape template with default properties. + PointVector maPoints; ///< Points for the polyline shape. + std::unique_ptr mxTextBox; ///< Text contents and properties. + std::unique_ptr mxClientData; ///< Excel specific client data. + OUString maLegacyDiagramPath;///< Legacy Diagram Fragment Path + OUString maFrom; ///< Start point for line shape. + OUString maTo; ///< End point for line shape. + OUString maControl1; ///< Bezier control point 1 + OUString maControl2; ///< Bezier control point 2 + OUString maVmlPath; ///< VML path for this shape + bool mbIsSignatureLine; ///< Shape is a signature line + OUString maSignatureId; ///< ID of the signature + OUString maSignatureLineSuggestedSignerName; + OUString maSignatureLineSuggestedSignerTitle; + OUString maSignatureLineSuggestedSignerEmail; + OUString maSignatureLineSigningInstructions; + bool mbSignatureLineShowSignDate; + bool mbSignatureLineCanAddComment; + bool mbInGroup; + OUString maHyperlink; ///< The hyperlink assigned to the shape + + explicit ShapeModel(); + ~ShapeModel(); + + /** Creates and returns a new shape textbox structure. */ + TextBox& createTextBox(ShapeTypeModel& rModel); + /** Creates and returns a new shape client data structure. */ + ClientData& createClientData(); +}; + + +/** A shape object that is part of a drawing. May inherit properties from a + shape template. */ +class OOX_DLLPUBLIC ShapeBase : public ShapeType +{ +public: + /** Returns read/write access to the shape model structure. */ + ShapeModel& getShapeModel() { return maShapeModel; } + /** Returns read access to the shape model structure. */ + const ShapeModel& getShapeModel() const { return maShapeModel; } + + /** Returns read access to the shape textbox. */ + const TextBox* getTextBox() const { return maShapeModel.mxTextBox.get(); } + /** Returns read access to the shape client data structure. */ + const ClientData* getClientData() const { return maShapeModel.mxClientData.get(); } + + /** Final processing after import of the drawing fragment. */ + virtual void finalizeFragmentImport(); + + /** Returns the real shape name if existing, or a generated shape name. */ + OUString getShapeName() const; + + /** Returns the shape template with the passed identifier from the child shapes. */ + virtual const ShapeType* getChildTypeById( const OUString& rShapeId ) const; + /** Returns the shape with the passed identifier from the child shapes. */ + virtual const ShapeBase* getChildById( const OUString& rShapeId ) const; + + /** Creates the corresponding XShape and inserts it into the passed container. */ + css::uno::Reference< css::drawing::XShape > + convertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const ShapeParentAnchor* pParentAnchor = nullptr ) const; + + /** Converts position and formatting into the passed existing XShape. */ + void convertFormatting( + const css::uno::Reference< css::drawing::XShape >& rxShape ) const; + + void setContainer(ShapeContainer* pContainer); + ShapeContainer* getContainer() const; + +protected: + explicit ShapeBase( Drawing& rDrawing ); + + /** Derived classes create the corresponding XShape and insert it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const = 0; + + /** Always called after implConvertAndInsert for the same task.*/ + virtual css::uno::Reference finalImplConvertAndInsert( + const css::uno::Reference& rxShape) const + { + return rxShape; + }; + + /** Calculates the final shape rectangle according to the passed anchor, + if present, otherwise according to the own anchor settings. */ + css::awt::Rectangle calcShapeRectangle( + const ShapeParentAnchor* pParentAnchor ) const; + + /** Converts common shape properties such as formatting attributes. */ + void convertShapeProperties( + const css::uno::Reference< css::drawing::XShape >& rxShape ) const; + +protected: + ShapeModel maShapeModel; ///< The model structure containing shape data. + ShapeContainer* mpContainer = nullptr; +}; + + +/** A simple shape object based on a specific UNO shape service. */ +class SimpleShape : public ShapeBase +{ +public: + explicit SimpleShape( Drawing& rDrawing, const OUString& rService ); + + void setService( const OUString& aService ) { maService = aService; } + +protected: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; + virtual css::uno::Reference finalImplConvertAndInsert( + const css::uno::Reference& rxShape) const override; + /** Used by both RectangleShape and ComplexShape. */ + css::uno::ReferencecreateEmbeddedPictureObject( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect, OUString const & rGraphicPath ) const; + + css::uno::ReferencecreatePictureObject( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect, + css::uno::Reference const & rxGraphic) const; + +private: + OUString maService; ///< Name of the UNO shape service. +}; + + +/** A rectangular shape object. */ +class RectangleShape final : public SimpleShape +{ +public: + explicit RectangleShape( Drawing& rDrawing ); +private: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference + implConvertAndInsert( + const css::uno::Reference& rxShapes, + const css::awt::Rectangle& rShapeRect) const override; +}; + + +/** An oval shape object. */ +class EllipseShape final : public SimpleShape +{ +public: + explicit EllipseShape( Drawing& rDrawing ); +}; + + +/** A polygon shape object. */ +class PolyLineShape final : public SimpleShape +{ +public: + explicit PolyLineShape( Drawing& rDrawing ); + +private: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; +}; + +/** A Line shape object. */ +class LineShape final : public SimpleShape +{ +public: + explicit LineShape( Drawing& rDrawing ); + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; + + +private: + /** Returns the absolute shape rectangle. */ + virtual css::awt::Rectangle getAbsRectangle() const override; + /** Returns the rectangle relative to the parent coordinate system. */ + virtual css::awt::Rectangle getRelRectangle() const override; +}; + +/** Bezier shape object that supports to, from, control1 and control2 + attribute or path attribute specification */ +class BezierShape final : public SimpleShape +{ +public: + explicit BezierShape( Drawing& rDrawing ); + +private: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; +}; + + +/** A shape object with custom geometry. */ +class CustomShape : public SimpleShape +{ +public: + explicit CustomShape( Drawing& rDrawing ); + +protected: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; +}; + + +/** A complex shape object. This can be a picture shape, a custom shape, an OLE + object, or an ActiveX form control. */ +class ComplexShape final : public CustomShape +{ +public: + explicit ComplexShape( Drawing& rDrawing ); + +private: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; +}; + + +/** A group shape that extends the basic shape by a container of child shapes. */ +class GroupShape final : public ShapeBase +{ +public: + explicit GroupShape( Drawing& rDrawing ); + virtual ~GroupShape() override; + + /** Returns read/write access to the container of child shapes and templates. */ + ShapeContainer& getChildren() { return *mxChildren; } + /** Returns read access to the container of child shapes and templates. */ + const ShapeContainer& getChildren() const { return *mxChildren; } + + /** Final processing after import of the drawing fragment. */ + virtual void finalizeFragmentImport() override; + + /** Returns the shape template with the passed identifier from the child shapes. */ + virtual const ShapeType* getChildTypeById( const OUString& rShapeId ) const override; + /** Returns the shape with the passed identifier from the child shapes. */ + virtual const ShapeBase* getChildById( const OUString& rShapeId ) const override; + +private: + /** Creates the corresponding XShape and inserts it into the passed container. */ + virtual css::uno::Reference< css::drawing::XShape > + implConvertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const css::awt::Rectangle& rShapeRect ) const override; + +private: + std::unique_ptr mxChildren; ///< Shapes and templates that are part of this group. +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmlshapecontainer.hxx b/include/oox/vml/vmlshapecontainer.hxx new file mode 100644 index 000000000..6f50730bc --- /dev/null +++ b/include/oox/vml/vmlshapecontainer.hxx @@ -0,0 +1,144 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLSHAPECONTAINER_HXX +#define INCLUDED_OOX_VML_VMLSHAPECONTAINER_HXX + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace drawing { class XShapes; } +} + +namespace oox::vml { + +class Drawing; +class ShapeType; +class ShapeBase; + + +struct ShapeParentAnchor +{ + css::awt::Rectangle maShapeRect; + css::awt::Rectangle maCoordSys; +}; + + +/** Container that holds a list of shapes and shape templates. */ +class ShapeContainer +{ +public: + explicit ShapeContainer( Drawing& rDrawing ); + ~ShapeContainer(); + + /** Returns the drawing this shape container is part of. */ + Drawing& getDrawing() { return mrDrawing; } + + /** Creates and returns a new shape template object. */ + std::shared_ptr createShapeType(); + /** Creates and returns a new shape object of the specified type. */ + template< typename ShapeT > + std::shared_ptr createShape(); + + /** Final processing after import of the drawing fragment. */ + void finalizeFragmentImport(); + + /** Returns true, if this container does not contain any shapes. */ + bool empty() const { return maShapes.empty(); } + + /** Returns the shape template with the passed identifier. + Searches in all group shapes too. */ + const ShapeType* getShapeTypeById( const OUString& rShapeId ) const; + /** Returns the shape with the passed identifier. + Searches in all group shapes too. */ + const ShapeBase* getShapeById( const OUString& rShapeId ) const; + + /** Searches for a shape by using the passed functor that takes a constant + reference of a ShapeBase object. */ + template< typename Functor > + const ShapeBase* findShape( const Functor& rFunctor ) const; + + /** + (Word only) Returns the last shape in the collection, if it is after the last + mark from pushMark(), and removes it. + */ + std::shared_ptr< ShapeBase > takeLastShape(); + /** + Adds a recursion mark to the stack. It is possible that a shape contains + which contains another shape, and writerfilter needs to know which shape is from the inner + ooxml context and which from the outer ooxml context, while it is necessary to keep + at least shape types across such blocks. Therefore this function marks beginning + of each shape xml block, and takeLastShape() returns only shapes from this block. + */ + void pushMark(); + /** + Removes a recursion mark. + */ + void popMark(); + + /** Creates and inserts all UNO shapes into the passed container. */ + void convertAndInsert( + const css::uno::Reference< css::drawing::XShapes >& rxShapes, + const ShapeParentAnchor* pParentAnchor = nullptr ) const; + +private: + typedef RefVector< ShapeType > ShapeTypeVector; + typedef RefVector< ShapeBase > ShapeVector; + typedef RefMap< OUString, ShapeType > ShapeTypeMap; + typedef RefMap< OUString, ShapeBase > ShapeMap; + + Drawing& mrDrawing; ///< The VML drawing page that contains this shape. + ShapeTypeVector maTypes; ///< All shape templates. + ShapeVector maShapes; ///< All shape definitions. + ShapeTypeMap maTypesById; ///< All shape templates mapped by identifier. + ShapeMap maShapesById; ///< All shape definitions mapped by identifier. + std::stack< size_t > markStack; ///< Recursion marks from pushMark()/popMark(). +}; + + +template< typename ShapeT > +std::shared_ptr ShapeContainer::createShape() +{ + auto xShape = std::make_shared( mrDrawing ); + xShape->setContainer(this); + maShapes.push_back( xShape ); + return xShape; +} + +template< typename Functor > +const ShapeBase* ShapeContainer::findShape( const Functor& rFunctor ) const +{ + return maShapes.findIf( rFunctor ).get(); +} + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmlshapecontext.hxx b/include/oox/vml/vmlshapecontext.hxx new file mode 100644 index 000000000..ce838297c --- /dev/null +++ b/include/oox/vml/vmlshapecontext.hxx @@ -0,0 +1,191 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLSHAPECONTEXT_HXX +#define INCLUDED_OOX_VML_VMLSHAPECONTEXT_HXX + +#include +#include +#include +#include +#include + +namespace oox { class AttributeList; } + +namespace oox::vml { + +class Drawing; + +struct ShapeTypeModel; +class ShapeType; + +struct ClientData; +struct ShapeModel; +class ShapeBase; +class GroupShape; +class RectangleShape; + +class ShapeContainer; + + +class ShapeLayoutContext final : public ::oox::core::ContextHandler2 +{ +public: + explicit ShapeLayoutContext( + ::oox::core::ContextHandler2Helper const & rParent, + Drawing& rDrawing ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + Drawing& mrDrawing; +}; + + +class ClientDataContext final : public ::oox::core::ContextHandler2 +{ +public: + explicit ClientDataContext( + ::oox::core::ContextHandler2Helper const & rParent, + ClientData& rClientData, + const AttributeList& rAttribs ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + virtual void onCharacters( const OUString& rChars ) override; + virtual void onEndElement() override; + +private: + ClientData& mrClientData; + OUString maElementText; +}; + + +class ShapeContextBase : public ::oox::core::ContextHandler2 +{ +public: + static ::oox::core::ContextHandlerRef + createShapeContext( + ::oox::core::ContextHandler2Helper const & rParent, + ShapeContainer& rShapes, + sal_Int32 nElement, + const AttributeList& rAttribs ); + +protected: + explicit ShapeContextBase( ::oox::core::ContextHandler2Helper const & rParent ); +}; + + +class ShapeTypeContext : public ShapeContextBase +{ +public: + explicit ShapeTypeContext( + ::oox::core::ContextHandler2Helper const & rParent, + std::shared_ptr const& pShapeType, + const AttributeList& rAttribs ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + /** Processes the 'style' attribute. */ + void setStyle( std::u16string_view rStyle ); + + /** Resolve a relation identifier to a fragment path. */ + OptValue< OUString > decodeFragmentPath( const AttributeList& rAttribs, sal_Int32 nToken ) const; + +private: + std::shared_ptr m_pShapeType; + ShapeTypeModel& mrTypeModel; +}; + + +class ShapeContext : public ShapeTypeContext +{ +public: + explicit ShapeContext(::oox::core::ContextHandler2Helper const& rParent, + const std::shared_ptr& pShape, const AttributeList& rAttribs); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + /** Processes the 'points' attribute. */ + void setPoints( std::u16string_view rPoints ); + /** Processes the 'from' attribute. */ + void setFrom( const OUString& rPoints ); + /** Processes the 'to' attribute. */ + void setTo( const OUString& rPoints ); + /** Processes the 'control1' attribute. */ + void setControl1( const OUString& rPoints ); + /** Processes the 'control2' attribute. */ + void setControl2( const OUString& rPoints ); + /** Processes the 'path' attribute. */ + void setVmlPath( const OUString& rPath ); + /** Processes the 'href' attribute. */ + void setHyperlink( const OUString& rHyperlink ); + +private: + ShapeBase& mrShape; + ShapeModel& mrShapeModel; +}; + + +class GroupShapeContext final : public ShapeContext +{ +public: + explicit GroupShapeContext(::oox::core::ContextHandler2Helper const& rParent, + const std::shared_ptr& pShape, + const AttributeList& rAttribs); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + +private: + ShapeContainer& mrShapes; +}; + + +class RectangleShapeContext final : public ShapeContext +{ +public: + explicit RectangleShapeContext(::oox::core::ContextHandler2Helper const& rParent, + const AttributeList& rAttribs, + const std::shared_ptr& pShape); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; +}; + +class ControlShapeContext final : public ShapeContextBase +{ +public: + explicit ControlShapeContext( + ::oox::core::ContextHandler2Helper const & rParent, + ShapeContainer& rShapes, + const AttributeList& rAttribs ); +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmltextbox.hxx b/include/oox/vml/vmltextbox.hxx new file mode 100644 index 000000000..fb6983315 --- /dev/null +++ b/include/oox/vml/vmltextbox.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLTEXTBOX_HXX +#define INCLUDED_OOX_VML_VMLTEXTBOX_HXX + +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace drawing { class XShape; } +} + +namespace oox::vml { + +struct ShapeTypeModel; + + +/// A text paragraph in a textbox. +struct TextParagraphModel +{ + OptValue moParaAdjust; ///< Paragraph adjust (left, center, right, etc.) + OptValue moParaStyleName; +}; + +/** Font settings for a text portion in a textbox. */ +struct OOX_DLLPUBLIC TextFontModel +{ + OptValue< OUString > moName; ///< Font name. + OptValue< OUString > moNameAsian; ///< Asian font name. + OptValue< OUString > moNameComplex; ///< Complex font name. + OptValue< OUString > moColor; ///< Font color, HTML encoded, sort of. + OptValue< sal_Int32 > monSize; ///< Font size in twips. + OptValue< sal_Int32 > monUnderline; ///< Single or double underline. + OptValue< sal_Int32 > monEscapement; ///< Subscript or superscript. + OptValue< bool > mobBold; + OptValue< bool > mobItalic; + OptValue< bool > mobStrikeout; + OptValue monSpacing; + + explicit TextFontModel(); +}; + + +/** A text portion in a textbox with the same formatting for all characters. */ +struct TextPortionModel +{ + TextParagraphModel maParagraph; + TextFontModel maFont; + OUString maText; + + explicit TextPortionModel( const TextParagraphModel& rParagraph, const TextFontModel& rFont, const OUString& rText ); +}; + + +/** The textbox contains all text contents and properties. */ +class OOX_DLLPUBLIC TextBox +{ +public: + explicit TextBox(ShapeTypeModel& rTypeModel); + + /** Appends a new text portion to the textbox. */ + void appendPortion( const TextParagraphModel& rParagraph, const TextFontModel& rFont, const OUString& rText ); + + /** Returns the current number of text portions. */ + size_t getPortionCount() const { return maPortions.size(); } + /** Returns the font settings of the first text portion. */ + const TextFontModel* getFirstFont() const; + /** Returns the entire text of all text portions. */ + OUString getText() const; + void convert(const css::uno::Reference& xShape) const; + + ShapeTypeModel& mrTypeModel; + /// Text distance from the border (inset attribute of v:textbox), valid only if set. + bool borderDistanceSet; + int borderDistanceLeft, borderDistanceTop, borderDistanceRight, borderDistanceBottom; + OUString maLayoutFlow; + OUString msNextTextbox; + +private: + typedef ::std::vector< TextPortionModel > PortionVector; + + PortionVector maPortions; +}; + + +} // namespace oox::vml + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/oox/vml/vmltextboxcontext.hxx b/include/oox/vml/vmltextboxcontext.hxx new file mode 100644 index 000000000..d5c3dde86 --- /dev/null +++ b/include/oox/vml/vmltextboxcontext.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OOX_VML_VMLTEXTBOXCONTEXT_HXX +#define INCLUDED_OOX_VML_VMLTEXTBOXCONTEXT_HXX + +#include + +#include +#include +#include +#include +#include + +namespace oox { + class AttributeList; + class GraphicHelper; + +namespace vml { + + +class TextPortionContext final : public ::oox::core::ContextHandler2 +{ +public: + explicit TextPortionContext( + ::oox::core::ContextHandler2Helper const & rParent, + TextBox& rTextBox, + TextParagraphModel const & rParagraph, + const TextFontModel& rParentFont, + sal_Int32 nElement, + const AttributeList& rAttribs ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + virtual void onCharacters( const OUString& rChars ) override; + virtual void onStartElement(const AttributeList& rAttribs) override; + virtual void onEndElement() override; + +private: + TextBox& mrTextBox; + TextParagraphModel maParagraph; + TextFontModel maFont; + size_t mnInitialPortions; +}; + + +class TextBoxContext final : public ::oox::core::ContextHandler2 +{ +public: + explicit TextBoxContext( + ::oox::core::ContextHandler2Helper const & rParent, + TextBox& rTextBox, + const AttributeList& rAttribs, + const GraphicHelper& graphicHelper ); + + virtual ::oox::core::ContextHandlerRef + onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) override; + virtual void onStartElement(const AttributeList& rAttribs) override; + virtual void onEndElement() override; + +private: + TextBox& mrTextBox; + TextParagraphModel maParagraph; +}; + + +} // namespace vml +} // namespace oox + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/opencl/OpenCLZone.hxx b/include/opencl/OpenCLZone.hxx new file mode 100644 index 000000000..8247e667d --- /dev/null +++ b/include/opencl/OpenCLZone.hxx @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OPENCL_INC_OPENCL_ZONE_HXX +#define INCLUDED_OPENCL_INC_OPENCL_ZONE_HXX + +#include + +#include + +#include + +class OPENCL_DLLPUBLIC OpenCLZone : public CrashZone +{ +public: + static void hardDisable(); +}; + +// Used during initial testing of OpenCL. +class OPENCL_DLLPUBLIC OpenCLInitialZone : public CrashZone +{ +}; + +#endif // INCLUDED_OPENCL_INC_OPENCL_ZONE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/opencl/openclconfig.hxx b/include/opencl/openclconfig.hxx new file mode 100644 index 000000000..7247b4fa6 --- /dev/null +++ b/include/opencl/openclconfig.hxx @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OPENCL_OPENCLCONFIG_HXX +#define INCLUDED_OPENCL_OPENCLCONFIG_HXX + +#include +#include + +#include +#include + +struct OpenCLDeviceInfo; +struct OpenCLPlatformInfo; + +struct OPENCL_DLLPUBLIC OpenCLConfig +{ + struct ImplMatcher + { + OUString maOS; + OUString maOSVersion; + OUString maPlatformVendor; + OUString maDevice; + OUString maDriverVersion; + + ImplMatcher() + { + } + + ImplMatcher(const OUString& rOS, + const OUString& rOSVersion, + const OUString& rPlatformVendor, + const OUString& rDevice, + const OUString& rDriverVersion) + : maOS(rOS), + maOSVersion(rOSVersion), + maPlatformVendor(rPlatformVendor), + maDevice(rDevice), + maDriverVersion(rDriverVersion) + { + } + + bool operator==(const ImplMatcher& r) const + { + return maOS == r.maOS && + maOSVersion == r.maOSVersion && + maPlatformVendor == r.maPlatformVendor && + maDevice == r.maDevice && + maDriverVersion == r.maDriverVersion; + } + bool operator!=(const ImplMatcher& r) const + { + return !operator==(r); + } + bool operator<(const ImplMatcher& r) const + { + return (maOS < r.maOS || + (maOS == r.maOS && + (maOSVersion < r.maOSVersion || + (maOSVersion == r.maOSVersion && + (maPlatformVendor < r.maPlatformVendor || + (maPlatformVendor == r.maPlatformVendor && + (maDevice < r.maDevice || + (maDevice == r.maDevice && + (maDriverVersion < r.maDriverVersion))))))))); + } + }; + + bool mbUseOpenCL; + + typedef std::set ImplMatcherSet; + + ImplMatcherSet maDenyList; + ImplMatcherSet maAllowList; + + OpenCLConfig(); + + bool operator== (const OpenCLConfig& r) const; + bool operator!= (const OpenCLConfig& r) const; + + static OpenCLConfig get(); + + void set(); + + bool checkImplementation(const OpenCLPlatformInfo& rPlatform, const OpenCLDeviceInfo& rDevice) const; +}; + +OPENCL_DLLPUBLIC std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig& rConfig); +OPENCL_DLLPUBLIC std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig::ImplMatcher& rImpl); +OPENCL_DLLPUBLIC std::ostream& operator<<(std::ostream& rStream, const OpenCLConfig::ImplMatcherSet& rSet); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/opencl/opencldllapi.h b/include/opencl/opencldllapi.h new file mode 100644 index 000000000..99bfd6cb9 --- /dev/null +++ b/include/opencl/opencldllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_OPENCL_OPENCLDLLAPI_H +#define INCLUDED_OPENCL_OPENCLDLLAPI_H + +#include + +#if defined(OPENCL_DLLIMPLEMENTATION) +#define OPENCL_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define OPENCL_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define OPENCL_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/opencl/openclwrapper.hxx b/include/opencl/openclwrapper.hxx new file mode 100644 index 000000000..81138ced2 --- /dev/null +++ b/include/opencl/openclwrapper.hxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SC_SOURCE_CORE_OPENCL_OPENCLWRAPPER_HXX +#define INCLUDED_SC_SOURCE_CORE_OPENCL_OPENCLWRAPPER_HXX + +#include + +#include + +#include +#include + +#define MAX_CLFILE_NUM 50 +#define OPENCL_CMDQUEUE_SIZE 1 // number of command queues per OpenCL device. + +#include + +struct OpenCLPlatformInfo; + +namespace openclwrapper +{ + +struct KernelEnv +{ + cl_context mpkContext; + cl_command_queue mpkCmdQueue; + cl_program mpkProgram; +}; + +struct OPENCL_DLLPUBLIC GPUEnv +{ + //share vb in all modules in hb library + cl_platform_id mpPlatformID; + cl_context mpContext; + cl_device_id mpDevID; + cl_command_queue mpCmdQueue[OPENCL_CMDQUEUE_SIZE]; + bool mbCommandQueueInitialized; + cl_program mpArryPrograms[MAX_CLFILE_NUM]; //one program object maps one kernel source file + int mnIsUserCreated; // 1: created , 0:no create and needed to create by opencl wrapper + int mnCmdQueuePos; + bool mnKhrFp64Flag; + bool mnAmdFp64Flag; + bool mbNeedsTDRAvoidance; + + static bool isOpenCLEnabled(); +}; + +extern OPENCL_DLLPUBLIC GPUEnv gpuEnv; +extern OPENCL_DLLPUBLIC sal_uInt64 kernelFailures; + +OPENCL_DLLPUBLIC bool canUseOpenCL(); + +OPENCL_DLLPUBLIC bool generatBinFromKernelSource( cl_program program, const char * clFileName ); +OPENCL_DLLPUBLIC bool buildProgramFromBinary(const char* buildOption, GPUEnv* gpuEnv, const char* filename, int idx); +OPENCL_DLLPUBLIC void setKernelEnv( KernelEnv *envInfo ); +OPENCL_DLLPUBLIC const std::vector& fillOpenCLInfo(); + +/** + * Used to set or switch between OpenCL devices. + * + * @param pDeviceId the id of the opencl device of type cl_device_id, NULL means use software calculation + * @param bAutoSelect use the algorithm to select the best OpenCL device + * @param rOutSelectedDeviceVersionIDString returns the selected device's version string. + * + * @return returns true if there is a valid opencl device that has been set up + */ +OPENCL_DLLPUBLIC bool switchOpenCLDevice(const OUString* pDeviceId, bool bAutoSelect, + bool bForceEvaluation, + OUString& rOutSelectedDeviceVersionIDString); + +OPENCL_DLLPUBLIC void getOpenCLDeviceInfo(size_t& rDeviceId, size_t& rPlatformId); + +OPENCL_DLLPUBLIC void getOpenCLDeviceName(OUString& rDeviceName, OUString& rPlatformName); + +/** + * Set the current command queue position in case of multiple command queues + * for a given device. + */ +OPENCL_DLLPUBLIC void setOpenCLCmdQueuePosition( int nPos ); + +/** + * Return a textual representation of an OpenCL error code. + * (Currently the symbolic name sans the CL_ prefix.) + */ +OPENCL_DLLPUBLIC const char* errorString(cl_int nError); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/opencl/platforminfo.hxx b/include/opencl/platforminfo.hxx new file mode 100644 index 000000000..5e54c052f --- /dev/null +++ b/include/opencl/platforminfo.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OPENCL_PLATFORMINFO_HXX +#define INCLUDED_OPENCL_PLATFORMINFO_HXX + +#include +#include + +#include + +#include +#include + +// Struct that describs an actual instance of an OpenCL device + +struct OpenCLDeviceInfo +{ + cl_device_id device; + OUString maName; + OUString maVendor; + OUString maDriver; + size_t mnMemory; + size_t mnComputeUnits; + size_t mnFrequency; + + OpenCLDeviceInfo(); +}; + +// Struct that describs an actual instance of an OpenCL platform implementation + +struct OpenCLPlatformInfo +{ + cl_platform_id platform; + OUString maVendor; + OUString maName; + std::vector maDevices; + + OpenCLPlatformInfo(); +}; + +OPENCL_DLLPUBLIC std::ostream& operator<<(std::ostream& rStream, const OpenCLPlatformInfo& rPlatform); +OPENCL_DLLPUBLIC std::ostream& operator<<(std::ostream& rStream, const OpenCLDeviceInfo& rDevice); + +#endif diff --git a/include/osl/conditn.h b/include/osl/conditn.h new file mode 100644 index 000000000..b39167a2d --- /dev/null +++ b/include/osl/conditn.h @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_CONDITN_H +#define INCLUDED_OSL_CONDITN_H + +#include "sal/config.h" + +#include "osl/time.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* oslCondition; + +typedef enum { + osl_cond_result_ok, /* wait() will not block, check() returns True. + + @attention @em all threads waiting on this condition are unblocked! + + @param Condition handle to a created condition. + @retval False if system-call failed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setCondition(oslCondition Condition); + +/** Sets condition to False => wait() will block, check() returns False + + @param Condition handle to a created condition. + @retval False if system-call failed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_resetCondition(oslCondition Condition); + +/** Blocks if condition is not set. + + @param Condition handle to a created condition. + @param pTimeout Timeout value or NULL for infinite waiting + @retval False Condition has been destroyed prematurely or system call has failed. +*/ +SAL_DLLPUBLIC oslConditionResult SAL_CALL osl_waitCondition(oslCondition Condition, const TimeValue* pTimeout); + +/** Queries the state of the condition without blocking. + + @param Condition handle to a created condition. + + @retval True condition is set + @retval False condition is not set +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_checkCondition(oslCondition Condition); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_CONDITN_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/conditn.hxx b/include/osl/conditn.hxx new file mode 100644 index 000000000..5eb9ba431 --- /dev/null +++ b/include/osl/conditn.hxx @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_CONDITN_HXX +#define INCLUDED_OSL_CONDITN_HXX + +#include "sal/config.h" + +#include + +#include "osl/time.h" +#include "osl/conditn.h" + +#if defined(MACOSX) && defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES) +# if __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES == 1 +# undef check +# endif +#endif + +namespace osl +{ + /** Condition variable + + A condition variable is essentially an object that is initially + cleared which a thread waits on until it is "set". It allows a + thread to synchronize execution by allowing other threads to wait + for the condition to change before that thread then continues + execution. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + + @attention Warning: the Condition abstraction is inadequate for + any situation where there may be multiple threads setting, + waiting, and resetting the same condition. It can only be + used to synchronise interactions between two threads + cf. lost wakeups in http://www.cs.wustl.edu/~schmidt/win32-cv-1.html + */ + class Condition + { + public: + enum Result + { + result_ok = osl_cond_result_ok, /*!< Successful completion. */ + result_error = osl_cond_result_error, /*!< Error occurred. @see osl_getLastSocketError() */ + result_timeout = osl_cond_result_timeout /*!< Blocking operation timed out. */ + }; + + /** Create a condition. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + Condition() + { + condition = osl_createCondition(); + } + + /** Release the OS-structures and free condition data-structure. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + ~Condition() + { + osl_destroyCondition(condition); + } + + /** Release all waiting threads, check returns true. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + void set() + { + osl_setCondition(condition); + } + + /** Reset condition to false: wait() will block, check() returns + false. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + void reset() { + osl_resetCondition(condition); + } + + /** Blocks the calling thread until condition is set. + + @param [in] pTimeout Timeout to wait before ending the condition. + Defaults to NULL + + @retval result_ok finished successfully + @retval result_error error occurred + @retval result_timeout timed out + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + Result wait(const TimeValue *pTimeout = NULL) + { + return static_cast(osl_waitCondition(condition, pTimeout)); + } + +#if defined LIBO_INTERNAL_ONLY + Result wait(TimeValue const & timeout) { return wait(&timeout); } +#endif + + /** Checks if the condition is set without blocking. + + @retval true condition is set + @retval false condition is not set + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + bool check() + { + return osl_checkCondition(condition); + } + + + private: + oslCondition condition; /*< condition variable */ + + /** Copy constructor + + The underlying oslCondition has no reference count. + + Since the underlying oslCondition is not a reference counted + object, copy constructed Condition may work on an already + destructed oslCondition object. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + Condition(const Condition& condition) SAL_DELETED_FUNCTION; + + /** This assignment operator is deleted for the same reason as + the copy constructor. + + @deprecated use C++11's std::condition_variable instead + for a more robust and helpful condition. + */ + Condition& operator= (const Condition&) SAL_DELETED_FUNCTION; + }; +} + +#endif // INCLUDED_OSL_CONDITN_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/detail/android-bootstrap.h b/include/osl/detail/android-bootstrap.h new file mode 100644 index 000000000..169f3efaf --- /dev/null +++ b/include/osl/detail/android-bootstrap.h @@ -0,0 +1,59 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OSL_DETAIL_ANDROID_BOOTSTRAP_H +#define INCLUDED_OSL_DETAIL_ANDROID_BOOTSTRAP_H + +#if defined(ANDROID) + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +typedef struct lo_apk_dir lo_apk_dir; + +void *lo_apkentry(const char *filename, + size_t *size); + +lo_apk_dir *lo_apk_opendir(const char *dirname); + +struct dirent *lo_apk_readdir(lo_apk_dir *dirp); + +int lo_apk_closedir(lo_apk_dir *dirp); + +int lo_apk_lstat(const char *path, struct stat *statp); + +/// "libreofficekit_" prefix, because it is exported from the .so, when we are +/// initializing the JNI externally. +void libreofficekit_set_javavm(JavaVM *vm); + +JavaVM *lo_get_javavm(void); + +const char *lo_get_app_data_dir(void); + +AAssetManager *lo_get_native_assetmgr(void); + +int setup_cdir(void); +int setup_assets_tree(void); + +#ifdef __cplusplus +} +#endif + +#endif // ANDROID + +#endif // ANDROID_BOOTSTRAP_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/detail/component-defines.h b/include/osl/detail/component-defines.h new file mode 100644 index 000000000..9a31cee93 --- /dev/null +++ b/include/osl/detail/component-defines.h @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OSL_DETAIL_COMPONENT_DEFINES_H +#define INCLUDED_OSL_DETAIL_COMPONENT_DEFINES_H + +/* Experimental direct constructor calls, under construction */ + +/* FIXME: Rather than hardcoded, this should be generated from + solenv/bin/native-code.py */ + +#define LO_URE_CURRENT_ENV 1 /*TODO*/ + +// sax/source/expatwrap/expwrap.component +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_xml_dot_sax_dot_FastParser 1 /*TODO*/ +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_xml_dot_sax_dot_FastParser com_sun_star_comp_extensions_xml_sax_FastParser_get_implementation +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_xml_dot_sax_dot_Parser 1 /*TODO*/ +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_xml_dot_sax_dot_Parser com_sun_star_comp_extensions_xml_sax_ParserExpat_get_implementation +// sfx2/util/sfx.component +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_document_dot_DocumentProperties 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_document_dot_DocumentProperties SfxDocumentMetaData_get_implementation +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_frame_dot_OfficeFrameLoader 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_frame_dot_OfficeFrameLoader com_sun_star_comp_office_FrameLoader_get_implementation +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_frame_dot_SynchronousFrameLoader 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_frame_dot_SynchronousFrameLoader com_sun_star_comp_office_FrameLoader_get_implementation +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_frame_dot_DocumentTemplates 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_frame_dot_DocumentTemplates com_sun_star_comp_sfx2_DocumentTemplates_get_implementation +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_frame_dot_GlobalEventBroadcaster 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_frame_dot_GlobalEventBroadcaster com_sun_star_comp_sfx2_GlobalEventBroadcaster_get_implementation +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_frame_dot_theGlobalEventBroadcaster 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_frame_dot_theGlobalEventBroadcaster com_sun_star_comp_sfx2_GlobalEventBroadcaster_get_implementation +// svtools/util/svt_dot_component +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_graphic_dot_GraphicProvider 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_graphic_dot_GraphicProvider com_sun_star_comp_graphic_GraphicProvider_get_implementation +// svx/util/svx_dot_component +#define LO_URE_CTOR_ENV_com_dot_sun_dot_star_dot_drawing_dot_CustomShapeEngine 1 +#define LO_URE_CTOR_FUN_com_dot_sun_dot_star_dot_drawing_dot_CustomShapeEngine com_sun_star_drawing_EnhancedCustomShapeEngine_get_implementation + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/detail/component-mapping.h b/include/osl/detail/component-mapping.h new file mode 100644 index 000000000..4d4264180 --- /dev/null +++ b/include/osl/detail/component-mapping.h @@ -0,0 +1,48 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OSL_DETAIL_COMPONENT_MAPPING_H +#define INCLUDED_OSL_DETAIL_COMPONENT_MAPPING_H + +#ifdef DISABLE_DYNLOADING + +#ifdef __cplusplus +extern "C" { +#endif + +/* On iOS and perhaps Android static linking of the LO code into one + * executable (on Android, into one shared library) is used. In order to get + * the needed UNO component linked in, the "main" code for an app needs to + * implement the lo_get_libmap() function to map UNO component library names + * as produced in a build for iOS (like configmgr.uno.a or libsclo.a) to the + * corresponding component_getFactory functions. + */ + +typedef struct { + const char *name; + void * (*component_getFactory_function)(const char *, void *, void *); +} lib_to_factory_mapping; + +typedef struct { + const char *name; + void * (*constructor_function)(void *, void *); +} lib_to_constructor_mapping; + +const lib_to_factory_mapping *lo_get_factory_map(void); +const lib_to_constructor_mapping *lo_get_constructor_map(void); + +#ifdef __cplusplus +} +#endif + +#endif /* DISABLE_DYNLOADING */ + +#endif // INCLUDED_OSL_DETAIL_COMPONENT_MAPPING_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/detail/file.h b/include/osl/detail/file.h new file mode 100644 index 000000000..acc308b8f --- /dev/null +++ b/include/osl/detail/file.h @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_OSL_DETAIL_FILE_H +#define INCLUDED_OSL_DETAIL_FILE_H + +#include "sal/config.h" + +/** @cond INTERNAL */ + +/* Some additions to the osl file functions for LibreOffice internal + use. Needed for details in the Android support. + */ + +/* More flags needed for semantics that match the open() call that + used to be in SvFileStream::Open(), and for temp files: +*/ +#define osl_File_OpenFlag_Trunc 0x00000010L +#define osl_File_OpenFlag_NoExcl 0x00000020L +#define osl_File_OpenFlag_Private 0x00000040L + +/** @endcond */ + +#endif /* INCLUDED_OSL_DETAIL_FILE_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/diagnose.h b/include/osl/diagnose.h new file mode 100644 index 000000000..356f2945b --- /dev/null +++ b/include/osl/diagnose.h @@ -0,0 +1,124 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_DIAGNOSE_H +#define INCLUDED_OSL_DIAGNOSE_H + +#include "sal/config.h" + +#include "sal/detail/log.h" +#include "sal/types.h" + +/** @file + Provides simple diagnostic support. + + @deprecated + The facilities provided by this header are deprecated. True assertions + (that detect broken program logic) should use standard assert (which aborts + if an assertion fails, and is controlled by the standard NDEBUG macro). + Logging of warnings (e.g., about malformed input) and traces (e.g., about + steps taken while executing some protocol) should use the facilities + provided by (C++ only) sal/log.hxx. + + Because the assertion macros (OSL_ASSERT, OSL_ENSURE, OSL_FAIL, OSL_PRECOND, + and OSL_POSTCOND) have been used for true assertions as well as for logged + warnings, they map to SAL_WARN instead of standard assert. OSL_TRACE maps + to SAL_INFO. + + The functions defined in this header are not intended to be used directly, + but through defined macros. The macros can be divided into three categories: + assertions, traces and other stuff .-) Their usability depends on the value + of OSL_DEBUG_LEVEL macro: assertions are only active if OSL_DEBUG_LEVEL is 1 + or greater, traces if OSL_DEBUG_LEVEL is 2 or greater. + + Traces: + OSL_TRACE(fmt, args...) + Prints trace message. The arguments have the same meaning as the + arguments of printf. + */ + +#if !defined OSL_DEBUG_LEVEL +#define OSL_DEBUG_LEVEL 0 +#endif + +/** @internal The macro OSL_LOG_PREFIX is intended to be an office internal macro for now + @deprecated superseded by (C++ only) SAL_WHERE +*/ +#define OSL_LOG_PREFIX SAL_DETAIL_WHERE + +/** Prints trace message. + + The arguments have the same meaning as the arguments of printf. +*/ +#define OSL_TRACE(...) \ + SAL_DETAIL_INFO_IF_FORMAT(OSL_DEBUG_LEVEL > 0, "legacy.osl", __VA_ARGS__) + +/** @defgroup assert Assertions + + Assertions (cond is bool, msg is char*). + + @{ + */ + +/** If cond is false, reports an error. */ +#define OSL_ASSERT(c) \ + SAL_DETAIL_WARN_IF_FORMAT(!(c), "legacy.osl", "OSL_ASSERT: %s", #c) +/** If cond is false, reports an error with message msg. */ +#define OSL_ENSURE(c, m) SAL_DETAIL_WARN_IF_FORMAT(!(c), "legacy.osl", "%s", m) +/** Reports an error with message msg unconditionally. */ +#define OSL_FAIL(m) SAL_DETAIL_WARN_IF_FORMAT(sal_True, "legacy.osl", "%s", m) + +/** Evaluates the expression and if it is false, reports an error. The + expression is evaluated once without regard of the value of + OSL_DEBUG_LEVEL. + + Example: + + @code{.c} + + void extractBool(Any const& rAny, bool& rBool) + { + OSL_VERIFY(rAny >>= rBool); + } + + @endcode +*/ +#define OSL_VERIFY(c) do { if (!(c)) OSL_ASSERT(0); } while (0) + +/** Check the precondition of functions. + + Functionally equivalent to OSL_ENSURE(cond, msg). +*/ +#define OSL_PRECOND(c, m) OSL_ENSURE(c, m) + +/** Check the postcondition of functions. + + Functionally equivalent to OSL_ENSURE(cond, msg). +*/ +#define OSL_POSTCOND(c, m) OSL_ENSURE(c, m) + +/** @} */ + +#endif // INCLUDED_OSL_DIAGNOSE_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/diagnose.hxx b/include/osl/diagnose.hxx new file mode 100644 index 000000000..71d49f3d8 --- /dev/null +++ b/include/osl/diagnose.hxx @@ -0,0 +1,200 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_OSL_DIAGNOSE_HXX +#define INCLUDED_OSL_DIAGNOSE_HXX + +/// @cond INTERNAL + +#include "sal/config.h" + +#include +#include +#include + +#include "osl/diagnose.h" +#include "osl/interlck.h" +#include "osl/mutex.hxx" +#include "rtl/instance.hxx" +#include "sal/log.hxx" +#include "sal/saldllapi.h" +#include "sal/types.h" + +namespace osl { +namespace detail { + +struct ObjectRegistryData; + +} // namespace detail +} // namespace osl + +extern "C" { + +SAL_DLLPUBLIC bool SAL_CALL osl_detail_ObjectRegistry_storeAddresses( + char const* pName ) + SAL_THROW_EXTERN_C(); + +SAL_DLLPUBLIC bool SAL_CALL osl_detail_ObjectRegistry_checkObjectCount( + ::osl::detail::ObjectRegistryData const& rData, ::std::size_t nExpected ) + SAL_THROW_EXTERN_C(); + +SAL_DLLPUBLIC void SAL_CALL osl_detail_ObjectRegistry_registerObject( + ::osl::detail::ObjectRegistryData & rData, void const* pObj ) + SAL_THROW_EXTERN_C(); + +SAL_DLLPUBLIC void SAL_CALL osl_detail_ObjectRegistry_revokeObject( + ::osl::detail::ObjectRegistryData & rData, void const* pObj ) + SAL_THROW_EXTERN_C(); + +// These functions presumably should not be extern "C", but changing +// that would break binary compatibility. +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreturn-type-c-linkage" +#endif + +SAL_DLLPUBLIC ::osl::Mutex & SAL_CALL osl_detail_ObjectRegistry_getMutex() + SAL_THROW_EXTERN_C(); + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +} // extern "C" + +namespace osl { + +namespace detail { + +struct VoidPtrHash { + ::std::size_t operator()( void const* p ) const { + ::std::size_t const d = static_cast< ::std::size_t >( + reinterpret_cast< ::std::ptrdiff_t >(p) ); + return d + (d >> 3); + } +}; + +typedef ::std::unordered_set VoidPointerSet; + +struct ObjectRegistryData { + ObjectRegistryData( ::std::type_info const& rTypeInfo ) + : m_pName(rTypeInfo.name()), m_nCount(0), + m_bStoreAddresses(osl_detail_ObjectRegistry_storeAddresses(m_pName)) {} + + char const* const m_pName; + oslInterlockedCount m_nCount; + VoidPointerSet m_addresses; + bool const m_bStoreAddresses; +}; + +template +class ObjectRegistry +{ +public: + ObjectRegistry() : m_data( typeid(T) ) {} + ~ObjectRegistry() { checkObjectCount(0); } + + bool checkObjectCount( ::std::size_t nExpected ) const { + bool const bRet = osl_detail_ObjectRegistry_checkObjectCount( + m_data, nExpected ); + if (!bRet && m_data.m_bStoreAddresses) { + MutexGuard const guard( osl_detail_ObjectRegistry_getMutex() ); + // following loop is for debugging purposes, iterating over map: + VoidPointerSet::const_iterator iPos(m_data.m_addresses.begin()); + VoidPointerSet::const_iterator const iEnd(m_data.m_addresses.end()); + for ( ; iPos != iEnd; ++iPos ) { + SAL_WARN_IF( *iPos == NULL, "sal.debug", "null pointer" ); + } + } + return bRet; + } + + void registerObject( void const* pObj ) { + osl_detail_ObjectRegistry_registerObject(m_data, pObj); + } + + void revokeObject( void const* pObj ) { + osl_detail_ObjectRegistry_revokeObject(m_data, pObj); + } + +private: + ObjectRegistry( ObjectRegistry const& ) SAL_DELETED_FUNCTION; + ObjectRegistry const& operator=( ObjectRegistry const& ) SAL_DELETED_FUNCTION; + + ObjectRegistryData m_data; +}; + +} // namespace detail + +/** Helper class which indicates leaking object(s) of a particular class in + non-pro builds; use e.g. + + @code{.cpp} + class MyClass : private osl::DebugBase {...}; + @endcode + + Using the environment variable + + OSL_DEBUGBASE_STORE_ADDRESSES=MyClass;YourClass;... + + you can specify a ';'-separated list of strings matching to class names + (or "all" for all classes), for which DebugBase stores addresses to created + objects instead of just counting them. This enables you to iterate over + leaking objects in your debugger. + + @tparam InheritingClassT binds the template instance to that class + @attention Use at own risk. + For now this is just public (yet unpublished) API and may change + in the future! +*/ +template +class DebugBase +{ +public: +#if OSL_DEBUG_LEVEL <= 0 + static bool checkObjectCount( ::std::size_t = 0 ) { return true; } +#else // OSL_DEBUG_LEVEL > 0 + /** @return whether the expected number of objects is alive, + else this function SAL_WARNs + */ + static bool checkObjectCount( ::std::size_t nExpected = 0 ) { + return StaticObjectRegistry::get().checkObjectCount(nExpected); + } + +protected: + DebugBase() { + StaticObjectRegistry::get().registerObject( this ); + } + ~DebugBase() { + StaticObjectRegistry::get().revokeObject( this ); + } + +private: + struct StaticObjectRegistry + : ::rtl::Static, + StaticObjectRegistry> {}; +#endif +}; + +} // namespace osl + +/// @endcond + +#endif // ! defined( INCLUDED_OSL_DIAGNOSE_HXX) + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/doublecheckedlocking.h b/include/osl/doublecheckedlocking.h new file mode 100644 index 000000000..f89ab3620 --- /dev/null +++ b/include/osl/doublecheckedlocking.h @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H +#define INCLUDED_OSL_DOUBLECHECKEDLOCKING_H + +#if defined __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** A platform specific macro needed to make double-checked locking work. + + See + + for a description of double-checked locking, why it is broken, and how it + can be fixed. On platforms where it is necessary, this macro will expand + to some memory barrier instruction. On many platforms, double-checked + locking works as it is, though, so on those platforms this macro will be + empty. This is a macro instead of a (C++ inline) function to allow for + maximum performance in both C and C++. + + If possible, use the rtl_Instance template instead of explicitly spelling + out the double-checked locking pattern. There are few cases where you + will have to spell it out explicitly (e.g., the logic of a certain + instance of the pattern is too complex to be mapped to the template, or + some compiler refuses to compile a template instantiation due to internal + compiler errors), though, and you should always call this macro at the + right places then: + + @code{.cpp} + static T * pInstance = 0; + + T * p = pInstance; + if (!p) + { + Guard aGuard(aMutex); + p = pInstance; + if (!p) + { + p = ...; + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + pInstance = p; + } + } + else + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + return p; + @endcode + + One extra advantage of this macro is that it makes it easier to find all + places where double-checked locking is used. + */ +#define OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER() /* empty */ + +#if defined __cplusplus +} +#endif /* __cplusplus */ + +#endif /* INCLUDED_OSL_DOUBLECHECKEDLOCKING_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/endian.h b/include/osl/endian.h new file mode 100644 index 000000000..fb9b514c1 --- /dev/null +++ b/include/osl/endian.h @@ -0,0 +1,155 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_ENDIAN_H +#define INCLUDED_OSL_ENDIAN_H + +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Define the platform byte order as OSL_BIGENDIAN or OSL_LITENDIAN. + */ + +#if defined _WIN32 +# if defined _M_ALPHA || defined _M_AMD64 || defined _M_IX86 \ + || defined _M_MRX000 || defined _M_PPC || defined _M_ARM64 +# define OSL_LITENDIAN +# endif +#elif defined ANDROID || defined LINUX || defined HAIKU +# include +# if __BYTE_ORDER == __LITTLE_ENDIAN +# define OSL_LITENDIAN +# elif __BYTE_ORDER == __BIG_ENDIAN +# define OSL_BIGENDIAN +# endif +#elif defined IOS || defined MACOSX || defined NETBSD +# include +# if BYTE_ORDER == LITTLE_ENDIAN +# define OSL_LITENDIAN +# elif BYTE_ORDER == BIG_ENDIAN +# define OSL_BIGENDIAN +# endif +#elif defined FREEBSD +# include +# include +# if defined _LITTLE_ENDIAN +# define OSL_LITENDIAN +# elif defined _BIG_ENDIAN +# define OSL_BIGENDIAN +# endif +#elif defined AIX +# include +# if BYTE_ORDER == LITTLE_ENDIAN +# define OSL_LITENDIAN +# elif BYTE_ORDER == BIG_ENDIAN +# define OSL_BIGENDIAN +# endif +#elif defined __sun +# include +# if defined _LITTLE_ENDIAN +# define OSL_LITENDIAN +# elif defined _BIG_ENDIAN +# define OSL_BIGENDIAN +# endif +#elif defined EMSCRIPTEN +# define OSL_LITENDIAN +#else +# error "Target platform not specified !" +#endif +#if defined OSL_LITENDIAN == defined OSL_BIGENDIAN +# error undetermined endianness +#endif + + +/** Define macros for byte order manipulation. + */ +#ifndef OSL_MAKEBYTE +# define OSL_MAKEBYTE(nl, nh) ((sal_uInt8)(((nl) & 0x0F) | (((nh) & 0x0F) << 4))) +#endif +#ifndef OSL_LONIBBLE +# define OSL_LONIBBLE(b) ((sal_uInt8)((b) & 0x0F)) +#endif +#ifndef OSL_HINIBBLE +# define OSL_HINIBBLE(b) ((sal_uInt8)(((b) >> 4) & 0x0F)) +#endif + +#ifndef OSL_MAKEWORD +# define OSL_MAKEWORD(bl, bh) ((sal_uInt16)((sal_uInt16)((bl) & 0xFF) | (((sal_uInt16)(bh) & 0xFF) << 8))) +#endif +#ifndef OSL_LOBYTE +# define OSL_LOBYTE(w) ((sal_uInt8)((sal_uInt16)(w) & 0xFF)) +#endif +#ifndef OSL_HIBYTE +# define OSL_HIBYTE(w) ((sal_uInt8)(((sal_uInt16)(w) >> 8) & 0xFF)) +#endif + +#ifndef OSL_MAKEDWORD +# define OSL_MAKEDWORD(wl, wh) ((sal_uInt32)((wl) & 0xFFFF) | (((sal_uInt32)(wh) & 0xFFFF) << 16)) +#endif +#ifndef OSL_LOWORD +# define OSL_LOWORD(d) ((sal_uInt16)((sal_uInt32)(d) & 0xFFFF)) +#endif +#ifndef OSL_HIWORD +# define OSL_HIWORD(d) ((sal_uInt16)(((sal_uInt32)(d) >> 16) & 0xFFFF)) +#endif + + +/** Define macros for swapping between host and network byte order. + */ +#ifdef OSL_BIGENDIAN +#ifndef OSL_NETWORD +# define OSL_NETWORD(w) (sal_uInt16)(w) +#endif +#ifndef OSL_NETDWORD +# define OSL_NETDWORD(d) (sal_uInt32)(d) +#endif +#else /* OSL_LITENDIAN */ +#ifndef OSL_NETWORD +# define OSL_NETWORD(w) OSL_MAKEWORD(OSL_HIBYTE(w),OSL_LOBYTE(w)) +#endif +#ifndef OSL_NETDWORD +# define OSL_NETDWORD(d) OSL_MAKEDWORD(OSL_NETWORD(OSL_HIWORD(d)),OSL_NETWORD(OSL_LOWORD(d))) +#endif +#endif /* OSL_BIGENDIAN */ + + +/** Define macros for swapping between byte orders. + */ +#ifndef OSL_SWAPWORD +# define OSL_SWAPWORD(w) OSL_MAKEWORD(OSL_HIBYTE(w),OSL_LOBYTE(w)) +#endif +#ifndef OSL_SWAPDWORD +# define OSL_SWAPDWORD(d) OSL_MAKEDWORD(OSL_SWAPWORD(OSL_HIWORD(d)),OSL_SWAPWORD(OSL_LOWORD(d))) +#endif + + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_ENDIAN_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/file.h b/include/osl/file.h new file mode 100644 index 000000000..07d2beb2a --- /dev/null +++ b/include/osl/file.h @@ -0,0 +1,1677 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_FILE_H +#define INCLUDED_OSL_FILE_H + +#include "sal/config.h" + +#include "osl/time.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @file + +Main goals and usage hints + +The main intention of this interface is to provide a universal portable and +high performance access to file system functionality on any operating +system. + +There are a few main goals: + +1. The path specifications always has to be absolute. Any usage of relative +path specifications is forbidden. Exceptions are osl_getSystemPathFromFileURL, +osl_getFileURLFromSystemPath and osl_getAbsoluteFileURL. Most operating +systems provide a "Current Directory" per process. This is the reason why +relative path specifications can cause problems in multithreading +environments. + +2. Proprietary notations of file paths are not supported. Every path notation +must the file URL specification. File URLs must be encoded in UTF8 and after +that escaped. Although the URL parameter is a unicode string, the must +contain only ASCII characters. + +3. The caller cannot get any information whether a file system is case +sensitive, case preserving or not. The operating system implementation +itself should determine if it can map case-insensitive paths. The case +correct notation of a filename or file path is part of the "File Info". This +case correct name can be used as a unique key if necessary. + +4. Obtaining information about files or volumes is controlled by a bitmask +which specifies which fields are of interest. Due to performance reasons it +is not recommended to obtain information which is not needed. But if the +operating system provides more information anyway the implementation can set +more fields on output as were requested. It is in the responsibility of the +caller to decide if they use this additional information or not. But they +should do so to prevent further unnecessary calls if the information is +already there. + +The input bitmask supports a flag osl_FileStatus_Mask_Validate which can be +used to force retrieving uncached validated information. Setting this flag +when calling osl_getFileStatus in combination with no other flag is a synonym +for a "FileExists". This should only be done when processing a single file +(i.e. before opening) and NEVER during enumeration of directory contents on +any step of information processing. This would change the runtime behaviour +from O(n) to O(n*n/2) on nearly every file system. On Windows NT reading the +contents of a directory with 7000 entries and getting full information about +every file only takes 0.6 seconds. Specifying the flag +osl_FileStatus_Mask_Validate for each entry will increase the time to 180 +seconds (!!!). + +*/ + +/* Error codes according to errno */ +typedef enum { + osl_File_E_None, /*!< on success */ + osl_File_E_PERM, /*!< operation not permitted */ + osl_File_E_NOENT, /*!< no such file or directory */ + osl_File_E_SRCH, /*!< no process matches the PID */ + osl_File_E_INTR, /*!< function call was interrupted */ + osl_File_E_IO, /*!< I/O error occurred */ + osl_File_E_NXIO, /*!< no such device or address */ + osl_File_E_2BIG, /*!< argument list too long */ + osl_File_E_NOEXEC, /*!< invalid executable file format */ + osl_File_E_BADF, /*!< bad file descriptor */ + osl_File_E_CHILD, /*!< there are no child processes */ + osl_File_E_AGAIN, /*!< resource temp unavailable, try again later */ + osl_File_E_NOMEM, /*!< no memory available */ + osl_File_E_ACCES, /*!< file permissions do not allow operation */ + osl_File_E_FAULT, /*!< bad address; an invalid pointer detected */ + osl_File_E_BUSY, /*!< resource busy */ + osl_File_E_EXIST, /*!< file exists where should only be created */ + osl_File_E_XDEV, /*!< improper link across file systems detected */ + osl_File_E_NODEV, /*!< wrong device type specified */ + osl_File_E_NOTDIR, /*!< file isn't a directory where one is needed */ + osl_File_E_ISDIR, /*!< file is a directory, invalid operation */ + osl_File_E_INVAL, /*!< invalid argument to library function */ + osl_File_E_NFILE, /*!< too many distinct file openings */ + osl_File_E_MFILE, /*!< process has too many distinct files open */ + osl_File_E_NOTTY, /*!< inappropriate I/O control operation */ + osl_File_E_FBIG, /*!< file too large */ + osl_File_E_NOSPC, /*!< no space left on device, write failed */ + osl_File_E_SPIPE, /*!< invalid seek operation (such as on pipe) */ + osl_File_E_ROFS, /*!< illegal modification to read-only filesystem */ + osl_File_E_MLINK, /*!< too many links to file */ + osl_File_E_PIPE, /*!< broken pipe; no process reading from other end of pipe */ + osl_File_E_DOM, /*!< domain error (mathematical error) */ + osl_File_E_RANGE, /*!< range error (mathematical error) */ + osl_File_E_DEADLK, /*!< deadlock avoided */ + osl_File_E_NAMETOOLONG, /*!< filename too long */ + osl_File_E_NOLCK, /*!< no locks available */ + osl_File_E_NOSYS, /*!< function not implemented */ + osl_File_E_NOTEMPTY, /*!< directory not empty */ + osl_File_E_LOOP, /*!< too many levels of symbolic links found during name lookup */ + osl_File_E_ILSEQ, /*!< invalid or incomplete byte sequence of multibyte char found */ + osl_File_E_NOLINK, /*!< link has been severed */ + osl_File_E_MULTIHOP, /*!< remote resource is not directly available */ + osl_File_E_USERS, /*!< file quote system is confused as there are too many users */ + osl_File_E_OVERFLOW, /*!< value too large for defined data type */ + osl_File_E_NOTREADY, /*!< device not ready */ + osl_File_E_invalidError, /*!< unmapped error: always last entry in enum! */ + osl_File_E_TIMEDOUT, /*!< socket operation timed out */ + osl_File_E_NETWORK, /*!< unexpected network error occurred (Windows) - could be a + user session was deleted, or an unexpected network error + occurred */ + osl_File_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslFileError; + +typedef void *oslDirectory; +typedef void *oslDirectoryItem; + +/** Open a directory for enumerating its contents. + + @param[in] pustrDirectoryURL + The full qualified URL of the directory. + + @param[out] pDirectory + On success it receives a handle used for subsequent calls by osl_getNextDirectoryItem(). + The handle has to be released by a call to osl_closeDirectory(). + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOENT the specified path doesn't exist + @retval osl_File_E_NOTDIR the specified path is not a directory + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_MFILE too many open files used by the process + @retval osl_File_E_NFILE too many open files in the system + @retval osl_File_E_NAMETOOLONG File name too long + @retval osl_File_E_LOOP Too many symbolic links encountered + + @see osl_getNextDirectoryItem() + @see osl_closeDirectory() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_openDirectory( + rtl_uString *pustrDirectoryURL, oslDirectory *pDirectory); + +/** Retrieve the next item of a previously opened directory. + + Retrieves the next item of a previously opened directory. + All handles have an initial refcount of 1. + + @param[in] Directory + A directory handle received from a previous call to osl_openDirectory(). + + @param[out] pItem + On success it receives a handle that can be used for subsequent calls to osl_getFileStatus(). + The handle has to be released by a call to osl_releaseDirectoryItem(). + + @param[in] uHint + With this parameter the caller can tell the implementation that (s)he + is going to call this function uHint times afterwards. This enables the implementation to + get the information for more than one file and cache it until the next calls. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_NOENT no more entries in this directory + @retval osl_File_E_BADF invalid oslDirectory parameter + @retval osl_File_E_OVERFLOW the value too large for defined data type + + @see osl_releaseDirectoryItem() + @see osl_acquireDirectoryItem() + @see osl_getDirectoryItem() + @see osl_getFileStatus() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getNextDirectoryItem( + oslDirectory Directory, + oslDirectoryItem *pItem, + sal_uInt32 uHint + ); + +/** Release a directory handle. + + @param[in] Directory + A handle received by a call to osl_openDirectory(). + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_BADF invalid oslDirectory parameter + @retval osl_File_E_INTR the function call was interrupted + + @see osl_openDirectory() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_closeDirectory( + oslDirectory Directory); + +/** Retrieve a single directory item. + + Retrieves a single directory item. The returned handle has an initial refcount of 1. + Due to performance issues it is not recommended to use this function while + enumerating the contents of a directory. In this case use osl_getNextDirectoryItem() instead. + + @param[in] pustrFileURL + An absolute file URL. + + @param[out] pItem + On success it receives a handle which can be used for subsequent calls to osl_getFileStatus(). + The handle has to be released by a call to osl_releaseDirectoryItem(). + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_MFILE too many open files used by the process + @retval osl_File_E_NFILE too many open files in the system + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_NAMETOOLONG the file name is too long + @retval osl_File_E_NOTDIR a component of the path prefix of path is not a directory + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_FAULT bad address + @retval osl_File_E_INTR the function call was interrupted + + @see osl_releaseDirectoryItem() + @see osl_acquireDirectoryItem() + @see osl_getFileStatus() + @see osl_getNextDirectoryItem() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getDirectoryItem( + rtl_uString *pustrFileURL, + oslDirectoryItem *pItem + ); + +/** Increase the refcount of a directory item handle. + + The caller responsible for releasing the directory item handle using osl_releaseDirectoryItem(). + + @param[in] Item + A handle received by a call to osl_getDirectoryItem() or osl_getNextDirectoryItem(). + + @retval osl_File_E_None on success + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getDirectoryItem() + @see osl_getNextDirectoryItem() + @see osl_releaseDirectoryItem() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_acquireDirectoryItem( + oslDirectoryItem Item ); + + +/** Decrease the refcount of a directory item handle. + + Decreases the refcount of a directory item handle. + If the refcount reaches 0 the data associated with + this directory item handle will be released. + + @param[in] Item + A handle received by a call to osl_getDirectoryItem() or osl_getNextDirectoryItem(). + + @retval osl_File_E_None on success + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getDirectoryItem() + @see osl_getNextDirectoryItem() + @see osl_acquireDirectoryItem() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_releaseDirectoryItem( + oslDirectoryItem Item ); + +/** Determine if two directory items point the same underlying file + + The comparison is done first by URL, and then by resolving links to + find the target, and finally by comparing inodes on unix. + + @param[in] pItemA + A directory handle to compare with another handle + + @param[in] pItemB + A directory handle to compare with pItemA + + @retval sal_True if the items point to an identical resource + @retval sal_False if the items point to a different resource, or a fatal error occurred + + @see osl_getDirectoryItem() + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_identicalDirectoryItem( + oslDirectoryItem pItemA, + oslDirectoryItem pItemB ); + +/** + @defgroup filetype File types + + @{ + */ +typedef enum { + osl_File_Type_Directory, /*< directory */ + osl_File_Type_Volume, /*< volume (e.g. C:, A:) */ + osl_File_Type_Regular, /*< regular file */ + osl_File_Type_Fifo, /*< named pipe */ + osl_File_Type_Socket, /*< socket */ + osl_File_Type_Link, /*< file link */ + osl_File_Type_Special, /*< special device file */ + osl_File_Type_Unknown /*< unknown file type */ +} oslFileType; +/** @} */ + +/** + @defgroup fileattrs File attributes + + @{ + */ +#define osl_File_Attribute_ReadOnly 0x00000001 +#define osl_File_Attribute_Hidden 0x00000002 +#define osl_File_Attribute_Executable 0x00000010 +#define osl_File_Attribute_GrpWrite 0x00000020 +#define osl_File_Attribute_GrpRead 0x00000040 +#define osl_File_Attribute_GrpExe 0x00000080 +#define osl_File_Attribute_OwnWrite 0x00000100 +#define osl_File_Attribute_OwnRead 0x00000200 +#define osl_File_Attribute_OwnExe 0x00000400 +#define osl_File_Attribute_OthWrite 0x00000800 +#define osl_File_Attribute_OthRead 0x00001000 +#define osl_File_Attribute_OthExe 0x00002000 +/** @} */ + +/** + @defgroup filestatus Flags specifying which fields to retrieve by osl_getFileStatus + + @{ + */ +#define osl_FileStatus_Mask_Type 0x00000001 +#define osl_FileStatus_Mask_Attributes 0x00000002 +#define osl_FileStatus_Mask_CreationTime 0x00000010 +#define osl_FileStatus_Mask_AccessTime 0x00000020 +#define osl_FileStatus_Mask_ModifyTime 0x00000040 +#define osl_FileStatus_Mask_FileSize 0x00000080 +#define osl_FileStatus_Mask_FileName 0x00000100 +#define osl_FileStatus_Mask_FileURL 0x00000200 +#define osl_FileStatus_Mask_LinkTargetURL 0x00000400 +#define osl_FileStatus_Mask_All 0x7FFFFFFF +#define osl_FileStatus_Mask_Validate 0x80000000 +/** @} */ + +/** Structure containing information about files and directories + + @see osl_getFileStatus() + @see oslFileType +*/ +typedef struct _oslFileStatus { +/** Must be initialized with the size in bytes of the structure before passing it to any function */ + sal_uInt32 uStructSize; +/** Determines which members of the structure contain valid data */ + sal_uInt32 uValidFields; +/** The type of the file (file, directory, volume). */ + oslFileType eType; +/** File attributes */ + sal_uInt64 uAttributes; +/** First creation time in nanoseconds since 1/1/1970. Can be the last modify time depending on + platform or file system. */ + TimeValue aCreationTime; +/** Last access time in nanoseconds since 1/1/1970. Can be the last modify time depending on + platform or file system. */ + TimeValue aAccessTime; +/** Last modify time in nanoseconds since 1/1/1970. */ + TimeValue aModifyTime; +/** Size in bytes of the file. Zero for directories and volumes. */ + sal_uInt64 uFileSize; +/** Case correct name of the file. Should be set to zero before calling osl_getFileStatus + and released after usage. */ + rtl_uString *ustrFileName; +/** Full URL of the file. Should be set to zero before calling osl_getFileStatus + and released after usage. */ + rtl_uString *ustrFileURL; +/** Full URL of the target file if the file itself is a link. + Should be set to zero before calling osl_getFileStatus + and released after usage. */ + rtl_uString *ustrLinkTargetURL; +} oslFileStatus; + +/** Retrieve information about a single file or directory. + + @param[in] Item + A handle received by a previous call to osl_getDirectoryItem() or osl_getNextDirectoryItem(). + + @param[in,out] pStatus + Points to a structure which receives the information of the file or directory + represented by the handle Item. The member uStructSize has to be initialized to + sizeof(oslFileStatus) before calling this function. + + @param[in] uFieldMask + Specifies which fields of the structure pointed to by pStatus are of interest to the caller. + + @retval osl_File_E_None on success + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_BADF invalid oslDirectoryItem parameter + @retval osl_File_E_FAULT bad address + @retval osl_File_E_OVERFLOW value too large for defined data type + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_MULTIHOP components of path require hopping to multiple + remote machines and the file system does not allow it + @retval osl_File_E_MFILE too many open files used by the process + @retval osl_File_E_NFILE too many open files in the system + @retval osl_File_E_NOSPC no space left on device + @retval osl_File_E_NXIO no such device or address + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_NOSYS function not implemented + + @see osl_getDirectoryItem() + @see osl_getNextDirectoryItem() + @see oslFileStatus +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFileStatus( + oslDirectoryItem Item, oslFileStatus *pStatus, sal_uInt32 uFieldMask ); + +typedef void *oslVolumeDeviceHandle; + +/** Release a volume device handle. + + Releases the given oslVolumeDeviceHandle which was acquired by a call to + osl_getVolumeInformation() or osl_acquireVolumeDeviceHandle(). + + @param[in] Handle + An oslVolumeDeviceHandle received by a call to osl_getVolumeInformation(). + + @retval + osl_File_E_None on success + + @todo + specify all error codes that may be returned + + @see osl_acquireVolumeDeviceHandle() + @see osl_getVolumeInformation() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_releaseVolumeDeviceHandle( + oslVolumeDeviceHandle Handle ); + +/** Acquire a volume device handle. + + Acquires the given oslVolumeDeviceHandle which was acquired by a call to + osl_getVolumeInformation(). The caller is responsible for releasing the + acquired handle by calling osl_releaseVolumeDeviceHandle(). + + @param[in] Handle + An oslVolumeDeviceHandle received by a call to osl_getVolumeInformation(). + + @retval + osl_File_E_None on success + + @todo + specify all error codes that may be returned + + @see osl_getVolumeInformation() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_acquireVolumeDeviceHandle( + oslVolumeDeviceHandle Handle ); + +/** Get the full qualified URL where a device is mounted to. + + @param[in] Handle + An oslVolumeDeviceHandle received by a call to osl_getVolumeInformation(). + + @param[out] ppustrDirectoryURL + Receives the full qualified URL where the device is mounted to. + + @retval osl_File_E_None on success + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_NXIO no such device or address + @retval osl_File_E_NODEV no such device + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_FAULT bad address + @retval osl_FilE_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_EOVERFLOW value too large for defined data type + + @see osl_getVolumeInformation() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getVolumeDeviceMountPath( + oslVolumeDeviceHandle Handle, rtl_uString **ppustrDirectoryURL); + +/** + @defgroup volattrs Volume attributes + + @{ + */ +#define osl_Volume_Attribute_Removeable 0x00000001 +#define osl_Volume_Attribute_Remote 0x00000002 +#define osl_Volume_Attribute_CompactDisc 0x00000004 +#define osl_Volume_Attribute_FixedDisk 0x00000008 +#define osl_Volume_Attribute_RAMDisk 0x00000010 +#define osl_Volume_Attribute_FloppyDisk 0x00000020 + +#define osl_Volume_Attribute_Case_Is_Preserved 0x00000040 +#define osl_Volume_Attribute_Case_Sensitive 0x00000080 + +/** @} */ + +/** + @defgroup volinfoflags Flags specifying which fields to retrieve by osl_getVolumeInfo + + @{ + */ + +#define osl_VolumeInfo_Mask_Attributes 0x00000001 +#define osl_VolumeInfo_Mask_TotalSpace 0x00000002 +#define osl_VolumeInfo_Mask_UsedSpace 0x00000004 +#define osl_VolumeInfo_Mask_FreeSpace 0x00000008 +#define osl_VolumeInfo_Mask_MaxNameLength 0x00000010 +#define osl_VolumeInfo_Mask_MaxPathLength 0x00000020 +#define osl_VolumeInfo_Mask_FileSystemName 0x00000040 +#define osl_VolumeInfo_Mask_DeviceHandle 0x00000080 +#define osl_VolumeInfo_Mask_FileSystemCaseHandling 0x00000100 + +/** @} */ + +/** Structure containing information about volumes + + @see osl_getVolumeInformation() + @see oslFileType +*/ + +typedef struct _oslVolumeInfo { +/** Must be initialized with the size in bytes of the structure before + passing it to any function */ + sal_uInt32 uStructSize; +/** Determines which members of the structure contain valid data */ + sal_uInt32 uValidFields; +/** Attributes of the volume (remote and/or removable) */ + sal_uInt32 uAttributes; +/** Total available space on the volume for the current process/user */ + sal_uInt64 uTotalSpace; +/** Used space on the volume for the current process/user */ + sal_uInt64 uUsedSpace; +/** Free space on the volume for the current process/user */ + sal_uInt64 uFreeSpace; +/** Maximum length of file name of a single item */ + sal_uInt32 uMaxNameLength; +/** Maximum length of a full qualified path in system notation */ + sal_uInt32 uMaxPathLength; +/** Points to a string that receives the name of the file system type. String + should be set to zero before calling osl_getVolumeInformation and released + after usage. */ + rtl_uString *ustrFileSystemName; +/** Pointer to handle the receives underlying device. Handle should be set to + zero before calling osl_getVolumeInformation */ + oslVolumeDeviceHandle *pDeviceHandle; +} oslVolumeInfo; + +/** Retrieve information about a volume. + + Retrieves information about a volume. A volume can either be a mount point, a network + resource or a drive depending on Operating System and File System. Before calling this + function osl_getFileStatus() should be called to determine if the type is + osl_file_Type_Volume. + + @param[in] pustrDirectoryURL + Full qualified URL of the volume + + @param[out] pInfo + On success it receives information about the volume. + + @param[in] uFieldMask + Specifies which members of the structure should be filled + + @retval osl_File_E_None on success + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOTDIR not a directory + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_LOOP too many symbolic links encountered + @retval ols_File_E_FAULT Bad address + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_NOSYS function not implemented + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_INTR function call was interrupted + + @see osl_getFileStatus() + @see oslVolumeInfo +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getVolumeInformation( + rtl_uString *pustrDirectoryURL, + oslVolumeInfo *pInfo, + sal_uInt32 uFieldMask ); + +typedef void *oslFileHandle; + +/* Open flags */ + +#define osl_File_OpenFlag_Read 0x00000001 +#define osl_File_OpenFlag_Write 0x00000002 +#define osl_File_OpenFlag_Create 0x00000004 +#define osl_File_OpenFlag_NoLock 0x00000008 +/* larger bit-fields reserved for internal use cf. detail/file.h */ + +/** Open a regular file. + + Open a file. Only regular files can be opened. + + @param[in] pustrFileURL + The full qualified URL of the file to open. + + @param[out] pHandle + On success it receives a handle to the open file. + + @param[in] uFlags + Specifies the open mode. + + On Android, if the file path is below the /assets folder, the file + exists only as a hopefully uncompressed element inside the app + package (.apk), which has been mapped into memory as a whole by + the LibreOffice Android bootstrapping code. So files "opened" from + there aren't actually files in the OS sense. + + @retval osl_File_E_None on success + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NAMETOOLONG pathname was too long + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_AGAIN a write lock could not be established + @retval osl_File_E_NOTDIR not a directory + @retval osl_File_E_NXIO no such device or address + @retval osl_File_E_NODEV no such device + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_TXTBSY text file busy + @retval osl_File_E_FAULT bad address + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_NOSPC no space left on device + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_MFILE too many open files used by the process + @retval osl_File_E_NFILE too many open files in the system + @retval osl_File_E_DQUOT quota exceeded + @retval osl_File_E_EXIST file exists + @retval osl_FilE_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_EOVERFLOW value too large for defined data type + + @see osl_closeFile() + @see osl_setFilePos() + @see osl_getFilePos() + @see osl_readFile() + @see osl_writeFile() + @see osl_setFileSize() + @see osl_getFileSize() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_openFile( + rtl_uString *pustrFileURL, oslFileHandle *pHandle, sal_uInt32 uFlags ); + +#define osl_Pos_Absolut 1 +#define osl_Pos_Current 2 +#define osl_Pos_End 3 + +/** Set the internal position pointer of an open file. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[in] uHow + How to calculate the offset - osl_Pos_Absolut means start at the + beginning of the file, osl_Pos_Current means offset from the current + seek position and osl_Pos_End means the offset will be negative and + the position will be calculated backwards from the end of the file by + the offset provided. + + @param[in] uPos + Seek offset, depending on uHow. If uHow is osl_Pos_End then the value must be negative. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + (e.g. if uHow is osl_Pos_End then must be negative) + @retval osl_File_E_OVERFLOW the resulting file offset would be a + value which cannot be represented correctly for regular files + + @see osl_openFile() + @see osl_getFilePos() +*/ +SAL_WARN_UNUSED_RESULT SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFilePos( + oslFileHandle Handle, sal_uInt32 uHow, sal_Int64 uPos ); + +/** Retrieve the current position of the internal pointer of an open file. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[out] pPos + On success receives the current position of the file pointer. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_OVERFLOW the resulting file offset would be a value + which cannot be represented correctly for regular files + + @see osl_openFile() + @see osl_setFilePos() + @see osl_readFile() + @see osl_writeFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFilePos( + oslFileHandle Handle, sal_uInt64 *pPos ); + +/** Set the file size of an open file. + + Sets the file size of an open file. The file can be truncated or enlarged by the function. + The position of the file pointer is not affeced by this function. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[in] uSize + New size in bytes. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_OVERFLOW the resulting file offset would be a value + which cannot be represented correctly for regular files + + @see osl_openFile() + @see osl_setFilePos() + @see osl_getFileStatus() + @see osl_getFileSize() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFileSize( + oslFileHandle Handle, sal_uInt64 uSize ); + +/** Get the file size of an open file. + + Gets the file size of an open file. + The position of the file pointer is not affeced by this function. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[out] pSize + Current size in bytes. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_OVERFLOW the resulting file offset would be a value + which cannot be represented correctly for regular files + + @see osl_openFile() + @see osl_setFilePos() + @see osl_getFileStatus() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFileSize( + oslFileHandle Handle, sal_uInt64 *pSize ); + +/** Indicate that the file can be accessed randomly (i.e. there is no sequential + reading). Basically it means that the first byte of every page in the + file-mapping will be read. + + @since UDK 3.2.10 + */ +#define osl_File_MapFlag_RandomAccess ((sal_uInt32)(0x1)) + +/** Map flag denoting that the mapped address space will be accessed by the + process soon (and it is advantageous for the operating system to already + start paging in the data). + + @attention As this assumes that madvise() with the WILLREAD flag is + asynchronous (which is I'm afraid an incorrect assumption), Linux systems + will ignore this flag. + + @since UDK 3.2.12 +*/ +#define osl_File_MapFlag_WillNeed ((sal_uInt32)(0x2)) + +/** Map a shared file into memory. + + Files can be mapped into memory to allow multiple processes to use + this memory-mapped file to share data. + + On Android, if the Handle refers to a file that is actually inside + the app package (.apk zip archive), no new mapping is created, + just a pointer to the file inside the already mapped .apk is + returned. + + @param[in] Handle Handle of the file to be mapped. + @param[in,out] ppAddr Memory address of the mapped file + @param[in] uLength Amount to map of the file from the offset + @param[in] uOffset Offset into the file to map + @param[in] uFlags osl_File_MapFlag_RandomAccess or + osl_File_MapFlag_WillNeed + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL invalid file handle, on Unix systems also + can mean that the address, length of the file or the + file offset are too large or not aligned on a page + boundary; on Linux can also mean after Linux 2.6.12 + that the length was set to 0 (illogical). + @retval osl_File_E_OVERFLOW requested mapping size too large, + or the file offset was too large + @retval osl_File_E_ACCES file descriptor to non-regular file, or + file descriptor not open for reading, or the file + descriptor is not open in read/write mode + @retval osl_File_E_AGAIN file has been locked, or too much memory + has been locked + @retval osl_File_E_NODEV underlying filesystem of specified file + does not support memory mapping + @retval osl_File_E_TXTBSY on Linux means that writing to the mapped + file is denied, but the file descriptor points to a file + open for writing + @retval osl_File_E_NOMEM process's maximum number of mappings have + been exceeded + + @since UDK 3.2.10 +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_mapFile ( + oslFileHandle Handle, + void** ppAddr, + sal_uInt64 uLength, + sal_uInt64 uOffset, + sal_uInt32 uFlags +); + + +#ifndef ANDROID + +/** Unmap a shared file from memory. + + This function just won't work on Android in general where for + (uncompressed) files inside the .apk, per SDK conventions in the + /assets folder, osl_mapFile() returns a pointer to the file inside + the already by LibreOffice Android-specific bootstrapping code + mmapped .apk archive. We can't go and randomly munmap part of the + .apk archive. So this function is not present on Android. + + @since UDK 3.2.10 +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_unmapFile ( + void* pAddr, + sal_uInt64 uLength +); + +#endif + +/** Unmap a file segment from memory. + + Like osl_unmapFile(), but takes also the oslFileHandle argument + passed to osl_mapFile() when creating this mapping. + + On Android, for files below /assets, i.e. located inside the app + archive (.apk), this won't actually unmap anything; all the .apk + stays mapped. + + @since UDK 3.6 +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_unmapMappedFile ( + oslFileHandle Handle, + void* pAddr, + sal_uInt64 uLength +); + +/** Read a number of bytes from a file. + + Reads a number of bytes from a file. The internal file pointer is + increased by the number of bytes read. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[out] pBuffer + Points to a buffer which receives data. The buffer must be large enough + to hold uBytesRequested bytes. + + @param[in] uBytesRequested + Number of bytes which should be retrieved. + + @param[out] pBytesRead + On success the number of bytes which have actually been retrieved. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_BADF bad file + @retval osl_File_E_FAULT bad address + @retval osl_File_E_AGAIN operation would block + @retval osl_File_E_NOLINK link has been severed + + @see osl_openFile() + @see osl_writeFile() + @see osl_readLine() + @see osl_setFilePos() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_readFile( + oslFileHandle Handle, void *pBuffer, sal_uInt64 uBytesRequested, sal_uInt64 *pBytesRead ); + +/** Test if the end of a file is reached. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[out] pIsEOF + Points to a variable that receives the end-of-file status. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_BADF bad file + @retval osl_File_E_FAULT bad address + @retval osl_File_E_AGAIN operation would block + @retval osl_File_E_NOLINK link has been severed + + @see osl_openFile() + @see osl_readFile() + @see osl_readLine() + @see osl_setFilePos() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_isEndOfFile( + oslFileHandle Handle, sal_Bool *pIsEOF ); + +/** Write a number of bytes to a file. + + Writes a number of bytes to a file. + The internal file pointer is increased by the number of bytes read. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[in] pBuffer + Points to a buffer which contains the data. + + @param[in] uBytesToWrite + Number of bytes which should be written. + + @param[out] pBytesWritten + On success the number of bytes which have actually been written. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_FBIG file too large + @retval osl_File_E_DQUOT quota exceeded + @retval osl_File_E_AGAIN operation would block + @retval osl_File_E_BADF bad file + @retval osl_File_E_FAULT bad address + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_NOLCK no record locks available + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_NOSPC no space left on device + @retval osl_File_E_NXIO no such device or address + + @see osl_openFile() + @see osl_readFile() + @see osl_setFilePos() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_writeFile( + oslFileHandle Handle, const void *pBuffer, sal_uInt64 uBytesToWrite, sal_uInt64 *pBytesWritten ); + +/** Read a number of bytes from a specified offset in a file. + + The current position of the internal file pointer may or may not be changed. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[in] uOffset + Offset position from start of file where read starts + + @param[out] pBuffer + Points to a buffer which receives data. The buffer must be large enough + to hold uBytesRequested bytes. + + @param[in] uBytesRequested + Number of bytes which should be retrieved. + + @param[out] pBytesRead + On success the number of bytes which have actually been retrieved. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_BADF bad file + @retval osl_File_E_FAULT bad address + @retval osl_File_E_AGAIN operation would block + @retval osl_File_E_NOLINK link has been severed + @since UDK 3.2.10 + */ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_readFileAt( + oslFileHandle Handle, + sal_uInt64 uOffset, + void* pBuffer, + sal_uInt64 uBytesRequested, + sal_uInt64* pBytesRead +); + +/** Write a number of bytes to a specified offset in a file. + + The current position of the internal file pointer may or may not be changed. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[in] uOffset + Position of file to write into. + + @param[in] pBuffer + Points to a buffer which contains the data. + + @param[in] uBytesToWrite + Number of bytes which should be written. + + @param[out] pBytesWritten + On success the number of bytes which have actually been written. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_FBIG file too large + @retval osl_File_E_DQUOT quota exceeded + @retval osl_File_E_AGAIN operation would block + @retval osl_File_E_BADF bad file + @retval osl_File_E_FAULT bad address + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_NOLCK no record locks available + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_NOSPC no space left on device + @retval osl_File_E_NXIO no such device or address + @since UDK 3.2.10 +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_writeFileAt( + oslFileHandle Handle, + sal_uInt64 uOffset, + const void* pBuffer, + sal_uInt64 uBytesToWrite, + sal_uInt64* pBytesWritten +); + +/** Read a line from a file. + + Reads a line from a file. The new line delimiter is NOT returned! + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @param[in,out] ppSequence + A pointer pointer to a sal_Sequence that will hold the line read on success. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_BADF bad file + @retval osl_File_E_FAULT bad address + @retval osl_File_E_AGAIN operation would block + @retval osl_File_E_NOLINK link has been severed + + @see osl_openFile() + @see osl_readFile() + @see osl_writeFile() + @see osl_setFilePos() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_readLine( + oslFileHandle Handle, sal_Sequence** ppSequence ); + +/** Synchronize the memory representation of a file with that on the physical medium. + + The function ensures that all modified data and attributes of the file associated with + the given file handle have been written to the physical medium. + In case the hard disk has a write cache enabled, the data may not really be on + permanent storage when osl_syncFile returns. + + @param Handle + [in] Handle to a file received by a previous call to osl_openFile(). + + @retval osl_File_E_None On success + @retval osl_File_E_INVAL The value of the input parameter is invalid + @retval osl_File_E_BADF The file associated with the given file handle is not open for writing + @retval osl_File_E_IO An I/O error occurred + @retval osl_File_E_NOSPC There is no enough space on the target device + @retval osl_File_E_ROFS The file associated with the given file handle is located on a read only file system + @retval osl_File_E_TIMEDOUT A remote connection timed out. This may happen when a file is on a remote location + + @see osl_openFile() + @see osl_writeFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_syncFile( oslFileHandle Handle ); + +/** Close an open file. + + @param[in] Handle + Handle to a file received by a previous call to osl_openFile(). + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_BADF Bad file + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_NOSPC no space left on device + @retval osl_File_E_IO on I/O errors + + @see osl_openFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_closeFile( oslFileHandle Handle ); + +/** Create a directory. + + @param[in] pustrDirectoryURL + Full qualified URL of the directory to create. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_EXIST file exists + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_NOTDIR not a directory + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_NOSPC no space left on device + @retval osl_File_E_DQUOT quota exceeded + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_FAULT bad address + @retval osl_FileE_IO on I/O errors + @retval osl_File_E_MLINK too many links + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + + @see osl_removeDirectory() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createDirectory( rtl_uString* pustrDirectoryURL ); + +/** Create a directory, passing flags. + + @param url + File URL of the directory to create. + + @param flags + A combination of the same osl_File_OpenFlag_*s used by osl_openFile, + except that osl_File_OpenFlag_Create is implied and ignored. Support for + the various flags can differ across operating systems. + + @see osl_createDirectory() + + @since LibreOffice 4.3 +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createDirectoryWithFlags( + rtl_uString * url, sal_uInt32 flags); + +/** Remove an empty directory. + + @param[in] pustrDirectoryURL + Full qualified URL of the directory. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_PERM operation not permitted + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_NOTDIR not a directory + @retval osl_File_E_NOTEMPTY directory not empty + @retval osl_File_E_FAULT bad address + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_BUSY device or resource busy + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_EXIST file exists + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + + @see osl_createDirectory() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_removeDirectory( rtl_uString* pustrDirectoryURL ); + +/** Function pointer representing a function that will be called by osl_createDirectoryPath + if a directory has been created. + + To avoid unpredictable results the callee must not access the directory whose + creation is just notified. + + @param pData + [in] User specified data given in osl_createDirectoryPath. + + @param aDirectoryUrl + [in] The absolute file URL of the directory that was just created by + osl_createDirectoryPath. + + @see osl_createDirectoryPath +*/ +typedef void (SAL_CALL *oslDirectoryCreationCallbackFunc)(void* pData, rtl_uString* aDirectoryUrl); + +/** Create a directory path. + + The osl_createDirectoryPath function creates a specified directory path. + All nonexisting sub directories will be created. + + @attention PLEASE NOTE You cannot rely on getting the error code + osl_File_E_EXIST for existing directories. Programming against this error + code is in general a strong indication of a wrong usage of osl_createDirectoryPath. + + @param aDirectoryUrl + [in] The absolute file URL of the directory path to create. + A relative file URL will not be accepted. + + @param aDirectoryCreationCallbackFunc + [in] Pointer to a function that will be called synchronously + for each sub directory that was created. The value of this + parameter may be NULL, in this case notifications will not be + sent. + + @param pData + [in] User specified data to be passed to the directory creation + callback function. The value of this parameter may be arbitrary + and will not be interpreted by osl_createDirectoryPath. + + @retval osl_File_E_None On success + @retval osl_File_E_INVAL The format of the parameters was not valid + @retval osl_File_E_ACCES Permission denied + @retval osl_File_E_EXIST The final node of the specified directory path already exist + @retval osl_File_E_NAMETOOLONG The name of the specified directory path exceeds the maximum allowed length + @retval osl_File_E_NOTDIR A component of the specified directory path already exist as file in any part of the directory path + @retval osl_File_E_ROFS Read-only file system + @retval osl_File_E_NOSPC No space left on device + @retval osl_File_E_DQUOT Quota exceeded + @retval osl_File_E_FAULT Bad address + @retval osl_File_E_IO I/O error + @retval osl_File_E_LOOP Too many symbolic links encountered + @retval osl_File_E_NOLINK Link has been severed + @retval osl_File_E_invalidError An unknown error occurred + + @see oslDirectoryCreationFunc + @see oslFileError + @see osl_createDirectory +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createDirectoryPath( + rtl_uString* aDirectoryUrl, + oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc, + void* pData); + +/** Remove a regular file. + + @param[in] pustrFileURL + Full qualified URL of the file to remove. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_PERM operation not permitted + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_FAULT bad address + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_IO on I/O errors + @retval osl_File_E_BUSY device or resource busy + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + @retval osl_File_E_TXTBSY text file busy + + @see osl_openFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_removeFile( + rtl_uString* pustrFileURL ); + +/** Copy a file to a new destination. + + Copies a file to a new destination. Copies only files not directories. + No assumptions should be made about preserving attributes or file time. + + @param[in] pustrSourceFileURL + Full qualified URL of the source file. + + @param[in] pustrDestFileURL + Full qualified URL of the destination file. A directory is NOT a valid destination file! + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_PERM operation not permitted + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_ISDIR is a directory + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_BUSY if the implementation internally requires resources that are + (temporarily) unavailable (added with LibreOffice 4.4) + + @see osl_moveFile() + @see osl_removeFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_copyFile( + rtl_uString* pustrSourceFileURL, rtl_uString *pustrDestFileURL ); + +/** Move a file or directory to a new destination or renames it. + + Moves a file or directory to a new destination or renames it. + File time and attributes are preserved. + + @param[in] pustrSourceFileURL + Full qualified URL of the source file. + + @param[in] pustrDestFileURL + Full qualified URL of the destination file. An existing directory is NOT a valid destination ! + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_PERM operation not permitted + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_BUSY if the implementation internally requires resources that are + (temporarily) unavailable (added with LibreOffice 4.4) + + @see osl_copyFile() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_moveFile( + rtl_uString* pustrSourceFileURL, rtl_uString *pustrDestFileURL ); + +/** Determine a valid unused canonical name for a requested name. + + Determines a valid unused canonical name for a requested name. + Depending on the Operating System and the File System the illegal characters are replaced by valid ones. + If a file or directory with the requested name already exists a new name is generated following + the common rules on the actual Operating System and File System. + + @param[in] pustrRequestedURL + Requested name of a file or directory. + + @param[out] ppustrValidURL + On success receives a name which is unused and valid on the actual Operating System and + File System. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getFileStatus() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getCanonicalName( + rtl_uString *pustrRequestedURL, rtl_uString **ppustrValidURL); + +/** Convert a path relative to a given directory into an full qualified file URL. + + Convert a path relative to a given directory into an full qualified file URL. + The function resolves symbolic links if possible and path ellipses, so on success + the resulting absolute path is fully resolved. + + @param[in] pustrBaseDirectoryURL + Base directory URL to which the relative path is related to. + + @param[in] pustrRelativeFileURL + A URL of a file or directory relative to the directory path specified by pustrBaseDirectoryURL + or an absolute path. + If pustrRelativeFileURL denotes an absolute path pustrBaseDirectoryURL will be ignored. + + @param[out] ppustrAbsoluteFileURL + On success it receives the full qualified absolute file URL. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_NOTDIR not a directory + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_NOENT no such file or directory + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_OVERFLOW value too large for defined data type + @retval osl_File_E_FAULT bad address + @retval osl_File_E_INTR function call was interrupted + @retval osl_File_E_LOOP too many symbolic links encountered + @retval osl_File_E_MULTIHOP multihop attempted + @retval osl_File_E_NOLINK link has been severed + + @see osl_getFileStatus() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getAbsoluteFileURL( + rtl_uString* pustrBaseDirectoryURL, + rtl_uString *pustrRelativeFileURL, + rtl_uString **ppustrAbsoluteFileURL ); + +/** Convert a system dependent path into a file URL. + + @param[in] pustrSystemPath + A System dependent path of a file or directory. + + @param[out] ppustrFileURL + On success it receives the file URL. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getSystemPathFromFileURL() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getFileURLFromSystemPath( + rtl_uString *pustrSystemPath, rtl_uString **ppustrFileURL); + +/** Search a full qualified system path or a file URL. + + @param[in] pustrFileName + A system dependent path, a file URL, a file or relative directory. + + @param[in] pustrSearchPath + @parblock + A list of system paths, in which a given file has to be searched. The Notation of a path + list is system dependent, e.g. on UNIX system "/usr/bin:/bin" and on Windows "C:\BIN;C:\BATCH". + These paths are only for the search of a file or a relative path, otherwise it will be ignored. + If pustrSearchPath is NULL or while using the search path the search failed, the function + searches for a matching file in all system directories and in the directories listed in the PATH + environment variable. + + The value of an environment variable should be used (e.g. + LD_LIBRARY_PATH) if the caller is not aware of the Operating System and so doesn't know which + path list delimiter to use. + @endparblock + + @param[out] ppustrFileURL + On success it receives the full qualified file URL. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOTDIR not a directory + @retval osl_File_E_NOENT no such file or directory not found + + @see osl_getFileURLFromSystemPath() + @see osl_getSystemPathFromFileURL() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_searchFileURL( + rtl_uString *pustrFileName, rtl_uString *pustrSearchPath, rtl_uString **ppustrFileURL ); + +/** Convert a file URL into a system dependent path. + + @param[in] pustrFileURL + A File URL. + + @param[out] ppustrSystemPath + On success it receives the system path. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getFileURLFromSystemPath() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getSystemPathFromFileURL( + rtl_uString *pustrFileURL, rtl_uString **ppustrSystemPath); + +/** Function pointer representing the function called back from osl_abbreviateSystemPath + + @param[in] ustrText + Text to calculate the width for + + @return + The width of the text specified by ustrText, e.g. it can return the width in pixel + or the width in character count. + + @see osl_abbreviateSystemPath() +*/ +typedef sal_uInt32 (SAL_CALL *oslCalcTextWidthFunc)( rtl_uString *ustrText ); + +/** Abbreviate a system notation path. + + @param[in] ustrSystemPath + The full system path to abbreviate + + @param[out] pustrCompacted + Receives the compacted system path on output + + @param[in] pCalcWidth + Function ptr that calculates the width of a string. Can be zero. + + @param[in] uMaxWidth + Maximum width allowed that is returned from pCalcWidth. + If pCalcWidth is zero the character count is assumed as width. + + @retval osl_File_E_None on success + + @see oslCalcTextWidthFunc +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_abbreviateSystemPath( + rtl_uString *ustrSystemPath, + rtl_uString **pustrCompacted, + sal_uInt32 uMaxWidth, + oslCalcTextWidthFunc pCalcWidth ); + +/** Set file attributes. + + @param[in] pustrFileURL + The full qualified file URL. + + @param[in] uAttributes + Attributes of the file to be set. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + + @see osl_getFileStatus() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFileAttributes( + rtl_uString *pustrFileURL, sal_uInt64 uAttributes ); + +/** Set the file time. + + @param[in] pustrFileURL + The full qualified URL of the file. + + @param[in] aCreationTime + Creation time of the given file. + + @param[in] aLastAccessTime + Time of the last access of the given file. + + @param[in] aLastWriteTime + Time of the last modifying of the given file. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOENT no such file or directory not found + + @see osl_getFileStatus() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_setFileTime( + rtl_uString *pustrFileURL, + const TimeValue *aCreationTime, + const TimeValue *aLastAccessTime, + const TimeValue *aLastWriteTime); + +/** Retrieves the file URL of the system's temporary directory path + + @param[out] pustrTempDirURL + On success receives the URL of system's temporary directory path. + + @retval osl_File_E_None on success + @retval osl_File_E_NOENT no such file or directory not found +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_getTempDirURL( + rtl_uString **pustrTempDirURL ); + +/** Creates a temporary file in the directory provided by the caller or the + directory returned by osl_getTempDirURL. + + Creates a temporary file in the directory provided by the caller or the + directory returned by osl_getTempDirURL. + Under UNIX Operating Systems the file will be created with read and write + access for the user exclusively. + If the caller requests only a handle to the open file but not the name of + it, the file will be automatically removed on close else the caller is + responsible for removing the file on success. + + Description of the different pHandle, ppustrTempFileURL parameter combinations. + pHandle is 0 and ppustrTempDirURL is 0 - this combination is invalid + pHandle is not 0 and ppustrTempDirURL is 0 - a handle to the open file + will be returned on success and the file will be automatically removed on close. + pHandle is 0 and ppustrTempDirURL is not 0 - the name of the file will be returned, + the caller is responsible for opening, closing and removing the file. + pHandle is not 0 and ppustrTempDirURL is not 0 - a handle to the open file as well as + the file name will be returned, the caller is responsible for closing and removing + the file. + + @param[in] pustrDirectoryURL + Specifies the full qualified URL where the temporary file should be created. + If pustrDirectoryURL is 0 the path returned by osl_getTempDirURL will be used. + + @param[out] pHandle + On success receives a handle to the open file. If pHandle is 0 the file will + be closed on return, in this case ppustrTempFileURL must not be 0. + + @param[out] ppustrTempFileURL + On success receives the full qualified URL of the temporary file. + If ppustrTempFileURL is 0 the file will be automatically removed on close, + in this case pHandle must not be 0. + If ppustrTempFileURL is not 0 the caller receives the name of the created + file and is responsible for removing the file, in this case + *ppustrTempFileURL must be 0 or must point to a valid rtl_uString. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameter is invalid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES Permission denied + @retval osl_File_E_NOENT No such file or directory + @retval osl_File_E_NOTDIR Not a directory + @retval osl_File_E_ROFS Read-only file system + @retval osl_File_E_NOSPC No space left on device + @retval osl_File_E_DQUOT Quota exceeded + + @see osl_getTempDirURL() +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_createTempFile( + rtl_uString* pustrDirectoryURL, + oslFileHandle* pHandle, + rtl_uString** ppustrTempFileURL); + +/** Move a file to a new destination or rename it, taking old file's identity (if exists). + + Moves or renames a file, replacing an existing file if exist. If the old file existed, + moved file's metadata, e.g. creation time (on FSes which keep files' creation time) or + ACLs, are set to old one's (to keep the old file's identity) - currently this is only + implemented fully on Windows; on other platforms, this is mostly equivalent to osl_moveFile. + + @param[in] pustrSourceFileURL + Full qualified URL of the source file. + + @param[in] pustrDestFileURL + Full qualified URL of the destination file. + + @retval osl_File_E_None on success + @retval osl_File_E_INVAL the format of the parameters was not valid + @retval osl_File_E_NOMEM not enough memory for allocating structures + @retval osl_File_E_ACCES permission denied + @retval osl_File_E_PERM operation not permitted + @retval osl_File_E_NAMETOOLONG file name too long + @retval osl_File_E_NOENT no such file + @retval osl_File_E_ROFS read-only file system + @retval osl_File_E_BUSY if the implementation internally requires resources that are + (temporarily) unavailable + + @see osl_moveFile() + + @since LibreOffice 6.2 +*/ +SAL_DLLPUBLIC oslFileError SAL_CALL osl_replaceFile(rtl_uString* pustrSourceFileURL, + rtl_uString* pustrDestFileURL); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_FILE_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/file.hxx b/include/osl/file.hxx new file mode 100644 index 000000000..fcbabe96d --- /dev/null +++ b/include/osl/file.hxx @@ -0,0 +1,1951 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_FILE_HXX +#define INCLUDED_OSL_FILE_HXX + +#include "sal/config.h" + +#include + +#include + +#include "sal/log.hxx" +#include "osl/time.h" +#include "rtl/ustring.hxx" + +#include "osl/file.h" +#include "osl/diagnose.h" + +namespace rtl { class ByteSequence; } + +namespace osl +{ + + +/** Base class for all File System specific objects. + + @see Directory + @see DirectoryItem + @see File + */ + +class FileBase +{ +public: + + enum RC { + E_None = osl_File_E_None, ///< on success + E_PERM = osl_File_E_PERM, ///< operation not permitted + E_NOENT = osl_File_E_NOENT, ///< no such file or directory + E_SRCH = osl_File_E_SRCH, ///< no process matches the PID + E_INTR = osl_File_E_INTR, ///< function call was interrupted + E_IO = osl_File_E_IO, ///< I/O error occurred + E_NXIO = osl_File_E_NXIO, ///< no such device or address + E_2BIG = osl_File_E_2BIG, ///< argument list too long + E_NOEXEC = osl_File_E_NOEXEC, ///< invalid executable file format + E_BADF = osl_File_E_BADF, ///< bad file descriptor + E_CHILD = osl_File_E_CHILD, ///< there are no child processes + E_AGAIN = osl_File_E_AGAIN, ///< resource temp unavailable, try again later + E_NOMEM = osl_File_E_NOMEM, ///< no memory available + E_ACCES = osl_File_E_ACCES, ///< file permissions do not allow operation + E_FAULT = osl_File_E_FAULT, ///< bad address; an invalid pointer detected + E_BUSY = osl_File_E_BUSY, ///< resource busy + E_EXIST = osl_File_E_EXIST, ///< file exists where should only be created + E_XDEV = osl_File_E_XDEV, ///< improper link across file systems detected + E_NODEV = osl_File_E_NODEV, ///< wrong device type specified + E_NOTDIR = osl_File_E_NOTDIR, ///< file isn't a directory where one is needed + E_ISDIR = osl_File_E_ISDIR, ///< file is a directory, invalid operation + E_INVAL = osl_File_E_INVAL, ///< invalid argument to library function + E_NFILE = osl_File_E_NFILE, ///< too many distinct file openings + E_MFILE = osl_File_E_MFILE, ///< process has too many distinct files open + E_NOTTY = osl_File_E_NOTTY, ///< inappropriate I/O control operation + E_FBIG = osl_File_E_FBIG, ///< file too large + E_NOSPC = osl_File_E_NOSPC, ///< no space left on device, write failed + E_SPIPE = osl_File_E_SPIPE, ///< invalid seek operation (such as on pipe) + E_ROFS = osl_File_E_ROFS, ///< illegal modification to read-only filesystem + E_MLINK = osl_File_E_MLINK, ///< too many links to file + E_PIPE = osl_File_E_PIPE, ///< broken pipe; no process reading from other end of pipe + E_DOM = osl_File_E_DOM, ///< domain error (mathematical error) + E_RANGE = osl_File_E_RANGE, ///< range error (mathematical error) + E_DEADLK = osl_File_E_DEADLK, ///< deadlock avoided + E_NAMETOOLONG = osl_File_E_NAMETOOLONG, ///< filename too long + E_NOLCK = osl_File_E_NOLCK, ///< no locks available + E_NOSYS = osl_File_E_NOSYS, ///< function not implemented + E_NOTEMPTY = osl_File_E_NOTEMPTY, ///< directory not empty + E_LOOP = osl_File_E_LOOP, ///< too many levels of symbolic links found during name lookup + E_ILSEQ = osl_File_E_ILSEQ, ///< invalid or incomplete byte sequence of multibyte char found + E_NOLINK = osl_File_E_NOLINK, ///< link has been severed + E_MULTIHOP = osl_File_E_MULTIHOP, ///< remote resource is not directly available + E_USERS = osl_File_E_USERS, ///< file quote system is confused as there are too many users + E_OVERFLOW = osl_File_E_OVERFLOW, ///< value too large for defined data type + E_NOTREADY = osl_File_E_NOTREADY, ///< device not ready + E_invalidError = osl_File_E_invalidError, ///< unmapped error: always last entry in enum! + E_TIMEDOUT = osl_File_E_TIMEDOUT, ///< socket operation timed out + E_NETWORK = osl_File_E_NETWORK + }; + + +public: + + /** Determine a valid unused canonical name for a requested name. + + Determines a valid unused canonical name for a requested name. + Depending on the Operating System and the File System the illegal characters are replaced by valid ones. + If a file or directory with the requested name already exists a new name is generated following + the common rules on the actual Operating System and File System. + + @param[in] ustrRequestedURL + Requested name of a file or directory. + + @param[out] ustrValidURL + On success receives a name which is unused and valid on the actual Operating System and + File System. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + + @see DirectoryItem::getFileStatus() + */ + + static RC getCanonicalName( const ::rtl::OUString& ustrRequestedURL, ::rtl::OUString& ustrValidURL ) + { + return static_cast< RC >( osl_getCanonicalName( ustrRequestedURL.pData, &ustrValidURL.pData ) ); + } + + /** Convert a path relative to a given directory into an full qualified file URL. + + Convert a path relative to a given directory into an full qualified file URL. + The function resolves symbolic links if possible and path ellipses, so on success + the resulting absolute path is fully resolved. + + @param[in] ustrBaseDirectoryURL + Base directory URL to which the relative path is related to. + + @param[in] ustrRelativeFileURL + A URL of a file or directory relative to the directory path specified by ustrBaseDirectoryURL + or an absolute path. + If ustrRelativeFileURL denotes an absolute path ustrBaseDirectoryURL will be ignored. + + @param[out] ustrAbsoluteFileURL + On success it receives the full qualified absolute file URL. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_NOTDIR not a directory + @retval E_ACCES permission denied + @retval E_NOENT no such file or directory + @retval E_NAMETOOLONG file name too long + @retval E_OVERFLOW value too large for defined data type + @retval E_FAULT bad address + @retval E_INTR function call was interrupted + @retval E_LOOP too many symbolic links encountered + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + + @see DirectoryItem::getFileStatus() + */ + + static RC getAbsoluteFileURL( const ::rtl::OUString& ustrBaseDirectoryURL, const ::rtl::OUString& ustrRelativeFileURL, ::rtl::OUString& ustrAbsoluteFileURL ) + { + return static_cast< RC >( osl_getAbsoluteFileURL( ustrBaseDirectoryURL.pData, ustrRelativeFileURL.pData, &ustrAbsoluteFileURL.pData ) ); + } + + /** Convert a file URL into a system dependent path. + + @param[in] ustrFileURL + A File URL. + + @param[out] ustrSystemPath + On success it receives the system path. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + + @see getFileURLFromSystemPath() + */ + + static RC getSystemPathFromFileURL( const ::rtl::OUString& ustrFileURL, ::rtl::OUString& ustrSystemPath ) + { + return static_cast< RC >( osl_getSystemPathFromFileURL( ustrFileURL.pData, &ustrSystemPath.pData ) ); + } + + /** Convert a system dependent path into a file URL. + + @param[in] ustrSystemPath + A System dependent path of a file or directory. + + @param[out] ustrFileURL + On success it receives the file URL. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + + @see getSystemPathFromFileURL() + */ + + static RC getFileURLFromSystemPath( const ::rtl::OUString& ustrSystemPath, ::rtl::OUString& ustrFileURL ) + { + return static_cast< RC >( osl_getFileURLFromSystemPath( ustrSystemPath.pData, &ustrFileURL.pData ) ); + } + + /** Search a full qualified system path or a file URL. + + @param[in] ustrFileName + A system dependent path, a file URL, a file or relative directory + + @param[in] ustrSearchPath + A list of system paths, in which a given file has to be searched. The Notation of a path list is + system dependent, e.g. on UNIX system "/usr/bin:/bin" and on Windows "C:\BIN;C:\BATCH". + These paths are only for the search of a file or a relative path, otherwise it will be ignored. + If ustrSearchPath is NULL or while using the search path the search failed, the function searches for + a matching file in all system directories and in the directories listed in the PATH environment + variable. + The value of an environment variable should be used (e.g. LD_LIBRARY_PATH) if the caller is not + aware of the Operating System and so doesn't know which path list delimiter to use. + + @param[out] ustrFileURL + On success it receives the full qualified file URL. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOTDIR not a directory + @retval E_NOENT no such file or directory not found + + @see getFileURLFromSystemPath() + @see getSystemPathFromFileURL() + */ + + static RC searchFileURL( const ::rtl::OUString& ustrFileName, const ::rtl::OUString& ustrSearchPath, ::rtl::OUString& ustrFileURL ) + { + return static_cast< RC >( osl_searchFileURL( ustrFileName.pData, ustrSearchPath.pData, &ustrFileURL.pData ) ); + } + + /** Retrieves the file URL of the system's temporary directory path. + + @param[out] ustrTempDirURL + On success receives the URL of system's temporary directory path. + + @retval E_None on success + @retval E_NOENT no such file or directory not found + */ + + static RC getTempDirURL( ::rtl::OUString& ustrTempDirURL ) + { + return static_cast< RC >( osl_getTempDirURL( &ustrTempDirURL.pData ) ); + } + + /** Creates a temporary file in the directory provided by the caller or the + directory returned by getTempDirURL. + Under UNIX Operating Systems the file will be created with read and write + access for the user exclusively. + If the caller requests only a handle to the open file but not the name of + it, the file will be automatically removed on close else the caller is + responsible for removing the file on success.

    + + @param[in] pustrDirectoryURL + Specifies the full qualified URL where the temporary file should be created. + If pustrDirectoryURL is 0 the path returned by osl_getTempDirURL will be used. + + @param[out] pHandle + On success receives a handle to the open file. + If pHandle is 0 the file will be closed on return, in this case + pustrTempFileURL must not be 0. + + @param[out] pustrTempFileURL + On success receives the full qualified URL of the temporary file. + If pustrTempFileURL is 0 the file will be automatically removed + on close, in this case pHandle must not be 0. + If pustrTempFileURL is not 0 the caller receives the name of the + created file and is responsible for removing the file. + + Description of the different pHandle, ppustrTempFileURL parameter combinations. + pHandle is 0 and pustrTempDirURL is 0 - this combination is invalid
    + pHandle is not 0 and pustrTempDirURL is 0 - a handle to the open file + will be returned on success and the file will be automatically removed on close
    + pHandle is 0 and pustrTempDirURL is not 0 - the name of the file will be + returned, the caller is responsible for opening, closing and removing the file.
    + pHandle is not 0 and pustrTempDirURL is not 0 - a handle to the open file as well as + the file name will be returned, the caller is responsible for closing and removing + the file.
    + + @retval E_None on success + @retval E_INVAL the format of the parameter is invalid + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES Permission denied + @retval E_NOENT No such file or directory + @retval E_NOTDIR Not a directory + @retval E_ROFS Read-only file system + @retval E_NOSPC No space left on device + @retval E_DQUOT Quota exceeded + + @see getTempDirURL() + */ + + static RC createTempFile( + ::rtl::OUString* pustrDirectoryURL, + oslFileHandle* pHandle, + ::rtl::OUString* pustrTempFileURL) + { + rtl_uString* pustr_dir_url = pustrDirectoryURL ? pustrDirectoryURL->pData : NULL; + rtl_uString** ppustr_tmp_file_url = pustrTempFileURL ? &pustrTempFileURL->pData : NULL; + + return static_cast< RC >( osl_createTempFile(pustr_dir_url, pHandle, ppustr_tmp_file_url) ); + } +}; + + +/** The VolumeDevice class. + + @see VolumeInfo +*/ + +class VolumeDevice : public FileBase +{ + oslVolumeDeviceHandle _aHandle; + +public: + + /** Constructor. + */ + + VolumeDevice() : _aHandle( NULL ) + { + } + + /** Copy constructor. + + @param rDevice + The other volume device. + */ + + VolumeDevice( const VolumeDevice & rDevice ) + { + _aHandle = rDevice._aHandle; + if ( _aHandle ) + osl_acquireVolumeDeviceHandle( _aHandle ); + } + + /** Destructor. + */ + + ~VolumeDevice() + { + if ( _aHandle ) + osl_releaseVolumeDeviceHandle( _aHandle ); + } + + /** Assignment operator. + + @param rDevice + The other volume device. + */ + + VolumeDevice & operator =( const VolumeDevice & rDevice ) + { + oslVolumeDeviceHandle newHandle = rDevice._aHandle; + + if ( newHandle ) + osl_acquireVolumeDeviceHandle( newHandle ); + + if ( _aHandle ) + osl_releaseVolumeDeviceHandle( _aHandle ); + + _aHandle = newHandle; + + return *this; + } + + /** Get the full qualified URL where a device is mounted to. + + @return + The full qualified URL where the device is mounted to. + */ + rtl::OUString getMountPath() + { + rtl::OUString aPath; + osl_getVolumeDeviceMountPath( _aHandle, &aPath.pData ); + return aPath; + } + + friend class VolumeInfo; +}; + + +class Directory; + +/** The VolumeInfo class. + + Neither copy nor assignment is allowed for this class. + + @see Directory::getVolumeInfo +*/ + + +class VolumeInfo +{ + oslVolumeInfo _aInfo; + sal_uInt32 _nMask; + VolumeDevice _aDevice; + + /** Copy constructor. + */ + + VolumeInfo( VolumeInfo& ) SAL_DELETED_FUNCTION; + + /** Assignment operator. + */ + + VolumeInfo& operator = ( VolumeInfo& ) SAL_DELETED_FUNCTION; + +public: + + /** Constructor. + + @param nMask + Set of flags describing the demanded information. + */ + VolumeInfo( sal_uInt32 nMask ) + : _nMask( nMask ) + { + memset( &_aInfo, 0, sizeof( oslVolumeInfo )); + _aInfo.uStructSize = sizeof( oslVolumeInfo ); + _aInfo.pDeviceHandle = &_aDevice._aHandle; + } + + ~VolumeInfo() + { + if( _aInfo.ustrFileSystemName ) + rtl_uString_release( _aInfo.ustrFileSystemName ); + } + + /** Check if specified fields are valid. + + @param nMask + Set of flags for the fields to check. + + @return true if all fields are valid else false. + */ + bool isValid( sal_uInt32 nMask ) const + { + return ( nMask & _aInfo.uValidFields ) == nMask; + } + + /** Check the remote flag. + + @return + true if Attributes are valid and the volume is remote else false. + */ + bool getRemoteFlag() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_Remote) != 0; + } + + /** Check the removable flag. + + @return + true if attributes are valid and the volume is removable else false. + */ + bool getRemoveableFlag() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_Removeable) != 0; + } + + /** Check the compact disc flag. + + @return + true if attributes are valid and the volume is a CDROM else false. + */ + + bool getCompactDiscFlag() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_CompactDisc) != 0; + } + + /** Check the floppy disc flag. + + @return + true if attributes are valid and the volume is a floppy disk else false. + */ + + bool getFloppyDiskFlag() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_FloppyDisk) != 0; + } + + /** Check the fixed disk flag. + + @return + true if attributes are valid and the volume is a fixed disk else false. + */ + + bool getFixedDiskFlag() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_FixedDisk) != 0; + } + + /** Check the RAM disk flag. + + @return + true if attributes are valid and the volume is a RAM disk else false. + */ + + bool getRAMDiskFlag() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_RAMDisk) != 0; + } + + /** Determine the total space of a volume device. + + @return + The total diskspace of this volume if this information is valid, + 0 otherwise. + */ + + sal_uInt64 getTotalSpace() const + { + return _aInfo.uTotalSpace; + } + + /** Determine the free space of a volume device. + + @return + The free diskspace of this volume if this information is valid, + 0 otherwise. + */ + + sal_uInt64 getFreeSpace() const + { + return _aInfo.uFreeSpace; + } + + /** Determine the used space of a volume device. + + @return + The used diskspace of this volume if this information is valid, + 0 otherwise. + */ + + sal_uInt64 getUsedSpace() const + { + return _aInfo.uUsedSpace; + } + + /** Determine the maximal length of a file name. + + @return + The maximal length of a file name if this information is valid, + 0 otherwise. + */ + + sal_uInt32 getMaxNameLength() const + { + return _aInfo.uMaxNameLength; + } + + /** Determine the maximal length of a path name. + + @return + The maximal length of a path if this information is valid, + 0 otherwise. + */ + + sal_uInt32 getMaxPathLength() const + { + return _aInfo.uMaxPathLength; + } + + /** Determine the name of the volume device's File System. + + @return + The name of the volume's filesystem if this information is valid, + otherwise an empty string. + */ + + ::rtl::OUString getFileSystemName() const + { + return _aInfo.ustrFileSystemName ? ::rtl::OUString( _aInfo.ustrFileSystemName ) : ::rtl::OUString(); + } + + + /** Get the volume device handle. + + @return + The device handle of the volume if this information is valid, + otherwise returns NULL; + */ + + VolumeDevice getDeviceHandle() const + { + return _aDevice; + } + + /** Return whether the file system is case sensitive or + case insensitive + + @return + true if the file system is case sensitive false otherwise + */ + bool isCaseSensitiveFileSystem() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_Case_Sensitive) != 0; + } + + /** Return whether the file system preserves the case of + file and directory names or not + + @return + true if the file system preserves the case of file and + directory names false otherwise + */ + bool isCasePreservingFileSystem() const + { + return (_aInfo.uAttributes & osl_Volume_Attribute_Case_Is_Preserved) != 0; + } + + friend class Directory; +}; + + +class DirectoryItem; + +/** The FileStatus class. + + @see DirectoryItem::getFileStatus +*/ + +class FileStatus +{ + oslFileStatus _aStatus; + sal_uInt32 _nMask; + + /** Copy constructor. + */ + + FileStatus( FileStatus& ) SAL_DELETED_FUNCTION; + + /** Assignment operator. + */ + + FileStatus& operator = ( FileStatus& ) SAL_DELETED_FUNCTION; + +public: + + enum Type { + Directory = osl_File_Type_Directory, + Volume = osl_File_Type_Volume, + Regular = osl_File_Type_Regular, + Fifo = osl_File_Type_Fifo, + Socket = osl_File_Type_Socket, + Link = osl_File_Type_Link, + Special = osl_File_Type_Special, + Unknown = osl_File_Type_Unknown + }; + + /** Constructor. + + @param nMask + Set of flags describing the demanded information. + */ + FileStatus(sal_uInt32 nMask) + : _nMask(nMask) + { + memset(&_aStatus, 0, sizeof(_aStatus)); + _aStatus.uStructSize = sizeof(_aStatus); + } + + /** Destructor. + */ + ~FileStatus() + { + if ( _aStatus.ustrFileURL ) + rtl_uString_release( _aStatus.ustrFileURL ); + if ( _aStatus.ustrLinkTargetURL ) + rtl_uString_release( _aStatus.ustrLinkTargetURL ); + if ( _aStatus.ustrFileName ) + rtl_uString_release( _aStatus.ustrFileName ); + } + + /** Check if specified fields are valid. + + @param nMask + Set of flags for the fields to check. + + @return + true if all fields are valid else false. + */ + + bool isValid( sal_uInt32 nMask ) const + { + return ( nMask & _aStatus.uValidFields ) == nMask; + } + + /** Get the file type. + + @return + The file type. + */ + Type getFileType() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_Type), "sal.osl", + "no FileStatus Type determined"); + return isValid(osl_FileStatus_Mask_Type) + ? static_cast< Type >(_aStatus.eType) : Unknown; + } + + /** Is it a directory? + This method returns True for both directories, and volumes. + + @return + True if it's a directory, False otherwise. + + @see getFileType + @since LibreOffice 3.6 + */ + bool isDirectory() const + { + return ( getFileType() == Directory || getFileType() == Volume ); + } + + /** Is it a regular file? + + @return + True if it's a regular file, False otherwise. + + @see getFileType + @see isFile + @see isLink + @since LibreOffice 3.6 + */ + bool isRegular() const + { + return ( getFileType() == Regular ); + } + + /** Is it a link? + + @return + True if it's a link, False otherwise. + + @see getFileType + @since LibreOffice 3.6 + */ + bool isLink() const + { + return ( getFileType() == Link ); + } + + /** Get the file attributes. + + @return + The set of attribute flags of this file. + */ + + sal_uInt64 getAttributes() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_Attributes), "sal.osl", + "no FileStatus Attributes determined"); + return _aStatus.uAttributes; + } + + /** Get the creation time of this file. + + @return + The creation time if this information is valid, an uninitialized + TimeValue otherwise. + */ + + TimeValue getCreationTime() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_CreationTime), "sal.osl", + "no FileStatus CreationTime determined"); + return _aStatus.aCreationTime; + } + + /** Get the file access time. + + @return + The last access time if this information is valid, an uninitialized + TimeValue otherwise. + */ + + TimeValue getAccessTime() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_AccessTime), "sal.osl", + "no FileStatus AccessTime determined"); + return _aStatus.aAccessTime; + } + + /** Get the file modification time. + + @return + The last modified time if this information is valid, an uninitialized + TimeValue otherwise. + */ + + TimeValue getModifyTime() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_ModifyTime), "sal.osl", + "no FileStatus ModifyTime determined"); + return _aStatus.aModifyTime; + } + + /** Get the size of the file. + + @return + The actual file size if this information is valid, 0 otherwise. + */ + + sal_uInt64 getFileSize() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_FileSize), "sal.osl", + "no FileStatus FileSize determined"); + return _aStatus.uFileSize; + } + + /** Get the file name. + + @return + The file name if this information is valid, an empty string otherwise. + */ + + ::rtl::OUString getFileName() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_FileName), "sal.osl", + "no FileStatus FileName determined"); + return isValid(osl_FileStatus_Mask_FileName) + ? rtl::OUString(_aStatus.ustrFileName) : rtl::OUString(); + } + + + /** Get the URL of the file. + + @return + The full qualified URL of the file if this information is valid, an + empty string otherwise. + */ + + ::rtl::OUString getFileURL() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_FileURL), "sal.osl", + "no FileStatus FileURL determined"); + return isValid(osl_FileStatus_Mask_FileURL) + ? rtl::OUString(_aStatus.ustrFileURL) : rtl::OUString(); + } + + /** Get the link target URL. + + @return + The link target URL if this information is valid, an empty string + otherwise. + */ + + ::rtl::OUString getLinkTargetURL() const + { + SAL_INFO_IF( + !isValid(osl_FileStatus_Mask_LinkTargetURL), "sal.osl", + "no FileStatus LinkTargetURL determined"); + return isValid(osl_FileStatus_Mask_LinkTargetURL) + ? rtl::OUString(_aStatus.ustrLinkTargetURL) : rtl::OUString(); + } + + friend class DirectoryItem; +}; + + +/** The file class object provides access to file contents and attributes. + + @see Directory + @see DirectoryItem + */ + +class File: public FileBase +{ + oslFileHandle _pData; + ::rtl::OUString _aPath; + + /** Copy constructor. + */ + + File( File& ) SAL_DELETED_FUNCTION; + + /** Assignment operator. + */ + + File& operator = ( File& ) SAL_DELETED_FUNCTION; + +public: + + /** Constructor. + + @param[in] ustrFileURL + The full qualified URL of the file. Relative paths are not allowed. + */ + + File( const ::rtl::OUString& ustrFileURL ): _pData( NULL ), _aPath( ustrFileURL ) {} + + /** Destructor + */ + + ~File() + { + close(); + } + + /** Obtain the URL. + + @return + the URL with which this File instance was created. + + @since LibreOffice 4.1 + */ + rtl::OUString getURL() const { return _aPath; } + + /** Open a regular file. + + Open a file. Only regular files can be opened. + + @param[in] uFlags + Specifies the open mode. + + @retval E_None on success + @retval E_NOMEM not enough memory for allocating structures + @retval E_INVAL the format of the parameters was not valid + @retval E_NAMETOOLONG pathname was too long + @retval E_NOENT no such file or directory + @retval E_ACCES permission denied + @retval E_AGAIN a write lock could not be established + @retval E_NOTDIR not a directory + @retval E_NXIO no such device or address + @retval E_NODEV no such device + @retval E_ROFS read-only file system + @retval E_TXTBSY text file busy + @retval E_FAULT bad address + @retval E_LOOP too many symbolic links encountered + @retval E_NOSPC no space left on device + @retval E_ISDIR is a directory + @retval E_MFILE too many open files used by the process + @retval E_NFILE too many open files in the system + @retval E_DQUOT quota exceeded + @retval E_EXIST file exists + @retval E_INTR function call was interrupted + @retval E_IO on I/O errors + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + @retval E_EOVERFLOW value too large for defined data type + + @see close() + @see setPos() + @see getPos() + @see read() + @see write() + @see getSize() + @see setSize() + */ + + RC open( sal_uInt32 uFlags ) + { + return static_cast< RC >( osl_openFile( _aPath.pData, &_pData, uFlags ) ); + } + + /** Close an open file. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_BADF Bad file + @retval E_INTR function call was interrupted + @retval E_NOLINK link has been severed + @retval E_NOSPC no space left on device + @retval E_IO on I/O errors + + @see open() + */ + + RC close() + { + oslFileError Error = osl_File_E_BADF; + + if( _pData ) + { + Error=osl_closeFile( _pData ); + _pData = NULL; + } + + return static_cast< RC >( Error ); + } + + /** Set the internal position pointer of an open file. + + @param[in] uHow + Distance to move the internal position pointer (from uPos). + + @param[in] uPos + Absolute position from the beginning of the file. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see getPos() + */ + + SAL_WARN_UNUSED_RESULT RC setPos( sal_uInt32 uHow, sal_Int64 uPos ) + { + return static_cast< RC >( osl_setFilePos( _pData, uHow, uPos ) ); + } + + /** Retrieve the current position of the internal pointer of an open file. + + @param[out] uPos + On success receives the current position of the file pointer. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see setPos() + @see read() + @see write() + */ + + RC getPos( sal_uInt64& uPos ) + { + return static_cast< RC >( osl_getFilePos( _pData, &uPos ) ); + } + + /** Test if the end of a file is reached. + + @param[out] pIsEOF + Points to a variable that receives the end-of-file status. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_INTR function call was interrupted + @retval E_IO on I/O errors + @retval E_ISDIR is a directory + @retval E_BADF bad file + @retval E_FAULT bad address + @retval E_AGAIN operation would block + @retval E_NOLINK link has been severed + + @see open() + @see read() + @see readLine() + @see setPos() + */ + + RC isEndOfFile( sal_Bool *pIsEOF ) + { + return static_cast< RC >( osl_isEndOfFile( _pData, pIsEOF ) ); + } + + /** Set the file size of an open file. + + Sets the file size of an open file. The file can be truncated or enlarged by the function. + The position of the file pointer is not affeced by this function. + + @param[in] uSize + New size in bytes. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see setPos() + @see getStatus() + */ + + RC setSize( sal_uInt64 uSize ) + { + return static_cast< RC >( osl_setFileSize( _pData, uSize ) ); + } + + /** Get the file size of an open file. + + Gets the file size of an open file. + The position of the file pointer is not affeced by this function. + + @param[out] rSize + Current size in bytes. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_OVERFLOW the resulting file offset would be a value which cannot be represented correctly for regular files + + @see open() + @see setPos() + @see getSize() + @see setSize() + @see getStatus() + */ + + RC getSize( sal_uInt64 &rSize ) + { + return static_cast< RC >( osl_getFileSize( _pData, &rSize ) ); + } + + /** Read a number of bytes from a file. + + Reads a number of bytes from a file. The internal file pointer is + increased by the number of bytes read. + + @param[out] pBuffer + Points to a buffer which receives data. The buffer must be large enough + to hold uBytesRequested bytes. + + @param[in] uBytesRequested + Number of bytes which should be retrieved. + + @param[out] rBytesRead + On success the number of bytes which have actually been retrieved. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_INTR function call was interrupted + @retval E_IO on I/O errors + @retval E_ISDIR is a directory + @retval E_BADF bad file + @retval E_FAULT bad address + @retval E_AGAIN operation would block + @retval E_NOLINK link has been severed + + @see open() + @see write() + @see readLine() + @see setPos() + */ + + RC read( void *pBuffer, sal_uInt64 uBytesRequested, sal_uInt64& rBytesRead ) + { + return static_cast< RC >( osl_readFile( _pData, pBuffer, uBytesRequested, &rBytesRead ) ); + } + + /** Write a number of bytes to a file. + + Writes a number of bytes to a file. + The internal file pointer is increased by the number of bytes read. + + @param[in] pBuffer + Points to a buffer which contains the data. + + @param[in] uBytesToWrite + Number of bytes which should be written. + + @param[out] rBytesWritten + On success the number of bytes which have actually been written. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_FBIG file too large + @retval E_DQUOT quota exceeded + @retval E_AGAIN operation would block + @retval E_BADF bad file + @retval E_FAULT bad address + @retval E_INTR function call was interrupted + @retval E_IO on I/O errors + @retval E_NOLCK no record locks available + @retval E_NOLINK link has been severed + @retval E_NOSPC no space left on device + @retval E_NXIO no such device or address + + @see open() + @see read() + @see setPos() + */ + + RC write(const void *pBuffer, sal_uInt64 uBytesToWrite, sal_uInt64& rBytesWritten) + { + return static_cast< RC >( osl_writeFile( _pData, pBuffer, uBytesToWrite, &rBytesWritten ) ); + } + + + /** Read a line from a file. + + Reads a line from a file. The new line delimiter is NOT returned! + + @param[in,out] aSeq + A reference to a ::rtl::ByteSequence that will hold the line read on success. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_INTR function call was interrupted + @retval E_IO on I/O errors + @retval E_ISDIR is a directory + @retval E_BADF bad file + @retval E_FAULT bad address + @retval E_AGAIN operation would block + @retval E_NOLINK link has been severed + + @see open() + @see read() + @see write() + @see setPos() + */ + + RC readLine( ::rtl::ByteSequence& aSeq ) + { + return static_cast< RC >( osl_readLine( _pData, reinterpret_cast(&aSeq) ) ); + } + + /** Synchronize the memory representation of a file with that on the physical medium. + + The function ensures that all modified data and attributes of the file associated with + the given file handle have been written to the physical medium. + In case the hard disk has a write cache enabled, the data may not really be on + permanent storage when osl_syncFile returns. + + @retval E_None On success + @retval E_INVAL The value of the input parameter is invalid + @retval E_BADF The file is not open for writing + @retval E_IO An I/O error occurred + @retval E_NOSPC There is no enough space on the target device + @retval E_ROFS The file is located on a read only file system + @retval E_TIMEDOUT A remote connection timed out. This may happen when a file is on a remote location + + @see osl_syncFile() + @see open() + @see write() + */ + RC sync() const + { + OSL_PRECOND(_pData, "File::sync(): File not open"); + return static_cast< RC >(osl_syncFile(_pData)); + } + + /** Copy a file to a new destination. + + Copies a file to a new destination. Copies only files not directories. + No assumptions should be made about preserving attributes or file time. + + @param[in] ustrSourceFileURL + Full qualified URL of the source file. + + @param[in] ustrDestFileURL + Full qualified URL of the destination file. A directory is NOT a valid destination file! + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_PERM operation not permitted + @retval E_NAMETOOLONG file name too long + @retval E_NOENT no such file or directory + @retval E_ISDIR is a directory + @retval E_ROFS read-only file system + + @see move() + @see remove() + */ + + static RC copy( const ::rtl::OUString& ustrSourceFileURL, const ::rtl::OUString& ustrDestFileURL ) + { + return static_cast< RC >( osl_copyFile( ustrSourceFileURL.pData, ustrDestFileURL.pData ) ); + } + + /** Move a file or directory to a new destination or renames it. + + Moves a file or directory to a new destination or renames it. + File time and attributes are preserved. + + @param[in] ustrSourceFileURL + Full qualified URL of the source file. + + @param[in] ustrDestFileURL + Full qualified URL of the destination file. An existing directory is NOT a valid destination ! + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_PERM operation not permitted + @retval E_NAMETOOLONG file name too long + @retval E_NOENT no such file or directory + @retval E_ROFS read-only file system + + @see copy() + */ + + static RC move( const ::rtl::OUString& ustrSourceFileURL, const ::rtl::OUString& ustrDestFileURL ) + { + return static_cast< RC >( osl_moveFile( ustrSourceFileURL.pData, ustrDestFileURL.pData ) ); + } + + /** Move a file to a new destination or rename it, taking old file's identity (if exists). + + Moves or renames a file, replacing an existing file if exist. If the old file existed, + moved file's metadata, e.g. creation time (on FSes which keep files' creation time) or + ACLs, are set to old one's (to keep the old file's identity) - currently this is only + implemented fully on Windows; on other platforms, this is mostly equivalent to move(). + + @param[in] ustrSourceFileURL + Full qualified URL of the source file. + + @param[in] ustrDestFileURL + Full qualified URL of the destination file. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_PERM operation not permitted + @retval E_NAMETOOLONG file name too long + @retval E_NOENT no such file + @retval E_ROFS read-only file system + @retval E_BUSY device or resource busy + + @see move() + + @since LibreOffice 6.2 + */ + static RC replace(const ::rtl::OUString& ustrSourceFileURL, + const ::rtl::OUString& ustrDestFileURL) + { + return static_cast(osl_replaceFile(ustrSourceFileURL.pData, ustrDestFileURL.pData)); + } + + /** Remove a regular file. + + @param[in] ustrFileURL + Full qualified URL of the file to remove. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_PERM operation not permitted + @retval E_NAMETOOLONG file name too long + @retval E_NOENT no such file or directory + @retval E_ISDIR is a directory + @retval E_ROFS read-only file system + @retval E_FAULT bad address + @retval E_LOOP too many symbolic links encountered + @retval E_IO on I/O errors + @retval E_BUSY device or resource busy + @retval E_INTR function call was interrupted + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + @retval E_TXTBSY text file busy + + @see open() + */ + + static RC remove( const ::rtl::OUString& ustrFileURL ) + { + return static_cast< RC >( osl_removeFile( ustrFileURL.pData ) ); + } + + /** Set file attributes. + + @param[in] ustrFileURL + The full qualified file URL. + + @param[in] uAttributes + Attributes of the file to be set. + + @return + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + + @see FileStatus + */ + + static RC setAttributes( const ::rtl::OUString& ustrFileURL, sal_uInt64 uAttributes ) + { + return static_cast< RC >( osl_setFileAttributes( ustrFileURL.pData, uAttributes ) ); + } + + /** Set the file time. + + @param[in] ustrFileURL + The full qualified URL of the file. + + @param[in] rCreationTime + Creation time of the given file. + + @param[in] rLastAccessTime + Time of the last access of the given file. + + @param[in] rLastWriteTime + Time of the last modifying of the given file. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOENT no such file or directory not found + + @see FileStatus + */ + + static RC setTime( + const ::rtl::OUString& ustrFileURL, + const TimeValue& rCreationTime, + const TimeValue& rLastAccessTime, + const TimeValue& rLastWriteTime ) + { + return static_cast< RC >( osl_setFileTime( + ustrFileURL.pData, + &rCreationTime, + &rLastAccessTime, + &rLastWriteTime ) ); + } + + friend class DirectoryItem; +}; + + +/** The directory item class object provides access to file status information. + + @see FileStatus + */ + +class DirectoryItem: public FileBase +{ + oslDirectoryItem _pData; + +public: + + /** Constructor. + */ + + DirectoryItem(): _pData( NULL ) + { + } + + /** Copy constructor. + */ + + DirectoryItem( const DirectoryItem& rItem ): _pData( rItem._pData) + { + if( _pData ) + osl_acquireDirectoryItem( _pData ); + } + + /** Destructor. + */ + + ~DirectoryItem() + { + if( _pData ) + osl_releaseDirectoryItem( _pData ); + } + + /** Assignment operator. + */ + + DirectoryItem& operator=(const DirectoryItem& rItem ) + { + if (&rItem != this) + { + if( _pData ) + osl_releaseDirectoryItem( _pData ); + + _pData = rItem._pData; + + if( _pData ) + osl_acquireDirectoryItem( _pData ); + } + return *this; + } + + /** Check for validity of this instance. + + @return + true if object is valid directory item else false. + */ + + bool is() + { + return _pData != NULL; + } + + /** Retrieve a single directory item. + + Retrieves a single directory item. The returned handle has an initial refcount of 1. + Due to performance issues it is not recommended to use this function while + enumerating the contents of a directory. In this case use osl_getNextDirectoryItem() instead. + + @param[in] ustrFileURL + An absolute file URL. + + @param[out] rItem + On success it receives a handle which can be used for subsequent calls to osl_getFileStatus(). + The handle has to be released by a call to osl_releaseDirectoryItem(). + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_MFILE too many open files used by the process + @retval E_NFILE too many open files in the system + @retval E_NOENT no such file or directory + @retval E_LOOP too many symbolic links encountered + @retval E_NAMETOOLONG the file name is too long + @retval E_NOTDIR a component of the path prefix of path is not a directory + @retval E_IO on I/O errors + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + @retval E_FAULT bad address + @retval E_INTR the function call was interrupted + + @see FileStatus + @see Directory::getNextItem() + */ + + static RC get( const ::rtl::OUString& ustrFileURL, DirectoryItem& rItem ) + { + if( rItem._pData) + { + osl_releaseDirectoryItem( rItem._pData ); + rItem._pData = NULL; + } + + return static_cast< RC >( osl_getDirectoryItem( ustrFileURL.pData, &rItem._pData ) ); + } + + /** Retrieve information about a single file or directory. + + @param[in,out] rStatus + Reference to a class which receives the information of the file or directory + represented by this directory item. + + @retval E_None on success + @retval E_NOMEM not enough memory for allocating structures + @retval E_INVAL the format of the parameters was not valid + @retval E_LOOP too many symbolic links encountered + @retval E_ACCES permission denied + @retval E_NOENT no such file or directory + @retval E_NAMETOOLONG file name too long + @retval E_BADF invalid oslDirectoryItem parameter + @retval E_FAULT bad address + @retval E_OVERFLOW value too large for defined data type + @retval E_INTR function call was interrupted + @retval E_NOLINK link has been severed + @retval E_MULTIHOP components of path require hopping to multiple remote machines and the file system does not allow it + @retval E_MFILE too many open files used by the process + @retval E_NFILE too many open files in the system + @retval E_NOSPC no space left on device + @retval E_NXIO no such device or address + @retval E_IO on I/O errors + @retval E_NOSYS function not implemented + + @see get() + @see Directory::getNextItem() + @see FileStatus + */ + + RC getFileStatus( FileStatus& rStatus ) + { + return static_cast< RC >( osl_getFileStatus( _pData, &rStatus._aStatus, rStatus._nMask ) ); + } + +/** Determine if a directory item point the same underlying file + + The comparison is done first by URL, and then by resolving links to + find the target, and finally by comparing inodes on unix. + + @param[in] pOther + A directory handle to compare with the underlying object's item + + @retval true if the items point to an identical resource
    + @retval false if the items point to a different resource, or a fatal error occurred
    + + @see osl_getDirectoryItem() + + @since LibreOffice 3.6 +*/ + bool isIdenticalTo( const DirectoryItem &pOther ) + { + return osl_identicalDirectoryItem( _pData, pOther._pData ); + } + + friend class Directory; +}; + + +/** Base class for observers of directory creation notifications. + + Clients which uses the method createDirectoryPath of the class + Directory may want to be informed about the directories that + have been created. This may be accomplished by deriving from + this base class and overwriting the virtual function + DirectoryCreated. + + @see Directory::createPath +*/ +class DirectoryCreationObserver +{ +public: + virtual ~DirectoryCreationObserver() {} + + /** This method will be called when a new directory has been + created and needs to be overwritten by derived classes. + You must not delete the directory that was just created + otherwise you will run into an endless loop. + + @param aDirectoryUrl + [in]The absolute file URL of the directory that was just created by + ::osl::Directory::createPath. + */ + virtual void DirectoryCreated(const rtl::OUString& aDirectoryUrl) = 0; +}; + + +// This just an internal helper function for +// private use. +extern "C" inline void SAL_CALL onDirectoryCreated(void* pData, rtl_uString* aDirectoryUrl) +{ + static_cast(pData)->DirectoryCreated(aDirectoryUrl); +} + +/** The directory class object provides an enumeration of DirectoryItems. + + @see DirectoryItem + @see File + */ + +class Directory: public FileBase +{ + oslDirectory _pData; + ::rtl::OUString _aPath; + + /** Copy constructor. + */ + + Directory( Directory& ) SAL_DELETED_FUNCTION; + + /** Assignment operator. + */ + + Directory& operator = ( Directory& ) SAL_DELETED_FUNCTION; + +public: + + /** Constructor. + + @param[in] strPath + The full qualified URL of the directory. + Relative URLs are not allowed. + */ + + Directory( const ::rtl::OUString& strPath ): _pData( NULL ), _aPath( strPath ) + { + } + + /** Destructor. + */ + + ~Directory() + { + close(); + } + + /** Obtain the URL. + + @return + the URL with which this Directory instance was created. + + @since LibreOffice 4.1 + */ + rtl::OUString getURL() const { return _aPath; } + + /** Open a directory for enumerating its contents. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOENT the specified path doesn't exist + @retval E_NOTDIR the specified path is not a directory + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_MFILE too many open files used by the process + @retval E_NFILE too many open files in the system + @retval E_NAMETOOLONG File name too long + @retval E_LOOP Too many symbolic links encountered + + @see getNextItem() + @see close() + */ + + RC open() + { + return static_cast< RC >( osl_openDirectory( _aPath.pData, &_pData ) ); + } + + /** Query if directory is open. + + Query if directory is open and so item enumeration is valid. + + @retval true if the directory is open else false. + + @see open() + @see close() + */ + + bool isOpen() { return _pData != NULL; } + + /** Close a directory. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_BADF invalid oslDirectory parameter + @retval E_INTR the function call was interrupted + + @see open() + */ + + RC close() + { + oslFileError Error = osl_File_E_BADF; + + if( _pData ) + { + Error=osl_closeDirectory( _pData ); + _pData = NULL; + } + + return static_cast< RC >( Error ); + } + + + /** Resets the directory item enumeration to the beginning. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOENT the specified path doesn't exist + @retval E_NOTDIR the specified path is not a directory + @retval E_NOMEM not enough memory for allocating structures + @retval E_ACCES permission denied + @retval E_MFILE too many open files used by the process + @retval E_NFILE too many open files in the system + @retval E_NAMETOOLONG File name too long + @retval E_LOOP Too many symbolic links encountered + + @see open() + */ + + RC reset() + { + close(); + return open(); + } + + /** Retrieve the next item of a previously opened directory. + + Retrieves the next item of a previously opened directory. + + @param[out] rItem + On success a valid DirectoryItem. + + @param[in] nHint + With this parameter the caller can tell the implementation that (s)he + is going to call this function uHint times afterwards. This enables the implementation to + get the information for more than one file and cache it until the next calls. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_NOENT no more entries in this directory + @retval E_BADF invalid oslDirectory parameter + @retval E_OVERFLOW the value too large for defined data type + + @see DirectoryItem + */ + + RC getNextItem( DirectoryItem& rItem, sal_uInt32 nHint = 0 ) + { + if( rItem._pData ) + { + osl_releaseDirectoryItem( rItem._pData ); + rItem._pData = NULL; + } + return static_cast(osl_getNextDirectoryItem( _pData, &rItem._pData, nHint )); + } + + + /** Retrieve information about a volume. + + Retrieves information about a volume. A volume can either be a mount point, a network + resource or a drive depending on Operating System and File System. + + @param[in] ustrDirectoryURL + Full qualified URL of the volume + + @param[out] rInfo + On success it receives information about the volume. + + @retval E_None on success + @retval E_NOMEM not enough memory for allocating structures + @retval E_INVAL the format of the parameters was not valid + @retval E_NOTDIR not a directory + @retval E_NAMETOOLONG file name too long + @retval E_NOENT no such file or directory + @retval E_ACCES permission denied + @retval E_LOOP too many symbolic links encountered + @retval E_FAULT Bad address + @retval E_IO on I/O errors + @retval E_NOSYS function not implemented + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + @retval E_INTR function call was interrupted + + @see FileStatus + @see VolumeInfo + */ + + static RC getVolumeInfo( const ::rtl::OUString& ustrDirectoryURL, VolumeInfo& rInfo ) + { + return static_cast< RC >( osl_getVolumeInformation( ustrDirectoryURL.pData, &rInfo._aInfo, rInfo._nMask ) ); + } + + /** Create a directory. + + @param[in] ustrDirectoryURL + Full qualified URL of the directory to create. + + @param[in] flags + Optional flags, see osl_createDirectoryWithFlags for details. This + defaulted parameter is new since LibreOffice 4.3. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_EXIST file exists + @retval E_ACCES permission denied + @retval E_NAMETOOLONG file name too long + @retval E_NOENT no such file or directory + @retval E_NOTDIR not a directory + @retval E_ROFS read-only file system + @retval E_NOSPC no space left on device + @retval E_DQUOT quota exceeded + @retval E_LOOP too many symbolic links encountered + @retval E_FAULT bad address + @retval E_IO on I/O errors + @retval E_MLINK too many links + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + + @see remove() + */ + + static RC create( + const ::rtl::OUString& ustrDirectoryURL, + sal_uInt32 flags = osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ) + { + return static_cast< RC >( + osl_createDirectoryWithFlags( ustrDirectoryURL.pData, flags ) ); + } + + /** Remove an empty directory. + + @param[in] ustrDirectoryURL + Full qualified URL of the directory. + + @retval E_None on success + @retval E_INVAL the format of the parameters was not valid + @retval E_NOMEM not enough memory for allocating structures + @retval E_PERM operation not permitted + @retval E_ACCES permission denied + @retval E_NOENT no such file or directory + @retval E_NOTDIR not a directory + @retval E_NOTEMPTY directory not empty + @retval E_FAULT bad address + @retval E_NAMETOOLONG file name too long + @retval E_BUSY device or resource busy + @retval E_ROFS read-only file system + @retval E_LOOP too many symbolic links encountered + @retval E_EXIST file exists + @retval E_IO on I/O errors + @retval E_MULTIHOP multihop attempted + @retval E_NOLINK link has been severed + + @see create() + */ + + static RC remove( const ::rtl::OUString& ustrDirectoryURL ) + { + return static_cast< RC >( osl_removeDirectory( ustrDirectoryURL.pData ) ); + } + + /** Create a directory path. + + The osl_createDirectoryPath function creates a specified directory path. + All nonexisting sub directories will be created. + + @attention You cannot rely on getting the error code E_EXIST for existing + directories. Programming against this error code is in general a strong + indication of a wrong usage of osl_createDirectoryPath. + + @param aDirectoryUrl + [in] The absolute file URL of the directory path to create. + A relative file URL will not be accepted. + + @param aDirectoryCreationObserver + [in] Pointer to an instance of type DirectoryCreationObserver that will + be informed about the creation of a directory. The value of this + parameter may be NULL, in this case notifications will not be sent. + + @retval E_None On success + @retval E_INVAL The format of the parameters was not valid + @retval E_ACCES Permission denied + @retval E_EXIST The final node of the specified directory path already exist + @retval E_NAMETOOLONG The name of the specified directory path exceeds the maximum allowed length + @retval E_NOTDIR A component of the specified directory path already exist as file in any part of the directory path + @retval E_ROFS Read-only file system + @retval E_NOSPC No space left on device + @retval E_DQUOT Quota exceeded + @retval E_FAULT Bad address + @retval E_IO I/O error + @retval E_LOOP Too many symbolic links encountered + @retval E_NOLINK Link has been severed + @retval E_invalidError An unknown error occurred + + @see DirectoryCreationObserver + @see create + */ + static RC createPath( + const ::rtl::OUString& aDirectoryUrl, + DirectoryCreationObserver* aDirectoryCreationObserver = NULL) + { + return static_cast< RC >(osl_createDirectoryPath( + aDirectoryUrl.pData, + aDirectoryCreationObserver ? onDirectoryCreated : NULL, + aDirectoryCreationObserver)); + } +}; + +} /* namespace osl */ + +#endif // INCLUDED_OSL_FILE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/getglobalmutex.hxx b/include/osl/getglobalmutex.hxx new file mode 100644 index 000000000..87d68b440 --- /dev/null +++ b/include/osl/getglobalmutex.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_GETGLOBALMUTEX_HXX +#define INCLUDED_OSL_GETGLOBALMUTEX_HXX + +#include "osl/mutex.hxx" + +namespace osl +{ +/** A helper functor for the rtl_Instance template. + + See the rtl_Instance template for examples of how this class is used. + */ +class GetGlobalMutex +{ +public: + ::osl::Mutex* operator()() { return ::osl::Mutex::getGlobalMutex(); } +}; +} + +#endif // INCLUDED_OSL_GETGLOBALMUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/interlck.h b/include/osl/interlck.h new file mode 100644 index 000000000..6264c595d --- /dev/null +++ b/include/osl/interlck.h @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_INTERLCK_H +#define INCLUDED_OSL_INTERLCK_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#if defined(_WIN32) +#include +#endif + +#if defined LIBO_INTERNAL_ONLY +#include "config_global.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef sal_Int32 oslInterlockedCount; + +/** Increments the count variable addressed by pCount. + @param pCount Address of count variable + @return The adjusted value of the count variable. +*/ +SAL_DLLPUBLIC oslInterlockedCount SAL_CALL osl_incrementInterlockedCount(oslInterlockedCount* pCount); + +/** Decrement the count variable addressed by pCount. + @param pCount Address of count variable + @return The adjusted value of the count variable. +*/ +SAL_DLLPUBLIC oslInterlockedCount SAL_CALL osl_decrementInterlockedCount(oslInterlockedCount* pCount); + + +/// @cond INTERNAL + +/** Increments the count variable addressed by p. + + @attention This functionality should only be used internally within + LibreOffice. + + @param p Address of count variable + @return The adjusted value of the count variable. + + @since LibreOffice 4.0 +*/ +#if HAVE_GCC_BUILTIN_ATOMIC +# define osl_atomic_increment(p) __sync_add_and_fetch((p), 1) +#elif defined WNT +# define osl_atomic_increment(p) _InterlockedIncrement(p) +#else +# define osl_atomic_increment(p) osl_incrementInterlockedCount((p)) +#endif + + +/** Decrement the count variable addressed by p. + + @attention This functionality should only be used internally within + LibreOffice. + + @param p Address of count variable + @return The adjusted value of the count variable. + + @since LibreOffice 4.0 +*/ +#if HAVE_GCC_BUILTIN_ATOMIC +# define osl_atomic_decrement(p) __sync_sub_and_fetch((p), 1) +#elif defined WNT +# define osl_atomic_decrement(p) _InterlockedDecrement(p) +#else +# define osl_atomic_decrement(p) osl_decrementInterlockedCount((p)) +#endif + +/// @endcond + +#ifdef __cplusplus +} +#endif + + +#endif // INCLUDED_OSL_INTERLCK_H + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/module.h b/include/osl/module.h new file mode 100644 index 000000000..9d80d352a --- /dev/null +++ b/include/osl/module.h @@ -0,0 +1,230 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_MODULE_H +#define INCLUDED_OSL_MODULE_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SAL_DLLPREFIX +#define SAL_MODULENAME(name) SAL_DLLPREFIX name SAL_DLLEXTENSION +#else +#define SAL_MODULENAME(name) name SAL_DLLEXTENSION +#endif + +#if defined(_WIN32) +#define SAL_MODULENAME_WITH_VERSION(name, version) name version SAL_DLLEXTENSION + +#elif defined(SAL_UNX) +#if defined(MACOSX) +#define SAL_MODULENAME_WITH_VERSION(name, version) SAL_DLLPREFIX name ".dylib." version +#else +#define SAL_MODULENAME_WITH_VERSION(name, version) SAL_DLLPREFIX name SAL_DLLEXTENSION "." version +#endif + +#endif + +#define SAL_LOADMODULE_DEFAULT 0x00000 +#define SAL_LOADMODULE_LAZY 0x00001 +#define SAL_LOADMODULE_NOW 0x00002 +#define SAL_LOADMODULE_GLOBAL 0x00100 + +typedef void* oslModule; + +/** Generic Function pointer type that will be used as symbol address. + + @see osl_getFunctionSymbol. + @see osl_getModuleURLFromFunctionAddress. +*/ +typedef void ( SAL_CALL *oslGenericFunction )( void ); + +#ifndef DISABLE_DYNLOADING + +/** Load a shared library or module. + + @param[in] strModuleName denotes the name of the module to be loaded. + @param[in] nRtldMode denotes the mode. + + @returns NULL if the module could not be loaded, otherwise a handle to the module. +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModule(rtl_uString *strModuleName, sal_Int32 nRtldMode); + +/** Load a shared library or module. + + @param[in] pModuleName denotes the name of the module to be loaded. + @param[in] nRtldMode denotes the mode. + + @return NULL if the module could not be loaded, otherwise a handle to the module. + + @since UDK 3.6 +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModuleAscii(const char *pModuleName, sal_Int32 nRtldMode); + +/** Load a module located relative to some other module. + + @param[in] baseModule must point to a function that is part of the code of some loaded module; + must not be NULL. + @param[in] relativePath a relative URL; must not be NULL. + @param[in] mode the SAL_LOADMODULE_xxx flags. + + @return a non-NULL handle to the loaded module, or NULL if an error occurred. + + @since UDK 3.2.8 +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModuleRelative( + oslGenericFunction baseModule, rtl_uString * relativePath, sal_Int32 mode); + +/** Load a module located relative to some other module. + + @param[in] baseModule must point to a function that is part of the code of some loaded module; + must not be NULL. + @param[in] relativePath a relative URL containing only ASCII (0x01--7F) characters; + must not be NULL. + @param[in] mode the SAL_LOADMODULE_xxx flags. + + @return a non-NULL handle to the loaded module, or NULL if an error occurred. + + @since LibreOffice 3.5 +*/ +SAL_DLLPUBLIC oslModule SAL_CALL osl_loadModuleRelativeAscii( + oslGenericFunction baseModule, char const * relativePath, sal_Int32 mode); + /* This function is guaranteed not to call into + FullTextEncodingDataSingleton in sal/textenc/textenc.cxx, so can be used + in its implementation without running into circles. */ + +#endif + +/** Retrieve the handle of an already loaded module. + + This function can be used to search for a function symbol in the process address space. + Do not use the returned handle as an argument to osl_unloadModule. On Unix platforms, + pModuleName gets ignored and the special handle RTLD_DEFAULT is returned. + + @param[in] pModuleName denotes the name of the module to search for. + @attention Ignored on Unix. + @param[out] pResult a pointer to a oslModule that is updated with the + requested module handle on success. + + @retval sal_True if the module handle could be retrieved and has been copied to *pResult. + @retval sal_False if the module has not been loaded yet. + + @see osl_getFunctionSymbol + @see osl_getAsciiFunctionSymbol +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getModuleHandle(rtl_uString *pModuleName, oslModule *pResult); + +#ifndef DISABLE_DYNLOADING + +/** Release the module +*/ +SAL_DLLPUBLIC void SAL_CALL osl_unloadModule(oslModule Module); + +#endif + +/** lookup the specified symbol name. + + @param[in] Module the handle of the Module. + @param[in] strSymbolName Name of the function that will be looked up. + + @return address of the symbol or NULL if lookup failed. + + @see osl_getFunctionSymbol +*/ +SAL_DLLPUBLIC void* SAL_CALL osl_getSymbol( oslModule Module, rtl_uString *strSymbolName); + +/** Lookup the specified function symbol name. + + osl_getFunctionSymbol is an alternative function for osl_getSymbol. + Use Function pointer as symbol address to conceal type conversion. + + @param[in] Module the handle of the Module. + @param[in] ustrFunctionSymbolName Unicode name of the function that will be looked up. + + @retval function-address on success + @retval NULL lookup failed or the parameter are invalid + + @see osl_getSymbol + @see osl_getAsciiFunctionSymbol +*/ +SAL_DLLPUBLIC oslGenericFunction SAL_CALL osl_getFunctionSymbol( + oslModule Module, rtl_uString *ustrFunctionSymbolName ); + +/** Lookup the specified function symbol name. + + osl_getAsciiFunctionSymbol is an alternative function for osl_getFunctionSymbol. + It expects the C-style function name string to contain ascii characters only. + + @param Module + [in] a module handle as returned by osl_loadModule or osl_getModuleHandle + + @param pSymbol + [in] Name of the function that will be looked up. + + @retval function-address on success + @retval NULL lookup failed or the parameter are invalid + + @see osl_getModuleHandle + @see osl_getFunctionSymbol +*/ +SAL_DLLPUBLIC oslGenericFunction SAL_CALL osl_getAsciiFunctionSymbol( + oslModule Module, const char *pSymbol ); + +/** Lookup URL of module which is mapped at the specified address. + + @param[in] pv specifies an address in the process memory space. + @param[out] pustrURL receives the URL of the module that is mapped at pv. + @return sal_True on success, sal_False if no module can be found at the specified address. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getModuleURLFromAddress( + void *pv, rtl_uString **pustrURL ); + +/** Lookup URL of module which is mapped at the specified function address. + + osl_getModuleURLFromFunctionAddress is an alternative function for osl_getModuleURLFromAddress. + Use Function pointer as symbol address to conceal type conversion. + + @param[in] pf function address in oslGenericFunction format. + @param[out] pustrFunctionURL receives the URL of the module that is mapped at pf. + + @retval sal_True on success + @retval sal_False no module can be found at the specified function address or parameter is somewhat invalid + + @see osl_getModuleURLFromAddress +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getModuleURLFromFunctionAddress( + oslGenericFunction pf, rtl_uString **pustrFunctionURL ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_MODULE_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/module.hxx b/include/osl/module.hxx new file mode 100644 index 000000000..37f7e249e --- /dev/null +++ b/include/osl/module.hxx @@ -0,0 +1,178 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_MODULE_HXX +#define INCLUDED_OSL_MODULE_HXX + +#include "sal/config.h" + +#include + +#include "rtl/ustring.hxx" +#include "osl/module.h" + +namespace osl +{ + +class Module +{ + Module( const Module&) SAL_DELETED_FUNCTION; + Module& operator = ( const Module&) SAL_DELETED_FUNCTION; + +public: + static bool getUrlFromAddress(void * addr, ::rtl::OUString & libraryUrl) { + return osl_getModuleURLFromAddress(addr, &libraryUrl.pData); + } + + /** Get module URL from the specified function address in the module. + + Similar to getUrlFromAddress, but use a function address to get URL of the Module. + Use Function pointer as symbol address to conceal type conversion. + + @param[in] addr function address in oslGenericFunction format. + @param[in,out] libraryUrl receives the URL of the module. + + @retval true on success + @retval false can not get the URL from the specified function address or the parameter is invalid. + + @see getUrlFromAddress + */ + static bool getUrlFromAddress( oslGenericFunction addr, ::rtl::OUString & libraryUrl){ + return osl_getModuleURLFromFunctionAddress( addr, &libraryUrl.pData ); + } + + Module(): m_Module(NULL){} + +#ifndef DISABLE_DYNLOADING + + Module( const ::rtl::OUString& strModuleName, sal_Int32 nRtldMode = SAL_LOADMODULE_DEFAULT) : m_Module(NULL) + { + load( strModuleName, nRtldMode); + } + +#endif + + ~Module() + { +#ifndef DISABLE_DYNLOADING + osl_unloadModule(m_Module); +#endif + } + +#ifndef DISABLE_DYNLOADING + + bool SAL_CALL load( const ::rtl::OUString& strModuleName, + sal_Int32 nRtldMode = SAL_LOADMODULE_DEFAULT) + { + unload(); + m_Module= osl_loadModule( strModuleName.pData, nRtldMode ); + return is(); + } + + /// @since UDK 3.2.8 + bool SAL_CALL loadRelative( + ::oslGenericFunction baseModule, ::rtl::OUString const & relativePath, + ::sal_Int32 mode = SAL_LOADMODULE_DEFAULT) + { + unload(); + m_Module = osl_loadModuleRelative(baseModule, relativePath.pData, mode); + return is(); + } + + /// @since LibreOffice 3.5 + bool SAL_CALL loadRelative( + oslGenericFunction baseModule, char const * relativePath, + sal_Int32 mode = SAL_LOADMODULE_DEFAULT) + { + unload(); + m_Module = osl_loadModuleRelativeAscii(baseModule, relativePath, mode); + return is(); + } + + void SAL_CALL unload() + { + if (m_Module) + { + osl_unloadModule(m_Module); + m_Module = NULL; + } + } + +#endif + + bool SAL_CALL is() const + { + return m_Module != NULL; + } + + void* SAL_CALL getSymbol( const ::rtl::OUString& strSymbolName) + { + return osl_getSymbol( m_Module, strSymbolName.pData ); + } + + /** Get function address by the function name in the module. + + getFunctionSymbol is an alternative function for getSymbol. + Use Function pointer as symbol address to conceal type conversion. + + @param[in] ustrFunctionSymbolName Function name to be looked up. + + @retval oslGenericFunction format function address on success + @retval NULL lookup failed or parameter is somewhat invalid + + @see getSymbol + */ + oslGenericFunction SAL_CALL getFunctionSymbol( const ::rtl::OUString& ustrFunctionSymbolName ) const + { + return osl_getFunctionSymbol( m_Module, ustrFunctionSymbolName.pData ); + } + + /// @since LibreOffice 3.5 + oslGenericFunction SAL_CALL getFunctionSymbol(char const * name) const { + return osl_getAsciiFunctionSymbol(m_Module, name); + } + + operator oslModule() const + { + return m_Module; + } + + /** Release the module so that it will not be unloaded from the destructor. + + This instance returns to the state of a default-constructed instance + again. + + @since LibreOffice 4.3 + */ + void release() { m_Module = NULL; } + +private: + oslModule m_Module; + +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/mutex.h b/include/osl/mutex.h new file mode 100644 index 000000000..efc619d28 --- /dev/null +++ b/include/osl/mutex.h @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_MUTEX_H +#define INCLUDED_OSL_MUTEX_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _oslMutexImpl; +typedef struct _oslMutexImpl * oslMutex; + +/** Create a mutex. + + @return 0 if the mutex could not be created, otherwise a handle to the mutex. +*/ +SAL_DLLPUBLIC oslMutex SAL_CALL osl_createMutex(void); + +/** Release the OS-structures and free mutex data-structure. + + @param Mutex the mutex-handle +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyMutex(oslMutex Mutex); + +/** Acquire the mutex, block if already acquired by another thread. + @param Mutex handle to a created mutex. + @retval False if system-call fails. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_acquireMutex(oslMutex Mutex); + +/** Try to acquire the mutex without blocking. + + @param Mutex handle to a created mutex. + + @retval False if it could not be acquired. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_tryToAcquireMutex(oslMutex Mutex); + +/** Release the mutex. + + @param Mutex handle to a created mutex. + @retval False if system-call fails. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_releaseMutex(oslMutex Mutex); + +/** Returns a unique and global mutex. + + @return the global mutex. +*/ +SAL_DLLPUBLIC oslMutex * SAL_CALL osl_getGlobalMutex(void); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_MUTEX_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/mutex.hxx b/include/osl/mutex.hxx new file mode 100644 index 000000000..96bfd3e02 --- /dev/null +++ b/include/osl/mutex.hxx @@ -0,0 +1,260 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_MUTEX_HXX +#define INCLUDED_OSL_MUTEX_HXX + +#include "osl/mutex.h" + +#include + +namespace osl +{ + /** A mutual exclusion synchronization object + */ + class SAL_WARN_UNUSED Mutex { + + public: + /** Create a mutex. + @return 0 if the mutex could not be created, otherwise a handle to the mutex. + @see ::osl_createMutex() + */ + Mutex() + { + mutex = osl_createMutex(); + } + + /** Release the OS-structures and free mutex data-structure. + @see ::osl_destroyMutex() + */ + ~Mutex() + { + osl_destroyMutex(mutex); + } + + /** Acquire the mutex, block if already acquired by another thread. + @return false if system-call fails. + @see ::osl_acquireMutex() + */ + bool acquire() + { + return osl_acquireMutex(mutex); + } + + /** Try to acquire the mutex without blocking. + @return false if it could not be acquired. + @see ::osl_tryToAcquireMutex() + */ + bool tryToAcquire() + { + return osl_tryToAcquireMutex(mutex); + } + + /** Release the mutex. + @return false if system-call fails. + @see ::osl_releaseMutex() + */ + bool release() + { + return osl_releaseMutex(mutex); + } + + /** Returns a global static mutex object. + The global and static mutex object can be used to initialize other + static objects in a thread safe manner. + @return the global mutex object + @see ::osl_getGlobalMutex() + */ + static Mutex * getGlobalMutex() + { + return reinterpret_cast(osl_getGlobalMutex()); + } + + private: + oslMutex mutex; + + // access to the oslMutex + friend oslMutex* SAL_CALL ::osl_getGlobalMutex(); + + /** The underlying oslMutex has no reference count. + + Since the underlying oslMutex is not a reference counted object, copy + constructed Mutex may work on an already destructed oslMutex object. + + */ + Mutex(const Mutex&) SAL_DELETED_FUNCTION; + + /** This assignment operator is deleted for the same reason as + the copy constructor. + */ + Mutex& operator= (const Mutex&) SAL_DELETED_FUNCTION; + }; + + /** Object lifetime scoped mutex object or interface lock. + * + * Acquires the template object on construction and releases it on + * destruction. + * + * @see MutexGuard + */ + template + class Guard + { + Guard(const Guard&) SAL_DELETED_FUNCTION; + Guard& operator=(const Guard&) SAL_DELETED_FUNCTION; + + protected: + T * pT; + + public: + /** Acquires the object specified as parameter. + */ + Guard(T * pT_) : pT(pT_) + { + assert(pT != NULL); + pT->acquire(); + } + + /** Acquires the object specified as parameter. + */ + Guard(T & t) : pT(&t) + { + pT->acquire(); + } + + /** Releases the mutex or interface. */ + ~Guard() + { + pT->release(); + } + }; + + /** Object lifetime scoped mutex object or interface lock with unlock. + * + * Use this if you can't use scoped code blocks and Guard. + * + * @see ClearableMutexGuard, Guard + */ + template + class ClearableGuard + { + ClearableGuard( const ClearableGuard& ) SAL_DELETED_FUNCTION; + ClearableGuard& operator=(const ClearableGuard&) SAL_DELETED_FUNCTION; + + protected: + T * pT; + + public: + /** Acquires the object specified as parameter. + */ + ClearableGuard(T * pT_) : pT(pT_) + { + assert(pT != NULL); + pT->acquire(); + } + + /** Acquires the object specified as parameter. + */ + ClearableGuard(T & t) : pT(&t) + { + pT->acquire(); + } + + /** Releases the mutex or interface if not already released by clear(). + */ + ~ClearableGuard() + { + if (pT) + pT->release(); + } + + /** Releases the mutex or interface. + */ + void clear() + { +#ifdef LIBO_INTERNAL_ONLY + assert(pT); +#else + if (pT) +#endif + { + pT->release(); + pT = NULL; + } + } + }; + + /** Template for temporary releasable mutex objects and interfaces locks. + * + * Use this if you want to acquire a lock but need to temporary release + * it and can't use multiple scoped Guard objects. + * + * @see ResettableMutexGuard + */ + template< class T > + class ResettableGuard : public ClearableGuard< T > + { + ResettableGuard(const ResettableGuard&) SAL_DELETED_FUNCTION; + ResettableGuard& operator=(const ResettableGuard&) SAL_DELETED_FUNCTION; + + protected: + T* pResetT; + + public: + /** Acquires the object specified as parameter. + */ + ResettableGuard( T* pT_ ) : + ClearableGuard( pT_ ), + pResetT( pT_ ) + {} + + /** Acquires the object specified as parameter. + */ + ResettableGuard( T& rT ) : + ClearableGuard( rT ), + pResetT( &rT ) + {} + + /** Re-acquires the mutex or interface. + */ + void reset() + { +#ifdef LIBO_INTERNAL_ONLY + assert(!this->pT); +#endif + if (pResetT) + { + this->pT = pResetT; + this->pT->acquire(); + } + } + }; + + typedef Guard MutexGuard; + typedef ClearableGuard ClearableMutexGuard; + typedef ResettableGuard< Mutex > ResettableMutexGuard; +} + +#endif // INCLUDED_OSL_MUTEX_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/nlsupport.h b/include/osl/nlsupport.h new file mode 100644 index 000000000..439c4db35 --- /dev/null +++ b/include/osl/nlsupport.h @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_NLSUPPORT_H +#define INCLUDED_OSL_NLSUPPORT_H + +#include "sal/config.h" + +#include "rtl/locale.h" +#include "rtl/textenc.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Determines the text encoding used by the underlying platform for the + specified locale. + + @param pLocale + the locale to return the text encoding for. If this parameter is NULL, + the default locale of the current process is used. + + @returns the rtl_TextEncoding that matches the platform specific encoding + description or RTL_TEXTENCODING_DONTKNOW if no mapping is available. +*/ + +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL osl_getTextEncodingFromLocale( + rtl_Locale * pLocale ); + + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_NLSUPPORT_H + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/pipe.h b/include/osl/pipe.h new file mode 100644 index 000000000..f8835428d --- /dev/null +++ b/include/osl/pipe.h @@ -0,0 +1,127 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_PIPE_H +#define INCLUDED_OSL_PIPE_H + +#include "sal/config.h" + +#include "osl/security.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + osl_Pipe_E_None, /*< no error */ + osl_Pipe_E_NotFound, /*< Pipe could not be found */ + osl_Pipe_E_AlreadyExists, /*< Pipe already exists */ + osl_Pipe_E_NoProtocol, /*< Protocol not available */ + osl_Pipe_E_NetworkReset, /*< Network dropped connection because of reset */ + osl_Pipe_E_ConnectionAbort, /*< Software caused connection abort */ + osl_Pipe_E_ConnectionReset, /*< Connection reset by peer */ + osl_Pipe_E_NoBufferSpace, /*< No buffer space available */ + osl_Pipe_E_TimedOut, /*< Connection timed out */ + osl_Pipe_E_ConnectionRefused, /*< Connection refused */ + osl_Pipe_E_invalidError, /*< unmapped error: always last entry in enum! */ + osl_Pipe_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslPipeError; + +/** Pipe creation options. + + A pipe can either be opened, or a new pipe can be created and opened. +*/ +typedef sal_uInt32 oslPipeOptions; +#define osl_Pipe_OPEN 0x0000 /*< open existing pipe */ +#define osl_Pipe_CREATE 0x0001 /*< create pipe and open it, fails if already exists */ + +typedef struct oslPipeImpl * oslPipe; + +/** Create or open a pipe. + + @param[in] strPipeName pipe name + @param[in] Options create or open the pipe + @param[in] Security pipe creator + + @returns nullptr on failure, otherwise returns the pipe handle + + @see osl_closePipe +*/ +SAL_DLLPUBLIC oslPipe SAL_CALL osl_createPipe( + rtl_uString *strPipeName, oslPipeOptions Options, oslSecurity Security); + +/** Decreases the refcount of the pipe. + + If the refcount drops to zero, the handle is destroyed. + + @param[in] Pipe pipe handle + + @see osl_acquirePipe + */ +SAL_DLLPUBLIC void SAL_CALL osl_releasePipe(oslPipe Pipe); + +/** Increases the refcount of the pipe. + + @param[in] Pipe pipe handle + + @see osl_releasePipe + */ +SAL_DLLPUBLIC void SAL_CALL osl_acquirePipe(oslPipe Pipe); + +/** Close the pipe. + + Any read, write or accept actions stop immediately. + + @param[in] Pipe pipe handle + + @see osl_createPipe + */ +SAL_DLLPUBLIC void SAL_CALL osl_closePipe(oslPipe Pipe); + + +SAL_DLLPUBLIC oslPipe SAL_CALL osl_acceptPipe(oslPipe Pipe); + +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_sendPipe(oslPipe Pipe, const void* pBuffer, sal_Int32 BufferSize); +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_receivePipe(oslPipe Pipe, void* pBuffer, sal_Int32 BufferSize); + +/** Reads blocking from the pipe. + @return Number of read bytes. If less than BufferSize, the pipe was closed. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_readPipe( oslPipe Pipe, void *pBuffer, sal_Int32 BufferSize ); + +/** Writes blocking onto the pipe. + @return Number of written bytes. If less than BufferSize, the pipe was closed. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_writePipe( oslPipe Pipe, const void *pBuffer, sal_Int32 BufferSize ); + +SAL_DLLPUBLIC oslPipeError SAL_CALL osl_getLastPipeError(oslPipe Pipe); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_PIPE_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/pipe.hxx b/include/osl/pipe.hxx new file mode 100644 index 000000000..cb9e2ec24 --- /dev/null +++ b/include/osl/pipe.hxx @@ -0,0 +1,224 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_OSL_PIPE_HXX +#define INCLUDED_OSL_PIPE_HXX + +#include "sal/config.h" + +#include + +#include "osl/pipe_decl.hxx" + +namespace osl +{ + + inline Pipe::Pipe() + : m_handle( NULL ) + {} + + + inline Pipe::Pipe(const ::rtl::OUString& strName, oslPipeOptions Options ) + : m_handle( osl_createPipe( strName.pData, Options , NULL ) ) + {} + + + inline Pipe::Pipe(const ::rtl::OUString& strName, oslPipeOptions Options,const Security & rSecurity) + : m_handle( osl_createPipe( strName.pData, Options , rSecurity.getHandle() ) ) + {} + + + inline Pipe::Pipe(const Pipe& pipe ) + : m_handle( pipe.m_handle ) + { + if( m_handle ) + osl_acquirePipe( m_handle ); + } + +#if defined LIBO_INTERNAL_ONLY + Pipe::Pipe(Pipe && other) noexcept : m_handle(other.m_handle) { + other.m_handle = nullptr; + } +#endif + + inline Pipe::Pipe( oslPipe pipe, __sal_NoAcquire ) + : m_handle ( pipe ) + {} + + + inline Pipe::Pipe(oslPipe pipe) + : m_handle( pipe ) + { + if( m_handle ) + osl_acquirePipe( m_handle ); + } + + + inline Pipe::~Pipe() + { + if( m_handle ) + osl_releasePipe( m_handle ); + } + + + inline bool Pipe::create( const ::rtl::OUString & strName, + oslPipeOptions Options, const Security &rSec ) + { + *this = Pipe( strName, Options, rSec ); + return is(); + } + + + inline bool Pipe::create( const ::rtl::OUString & strName, oslPipeOptions Options ) + { + *this = Pipe( strName, Options ); + return is(); + } + + inline Pipe& SAL_CALL Pipe::operator= (const Pipe& pipe) + { + *this = pipe.getHandle(); + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + Pipe & Pipe::operator =(Pipe && other) noexcept { + if (m_handle != nullptr) { + osl_releasePipe(m_handle); + } + m_handle = other.m_handle; + other.m_handle = nullptr; + return *this; + } +#endif + + inline Pipe & SAL_CALL Pipe::operator=( oslPipe pipe) + { + if( pipe ) + osl_acquirePipe( pipe ); + if( m_handle ) + osl_releasePipe( m_handle ); + m_handle = pipe; + return *this; + } + + + inline bool SAL_CALL Pipe::is() const + { + return m_handle != NULL; + } + + + inline bool SAL_CALL Pipe::operator==( const Pipe& rPipe ) const + { + return m_handle == rPipe.m_handle; + } + + + inline void SAL_CALL Pipe::close() + { + osl_closePipe( m_handle ); + } + + + inline void SAL_CALL Pipe::clear() + { + if( m_handle ) + { + osl_releasePipe( m_handle ); + m_handle = NULL; + } + } + + + inline oslPipeError SAL_CALL Pipe::accept(StreamPipe& Connection) + { + Connection = StreamPipe( osl_acceptPipe( m_handle ), SAL_NO_ACQUIRE); + if( Connection.is() ) + return osl_Pipe_E_None; + else + return getError(); + } + + + inline oslPipeError SAL_CALL Pipe::getError() const + { + return osl_getLastPipeError( NULL ); + } + + + inline oslPipe SAL_CALL Pipe::getHandle() const + { + return m_handle; + } + + + inline StreamPipe::StreamPipe(){} + + + inline StreamPipe::StreamPipe(oslPipe hPipe) + : Pipe( hPipe ) + { + } + + + inline StreamPipe::StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security &rSec ) + : Pipe( strName, Options , rSec ) + {} + + + inline StreamPipe::StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options ) + : Pipe( strName, Options ) + {} + + inline StreamPipe::StreamPipe( oslPipe pipe, __sal_NoAcquire noacquire ) + : Pipe( pipe , noacquire ) + {} + + + inline sal_Int32 SAL_CALL StreamPipe::read(void* pBuffer, sal_Int32 n) const + { + return osl_readPipe( m_handle, pBuffer, n ); + } + + + inline sal_Int32 SAL_CALL StreamPipe::write(const void* pBuffer, sal_Int32 n) const + { + return osl_writePipe( m_handle, pBuffer , n ); + } + + + inline sal_Int32 SAL_CALL StreamPipe::recv(void* pBuffer, sal_Int32 BytesToRead) const + { + return osl_receivePipe( m_handle, pBuffer , BytesToRead ); + } + + + inline sal_Int32 SAL_CALL StreamPipe::send(const void* pBuffer, sal_Int32 BytesToSend) const + { + return osl_sendPipe( m_handle, pBuffer , BytesToSend ); + } + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/pipe_decl.hxx b/include/osl/pipe_decl.hxx new file mode 100644 index 000000000..cad7538c7 --- /dev/null +++ b/include/osl/pipe_decl.hxx @@ -0,0 +1,242 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_OSL_PIPE_DECL_HXX +#define INCLUDED_OSL_PIPE_DECL_HXX + +#include "osl/pipe.h" +#include "osl/security.hxx" +#include "rtl/ustring.hxx" + +namespace osl +{ +class StreamPipe; + +/** Represents a pipe. +*/ +class Pipe +{ +protected: + oslPipe m_handle; + +public: + /** Does not create a pipe. Use assignment operator to + make this a usable pipe. + */ + inline Pipe(); + + /** Creates an insecure pipe that is accessible for all users. + @param strName + @param Options + */ + inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options); + + /** Creates a secure pipe that access depends on the umask settings. + @param strName + @param Options + @param rSecurity + */ + inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security& rSecurity); + + /** Copy constructor. + */ + inline Pipe(const Pipe& pipe); + +#if defined LIBO_INTERNAL_ONLY + inline Pipe(Pipe&& other) noexcept; +#endif + + /** Constructs a Pipe reference without acquiring the handle + */ + inline Pipe(oslPipe pipe, __sal_NoAcquire noacquire); + + /** Creates pipe as wrapper around the underlying oslPipe. + @param Pipe + */ + inline Pipe(oslPipe Pipe); + + /** Destructor. Destroys the underlying oslPipe. + */ + inline ~Pipe(); + + inline bool SAL_CALL is() const; + + /** Creates an insecure pipe that is accessible for all users + with the given attributes. + If the pipe was already created, the old one will be discarded. + @param strName + @param Options + @param rSec + @return True if socket was successfully created. + */ + inline bool create(const ::rtl::OUString& strName, oslPipeOptions Options, + const Security& rSec); + + /** Creates a secure that access rights depend on the umask settings + with the given attributes. + + If socket was already created, the old one will be discarded. + @param strName + @param Options + @return True if socket was successfully created. + */ + inline bool create(const ::rtl::OUString& strName, oslPipeOptions Options = osl_Pipe_OPEN); + + /** releases the underlying handle + */ + inline void SAL_CALL clear(); + + /** Assignment operator. If pipe was already created, the old one will + be discarded. + */ + inline Pipe& SAL_CALL operator=(const Pipe& pipe); + +#if defined LIBO_INTERNAL_ONLY + inline Pipe& operator=(Pipe&& other) noexcept; +#endif + + /** Assignment operator. If pipe was already created, the old one will + be discarded. + */ + inline Pipe& SAL_CALL operator=(const oslPipe pipe); + + /** Checks if the pipe is valid. + @return True if the object represents a valid pipe. + */ + inline bool SAL_CALL isValid() const; + + inline bool SAL_CALL operator==(const Pipe& rPipe) const; + + /** Closes the pipe. + */ + inline void SAL_CALL close(); + + /** Accept connection on an existing pipe + */ + inline oslPipeError SAL_CALL accept(StreamPipe& Connection); + + /** Delivers a constant describing the last error for the pipe system. + @return ENONE if no error occurred, invalid_PipeError if + an unknown (unmapped) error occurred, otherwise an enum describing the + error. + */ + inline oslPipeError SAL_CALL getError() const; + + inline oslPipe SAL_CALL getHandle() const; +}; + +/** A pipe to send or receive a stream of data. +*/ +class StreamPipe : public Pipe +{ +public: + /** Creates an unattached pipe. You must attach the pipe to an oslPipe + e.g. by using the operator=(oslPipe), before you can use the stream- + functionality of the object. + */ + inline StreamPipe(); + + /** Creates pipe as wrapper around the underlying oslPipe. + + @param Pipe + */ + inline StreamPipe(oslPipe Pipe); + + /** Creates a pipe. + + @param[in] strName Pipe name + @param[in] Options Pipe options + */ + inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options = osl_Pipe_OPEN); + + /** Creates a pipe. + + @param[in] strName Pipe name + @param[in] Options Pipe options + @param[in] rSec Security for the pipe + */ + inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security& rSec); + + /** Constructs a Pipe reference without acquiring the handle + */ + inline StreamPipe(oslPipe pipe, __sal_NoAcquire noacquire); + + /** Attaches the oslPipe to this object. If the object + already was attached to an oslPipe, the old one will + be closed and destroyed. + + @param[in] Pipe Pipe to attach to this object + */ + inline StreamPipe& SAL_CALL operator=(oslPipe Pipe); + + /** Assignment operator + */ + inline StreamPipe& SAL_CALL operator=(const Pipe& pipe); + + /** Tries to receives BytesToRead data from the connected pipe, + + @param[out] pBuffer Points to a buffer that will be filled with the received + data. + @param[in] BytesToRead The number of bytes to read. pBuffer must have at least + this size. + + @return the number of received bytes. + */ + inline sal_Int32 SAL_CALL recv(void* pBuffer, sal_Int32 BytesToRead) const; + + /** Tries to sends BytesToSend data from the connected pipe. + + @param[in] pBuffer Points to a buffer that contains the send-data. + @param[in] BytesToSend The number of bytes to send. pBuffer must have at least + this size. + + @return the number of transferred bytes. + */ + inline sal_Int32 SAL_CALL send(const void* pBuffer, sal_Int32 BytesToSend) const; + + /** Retrieves n bytes from the stream and copies them into pBuffer. + The method avoids incomplete reads due to packet boundaries. + + @param[in] pBuffer receives the read data. + @param[in] n the number of bytes to read. pBuffer must be large enough + to hold the n bytes! + + @return the number of read bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + inline sal_Int32 SAL_CALL read(void* pBuffer, sal_Int32 n) const; + + /** Writes n bytes from pBuffer to the stream. The method avoids + incomplete writes due to packet boundaries. + + @param[in] pBuffer contains the data to be written. + @param[in] n the number of bytes to write. + + @return the number of written bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + sal_Int32 SAL_CALL write(const void* pBuffer, sal_Int32 n) const; +}; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/process.h b/include/osl/process.h new file mode 100644 index 000000000..14b9c2028 --- /dev/null +++ b/include/osl/process.h @@ -0,0 +1,425 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_PROCESS_H +#define INCLUDED_OSL_PROCESS_H + +#include "sal/config.h" + +#include "osl/file.h" +#include "osl/security.h" +#include "osl/time.h" +#include "rtl/locale.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef sal_Int32 oslProcessOption; +#define osl_Process_WAIT 0x0001 /* wait for completion */ +#define osl_Process_SEARCHPATH 0x0002 /* search path for executable */ +#define osl_Process_DETACHED 0x0004 /* run detached */ +#define osl_Process_NORMAL 0x0000 /* run in normal window */ +#define osl_Process_HIDDEN 0x0010 /* run hidden */ +#define osl_Process_MINIMIZED 0x0020 /* run in minimized window */ +#define osl_Process_MAXIMIZED 0x0040 /* run in maximized window */ +#define osl_Process_FULLSCREEN 0x0080 /* run in fullscreen window */ + +typedef sal_Int32 oslProcessData; + +/* defines for osl_getProcessInfo , can be OR'ed */ +#define osl_Process_IDENTIFIER 0x0001 /* retrieves the process identifier */ +#define osl_Process_EXITCODE 0x0002 /* retrieves exit code of the process */ +#define osl_Process_CPUTIMES 0x0004 /* retrieves used cpu time */ +#define osl_Process_HEAPUSAGE 0x0008 /* retrieves the used size of heap */ + +typedef sal_uInt32 oslProcessIdentifier; +typedef sal_uInt32 oslProcessExitCode; + +typedef enum { + osl_Process_E_None, /* no error */ + osl_Process_E_NotFound, /* image not found */ + osl_Process_E_TimedOut, /* timeout occurred */ + osl_Process_E_NoPermission, /* permission denied */ + osl_Process_E_Unknown, /* unknown error */ + osl_Process_E_InvalidError, /* unmapped error */ + osl_Process_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslProcessError; + +#ifdef _WIN32 +# pragma pack(push, 8) +#endif + +typedef struct { + sal_uInt32 Size; + oslProcessData Fields; + oslProcessIdentifier Ident; + oslProcessExitCode Code; + TimeValue UserTime; + TimeValue SystemTime; + sal_uInt32 HeapUsage; +} oslProcessInfo; + +#if defined( _WIN32) +# pragma pack(pop) +#endif + +/** Process handle + + @see osl_executeProcess + @see osl_terminateProcess + @see osl_freeProcessHandle + @see osl_getProcessInfo + @see osl_joinProcess +*/ +typedef void* oslProcess; + +/** Execute a process. + + Executes the program image provided in strImageName in a new process. + + @param[in] ustrImageName + The file URL of the executable to be started. + Can be NULL in this case the file URL of the executable must be the first element + in ustrArguments. + + @param[in] ustrArguments + An array of argument strings. Can be NULL if strImageName is not NULL. + If strImageName is NULL it is expected that the first element contains + the file URL of the executable to start. + + @param[in] nArguments + The number of arguments provided. If this number is 0 strArguments will be ignored. + + @param[in] Options + A combination of int-constants to describe the mode of execution. + + @param[in] Security + The user and his rights for which the process is started. May be NULL in which case + the process will be started in the context of the current user. + + @param[in] ustrDirectory + The file URL of the working directory of the new process. If the specified directory + does not exist or is inaccessible the working directory of the newly created process + is undefined. If this parameter is NULL or the caller provides an empty string the + new process will have the same current working directory as the calling process. + + @param[in] ustrEnvironments + An array of strings describing environment variables that should be merged into the + environment of the new process. Each string has to be in the form "variable=value". + This parameter can be NULL in which case the new process gets the same environment + as the parent process. + + @param[in] nEnvironmentVars + The number of environment variables to set. + + @param[out] pProcess + Pointer to a oslProcess variable, which receives the handle of the newly created process. + This parameter must not be NULL. + + @retval osl_Process_E_None on success + @retval osl_Process_E_NotFound if the specified executable could not be found + @retval osl_Process_E_InvalidError if invalid parameters will be detected + @retval osl_Process_E_Unknown if arbitrary other errors occur + + @see oslProcessOption + @see osl_executeProcess_WithRedirectedIO + @see osl_freeProcessHandle + @see osl_loginUser +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_executeProcess( + rtl_uString* ustrImageName, + rtl_uString* ustrArguments[], + sal_uInt32 nArguments, + oslProcessOption Options, + oslSecurity Security, + rtl_uString* ustrDirectory, + rtl_uString* ustrEnvironments[], + sal_uInt32 nEnvironmentVars, + oslProcess* pProcess); + + +/** Execute a process and redirect child process standard IO. + + @param[in] strImageName + The file URL of the executable to be started. + Can be NULL in this case the file URL of the executable must be the first element + in ustrArguments. + + @param[in] ustrArguments + An array of argument strings. Can be NULL if strImageName is not NULL. + If strImageName is NULL it is expected that the first element contains + the file URL of the executable to start. + + @param[in] nArguments + The number of arguments provided. If this number is 0 strArguments will be ignored. + + @param[in] Options + A combination of int-constants to describe the mode of execution. + + @param[in] Security + The user and his rights for which the process is started. May be NULL in which case + the process will be started in the context of the current user. + + @param[in] ustrDirectory + The file URL of the working directory of the new process. If the specified directory + does not exist or is inaccessible the working directory of the newly created process + is undefined. If this parameter is NULL or the caller provides an empty string the + new process will have the same current working directory as the calling process. + + @param[in] ustrEnvironments + An array of strings describing environment variables that should be merged into the + environment of the new process. Each string has to be in the form "variable=value". + This parameter can be NULL in which case the new process gets the same environment + as the parent process. + + @param[in] nEnvironmentVars + The number of environment variables to set. + + @param[out] pProcess + Pointer to a oslProcess variable, which receives the handle of the newly created process. + This parameter must not be NULL. + + @param[out] pChildInputWrite + Pointer to a oslFileHandle variable that receives the handle which can be used to write + to the child process standard input device. The returned handle is not random accessible. + The handle has to be closed with osl_closeFile if no longer used. This parameter can be NULL. + + @param[out] pChildOutputRead + Pointer to a oslFileHandle variable that receives the handle which can be used to read from + the child process standard output device. The returned handle is not random accessible. + The Handle has to be closed with osl_closeFile if no longer used. This parameter can be NULL. + + @param[out] pChildErrorRead + Pointer to a oslFileHandle variable that receives the handle which can be used to read from + the child process standard error device. The returned handle is not random accessible. + The Handle has to be closed with osl_closeFile if no longer used. This parameter can be NULL. + + @retval osl_Process_E_None on success + @retval osl_Process_E_NotFound if the specified executable could not be found + @retval osl_Process_E_InvalidError if invalid parameters will be detected + @retval osl_Process_E_Unknown if arbitrary other errors occur + + @see oslProcessOption + @see osl_executeProcess + @see osl_freeProcessHandle + @see osl_loginUser + @see osl_closeFile +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_executeProcess_WithRedirectedIO( + rtl_uString* strImageName, + rtl_uString* ustrArguments[], + sal_uInt32 nArguments, + oslProcessOption Options, + oslSecurity Security, + rtl_uString* ustrDirectory, + rtl_uString* ustrEnvironments[], + sal_uInt32 nEnvironmentVars, + oslProcess* pProcess, + oslFileHandle* pChildInputWrite, + oslFileHandle* pChildOutputRead, + oslFileHandle* pChildErrorRead); + +/** Terminate a process + + @param[in] Process the handle of the process to be terminated + + @see osl_executeProcess + @see osl_getProcess + @see osl_joinProcess + */ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_terminateProcess( + oslProcess Process); + + +/** @deprecated + + Retrieve the process handle of a process identifier + + @param[in] Ident a process identifier + + @return the process handle on success, NULL in all other cases + */ +SAL_DLLPUBLIC oslProcess SAL_CALL osl_getProcess( + oslProcessIdentifier Ident) SAL_COLD; + + +/** Free the specified process-handle. + + @param[in] Process +*/ +SAL_DLLPUBLIC void SAL_CALL osl_freeProcessHandle( + oslProcess Process); + + +/** Wait for completion of the specified childprocess. + @param[in] Process + + @retval ols_Process_E_None + + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_joinProcess( + oslProcess Process); + +/** Wait with a timeout for the completion of the specified child + process. + + @param[in] Process A process identifier. + @param[in] pTimeout A timeout value or NULL for infinite waiting. + The unit of resolution is second. + + @retval osl_Process_E_None on success + @retval osl_Process_E_TimedOut waiting for the child process timed out + @retval osl_Process_E_Unknown an error occurred or the parameter are invalid + + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_joinProcessWithTimeout( + oslProcess Process, const TimeValue* pTimeout); + +/** Retrieves information about a Process + @param[in] Process the process handle of the process + @param[in] Fields the information which is to be retrieved + this can be one or more of + osl_Process_IDENTIFIER + osl_Process_EXITCODE + osl_Process_CPUTIMES + osl_Process_HEAPUSAGE + @param[out] pInfo a pointer to a valid oslProcessInfo structure. + the Size field has to be initialized with the size + of the oslProcessInfo structure. + on success the Field member holds the (or'ed) + retrieved valid information fields. + @retval osl_Process_E_None on success + @retval osl_Process_E_Unknown on failure + */ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getProcessInfo( + oslProcess Process, oslProcessData Fields, oslProcessInfo* pInfo); + +/** Get the filename of the executable. + @param[out] strFile the string that receives the executable file path. + @return osl_Process_E_None or does not return. + @see osl_executeProcess + + Ideally this will return the true executable file path as a file: + URL, but actually in case something else happens to have been + passed as argv[0] to osl_setCommandArgs(), it will return that + either as a file URL, or as such in case it doesn't look like an + absolute pathname. +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getExecutableFile( + rtl_uString **strFile); + +/** @return the number of commandline arguments passed to the main-function of + this process + @see osl_getCommandArg +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getCommandArgCount(void); + +/** Get the nArg-th command-line argument passed to the main-function of this process. + @param[in] nArg The number of the argument to return. + @param[out] strCommandArg The string receives the nArg-th command-line argument. + @return osl_Process_E_None or does not return. + @see osl_executeProcess +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getCommandArg( + sal_uInt32 nArg, rtl_uString **strCommandArg); + +/** Set the command-line arguments as passed to the main-function of this process. + + Deprecated: This function is only for internal use. Passing the args from main will + only work for Unix, on Windows there's no effect, the full command line will automatically + be taken. This is due to Windows 9x/ME limitation that don't allow UTF-16 wmain to provide + a osl_setCommandArgsU( int argc, sal_Unicode **argv ); + + @param[in] argc The number of elements in the argv array. + @param[in] argv The array of command-line arguments. + @see osl_getExecutableFile + @see osl_getCommandArgCount + @see osl_getCommandArg +*/ +SAL_DLLPUBLIC void SAL_CALL osl_setCommandArgs (int argc, char **argv); + +/** Get the value of one environment variable. + @param[in] strVar denotes the name of the variable to get. + @param[out] strValue string that receives the value of environment variable. +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getEnvironment( + rtl_uString *strVar, rtl_uString **strValue); + +/** Set the value of one environment variable. + @param[in] strVar denotes the name of the variable to set. + @param[in] strValue string of the new value of environment variable. + + @since UDK 3.2.13 +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_setEnvironment( + rtl_uString *strVar, rtl_uString *strValue); + +/** Unsets the value of one environment variable. + @param[in] strVar denotes the name of the variable to unset. + + @since UDK 3.2.13 +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_clearEnvironment( + rtl_uString *strVar); + +/** Get the working directory of the current process as a file URL. + + The file URL is encoded as common for the OSL file API. + @param[out] pustrWorkingDir string that receives the working directory file URL. +*/ + +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getProcessWorkingDir( + rtl_uString **pustrWorkingDir ); + +/** Get the locale the process is currently running in. + + @param[out] ppLocale a pointer that receives the currently selected locale structure +*/ + +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_getProcessLocale( + rtl_Locale ** ppLocale ); + +/** Change the locale of the process. + + @param[in] pLocale a pointer to the locale to be set + + @deprecated LibreOffice itself does not use this, and client code should + not have good use for it either. It may eventually be removed. +*/ + +SAL_DLLPUBLIC oslProcessError SAL_CALL osl_setProcessLocale( + rtl_Locale * pLocale ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_PROCESS_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/profile.h b/include/osl/profile.h new file mode 100644 index 000000000..082f0e0a0 --- /dev/null +++ b/include/osl/profile.h @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_PROFILE_H +#define INCLUDED_OSL_PROFILE_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef sal_uInt32 oslProfileOption; + +#define osl_Profile_DEFAULT 0x0000 +#define osl_Profile_SYSTEM 0x0001 /* use system depended functionality */ +#define osl_Profile_READLOCK 0x0002 /* lock file for reading */ +#define osl_Profile_WRITELOCK 0x0004 /* lock file for writing */ +#define osl_Profile_FLUSHWRITE 0x0010 /* writing only with flush */ + + +typedef void* oslProfile; + +/** Deprecated API. + Open or create a configuration profile. + @retval 0 if the profile could not be created, otherwise a handle to the profile. + @deprecated +*/ +SAL_DLLPUBLIC oslProfile SAL_CALL osl_openProfile( + rtl_uString *strProfileName, oslProfileOption Options) SAL_COLD; + +/** Deprecated API. + Close the opened profile an flush all data to the disk. + @param Profile handle to an opened profile. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_closeProfile( + oslProfile Profile) SAL_COLD; + +/** Deprecated API. + @deprecated +*/ + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_flushProfile( + oslProfile Profile) SAL_COLD; +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_readProfileString( + oslProfile Profile, + const char* pszSection, const char* pszEntry, + char* pszString, sal_uInt32 MaxLen, + const char* pszDefault) SAL_COLD; +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_readProfileBool( + oslProfile Profile, + const char* pszSection, const char* pszEntry, + sal_Bool Default) SAL_COLD; +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_readProfileIdent( + oslProfile Profile, + const char* pszSection, const char* pszEntry, + sal_uInt32 FirstId, const char* Strings[], + sal_uInt32 Default) SAL_COLD; + +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_writeProfileString( + oslProfile Profile, + const char* pszSection, const char* pszEntry, + const char* pszString) SAL_COLD; + +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_writeProfileBool( + oslProfile Profile, + const char* pszSection, const char* pszEntry, + sal_Bool Value) SAL_COLD; + +/** Deprecated API. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_writeProfileIdent( + oslProfile Profile, + const char* pszSection, const char* pszEntry, + sal_uInt32 FirstId, const char* Strings[], + sal_uInt32 Value) SAL_COLD; + +/** Deprecated API. + Acquire the mutex, block if already acquired by another thread. + @retval False if section or entry could not be found. + @deprecated +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_removeProfileEntry( + oslProfile Profile, + const char *pszSection, const char *pszEntry) SAL_COLD; + +/** Deprecated API. + Get all entries belonging to the specified section. + @returns Pointer to an array of pointers. + @deprecated +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getProfileSectionEntries( + oslProfile Profile, const char *pszSection, + char* pszBuffer, sal_uInt32 MaxLen) SAL_COLD; + +/** Deprecated API. + Get all section entries + @retval Pointer to an array of pointers. + @deprecated +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getProfileSections( + oslProfile Profile, char* pszBuffer, sal_uInt32 MaxLen) SAL_COLD; + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_PROFILE_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/profile.hxx b/include/osl/profile.hxx new file mode 100644 index 000000000..ec75e3ce3 --- /dev/null +++ b/include/osl/profile.hxx @@ -0,0 +1,212 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_PROFILE_HXX +#define INCLUDED_OSL_PROFILE_HXX + +#include "osl/profile.h" +#include "rtl/ustring.hxx" + +#include +#include +#include + +namespace osl { + + typedef oslProfileOption ProfileOption; + + const int Profile_DEFAULT = osl_Profile_DEFAULT; + const int Profile_SYSTEM = osl_Profile_SYSTEM; /* use system depended functionality */ + const int Profile_READLOCK = osl_Profile_READLOCK; /* lock file for reading */ + const int Profile_WRITELOCK = osl_Profile_WRITELOCK; /* lock file for writing */ + + /** Deprecated API. + @deprecated + */ + class Profile { + oslProfile profile; + + public: + /** Open or create a configuration profile. + @retval 0 if the profile could not be created, otherwise a handle to the profile. + */ + Profile(const rtl::OUString & strProfileName, oslProfileOption Options = Profile_DEFAULT ) + { + profile = osl_openProfile(strProfileName.pData, Options); + if( ! profile ) + throw std::exception(); + } + + + /** Close the opened profile an flush all data to the disk. + */ + ~Profile() + { + osl_closeProfile(profile); + } + + + bool flush() + { + return osl_flushProfile(profile); + } + + rtl::OString readString( const rtl::OString& rSection, const rtl::OString& rEntry, + const rtl::OString& rDefault) + { + char aBuf[1024]; + return osl_readProfileString( profile, + rSection.getStr(), + rEntry.getStr(), + aBuf, + sizeof( aBuf ), + rDefault.getStr() ) ? rtl::OString( aBuf ) : rtl::OString(); + + } + + bool readBool( const rtl::OString& rSection, const rtl::OString& rEntry, bool bDefault ) + { + return osl_readProfileBool( profile, rSection.getStr(), rEntry.getStr(), bDefault ); + } + + sal_uInt32 readIdent(const rtl::OString& rSection, const rtl::OString& rEntry, + sal_uInt32 nFirstId, const std::list< rtl::OString >& rStrings, + sal_uInt32 nDefault) + { + size_t nItems = rStrings.size(); + const char** pStrings = new const char*[ nItems+1 ]; + std::list< rtl::OString >::const_iterator it = rStrings.begin(); + nItems = 0; + while( it != rStrings.end() ) + { + pStrings[ nItems++ ] = it->getStr(); + ++it; + } + pStrings[ nItems ] = NULL; + sal_uInt32 nRet = osl_readProfileIdent(profile, rSection.getStr(), rEntry.getStr(), nFirstId, pStrings, nDefault); + delete[] pStrings; + return nRet; + } + + bool writeString(const rtl::OString& rSection, const rtl::OString& rEntry, + const rtl::OString& rString) + { + return osl_writeProfileString(profile, rSection.getStr(), rEntry.getStr(), rString.getStr()); + } + + bool writeBool(const rtl::OString& rSection, const rtl::OString& rEntry, bool Value) + { + return osl_writeProfileBool(profile, rSection.getStr(), rEntry.getStr(), Value); + } + + bool writeIdent(const rtl::OString& rSection, const rtl::OString& rEntry, + sal_uInt32 nFirstId, const std::list< rtl::OString >& rStrings, + sal_uInt32 nValue) + { + size_t nItems = rStrings.size(); + const char** pStrings = new const char*[ nItems+1 ]; + std::list< rtl::OString >::const_iterator it = rStrings.begin(); + nItems = 0; + while( it != rStrings.end() ) + { + pStrings[ nItems++ ] = it->getStr(); + ++it; + } + pStrings[ nItems ] = NULL; + bool bRet = + osl_writeProfileIdent(profile, rSection.getStr(), rEntry.getStr(), nFirstId, pStrings, nValue ); + delete[] pStrings; + return bRet; + } + + /** Remove an entry from a section. + @param rSection Name of the section. + @param rEntry Name of the entry to remove. + @retval False if section or entry could not be found. + */ + bool removeEntry(const rtl::OString& rSection, const rtl::OString& rEntry) + { + return osl_removeProfileEntry(profile, rSection.getStr(), rEntry.getStr()); + } + + /** Get all entries belonging to the specified section. + @param rSection Name of the section. + @return Pointer to an array of pointers. + */ + std::list< rtl::OString > getSectionEntries(const rtl::OString& rSection ) + { + std::list< rtl::OString > aEntries; + + // count buffer size necessary + size_t n = osl_getProfileSectionEntries( profile, rSection.getStr(), NULL, 0 ); + if( n > 1 ) + { + char* pBuf = new char[ n+1 ]; + osl_getProfileSectionEntries( profile, rSection.getStr(), pBuf, n+1 ); + size_t nLen; + for( n = 0; ; n += nLen+1 ) + { + nLen = strlen( pBuf+n ); + if (!nLen) + break; + aEntries.push_back( rtl::OString( pBuf+n ) ); + } + delete[] pBuf; + } + + return aEntries; + } + + /** Get all section entries + @return Pointer to an array of pointers. + */ + std::list< rtl::OString > getSections() + { + std::list< rtl::OString > aSections; + + // count buffer size necessary + size_t n = osl_getProfileSections( profile, NULL, 0 ); + if( n > 1 ) + { + char* pBuf = new char[ n+1 ]; + osl_getProfileSections( profile, pBuf, n+1 ); + size_t nLen; + for( n = 0; ; n += nLen+1 ) + { + nLen = strlen( pBuf+n ); + if (!nLen) + break; + aSections.push_back( rtl::OString( pBuf+n ) ); + } + delete[] pBuf; + } + + return aSections; + } + }; +} + +#endif // INCLUDED_OSL_PROFILE_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/security.h b/include/osl/security.h new file mode 100644 index 000000000..56674027e --- /dev/null +++ b/include/osl/security.h @@ -0,0 +1,177 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SECURITY_H +#define INCLUDED_OSL_SECURITY_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + osl_Security_E_None, + osl_Security_E_UserUnknown, + osl_Security_E_WrongPassword, + osl_Security_E_Unknown, + osl_Security_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSecurityError; + +/** Process handle + @see osl_loginUser + @see osl_freeSecurityHandle + @see osl_executeProcess +*/ +typedef void* oslSecurity; + +/** Create a security handle for the current user. + @return a security handle or NULL on failure. + @see osl_freeSecurityHandle + @see osl_executeProcess + @see osl_executeApplication +*/ +SAL_DLLPUBLIC oslSecurity SAL_CALL osl_getCurrentSecurity(void); + +/** Deprecated API + Create a security handle for the denoted user. + Try to log in the user on the local system. + @param[in] strUserName denotes the name of the user to log in. + @param[in] strPasswd the password for this user. + @param[out] pSecurity returns the security handle if user could be logged in. + @return osl_Security_E_None if user could be logged in, otherwise an error-code. + @see osl_freeSecurityHandle + @see osl_executeProcess + @see osl_executeApplication +*/ +SAL_DLLPUBLIC oslSecurityError SAL_CALL osl_loginUser( + rtl_uString *strUserName, + rtl_uString *strPasswd, + oslSecurity *pSecurity + ); + +/** Create a security handle for the denoted user. + Try to log in the user on the denoted file server. On success the homedir will be + the mapped drive on this server. + @param[in] strUserName denotes the name of the user to log in. + @param[in] strPasswd the password for this user. + @param[in] strFileServer denotes the file server on which the user is logged in. + @param[out] pSecurity returns the security handle if user could be logged in. + @return osl_Security_E_None if user could be logged in, otherwise an error-code. + @see osl_freeSecurityHandle + @see osl_executeProcess + @see osl_executeApplication +*/ +SAL_DLLPUBLIC oslSecurityError SAL_CALL osl_loginUserOnFileServer( + rtl_uString *strUserName, + rtl_uString *strPasswd, + rtl_uString *strFileServer, + oslSecurity *pSecurity + ); + +/** Query if the user who is denotes by this security has administrator rights. + @param[in] Security the security handle for th user. + @return True, if the user has administrator rights, otherwise false. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isAdministrator( + oslSecurity Security); + +/** Free the security handle, created by osl_loginUser or osl_getCurrentSecurity. + @param[in] Security the security handle. + @see osl_loginUser +*/ +SAL_DLLPUBLIC void SAL_CALL osl_freeSecurityHandle( + oslSecurity Security); + +/** Get the login ident for the user of this security handle. + @param[in] Security the security handle. + @param[out] strIdent the string that receives the ident on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getUserIdent( + oslSecurity Security, rtl_uString **strIdent); + +/** Get the login name for the user of this security handle. + @param[in] Security the security handle. + @param[out] strName the string that receives the user name on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getUserName( + oslSecurity Security, rtl_uString **strName); + +/** Get the login name for the user of this security handle, + excluding the domain name on Windows. + @param[in] Security the security handle. + @param[out] strName the string that receives the user name on success. + @return True, if the security handle is valid, otherwise False. + @since LibreOffice 5.2 +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getShortUserName( + oslSecurity Security, rtl_uString **strName); + +/** Get the home directory of the user of this security handle. + @param[in] Security the security handle. + @param[out] strDirectory the string that receives the directory path on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getHomeDir( + oslSecurity Security, rtl_uString **strDirectory); + +/** Get the directory for configuration data of the user of this security handle. + @param[in] Security the security handle. + @param[out] strDirectory the string that receives the directory path on success. + @return True, if the security handle is valid, otherwise False. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getConfigDir( + oslSecurity Security, rtl_uString **strDirectory); + + +/** Load Profile of the User + Implemented just for Windows + @param[in] Security previously fetch Security of the User + @return True if the Profile could successfully loaded, False otherwise. +*/ + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_loadUserProfile( + oslSecurity Security); + + +/** Unload a User Profile + Implemented just for Windows + @param[in] Security previously fetch Security of the User + @return nothing is returned! +*/ + +SAL_DLLPUBLIC void SAL_CALL osl_unloadUserProfile( + oslSecurity Security); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_SECURITY_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/security.hxx b/include/osl/security.hxx new file mode 100644 index 000000000..6c928ea5d --- /dev/null +++ b/include/osl/security.hxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SECURITY_HXX +#define INCLUDED_OSL_SECURITY_HXX + +#include "sal/config.h" + +#include + +#include "rtl/ustring.hxx" +#include "osl/security_decl.hxx" + +namespace osl +{ + +inline Security::Security() +{ + m_handle = osl_getCurrentSecurity(); +} + +inline Security::~Security() +{ + osl_freeSecurityHandle(m_handle); +} + +inline bool Security::logonUser(const rtl::OUString& strName, + const rtl::OUString& strPasswd) +{ + osl_freeSecurityHandle(m_handle); + + m_handle = NULL; + + return (osl_loginUser( strName.pData, strPasswd.pData, &m_handle) + == osl_Security_E_None); +} + +inline bool Security::logonUser( const rtl::OUString& strName, + const rtl::OUString& strPasswd, + const rtl::OUString& strFileServer ) +{ + osl_freeSecurityHandle(m_handle); + + m_handle = NULL; + + return (osl_loginUserOnFileServer(strName.pData, strPasswd.pData, strFileServer.pData, &m_handle) + == osl_Security_E_None); +} + +inline bool Security::getUserIdent( rtl::OUString& strIdent) const +{ + return osl_getUserIdent( m_handle, &strIdent.pData ); +} + + +inline bool Security::getUserName( rtl::OUString& strName, bool bIncludeDomain ) const +{ + if (bIncludeDomain) + return osl_getUserName( m_handle, &strName.pData ); + return osl_getShortUserName( m_handle, &strName.pData ); +} + + +inline bool Security::getHomeDir( rtl::OUString& strDirectory) const +{ + return osl_getHomeDir(m_handle, &strDirectory.pData ); +} + + +inline bool Security::getConfigDir( rtl::OUString& strDirectory ) const +{ + return osl_getConfigDir( m_handle, &strDirectory.pData ); +} + +inline bool Security::isAdministrator() const +{ + return osl_isAdministrator(m_handle); +} + +inline oslSecurity Security::getHandle() const +{ + return m_handle; +} + + +} + +#endif // INCLUDED_OSL_SECURITY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/security_decl.hxx b/include/osl/security_decl.hxx new file mode 100644 index 000000000..464872b22 --- /dev/null +++ b/include/osl/security_decl.hxx @@ -0,0 +1,133 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SECURITY_DECL_HXX +#define INCLUDED_OSL_SECURITY_DECL_HXX + +#include "rtl/ustring.hxx" +#include "osl/security.h" + +namespace osl +{ + +/** Encapsulate security information for one user. + A object of this class is used to execute a process with the rights an + security options of a specified user. + @see Process::executeProcess +*/ +class Security +{ +protected: + oslSecurity m_handle; + +public: + inline Security(); + inline ~Security(); + + /** get the security information for one user. + The underlying operating system is asked for this information. + + @param[in] strName denotes the name of the user + @param[in] strPasswd denotes the password of this user + + @retval True, if the specified user is known by the underlying operating system + @retval False unknown user + */ + inline bool SAL_CALL logonUser(const rtl::OUString& strName, + const rtl::OUString& strPasswd); + + /** get the security information for one user. + + @verbatim + This method will try to login the user at the denoted file server. + If a network resource named \\server\username exists and this resource + could be connected by this user, the method will return true and getHomeDir + will return \\server\username. + @endverbatim + + @param[in] strName denotes the name of the user + @param[in] strPasswd denotes the password of this user + @param[in] strFileServer denotes the file server to login to + + @retval True if the specified user is known by the file server and they + could be connected + @retval False if the user is not known by the file server + */ + inline bool SAL_CALL logonUser(const rtl::OUString & strName, + const rtl::OUString & strPasswd, + const rtl::OUString & strFileServer); + + /** get the ident of the logged in user. + + @param[out] strIdent is the OUString which returns the name + + @retval True if any user is successfully logged in + @retval False no user logged in + */ + inline bool SAL_CALL getUserIdent( rtl::OUString& strIdent) const; + + /** get the name of the logged in user. + + @param[out] strName is the OUString which returns the name + @param[in] bIncludeDomain Include the Domain name (like "ORG\username"). Affects Windows only. + This parameter is available since LibreOffice 5.2. + + @retval True if any user is successfully logged in + @retval False if no user is logged in + */ + inline bool SAL_CALL getUserName( rtl::OUString& strName, bool bIncludeDomain=true ) const; + + /** get the home directory of the logged in user. + @param[out] strDirectory is the OUString which returns the directory name + + @retval True if any user is successfully logged in + @retval False if user is not logged in + */ + inline bool SAL_CALL getHomeDir( rtl::OUString& strDirectory) const; + + /** get the directory for configuration data of the logged in user. + + @param[out] strDirectory is the OUString which returns the directory name + + @retval True if any user is successfully logged in + @retval False if user is not logged in + */ + inline bool SAL_CALL getConfigDir( rtl::OUString & strDirectory) const; + + /** Query if the user who is logged in has administrator rights. + + @retval True if the user has administrator rights + @retval False if the user does not have admin rights + */ + inline bool SAL_CALL isAdministrator() const; + + /** Returns the underlying oslSecurity handle + */ + inline oslSecurity getHandle() const; +}; + +} + +#endif // INCLUDED_OSL_SECURITY_DECL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/signal.h b/include/osl/signal.h new file mode 100644 index 000000000..66eb9db5e --- /dev/null +++ b/include/osl/signal.h @@ -0,0 +1,112 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SIGNAL_H +#define INCLUDED_OSL_SIGNAL_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define OSL_SIGNAL_USER_RESERVED 0 + +#define OSL_SIGNAL_USER_X11SUBSYSTEMERROR (OSL_SIGNAL_USER_RESERVED - 2) + +typedef void* oslSignalHandler; + +typedef enum +{ + osl_Signal_System, + osl_Signal_Terminate, + osl_Signal_AccessViolation, + osl_Signal_IntegerDivideByZero, + osl_Signal_FloatDivideByZero, + osl_Signal_DebugBreak, + osl_Signal_User, + osl_Signal_Alarm, + osl_Signal_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSignal; + +typedef enum +{ + osl_Signal_ActCallNextHdl, + osl_Signal_ActIgnore, + osl_Signal_ActAbortApp, + osl_Signal_ActKillApp, + osl_Signal_Act_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSignalAction; + +#ifdef _WIN32 +# pragma pack(push, 8) +#endif + +typedef struct +{ + oslSignal Signal; + sal_Int32 UserSignal; + void* UserData; +} oslSignalInfo; + +#if defined( _WIN32) +# pragma pack(pop) +#endif + +/** The function-ptr representing the signal handler-function. +*/ +typedef oslSignalAction (SAL_CALL *oslSignalHandlerFunction)(void* pData, oslSignalInfo* pInfo); + +SAL_DLLPUBLIC oslSignalHandler SAL_CALL osl_addSignalHandler( + oslSignalHandlerFunction Handler, void* pData); + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_removeSignalHandler( + oslSignalHandler hHandler); + +SAL_DLLPUBLIC oslSignalAction SAL_CALL osl_raiseSignal( + sal_Int32 UserSignal, void* UserData); + +/** Enables or disables error reporting + + On default error reporting is enabled after process startup. + + @param[in] bEnable Enables or disables error reporting. + + @retval sal_True if previous state of error reporting was enabled + @retval sal_False if previous state of error reporting was disabled +*/ + +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setErrorReporting( + sal_Bool bEnable ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_SIGNAL_H + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/socket.h b/include/osl/socket.h new file mode 100644 index 000000000..7f87da312 --- /dev/null +++ b/include/osl/socket.h @@ -0,0 +1,862 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SOCKET_H +#define INCLUDED_OSL_SOCKET_H + +#include "rtl/ustring.h" +#include "osl/time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* error returns */ +#define OSL_INADDR_NONE 0xffffffff +#define OSL_INVALID_PORT (-1) + +/**@{ begin section types +*/ + +/** + Opaque datatype SocketAddr. +*/ +typedef struct oslSocketAddrImpl * oslSocketAddr; + +/** + Represents the address-family of a socket +*/ +typedef enum { + osl_Socket_FamilyInet, /*!< IP (AF_INET) */ + osl_Socket_FamilyIpx, /*!< Novell IPX/SPX (AF_IPX) */ + osl_Socket_FamilyInvalid, /*!< always last entry in enum! */ + osl_Socket_Family_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslAddrFamily; + +/** + represent a specific protocol within an address-family +*/ +typedef enum { + osl_Socket_ProtocolIp, /*!< for all af_inet */ + osl_Socket_ProtocolIpx, /*!< af_ipx datagram sockets (IPX) */ + osl_Socket_ProtocolSpx, /*!< af_ipx seqpacket or stream for SPX */ + osl_Socket_ProtocolSpxII, /*!< af_ipx seqpacket or stream for SPX II */ + osl_Socket_ProtocolInvalid, /*!< always last entry in enum */ + osl_Socket_Protocol_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslProtocol; + +/** + Represents the type of a socket +*/ +typedef enum { + osl_Socket_TypeStream, /*!< stream socket */ + osl_Socket_TypeDgram, /*!< datagram socket */ + osl_Socket_TypeRaw, /*!< raw socket */ + osl_Socket_TypeRdm, /*!< connectionless, message-oriented, + reliably delivered message (RDM) + sockets */ + osl_Socket_TypeSeqPacket, /*!< connection-oriented and reliable + two-way transport of ordered byte + streams */ + osl_Socket_TypeInvalid, /*!< always last entry in enum */ + osl_Socket_Type_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketType; + + +/** + Represents socket-options +*/ +typedef enum { + osl_Socket_OptionDebug, /*!< record debugging info */ + osl_Socket_OptionAcceptConn, /*!< listen for connection */ + osl_Socket_OptionReuseAddr, /*!< bind to address already in use */ + osl_Socket_OptionKeepAlive, /*!< use keep-alive */ + osl_Socket_OptionDontRoute, /*!< do not route packet, send direct to + interface addresses */ + osl_Socket_OptionBroadcast, /*!< send broadcast message */ + osl_Socket_OptionUseLoopback, /*!< socket receives copy of everything + sent on the socket */ + osl_Socket_OptionLinger, /*!< don't immediately close - "linger" + a while to allow for graceful + connection closure */ + osl_Socket_OptionOOBinLine, /*!< out-of-band (OOB) data placed in + normal input queue (i.e. OOB inline) */ + osl_Socket_OptionSndBuf, /*!< send buffer */ + osl_Socket_OptionRcvBuf, /*!< receive buffer */ + osl_Socket_OptionSndLowat, /*!< send "low-water" mark - amount of + available space in send buffer for + select() to return "writable" */ + osl_Socket_OptionRcvLowat, /*!< receive "low-water" mark - amount of + available space in receive buffer + for select() to receive "readable" */ + osl_Socket_OptionSndTimeo, /*!< send timeout */ + osl_Socket_OptionRcvTimeo, /*!< receive timeout */ + osl_Socket_OptionError, /*!< socket error */ + osl_Socket_OptionType, /*!< returns socket type (e.g. datagram, + stream). */ + osl_Socket_OptionTcpNoDelay, /*!< disable TCP Nagle algorithm */ + osl_Socket_OptionInvalid, /*!< always last entry in enum */ + osl_Socket_Option_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketOption; + +/** + Represents the different socket-option levels +*/ +typedef enum { + osl_Socket_LevelSocket, + osl_Socket_LevelTcp, + osl_Socket_LevelInvalid, /*!< always last entry in enum */ + osl_Socket_Level_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketOptionLevel; + +/** + Represents flags to be used with send/recv-calls. +*/ +typedef enum { + osl_Socket_MsgNormal, + osl_Socket_MsgOOB, + osl_Socket_MsgPeek, + osl_Socket_MsgDontRoute, + osl_Socket_MsgMaxIOVLen, + osl_Socket_MsgInvalid, /*!< always last entry in enum */ + osl_Socket_Msg_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketMsgFlag; + +/** + Used by shutdown to denote which end of the socket to "close". +*/ +typedef enum { + osl_Socket_DirRead, + osl_Socket_DirWrite, + osl_Socket_DirReadWrite, + osl_Socket_DirInvalid, /*!< always last entry in enum */ + osl_Socket_Dir_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketDirection; + +/** Describes the various error socket error conditions, which may + occur */ +typedef enum { + osl_Socket_E_None, /*!< no error */ + osl_Socket_E_NotSocket, /*!< Socket operation on non-socket */ + osl_Socket_E_DestAddrReq, /*!< Destination address required */ + osl_Socket_E_MsgSize, /*!< Message too long */ + osl_Socket_E_Prototype, /*!< Protocol wrong type for socket */ + osl_Socket_E_NoProtocol, /*!< Protocol not available */ + osl_Socket_E_ProtocolNoSupport, /*!< Protocol not supported */ + osl_Socket_E_TypeNoSupport, /*!< Socket type not supported */ + osl_Socket_E_OpNotSupport, /*!< Operation not supported on socket */ + osl_Socket_E_PfNoSupport, /*!< Protocol family not supported */ + osl_Socket_E_AfNoSupport, /*!< Address family not supported by */ + /*!< protocol family */ + osl_Socket_E_AddrInUse, /*!< Address already in use */ + osl_Socket_E_AddrNotAvail, /*!< Can't assign requested address */ + osl_Socket_E_NetDown, /*!< Network is down */ + osl_Socket_E_NetUnreachable, /*!< Network is unreachable */ + osl_Socket_E_NetReset, /*!< Network dropped connection because + of reset */ + osl_Socket_E_ConnAborted, /*!< Software caused connection abort */ + osl_Socket_E_ConnReset, /*!< Connection reset by peer */ + osl_Socket_E_NoBufferSpace, /*!< No buffer space available */ + osl_Socket_E_IsConnected, /*!< Socket is already connected */ + osl_Socket_E_NotConnected, /*!< Socket is not connected */ + osl_Socket_E_Shutdown, /*!< Can't send after socket shutdown */ + osl_Socket_E_TooManyRefs, /*!< Too many references: can't splice */ + osl_Socket_E_TimedOut, /*!< Connection timed out */ + osl_Socket_E_ConnRefused, /*!< Connection refused */ + osl_Socket_E_HostDown, /*!< Host is down */ + osl_Socket_E_HostUnreachable, /*!< No route to host */ + osl_Socket_E_WouldBlock, /*!< call would block on non-blocking socket */ + osl_Socket_E_Already, /*!< operation already in progress */ + osl_Socket_E_InProgress, /*!< operation now in progress */ + osl_Socket_E_InvalidError, /*!< unmapped error: always last entry in enum */ + osl_Socket_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketError; + +/** Common return codes of socket related functions. + */ +typedef enum { + osl_Socket_Ok, /*!< successful completion */ + osl_Socket_Error, /*!< error occurred, check + osl_getLastSocketError() for details */ + osl_Socket_TimedOut, /*!< blocking operation timed out */ + osl_Socket_Interrupted, /*!< blocking operation was interrupted */ + osl_Socket_InProgress, /*!< nonblocking operation is in progress */ + osl_Socket_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslSocketResult; + +typedef sal_uInt8 oslSocketIpxNetNumber[4]; +typedef sal_uInt8 oslSocketIpxNodeNumber[6]; + +/**@} end section types +*/ + +/**@{ begin section oslSocket +*/ + +typedef struct oslSocketImpl * oslSocket; + +/** Create a socket of the specified Family and Type. The semantic of + the Protocol parameter depends on the given family and type. + + @returns 0 if socket could not be created, otherwise you get a handle + to the allocated socket-datastructure. +*/ +SAL_DLLPUBLIC oslSocket SAL_CALL osl_createSocket( + oslAddrFamily Family, + oslSocketType Type, + oslProtocol Protocol); + +/** increases the refcount of the socket handle by one + */ +SAL_DLLPUBLIC void SAL_CALL osl_acquireSocket(oslSocket Socket); + +/** decreases the refcount of the socket handle by one. + + If the refcount drops to zero, the underlying socket handle + is destroyed and becomes invalid. + */ +SAL_DLLPUBLIC void SAL_CALL osl_releaseSocket(oslSocket Socket); + +/** Retrieves the Address of the local end of the socket. + Note that a socket must be bound or connected before + a valid address can be returned. + + @returns 0 if socket-address could not be created, otherwise you get + the created Socket-Address. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_getLocalAddrOfSocket(oslSocket Socket); + +/** Retrieves the Address of the remote end of the socket. + Note that a socket must be connected before + a valid address can be returned. + @retval 0 if socket-address could not be created, otherwise you get + the created Socket-Address. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_getPeerAddrOfSocket(oslSocket Socket); + +/** Binds the given address to the socket. + @param[in] Socket + @param[in] Addr + @retval sal_False if the bind failed + @retval sal_True if bind is successful + @see osl_getLastSocketError() +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_bindAddrToSocket( + oslSocket Socket, + oslSocketAddr Addr); + +/** Connects the socket to the given address. + + @param[in] Socket a bound socket. + @param[in] Addr the peer address. + @param pTimeout Timeout value or NULL for blocking. + + @retval osl_Socket_Ok on successful connection, + @retval osl_Socket_TimedOut if operation timed out, + @retval osl_Socket_Interrupted if operation was interrupted + @retval osl_Socket_Error if the connection failed. +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_connectSocketTo( + oslSocket Socket, + oslSocketAddr Addr, + const TimeValue* pTimeout); + + +/** Prepares the socket to act as an acceptor of incoming connections. + You should call "listen" before you use "accept". + @param[in] Socket The socket to listen on. + @param[in] MaxPendingConnections denotes the length of the queue of + pending connections for this socket. If MaxPendingConnections is + -1, the systems default value will be used (Usually 5). + @retval sal_False if the listen failed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_listenOnSocket( + oslSocket Socket, + sal_Int32 MaxPendingConnections); + + +/** Waits for an ingoing connection on the socket. + This call blocks if there is no incoming connection present. + @param[in] Socket The socket to accept the connection on. + @param[in] pAddr if pAddr is != 0, the peers address is returned. + @retval 0 if the accept-call failed, otherwise you get a socket + representing the new connection. +*/ +SAL_DLLPUBLIC oslSocket SAL_CALL osl_acceptConnectionOnSocket( + oslSocket Socket, + oslSocketAddr* pAddr); + +/** Tries to receive BytesToRead data from the connected socket, + if no error occurs. Note that incomplete recvs due to + packet boundaries may occur. + + @param[in] Socket A connected socket to be used to listen on. + @param[out] pBuffer Points to a buffer that will be filled with the received + data. + @param[in] BytesToRead The number of bytes to read. pBuffer must have at least + this size. + @param[in] Flag Modifier for the call. Valid values are: + osl_Socket_MsgNormal + osl_Socket_MsgOOB + osl_Socket_MsgPeek + osl_Socket_MsgDontRoute + osl_Socket_MsgMaxIOVLen + + @return the number of received bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_receiveSocket( + oslSocket Socket, + void* pBuffer, + sal_uInt32 BytesToRead, + oslSocketMsgFlag Flag); + +/** Tries to receives BufferSize data from the (usually unconnected) + (datagram-)socket, if no error occurs. + + @param[in] Socket A bound socket to be used to listen for a datagram. + @param[out] SenderAddr A pointer to a created oslSocketAddr handle + or to a null handle. After the call, it will contain the constructed + oslSocketAddr of the datagrams sender. If pSenderAddr itself is 0, + it is ignored. + @param[out] pBuffer Points to a buffer that will be filled with the received + datagram. + @param[in] BufferSize The size of pBuffer. + @param[in] Flag Modifier for the call. Valid values are: + osl_Socket_MsgNormal + osl_Socket_MsgOOB + osl_Socket_MsgPeek + osl_Socket_MsgDontRoute + osl_Socket_MsgMaxIOVLen + + @return the number of received bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_receiveFromSocket( + oslSocket Socket, + oslSocketAddr SenderAddr, + void* pBuffer, + sal_uInt32 BufferSize, + oslSocketMsgFlag Flag); + +/** Tries to send BytesToSend data from the connected socket, + if no error occurs. + + @param[in] Socket A connected socket. + @param[in] pBuffer Points to a buffer that contains the send-data. + @param[in] BytesToSend The number of bytes to send. pBuffer must have at least + this size. + @param[in] Flag Modifier for the call. Valid values are: + @li osl_Socket_MsgNormal + @li osl_Socket_MsgOOB + @li osl_Socket_MsgPeek + @li osl_Socket_MsgDontRoute + @li osl_Socket_MsgMaxIOVLen + + @return the number of transferred bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_sendSocket( + oslSocket Socket, + const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag Flag); + +/** Tries to send one datagram with BytesToSend data to the given ReceiverAddr + via the (implicitly unconnected) datagram-socket. + Since there is only sent one packet, the function sends the data always complete + even with incomplete packet boundaries. + + @param[in] Socket A bound or unbound socket. Socket will be bound + after a successful call. + + @param[in] ReceiverAddr An initialized oslSocketAddress that contains + the destination address for this send. + + @param[in] pBuffer Points to a buffer that contains the send-data. + @param[in] BytesToSend The number of bytes to send. pBuffer must have at least + this size. + @param[in] Flag + @parblock + Modifier for the call. Valid values are: + @li osl_Socket_MsgNormal + @li osl_Socket_MsgOOB + @li osl_Socket_MsgPeek + @li osl_Socket_MsgDontRoute + @li osl_Socket_MsgMaxIOVLen + @endparblock + + @return the number of transferred bytes. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_sendToSocket( + oslSocket Socket, + oslSocketAddr ReceiverAddr, + const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag Flag); + +/** Checks if read operations will block. + + You can specify a timeout-value in seconds/microseconds that denotes + how long the operation will block if the Socket is not ready. + + @param Socket the Socket to perform the operation on. + @param pTimeout if NULL, the operation will block without a timeout. + + @retval sal_True if read operations (recv, recvFrom, accept) on the Socket + will NOT block; + @retval sal_False if it would block or if an error occurred. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isReceiveReady( + oslSocket Socket, + const TimeValue* pTimeout); + +/** Checks if send operations will block. + You can specify a timeout-value in seconds/microseconds that denotes + how long the operation will block if the Socket is not ready. + + @param Socket the Socket to perform the operation on. + @param pTimeout if NULL, the operation will block without a timeout. Otherwise + the time define by timeout value. + + @retval sal_True if send operations (send, sendTo) on the Socket + will NOT block + @retval sal_False if it would block or if an error occurred. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isSendReady( + oslSocket Socket, + const TimeValue* pTimeout); + +/** Checks if a request for out-of-band data will block. + You can specify a timeout-value in seconds/microseconds that denotes + how long the operation will block if the Socket has no pending OOB data. + + @param Socket the Socket to perform the operation on. + @param pTimeout if NULL, the operation will block without a timeout. + + @retval sal_True if OOB-request operations (recv with appropriate flags) + on the Socket will NOT block + @retval sal_False if it would block or if an error occurred. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isExceptionPending( + oslSocket Socket, + const TimeValue* pTimeout); + +/** Shuts down communication on a connected socket. + @param[in] Socket the Socket to perform the operation on. + @param[in] Direction + @parblock + Direction denotes which end of the socket should be closed: + @li osl_Socket_DirRead - closes read operations. + @li osl_Socket_DirReadWrite - closes write operations. + @li osl_Socket_DirWrite - closes read and write operations. + @endparblock + + @retval sal_True if the socket could be closed down. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_shutdownSocket( + oslSocket Socket, + oslSocketDirection Direction); + +/** Retrieves attributes associated with the socket. + + @param Socket is the socket to query. + @param Level + @parblock + Selects the level for which an option should be queried. + Valid values are: + @li osl_sol_socket - Socket Level + @li osl_sol_tcp - Level of Transmission Control Protocol + @endparblock + + @param Option + @parblock + Denotes the option to query. Valid values (depending on the Level) are: + @li osl_Socket_Option_Debug - (sal_Bool) Socket debug flag 1 = enabled, 0 = disabled. + @li osl_Socket_OptionAcceptConn + @li osl_Socket_OptionReuseAddr - (sal_Bool) Allows the socket to be bound to an address that is + already in use. 1 = multiple bound allowed, 0 = no multiple bounds allowed + @li osl_Socket_OptionKeepAlive (sal_Bool) Keepalive packets are sent by the underlying socket. + 1 = enabled, 0 = disabled + @li osl_Socket_OptionDontRoute - (sal_Bool) Do not route: send directly to interface. + 1 = do not route , 0 = routing possible + @li osl_Socket_OptionBroadcast - (sal_Bool) Transmission of broadcast messages are allowed on the socket. + 1 = transmission allowed, 0 = transmission disallowed + @li osl_Socket_OptionUseLoopback + @li osl_Socket_OptionLinger (sal_Int32) Linger on close if unsent data is present. + 0 = linger is off, > 0 = timeout in seconds. + @li osl_Socket_OptionOOBinLine + @li osl_Socket_OptionSndBuf (sal_Int32) Size of the send buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing to the socket. + @li osl_Socket_OptionRcvBuf (sal_Int32) Size of the receive buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing to the socket and larger packet sizes. + @li osl_Socket_OptionSndLowat + @li osl_Socket_OptionRcvLowat + @li osl_Socket_OptionSndTimeo (sal_Int32) Data is sent after this timeout. This allows gathering + of data to send larger packages but increases latency times. + @li osl_Socket_OptionRcvTimeo + @li osl_Socket_OptionError + @li osl_Socket_OptionType + @li osl_Socket_OptionTcpNoDelay Disables the Nagle algorithm for send coalescing. (Do not + collect data until a packet is full, instead send immediately. This increases network traffic + but might improve latency-times.) + 1 = disables the algorithm, 0 = keeps it enabled. + + If not above mentioned otherwise, the options are only valid for level osl_Socket_LevelSocket. + @endparblock + @param pBuffer Pointer to a buffer large enough to take the desired attribute-value. + @param BufferLen contains the length of the Buffer. + + @return -1 if an error occurred or else the size of the data copied into pBuffer. + + @see osl_setSocketOption() +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_getSocketOption( + oslSocket Socket, + oslSocketOptionLevel Level, + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen); + +/** Sets the sockets attributes. + + @param Socket is the socket to modify. + @param Level + @parblock + selects the level for which an option should be changed. + Valid values are: + @li osl_sol_socket - Socket Level + @li osl_sol_tcp - Level of Transmission Control Protocol + @endparblock + @param Option denotes the option to modify. See osl_setSocketOption() for more + details. + @param pBuffer Pointer to a Buffer which contains the attribute-value. + @param BufferLen contains the length of the Buffer. + + @retval True if the option could be changed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setSocketOption( + oslSocket Socket, + oslSocketOptionLevel Level, + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen); + +/** Enables/disables non-blocking-mode of the socket. + + @param Socket Change mode for this socket. + @param On sal_True enables non-blocking mode, sal_False disables non-blocking mode. + + @retval sal_True if mode could be changed. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_enableNonBlockingMode( + oslSocket Socket, + sal_Bool On); + + +/** Query state of non-blocking-mode of the socket. + + @param Socket Query mode for this socket. + + @retval True if non-blocking-mode is enabled. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isNonBlockingMode(oslSocket Socket); + +/** Queries the socket for its type. + + @param[in] Socket The socket to query. + + @retval osl_Socket_TypeStream + @retval osl_Socket_TypeDgram + @retval osl_Socket_TypeRaw + @retval osl_Socket_TypeRdm + @retval osl_Socket_TypeSeqPacket + @retval osl_invalid_SocketType if an error occurred +*/ +SAL_DLLPUBLIC oslSocketType SAL_CALL osl_getSocketType(oslSocket Socket); + +/** returns a string which describes the last socket error. + + @param[in] Socket The socket to query. + @param[out] strError The string that receives the error message. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_getLastSocketErrorDescription( + oslSocket Socket, + rtl_uString **strError); + +/** Returns a constant describing the last error for the socket system. + + @retval osl_Socket_E_NONE if no error occurred + @retval osl_invalid_SocketError if an unknown (unmapped) + error occurred, otherwise an enum describing the error. +*/ +SAL_DLLPUBLIC oslSocketError SAL_CALL osl_getLastSocketError( + oslSocket Socket); + +/** Closes the socket terminating any ongoing dataflow. + + @param[in] Socket The socket to close. + */ +SAL_DLLPUBLIC void SAL_CALL osl_closeSocket(oslSocket Socket); + + +/** Retrieves n bytes from the stream and copies them into pBuffer. + The function avoids incomplete reads due to packet boundaries. + + @param[in] Socket The socket to read from. + @param[out] pBuffer receives the read data. + @param[out] nSize the number of bytes to read. pBuffer must be large enough + to hold the n bytes! + + @return the number of read bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_readSocket( + oslSocket Socket, + void *pBuffer, + sal_Int32 nSize); + + +/** Writes n bytes from pBuffer to the stream. The method avoids + incomplete writes due to packet boundaries. + + @param[out] Socket The socket to write to. + @param[in] pBuffer contains the data to be written. + @param[in] nSize the number of bytes to write. + + @return the number of written bytes. The number will only be smaller than + nSize if an exceptional condition (e.g. connection closed) occurs. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_writeSocket( + oslSocket Socket, + const void *pBuffer, + sal_Int32 nSize); + +/**@} end section oslSocket +*/ +/**@{ begin section oslSocketAddr +*/ + +/** Creates a socket-address for the given family. + @param Family If family == osl_Socket_FamilyInet the address is + set to INADDR_ANY port 0. + @return 0 if address could not be created. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_createEmptySocketAddr( + oslAddrFamily Family); + + +/** Creates a new SocketAddress and fills it from Addr. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_copySocketAddr( + oslSocketAddr Addr); + +/** Compares the values of two SocketAddresses. + @retval sal_True if both addresses denote the same socket address. + @retval sal_False if both addresses do not denote the same socket address. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isEqualSocketAddr( + oslSocketAddr Addr1, oslSocketAddr Addr2); + +/** Uses the systems name-service interface to find an address for strHostname. + @param[in] strHostname The name for which you search for an address. + @return The desired address if one could be found, otherwise 0. + Don't forget to destroy the address if you don't need it any longer. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_resolveHostname( + rtl_uString *strHostname); + +/** Create an internet address usable for sending broadcast datagrams. + To limit the broadcast to your subnet, pass your hosts IP address + in dotted decimal notation as first argument. + @see osl_sendToSocket() + @see oslSocketAddr + @param[in] strDottedAddr dotted decimal internet address, may be 0. + @param[in] Port port number in host byte order. + @retval 0 if address could not be created. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_createInetBroadcastAddr( + rtl_uString *strDottedAddr, sal_Int32 Port); + + +/** Create an internet-address, consisting of host address and port. + We interpret strDottedAddr as a dotted-decimal inet-addr + (e.g. "141.99.128.50"). + @param[in] strDottedAddr String with dotted address. + @param[in] Port portnumber in host byte order. + @retval 0 if address could not be created. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_createInetSocketAddr ( + rtl_uString *strDottedAddr, sal_Int32 Port); + + +/** Frees all resources allocated by Addr. The handle Addr must not + be used after the call anymore. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroySocketAddr( + oslSocketAddr Addr); + +/** Looks up the port-number designated to the specified service/protocol-pair. + (e.g. "ftp" "tcp"). + @retval OSL_INVALID_PORT if no appropriate entry was found, otherwise the port-number. +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_getServicePort( + rtl_uString *strServicename, rtl_uString *strProtocol); + + + +/** Retrieves the address-family from the Addr. + @return the family of the socket-address. + In case of an unknown family you get osl_Socket_FamilyInvalid. +*/ +SAL_DLLPUBLIC oslAddrFamily SAL_CALL osl_getFamilyOfSocketAddr( + oslSocketAddr Addr); + + +/** Retrieves the internet port-number of Addr. + @return the port-number of the address in host-byte order. If Addr + is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL osl_getInetPortOfSocketAddr( + oslSocketAddr Addr); + + +/** Sets the Port of Addr. + @param[in] Addr the SocketAddr to perform the operation on. + @param[in] Port is expected in host byte-order. + @retval sal_False if Addr is not an inet-addr. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setInetPortOfSocketAddr( + oslSocketAddr Addr, sal_Int32 Port); + + +/** Returns the hostname represented by Addr. + @param[in] Addr The socket address from which to extract the hostname. + @param[out] strHostname The hostname represented by the address. If + there is no hostname to be found, it returns 0. +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getHostnameOfSocketAddr( + oslSocketAddr Addr, rtl_uString **strHostname); + + +/** Gets the address in dotted decimal format. + + @param[in] Addr The socket address from which to extract the dotted decimal address. + @param[out] strDottedInetAddr Contains the dotted decimal address + (e.g. 141.99.20.34) represented by the address. + + @retval If the address is invalid or not of type osl_Socket_FamilyInet, it returns 0. + @retval osl_Socket_Ok + @retval osl_Socket_Error +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getDottedInetAddrOfSocketAddr( + oslSocketAddr Addr, rtl_uString **strDottedInetAddr); + +/** Sets the addr field in the struct sockaddr with pByteSeq. pByteSeq must be in network byte order. + */ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_setAddrOfSocketAddr( + oslSocketAddr Addr, sal_Sequence *pByteSeq ); + +/** Returns the addr field in the struct sockaddr. + @param[in] Addr The socket address from which to extract the ipaddress. + @param[out] ppByteSeq After the call, *ppByteSeq contains the ipaddress + in network byte order. *ppByteSeq may be 0 in case of an invalid socket handle. + @retval osl_Socket_Ok + @retval osl_Socket_Error + */ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getAddrOfSocketAddr( + oslSocketAddr Addr, sal_Sequence **ppByteSeq ); + +/* + Opaque datatype HostAddr. +*/ +typedef struct oslHostAddrImpl * oslHostAddr; + + +/** Create an oslHostAddr from given hostname and socket address. + @param[in] strHostname The hostname to be stored. + @param[in] Addr The socket address to be stored. + @return The created address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_createHostAddr( + rtl_uString *strHostname, const oslSocketAddr Addr); + + +/** Create an oslHostAddr by resolving the given strHostname. + Successful name resolution should result in the fully qualified + domain name (FQDN) and its address as hostname and socket address + members of the resulting oslHostAddr. + @param[in] strHostname The hostname to be resolved. + @return The resulting address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_createHostAddrByName(rtl_uString *strHostname); + + +/** Create an oslHostAddr by reverse resolution of the given Addr. + Successful name resolution should result in the fully qualified + domain name (FQDN) and its address as hostname and socket address + members of the resulting oslHostAddr. + @param[in] Addr The socket address to be reverse resolved. + @return The resulting address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_createHostAddrByAddr(const oslSocketAddr Addr); + + +/** Create a copy of the given Addr. + @return The copied address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslHostAddr SAL_CALL osl_copyHostAddr(const oslHostAddr Addr); + + +/** Frees all resources allocated by Addr. The handle Addr must not + be used after the call anymore. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyHostAddr(oslHostAddr Addr); + + +/** Get the hostname member of Addr. + @return The hostname or 0 upon failure. +*/ +SAL_DLLPUBLIC void SAL_CALL osl_getHostnameOfHostAddr(const oslHostAddr Addr, rtl_uString **strHostname); + + +/** Get the socket address member of Addr. + @return The socket address or 0 upon failure. +*/ +SAL_DLLPUBLIC oslSocketAddr SAL_CALL osl_getSocketAddrOfHostAddr(const oslHostAddr Addr); + +/** Retrieve this machines hostname (NOT the FQDN) + @param strLocalHostname out-parameter. The string that receives the local host name. + @retval sal_True upon success + @retval sal_False +*/ +SAL_DLLPUBLIC oslSocketResult SAL_CALL osl_getLocalHostname(rtl_uString **strLocalHostname); + + +/**@} end section oslHostAddr +*/ + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_SOCKET_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/socket.hxx b/include/osl/socket.hxx new file mode 100644 index 000000000..78d410e99 --- /dev/null +++ b/include/osl/socket.hxx @@ -0,0 +1,571 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SOCKET_HXX +#define INCLUDED_OSL_SOCKET_HXX + +#include "osl/socket_decl.hxx" + +namespace osl +{ + + inline SocketAddr::SocketAddr() + : m_handle( osl_createEmptySocketAddr( osl_Socket_FamilyInet ) ) + {} + + + inline SocketAddr::SocketAddr(const SocketAddr& Addr) + : m_handle( osl_copySocketAddr( Addr.m_handle ) ) + { + } + +#if defined LIBO_INTERNAL_ONLY + SocketAddr::SocketAddr(SocketAddr && other) noexcept : m_handle(other.m_handle) { + other.m_handle = nullptr; + } +#endif + + inline SocketAddr::SocketAddr(oslSocketAddr Addr) + : m_handle( osl_copySocketAddr( Addr ) ) + { + } + + + inline SocketAddr::SocketAddr(oslSocketAddr Addr, __osl_socket_NoCopy ) + : m_handle( Addr ) + { + } + + + inline SocketAddr::SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort) + : m_handle( osl_createInetSocketAddr( strAddrOrHostName.pData, nPort ) ) + { + if(! m_handle ) + { + m_handle = osl_resolveHostname(strAddrOrHostName.pData); + + // host found? + if(m_handle) + { + osl_setInetPortOfSocketAddr(m_handle, nPort); + } + else + { + osl_destroySocketAddr( m_handle ); + m_handle = NULL; + } + } + } + + + inline SocketAddr::~SocketAddr() + { + if( m_handle ) + osl_destroySocketAddr( m_handle ); + } + + + inline ::rtl::OUString SocketAddr::getHostname( oslSocketResult *pResult ) const + { + ::rtl::OUString hostname; + oslSocketResult result = osl_getHostnameOfSocketAddr( m_handle, &(hostname.pData) ); + if( pResult ) + *pResult = result; + return hostname; + } + + + inline sal_Int32 SAL_CALL SocketAddr::getPort() const + { + return osl_getInetPortOfSocketAddr(m_handle); + } + + + inline bool SAL_CALL SocketAddr::setPort( sal_Int32 nPort ) + { + return osl_setInetPortOfSocketAddr(m_handle, nPort ); + } + + inline bool SAL_CALL SocketAddr::setHostname( const ::rtl::OUString &sDottedIpOrHostname ) + { + *this = SocketAddr( sDottedIpOrHostname , getPort() ); + return is(); + } + + + inline bool SAL_CALL SocketAddr::setAddr( const ::rtl::ByteSequence & address ) + { + return osl_setAddrOfSocketAddr( m_handle, address.getHandle() ) + == osl_Socket_Ok; + } + + inline ::rtl::ByteSequence SAL_CALL SocketAddr::getAddr( oslSocketResult *pResult ) const + { + ::rtl::ByteSequence sequence; + oslSocketResult result = osl_getAddrOfSocketAddr( m_handle, reinterpret_cast(&sequence) ); + if( pResult ) + *pResult = result; + return sequence; + } + + + inline SocketAddr & SAL_CALL SocketAddr::operator= (oslSocketAddr Addr) + { + oslSocketAddr pNewAddr = osl_copySocketAddr( Addr ); + if( m_handle ) + osl_destroySocketAddr( m_handle ); + m_handle = pNewAddr; + return *this; + } + + + inline SocketAddr & SAL_CALL SocketAddr::operator= (const SocketAddr& Addr) + { + *this = Addr.getHandle(); + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + SocketAddr & SocketAddr::operator =(SocketAddr && other) noexcept { + if (m_handle != nullptr) { + osl_destroySocketAddr(m_handle); + } + m_handle = other.m_handle; + other.m_handle = nullptr; + return *this; + } +#endif + + inline SocketAddr & SAL_CALL SocketAddr::assign( oslSocketAddr Addr, __osl_socket_NoCopy ) + { + if( m_handle ) + osl_destroySocketAddr( m_handle ); + m_handle = Addr; + return *this; + } + + + inline bool SAL_CALL SocketAddr::operator== (oslSocketAddr Addr) const + { + return osl_isEqualSocketAddr( m_handle, Addr ); + } + + inline oslSocketAddr SocketAddr::getHandle() const + { + return m_handle; + } + + + inline bool SocketAddr::is() const + { + return m_handle != NULL; + } + + inline ::rtl::OUString SAL_CALL SocketAddr::getLocalHostname( oslSocketResult *pResult ) + { + ::rtl::OUString hostname; + oslSocketResult result = osl_getLocalHostname( &(hostname.pData) ); + if(pResult ) + *pResult = result; + return hostname; + } + + inline void SAL_CALL SocketAddr::resolveHostname( + const ::rtl::OUString & strHostName, SocketAddr &Addr) + { + Addr = SocketAddr( osl_resolveHostname( strHostName.pData ) , SAL_NO_COPY ); + } + + inline sal_Int32 SAL_CALL SocketAddr::getServicePort( + const ::rtl::OUString& strServiceName, + const ::rtl::OUString & strProtocolName ) + { + return osl_getServicePort( strServiceName.pData, strProtocolName.pData ); + } + + + inline Socket::Socket(oslSocketType Type, + oslAddrFamily Family, + oslProtocol Protocol) + : m_handle( osl_createSocket(Family, Type, Protocol) ) + {} + + + inline Socket::Socket( oslSocket socketHandle, __sal_NoAcquire ) + : m_handle( socketHandle ) + {} + + + inline Socket::Socket( oslSocket socketHandle ) + : m_handle( socketHandle ) + { + osl_acquireSocket( m_handle ); + } + + + inline Socket::Socket( const Socket & socket ) + : m_handle( socket.getHandle() ) + { + osl_acquireSocket( m_handle ); + } + + + inline Socket::~Socket() + { + osl_releaseSocket( m_handle ); + } + + + inline Socket& Socket::operator= ( oslSocket socketHandle) + { + osl_acquireSocket( socketHandle ); + osl_releaseSocket( m_handle ); + m_handle = socketHandle; + return *this; + } + + + inline Socket& Socket::operator= (const Socket& sock) + { + *this = sock.getHandle(); + return *this; + } + + + inline bool Socket::operator==( const Socket& rSocket ) const + { + return m_handle == rSocket.getHandle(); + } + + + inline bool Socket::operator==( const oslSocket socketHandle ) const + { + return m_handle == socketHandle; + } + + + inline void Socket::shutdown( oslSocketDirection Direction ) + { + osl_shutdownSocket( m_handle , Direction ); + } + + + inline void Socket::close() + { + osl_closeSocket( m_handle ); + } + + + inline void Socket::getLocalAddr( SocketAddr & addr) const + { + addr.assign( osl_getLocalAddrOfSocket( m_handle ) , SAL_NO_COPY ); + } + + + inline sal_Int32 Socket::getLocalPort() const + { + SocketAddr addr( NULL ); + getLocalAddr( addr ); + return addr.getPort(); + } + + + inline ::rtl::OUString Socket::getLocalHost() const + { + SocketAddr addr( NULL ); + getLocalAddr( addr ); + return addr.getHostname(); + } + + + inline void Socket::getPeerAddr( SocketAddr &addr ) const + { + addr.assign( osl_getPeerAddrOfSocket( m_handle ), SAL_NO_COPY ); + } + + + inline sal_Int32 Socket::getPeerPort() const + { + SocketAddr addr( NULL ); + getPeerAddr( addr ); + return addr.getPort(); + } + + + inline ::rtl::OUString Socket::getPeerHost() const + { + SocketAddr addr( NULL ); + getPeerAddr( addr ); + return addr.getHostname(); + } + + + inline bool Socket::bind(const SocketAddr& LocalInterface) + { + return osl_bindAddrToSocket( m_handle , LocalInterface.getHandle() ); + } + + + inline bool Socket::isRecvReady(const TimeValue *pTimeout ) const + { + return osl_isReceiveReady( m_handle , pTimeout ); + } + + + inline bool Socket::isSendReady(const TimeValue *pTimeout ) const + { + return osl_isSendReady( m_handle, pTimeout ); + } + + + inline bool Socket::isExceptionPending(const TimeValue *pTimeout ) const + { + return osl_isExceptionPending( m_handle, pTimeout ); + } + + + inline oslSocketType Socket::getType() const + { + return osl_getSocketType( m_handle ); + } + + + inline sal_Int32 Socket::getOption( + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level) const + { + return osl_getSocketOption( m_handle, Level, Option, pBuffer , BufferLen ); + } + + + inline bool Socket::setOption( oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level ) const + { + return osl_setSocketOption( m_handle, Level, Option , pBuffer, BufferLen ); + } + + + inline bool Socket::setOption( oslSocketOption option, sal_Int32 nValue ) + { + return setOption( option, &nValue, sizeof( nValue ) ); + } + + + inline sal_Int32 Socket::getOption( oslSocketOption option ) const + { + sal_Int32 n; + getOption( option, &n, sizeof( n ) ); + return n; + } + + + inline bool Socket::enableNonBlockingMode( bool bNonBlockingMode) + { + return osl_enableNonBlockingMode( m_handle , bNonBlockingMode ); + } + + + inline bool Socket::isNonBlockingMode() const + { + return osl_isNonBlockingMode( m_handle ); + } + + + inline void SAL_CALL Socket::clearError() const + { + sal_Int32 err = 0; + getOption(osl_Socket_OptionError, &err, sizeof(err)); + } + + + inline oslSocketError Socket::getError() const + { + return osl_getLastSocketError( m_handle ); + } + + + inline ::rtl::OUString Socket::getErrorAsString( ) const + { + ::rtl::OUString error; + osl_getLastSocketErrorDescription( m_handle, &(error.pData) ); + return error; + } + + + inline oslSocket Socket::getHandle() const + { + return m_handle; + } + + + inline StreamSocket::StreamSocket(oslAddrFamily Family, + oslProtocol Protocol, + oslSocketType Type ) + : Socket( Type, Family, Protocol ) + {} + + + inline StreamSocket::StreamSocket( oslSocket socketHandle, __sal_NoAcquire noacquire ) + : Socket( socketHandle, noacquire ) + {} + + + inline StreamSocket::StreamSocket( oslSocket socketHandle ) + : Socket( socketHandle ) + {} + + + inline sal_Int32 StreamSocket::read(void* pBuffer, sal_uInt32 n) + { + return osl_readSocket( m_handle, pBuffer, n ); + } + + + inline sal_Int32 StreamSocket::write(const void* pBuffer, sal_uInt32 n) + { + return osl_writeSocket( m_handle, pBuffer, n ); + } + + + inline sal_Int32 StreamSocket::recv(void* pBuffer, + sal_uInt32 BytesToRead, + oslSocketMsgFlag Flag) + { + return osl_receiveSocket( m_handle, pBuffer,BytesToRead, Flag ); + } + + + inline sal_Int32 StreamSocket::send(const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag Flag) + { + return osl_sendSocket( m_handle, pBuffer, BytesToSend, Flag ); + } + + + inline ConnectorSocket::ConnectorSocket(oslAddrFamily Family, + oslProtocol Protocol, + oslSocketType Type) + : StreamSocket( Family, Protocol ,Type ) + {} + + + inline oslSocketResult ConnectorSocket::connect( const SocketAddr& TargetHost, + const TimeValue* pTimeout ) + { + return osl_connectSocketTo( m_handle , TargetHost.getHandle(), pTimeout ); + } + + + inline AcceptorSocket::AcceptorSocket(oslAddrFamily Family , + oslProtocol Protocol , + oslSocketType Type ) + : Socket( Type, Family, Protocol ) + {} + + + inline bool AcceptorSocket::listen(sal_Int32 MaxPendingConnections) + { + return osl_listenOnSocket( m_handle, MaxPendingConnections ); + } + + + inline oslSocketResult AcceptorSocket::acceptConnection( StreamSocket& Connection) + { + oslSocket o = osl_acceptConnectionOnSocket( m_handle, NULL ); + oslSocketResult status = osl_Socket_Ok; + if( o ) + { + Connection = StreamSocket( o , SAL_NO_ACQUIRE ); + } + else + { + Connection = StreamSocket(); + status = osl_Socket_Error; + } + return status; + } + + + inline oslSocketResult AcceptorSocket::acceptConnection( + StreamSocket& Connection, SocketAddr & PeerAddr) + { + // TODO change in/OUT parameter + oslSocket o = osl_acceptConnectionOnSocket( + m_handle, reinterpret_cast(&PeerAddr)); + oslSocketResult status = osl_Socket_Ok; + if( o ) + { + Connection = StreamSocket( o , SAL_NO_ACQUIRE ); + } + else + { + Connection = StreamSocket(); + status = osl_Socket_Error; + } + return status; + } + + + inline DatagramSocket::DatagramSocket(oslAddrFamily Family, + oslProtocol Protocol, + oslSocketType Type) + : Socket( Type, Family, Protocol ) + {} + + + inline sal_Int32 DatagramSocket::recvFrom(void* pBuffer, + sal_uInt32 BufferSize, + SocketAddr* pSenderAddr, + oslSocketMsgFlag Flag ) + { + sal_Int32 nByteRead; + if( pSenderAddr ) + { + // TODO : correct the out-parameter pSenderAddr outparameter + nByteRead = osl_receiveFromSocket( m_handle, pSenderAddr->getHandle() , pBuffer, + BufferSize, Flag); + } + else + { + nByteRead = osl_receiveFromSocket( m_handle, NULL , pBuffer , BufferSize , Flag ); + } + return nByteRead; + } + + + inline sal_Int32 DatagramSocket::sendTo( const SocketAddr& ReceiverAddr, + const void* pBuffer, + sal_uInt32 BufferSize, + oslSocketMsgFlag Flag ) + { + return osl_sendToSocket( m_handle, ReceiverAddr.getHandle(), pBuffer, BufferSize, Flag ); + } +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/socket_decl.hxx b/include/osl/socket_decl.hxx new file mode 100644 index 000000000..de6442b27 --- /dev/null +++ b/include/osl/socket_decl.hxx @@ -0,0 +1,750 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_SOCKET_DECL_HXX +#define INCLUDED_OSL_SOCKET_DECL_HXX + +#include "sal/config.h" + +#include + +#include "osl/socket.h" +#include "rtl/ustring.hxx" +#include "rtl/byteseq.hxx" + +namespace osl +{ + enum __osl_socket_NoCopy { SAL_NO_COPY }; + + /** The class should be understood as a reference to a socket address handle (struct sockaddr). + + The handle is mutable. + */ + class SocketAddr + { + protected: + oslSocketAddr m_handle; + public: + + /** Creates socket address of unknown type. + */ + inline SocketAddr(); + + /** Copy constructor. + */ + inline SocketAddr(const SocketAddr& Addr); + +#if defined LIBO_INTERNAL_ONLY + inline SocketAddr(SocketAddr && other) noexcept; +#endif + + /** The SocketAddr takes over the responsibility of the handle (which means + that the handle gets destructed by the destructor of this reference) + + @param Addr a handle + @param nocopy use SAL_NO_COPY + */ + inline SocketAddr(const oslSocketAddr Addr, __osl_socket_NoCopy nocopy ); + + /** Copyconstructs the oslSocketAddr handle. + + @param Addr a handle + */ + inline SocketAddr(oslSocketAddr Addr); + + /** TCP/IP-specific constructor. + + @param strAddrOrHostName strAddrOrHostName hostname or dotted ip-number of the network + interface, the socket shall be created on. + @param nPort tcp-ip port number + */ + inline SocketAddr(const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort); + + /** destroys underlying oslSocketAddress + */ + inline ~SocketAddr(); + + /** Checks if the SocketAddr was created successful. + + @retval true if there is a valid underlying handle + @retval false no valid underlying handle + */ + inline bool is() const; + + /** Converts the address to a (human readable) domain-name. + + @param[out] pResult value of 0 if you are not interested in errors, + otherwise *pResult contains an error code on failure + or osl_Socket_Ok on success + + @return the hostname of this SocketAddr or an empty string on failure. + + @see osl_getHostnameOfSocketAddr + */ + inline ::rtl::OUString SAL_CALL getHostname(oslSocketResult *pResult = NULL) const; + + /** Sets the IP address or hostname of the SocketAddress + + @param[in] sDottedIpOrHostname IP address or hostname + + @retval true success + @retval false failure + */ + inline bool SAL_CALL setHostname(const ::rtl::OUString &sDottedIpOrHostname); + + /** Returns the port number of the address. + + @return the port in host-byte order or OSL_INVALID_PORT on errors. + */ + inline sal_Int32 SAL_CALL getPort() const; + + /** Sets the port number of the address. + + @param[in] nPort port number + + @retval true success + @retval false failure + */ + inline bool SAL_CALL setPort(sal_Int32 nPort); + + /** Sets the address of the underlying socket address struct in network byte order. + + @retval true success + @retval false failure + */ + inline bool SAL_CALL setAddr(const ::rtl::ByteSequence & address); + + /** Returns the address of the underlying socket in network byte order + */ + inline ::rtl::ByteSequence SAL_CALL getAddr(oslSocketResult *pResult = NULL) const; + + /** assign the handle to this reference. The previous handle is released. + */ + inline SocketAddr & SAL_CALL operator= (oslSocketAddr Addr); + + inline SocketAddr & SAL_CALL operator= (const SocketAddr& Addr); + +#if defined LIBO_INTERNAL_ONLY + inline SocketAddr & operator =(SocketAddr && other) noexcept; +#endif + + /** Assigns the socket addr without copyconstructing it. + @param Addr the socket address. + @param nocopy use SAL_NO_COPY + */ + inline SocketAddr & SAL_CALL assign( oslSocketAddr Addr, __osl_socket_NoCopy nocopy ); + + /** Returns true if the underlying handle is identical to the Addr handle. + */ + inline bool SAL_CALL operator== (oslSocketAddr Addr) const; + + /** Returns true if the underlying handle is identical to the Addr handle. + */ + inline bool SAL_CALL operator== (const SocketAddr & Addr) const; + + /** Returns the underlying SocketAddr handle without copyconstructing it. + */ + inline oslSocketAddr SAL_CALL getHandle() const; + + /** Get the hostname for the local interface. + @param pResult after the call *pResult contains osl_Socket_Ok on success or + an error on failure. + @return the hostname + */ + static inline ::rtl::OUString SAL_CALL getLocalHostname( oslSocketResult *pResult = NULL); + + /** Tries to find an address for a host. + @see osl_resolveHostname() + @return A new created socket-address or 0 if the name could not be found. + */ + static inline void SAL_CALL resolveHostname( + const ::rtl::OUString & strHostName , SocketAddr & Addr ); + + /** + Tries to find the port associated with the given service/protocol- + pair (e.g. "ftp"/"tcp"). + @return the port number in host-byte order or OSL_INVALID_PORT + if no service/protocol pair could be found. + */ + static inline sal_Int32 SAL_CALL getServicePort( + const ::rtl::OUString& strServiceName, + const ::rtl::OUString & strProtocolName= ::rtl::OUString("tcp") ); + }; + + + class Socket + { + protected: + oslSocket m_handle; + protected: + /** Creates a socket. Note it's protected. + @param Type + @param Family + @param Protocol + */ + inline Socket(oslSocketType Type, + oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp); + public: + inline Socket( ); + + inline Socket( const Socket & socket ); + + inline Socket( oslSocket socketHandle ); + + /** The instance takes over the handle's ownership without acquiring the + handle, but releases it within the dtor. + @param socketHandle the handle + @param noacquire use SAL_NO_ACQUIRE + */ + inline Socket( oslSocket socketHandle, __sal_NoAcquire noacquire ); + + /** Destructor. Releases the underlying handle + */ + inline ~Socket(); + + /** Assignment operator. If socket was already created, the old one will + be discarded. + */ + inline Socket& SAL_CALL operator= ( oslSocket socketHandle); + + /** Assignment operator. If socket was already created, the old one will + be discarded. + */ + inline Socket& SAL_CALL operator= (const Socket& sock); + + /** + @return true, when the underlying handle of both + Socket instances are identical, false otherwise. + */ + inline bool SAL_CALL operator==( const Socket& rSocket ) const ; + + /** + @return true, when the underlying handle of both + Socket instances are identical, false otherwise. + */ + inline bool SAL_CALL operator==( const oslSocket socketHandle ) const; + + /** Closes a definite or both directions of the bidirectional stream. + + @param Direction + @see osl_shutdownSocket() + */ + inline void SAL_CALL shutdown( oslSocketDirection Direction = osl_Socket_DirReadWrite ); + + /** Closes a socket. + Note that closing a socket is identical to shutdown( osl_Socket_DirReadWrite ), + as the operating system distinguish both cases, both functions or offered in this API. + @see osl_closeSocket() + */ + inline void SAL_CALL close(); + + /** Retrieves the address of the local interface of this socket. + @param Addr [out] receives the address. + @see osl_getLocalAddrOfSocket() + */ + inline void SAL_CALL getLocalAddr( SocketAddr &Addr ) const; + + /** Get the local port of the socket. Usually used after bind(). + @return the port number or OSL_INVALID_PORT on errors. + */ + inline sal_Int32 SAL_CALL getLocalPort() const; + + /** Get the hostname for the local interface. + @return the hostname or an empty string (""). + */ + inline ::rtl::OUString SAL_CALL getLocalHost() const; + + /** Retrieves the address of the remote host of this socket. + @param Addr [out] receives the address. + */ + inline void SAL_CALL getPeerAddr( SocketAddr & Addr) const; + + /** Get the remote port of the socket. + @return the port number or OSL_INVALID_PORT on errors. + */ + inline sal_Int32 SAL_CALL getPeerPort() const; + + /** Get the hostname for the remote interface. + @return the hostname or an empty string (""). + */ + inline ::rtl::OUString SAL_CALL getPeerHost() const; + + /** Binds the socket to the specified (local) interface. + @param LocalInterface Address of the Interface + @return True if bind was successful. + */ + inline bool SAL_CALL bind(const SocketAddr& LocalInterface); + + /** Checks if read operations will block. + + You can specify a timeout-value in seconds/nanoseconds that denotes + how the operation will block if the Socket is not ready. + @return true if read operations (recv, recvFrom, accept) on the Socket + will NOT block; false if it would block or if an error occurred. + + @param pTimeout if 0, the operation will block without a timeout. Otherwise + the specified amount of time. + */ + inline bool SAL_CALL isRecvReady(const TimeValue *pTimeout = NULL) const; + + /** Checks if send operations will block. + + You can specify a timeout-value in seconds/nanoseconds that denotes + how the operation will block if the Socket is not ready. + @return true if send operations (send, sendTo) on the Socket + will NOT block; false if it would block or if an error occurred. + + @param pTimeout if 0, the operation will block without a timeout. Otherwise + the specified amount of time. + */ + inline bool SAL_CALL isSendReady(const TimeValue *pTimeout = NULL) const; + + + /** Checks if a request for out-of-band data will block. + + You can specify a timeout-value in seconds/nanoseconds that denotes + how the operation will block if the Socket has no pending OOB data. + + @return true if OOB-request operations (recv with appropriate flags) + on the Socket will NOT block; false if it would block or if + an error occurred. + + @param pTimeout if 0, the operation will block without a timeout. Otherwise + the specified amount of time. + */ + inline bool SAL_CALL isExceptionPending(const TimeValue *pTimeout = NULL) const; + + + /** Queries the socket for its type. + + @retval osl_Socket_TypeStream + @retval osl_Socket_TypeDgram + @retval osl_Socket_TypeRaw + @retval osl_Socket_TypeRdm + @retval osl_Socket_TypeSeqPacket + @retval osl_invalid_SocketType if an error occurred + */ + inline oslSocketType SAL_CALL getType() const; + + /** Retrieves option-attributes associated with the socket. + @param Option The attribute to query. + Valid values (depending on the Level) are: +
      +
    • osl_Socket_Option_Debug
      + (sal_Bool) Socket debug flag 1 = enabled, 0 = disabled. + +
    • osl_Socket_OptionAcceptConn
      +
    • osl_Socket_OptionReuseAddr
      + (sal_Bool) Allows the socket to be bound to an address that is + already in use. + 1 = multiple bound allowed, 0 = no multiple bounds allowed + +
    • osl_Socket_OptionKeepAlive
      + (sal_Bool) Keepalive packets are sent by the underlying socket. + 1 = enabled, 0 = disabled + +
    • osl_Socket_OptionDontRoute
      + (sal_Bool) Do not route: send directly to interface. + 1 = do not route , 0 = routing possible + +
    • osl_Socket_OptionBroadcast
      + (sal_Bool) Transmission of broadcast messages are allowed on the socket. + 1 = transmission allowed, 0 = transmission disallowed + +
    • osl_Socket_OptionUseLoopback
      + +
    • osl_Socket_OptionLinger
      + (linger) Linger on close if unsent data is present. + linger has two members: l_onoff, l_linger + l_onoff = 0 is off, l_onoff > 0 and l_linger= timeout in seconds. + +
    • osl_Socket_OptionOOBinLine
      + + +
    • osl_Socket_OptionSndBuf
      + (sal_Int32) Size of the send buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing + to the socket. + +
    • osl_Socket_OptionRcvBuf
      + (sal_Int32) Size of the receive buffer in bytes. Data is sent after + SndTimeo or when the buffer is full. This allows faster writing + to the socket and larger packet sizes. + +
    • osl_Socket_OptionSndLowat
      + +
    • osl_Socket_OptionRcvLowat
      + +
    • osl_Socket_OptionSndTimeo
      + (sal_Int32) Data is sent after this timeout. This allows gathering + of data to send larger packages but increases latency times. + +
    • osl_Socket_OptionRcvTimeo
      + +
    • osl_Socket_OptionError
      +
    • osl_Socket_OptionType
      + +
    • osl_Socket_OptionTcpNoDelay
      + Disables the Nagle algorithm for send coalescing. (Do not + collect data until a packet is full, instead send immediately. + This increases network traffic but might improve latency-times.) + 1 = disables the algorithm, 0 = keeps it enabled. +
    + + If not above mentioned otherwise, the options are only valid for + level osl_Socket_LevelSocket. + @param pBuffer The Buffer will be filled with the attribute. + + @param BufferLen The size of pBuffer. + + @param Level The option level. + + Valid values are: +
      +
    • osl_Socket_LevelSocket : Socket Level +
    • osl_Socket_LevelTcp : Level of Transmission Control Protocol +
    + @return The size of the attribute copied into pBuffer or -1 if an error + occurred. + */ + inline sal_Int32 SAL_CALL getOption( + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket) const; + + /** Sets the sockets attributes. + + @param Option denotes the option to modify. + Valid values (depending on the Level) are: +
      +
    • osl_Socket_Option_Debug +
    • osl_Socket_OptionAcceptConn +
    • osl_Socket_OptionReuseAddr +
    • osl_Socket_OptionKeepAlive +
    • osl_Socket_OptionDontRoute +
    • osl_Socket_OptionBroadcast +
    • osl_Socket_OptionUseLoopback +
    • osl_Socket_OptionLinger +
    • osl_Socket_OptionOOBinLine +
    • osl_Socket_OptionSndBuf +
    • osl_Socket_OptionRcvBuf +
    • osl_Socket_OptionSndLowat +
    • osl_Socket_OptionRcvLowat +
    • osl_Socket_OptionSndTimeo +
    • osl_Socket_OptionRcvTimeo +
    • osl_Socket_OptionError +
    • osl_Socket_OptionType +
    • osl_Socket_OptionTcpNoDelay +
    + + If not above mentioned otherwise, the options are only valid for + level osl_Socket_LevelSocket. + + @param pBuffer Pointer to a Buffer which contains the attribute-value. + + @param BufferLen contains the length of the Buffer. + + @param Level selects the level for which an option should be changed. + Valid values are: +
      +
    • osl_Socket_evel_Socket : Socket Level +
    • osl_Socket_Level_Tcp : Level of Transmission Control Protocol +
    + + @return True if the option could be changed. + */ + inline bool SAL_CALL setOption( oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket ) const; + + /** Convenience function for setting sal_Bool and sal_Int32 option values. + @see setOption() + */ + inline bool setOption( oslSocketOption option, sal_Int32 nValue ); + + /** Convenience function for retrieving sal_Bool and sal_Int32 option values. + @see setOption() + */ + inline sal_Int32 getOption( oslSocketOption option ) const; + + /** Enables/disables non-blocking mode of the socket. + @param bNonBlockingMode If true, blocking mode will be switched off + If false, the socket will become a blocking + socket (which is the default behaviour of a socket). + @return true if mode could be set. + */ + inline bool SAL_CALL enableNonBlockingMode( bool bNonBlockingMode); + + /** Query blocking mode of the socket. + @return true if non-blocking mode is set. + */ + inline bool SAL_CALL isNonBlockingMode() const; + + + /** clears the error status + */ + inline void SAL_CALL clearError() const; + + /** returns a constant describing the last error for the socket system. + + @return osl_Socket_E_NONE if no error occurred, invalid_SocketError if + an unknown (unmapped) error occurred, otherwise an enum describing the + error. + @see osl_getLastSocketError() + */ + inline oslSocketError getError() const; + + /** Builds a string with the last error-message for the socket. + */ + inline ::rtl::OUString getErrorAsString( ) const; + + /** Returns the underlying handle unacquired (The caller must acquire it to keep it). + */ + inline oslSocket getHandle() const; + }; + + + class StreamSocket : public Socket + { + public: + /** Creates a socket. + @param Family the Family of the socket (Inet by default) + @param Protocol the Protocon of the socket (IP by default) + @param Type For some protocols it might be desirable to + use a different type than osl_Socket_TypeStream + (like osl_Socket_TypeSeqPacket). + Therefore this parameter is not hidden. + */ + inline StreamSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + inline StreamSocket( oslSocket Socket , __sal_NoAcquire noacquire ); + + inline StreamSocket( oslSocket Socket ); + + /** Retrieves n bytes from the stream and copies them into pBuffer. + The method avoids incomplete reads due to packet boundaries and is thus + blocking. + @param pBuffer receives the read data. pBuffer must be large enough + to hold n bytes. + @param n the number of bytes to read. + @return the number of read bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + inline sal_Int32 SAL_CALL read(void* pBuffer, sal_uInt32 n); + + /** Writes n bytes from pBuffer to the stream. The method avoids + incomplete writes due to packet boundaries and is thus blocking. + @param pBuffer contains the data to be written. + @param n the number of bytes to write. + @return the number of written bytes. The number will only be smaller than + n if an exceptional condition (e.g. connection closed) occurs. + */ + inline sal_Int32 SAL_CALL write(const void* pBuffer, sal_uInt32 n); + + + /** Tries to receive BytesToRead data from the connected socket, + + @param[out] pBuffer Points to a buffer that will be filled with the received + data. pBuffer must have at least have a size of BytesToRead. + @param[in] BytesToRead The number of bytes to read. + @param[in] flags Modifier for the call. Valid values are: + +
      +
    • osl_Socket_MsgNormal +
    • osl_Socket_MsgOOB +
    • osl_Socket_MsgPeek +
    • osl_Socket_MsgDontRoute +
    • osl_Socket_MsgMaxIOVLen +
    + @return the number of received bytes, which may be less than BytesToRead. + */ + inline sal_Int32 SAL_CALL recv(void* pBuffer, + sal_uInt32 BytesToRead, + oslSocketMsgFlag flags= osl_Socket_MsgNormal); + + /** Tries to send BytesToSend data to the connected socket. + + @param pBuffer [in] Points to a buffer that contains the send-data. + @param BytesToSend [in] The number of bytes to send. pBuffer must have at least + this size. + @param Flag [in] Modifier for the call. Valid values are: +
      +
    • osl_Socket_MsgNormal +
    • osl_Socket_MsgOOB +
    • osl_Socket_MsgPeek +
    • osl_Socket_MsgDontRoute +
    • osl_Socket_MsgMaxIOVLen +
    + + @return the number of transferred bytes. It may be less than BytesToSend. + */ + sal_Int32 SAL_CALL send(const void* pBuffer, + sal_uInt32 BytesToSend, + oslSocketMsgFlag= osl_Socket_MsgNormal); + }; + + class ConnectorSocket : public StreamSocket + { + public: + /** Creates a socket that can connect to a (remote) host. + @param Family the Family of the socket (Inet by default) + @param Protocol the Protocon of the socket (IP by default) + @param Type For some protocols it might be desirable to + use a different type than sock_stream osl_Socket_TypeSeqPacket + (like osl_Socket_TypeSeqPacket). + Therefore we do not hide this parameter here. + */ + ConnectorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + + /** Connects the socket to a (remote) host. + @param TargetHost The address of the target. + @param pTimeout The timeout for blocking. If 0, a default system dependent timeout + us used. + @return osl_Socket_Ok if connected successfully, + osl_Socket_TimedOut on timeout, + osl_Socket_Interrupted if unblocked forcefully (by osl::Socket::close()), + osl_Socket_Error if connect failed. + */ + oslSocketResult SAL_CALL connect(const SocketAddr& TargetHost, const TimeValue* pTimeout = NULL); + }; + + /** Allows to accept socket connections. + */ + class AcceptorSocket : public Socket + { + public: + inline AcceptorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + /** Prepare a socket for the accept-call. The socket must have been + bound before to the local address. + @param MaxPendingConnections The maximum number of pending + connections (waiting to be accepted) on this socket. If you use + -1, a system default value is used. + @return true if call was successful. + */ + inline bool SAL_CALL listen(sal_Int32 MaxPendingConnections= -1); + + /** Accepts incoming connections on the socket. You must + precede this call with osl::Socket::bind() and listen(). + @param Connection receives the incoming connection. + @return osl_Socket_Ok, if a connection has been accepted, + osl_Socket_TimedOut, if m_RecvTimeout milliseconds passed without connect, + osl_Socket_Error on errors. + */ + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection); + + /** Accepts incoming connections on the socket. You must + precede this call with osl::Socket::bind() and listen(). + @param PeerAddr receives the address of the connecting entity + (your communication partner). + @param Connection receives the incoming connection. + @return osl_Socket_Ok, if a connection has been accepted, + osl_Socket_TimedOut, if m_RecvTimeout milliseconds passed without connect, + osl_Socket_Error on errors. + */ + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection, SocketAddr & PeerAddr); + }; + + + /** A connectionless socket to send and receive datagrams. + */ + class DatagramSocket : public Socket + { + public: + + /** Creates a datagram socket. + @param Family the Family of the socket (Inet by default) + @param Protocol the Protocon of the socket (IP by default) + @param Type is sock_dgram by default. + */ + inline DatagramSocket(oslAddrFamily Family= osl_Socket_FamilyInet, + oslProtocol Protocol= osl_Socket_ProtocolIp, + oslSocketType Type= osl_Socket_TypeDgram); + + /** Tries to receives BufferSize data from the socket, if no error occurs. + + @param pSenderAddr [out] You must provide pointer to a SocketAddr. + It will be filled with the address of the datagrams sender. + If pSenderAddr is 0, it is ignored. + @param pBuffer [out] Points to a buffer that will be filled with the received + datagram. + @param BufferSize [in] The size of pBuffer. + @param Flag [in] Modifier for the call. Valid values are: +
      +
    • osl_Socket_MsgNormal +
    • osl_Socket_MsgOOB +
    • osl_Socket_MsgPeek +
    • osl_Socket_MsgDontRoute +
    • osl_Socket_MsgMaxIOVLen +
    + + @return the number of received bytes. + */ + inline sal_Int32 SAL_CALL recvFrom(void* pBuffer, + sal_uInt32 BufferSize, + SocketAddr* pSenderAddr= NULL, + oslSocketMsgFlag Flag= osl_Socket_MsgNormal); + + /** Tries to send one datagram with BytesToSend size to the given ReceiverAddr. + Since there is only send one packet, the function doesn't care about + packet boundaries. + + @param ReceiverAddr [in] A SocketAddr that contains + the destination address for this send. + + @param pBuffer [in] Points to a buffer that contains the send-data. + @param BufferSize [in] The number of bytes to send. pBuffer must have at least + this size. + @param Flag [in] Modifier for the call. Valid values are: + +
      +
    • osl_Socket_MsgNormal +
    • osl_Socket_MsgOOB +
    • osl_Socket_MsgPeek +
    • osl_Socket_MsgDontRoute +
    • osl_Socket_MsgMaxIOVLen +
    + + @return the number of transferred bytes. + */ + inline sal_Int32 SAL_CALL sendTo( const SocketAddr& ReceiverAddr, + const void* pBuffer, + sal_uInt32 BufferSize, + oslSocketMsgFlag Flag= osl_Socket_MsgNormal); + }; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/test/uniquepipename.hxx b/include/osl/test/uniquepipename.hxx new file mode 100644 index 000000000..bbeedcafb --- /dev/null +++ b/include/osl/test/uniquepipename.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include "sal/types.h" +#include "rtl/ustring.h" +#include "rtl/ustring.hxx" +#include + +#include "osl/process.h" + +namespace osl { +namespace test { + +OUString uniquePipeName(OUString const & name) +{ + oslProcessInfo info; + info.Size = sizeof info; + + CPPUNIT_ASSERT_EQUAL( + osl_Process_E_None, + osl_getProcessInfo(nullptr, osl_Process_IDENTIFIER, &info)); + + return name + OUString::number(info.Ident); +} + +} // test namespace +} // osl namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/thread.h b/include/osl/thread.h new file mode 100644 index 000000000..03d7cbd9d --- /dev/null +++ b/include/osl/thread.h @@ -0,0 +1,232 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_THREAD_H +#define INCLUDED_OSL_THREAD_H + +#include "sal/config.h" + +#include "osl/time.h" +#include "rtl/textenc.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Opaque data type for threads. As with all other osl-handles + you can initialize and/or test it to/for 0. +*/ +typedef void* oslThread; + +/** the function-ptr. representing the threads worker-function. +*/ +typedef void (SAL_CALL *oslWorkerFunction)(void*); + +/** levels of thread-priority + Note that oslThreadPriorityUnknown might be returned + by getPriorityOfThread() (e.g. when it is terminated), + but mustn't be used with setPriority()! +*/ +typedef enum +{ + osl_Thread_PriorityHighest, + osl_Thread_PriorityAboveNormal, + osl_Thread_PriorityNormal, + osl_Thread_PriorityBelowNormal, + osl_Thread_PriorityLowest, + osl_Thread_PriorityUnknown, /* don't use to set */ + osl_Thread_Priority_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} oslThreadPriority; + + +typedef sal_uInt32 oslThreadIdentifier; + +typedef void* oslThreadKey; + +/** Create the thread, using the function-ptr pWorker as + its main (worker) function. This function receives in + its void* parameter the value supplied by pThreadData. + Once the OS-structures are initialized,the thread starts + running. + + @param pWorker Thread worker function + @param pThreadData Thread local data + + @return 0 if creation failed, otherwise a handle to the thread +*/ +SAL_DLLPUBLIC oslThread SAL_CALL osl_createThread(oslWorkerFunction pWorker, void* pThreadData); + +/** Create the thread, using the function-ptr pWorker as + its main (worker) function. This function receives in + its void* parameter the value supplied by pThreadData. + The thread will be created, but it won't start running. + To wake-up the thread, use resume(). + + @param pWorker Thread worker function + @param pThreadData Thread local data + + @return 0 if creation failed, otherwise a handle to the thread +*/ +SAL_DLLPUBLIC oslThread SAL_CALL osl_createSuspendedThread(oslWorkerFunction pWorker, void* pThreadData); + +/** Get the identifier for the specified thread or if parameter + Thread is NULL of the current active thread. + + @param Thread Handle to thread for the thread ID + + @return identifier of the thread +*/ +SAL_DLLPUBLIC oslThreadIdentifier SAL_CALL osl_getThreadIdentifier(oslThread Thread); + +/** Release the thread handle. + If Thread is NULL, the function won't do anything. + Note that we do not interfere with the actual running of + the thread, we just free up the memory needed by the handle. + + @param Thread Handle to thread to release +*/ +SAL_DLLPUBLIC void SAL_CALL osl_destroyThread(oslThread Thread); + +/** Wake-up a thread that was suspended with suspend() or + createSuspended(). The oslThread must be valid! + + @param Thread Handle to thread to resume +*/ +SAL_DLLPUBLIC void SAL_CALL osl_resumeThread(oslThread Thread); + +/** Suspend the execution of the thread. If you want the thread + to continue, call resume(). The oslThread must be valid! + + @param Thread Handle to thread to suspend +*/ +SAL_DLLPUBLIC void SAL_CALL osl_suspendThread(oslThread Thread); + +/** Changes the threads priority. + The oslThread must be valid! + + @param Thread Handle to thread to which to change priority + @param Priority Thread priority +*/ +SAL_DLLPUBLIC void SAL_CALL osl_setThreadPriority(oslThread Thread, oslThreadPriority Priority); + +/** Retrieves the threads priority. + Returns oslThreadPriorityUnknown for invalid Thread-argument or + terminated thread. (i.e. the oslThread might be invalid.) + + @param Thread Handle to thread for which the priority is retrieved +*/ +SAL_DLLPUBLIC oslThreadPriority SAL_CALL osl_getThreadPriority(const oslThread Thread); + +/** Returns True if the thread was created and has not terminated yet. + Note that according to this definition a "running" thread might be + suspended! Also returns False is Thread is NULL. + + @param Thread Handle to thread +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_isThreadRunning(const oslThread Thread); + +/** Blocks the calling thread until Thread has terminated. + Returns immediately if Thread is NULL. + + @param Thread Handle to thread to join +*/ +SAL_DLLPUBLIC void SAL_CALL osl_joinWithThread(oslThread Thread); + +/** Suspends the execution of the calling thread for at least the given + time. + + @param pDelay Timeout value to wait +*/ +SAL_DLLPUBLIC void SAL_CALL osl_waitThread(const TimeValue* pDelay); + +/** The requested thread will get terminate the next time + scheduleThread() is called. + + @param Thread Handle to thread to terminate +*/ +SAL_DLLPUBLIC void SAL_CALL osl_terminateThread(oslThread Thread); + +/** Schedules in thread to wait till after time slice of specified + thread. scheduleThread() should be called in the working loop + of the thread, so any other thread could also get the + processor. Returns False if the thread should terminate, so + the thread could free any allocated resources. + + @param Thread Handle to thread to schedule in after +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_scheduleThread(oslThread Thread); + +/** Offers the rest of the threads time-slice to the OS. + Under POSIX you _need_ to yield(), otherwise, since the + threads are not preempted during execution, NO other thread + (even with higher priority) gets the processor. Control is + only given to another thread if the current thread blocks + or uses yield(). +*/ +SAL_DLLPUBLIC void SAL_CALL osl_yieldThread(void); + +/** Attempts to set the name of the current thread. + + The name of a thread is usually evaluated for debugging purposes. Not all + platforms support this. On Linux, a set thread name can be observed with + "ps -L". On Windows a thread name set while a debugger is attached can be + observed within the debugger. + + @param name the name of the thread; must not be null; on Linux, only the + first 16 characters are used +*/ +SAL_DLLPUBLIC void SAL_CALL osl_setThreadName(char const * name); + +/* Callback when data stored in a thread key is no longer needed */ + +typedef void (SAL_CALL *oslThreadKeyCallbackFunction)(void *); + +/** Create a key to an associated thread local storage pointer. */ +SAL_DLLPUBLIC oslThreadKey SAL_CALL osl_createThreadKey(oslThreadKeyCallbackFunction pCallback); + +/** Destroy a key to an associated thread local storage pointer. */ +SAL_DLLPUBLIC void SAL_CALL osl_destroyThreadKey(oslThreadKey Key); + +/** Get to key associated thread specific data. */ +SAL_DLLPUBLIC void* SAL_CALL osl_getThreadKeyData(oslThreadKey Key); + +/** Set to key associated thread specific data. */ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_setThreadKeyData(oslThreadKey Key, void *pData); + +/** Get the current thread local text encoding. */ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL osl_getThreadTextEncoding(void); + +/** Set the thread local text encoding. + @return the old text encoding. +*/ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL osl_setThreadTextEncoding(rtl_TextEncoding Encoding); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_THREAD_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/thread.hxx b/include/osl/thread.hxx new file mode 100644 index 000000000..dd3a4cbd3 --- /dev/null +++ b/include/osl/thread.hxx @@ -0,0 +1,240 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_THREAD_HXX +#define INCLUDED_OSL_THREAD_HXX + +#include "sal/config.h" + +#include +#include + +#include "osl/time.h" +#include "osl/thread.h" +#include "rtl/alloc.h" + +namespace osl +{ +/** threadFunc is the function which is executed by the threads + created by the osl::Thread class. The function's signature + matches the one of oslWorkerFunction which is declared in + osl/thread.h +*/ +extern "C" inline void SAL_CALL threadFunc( void* param); + +/** + A thread abstraction. + + @deprecated use ::salhelper::Thread instead. Only the static member + functions ::osl::Thread::getCurrentIdentifier, ::osl::Thread::wait, and + ::osl::Thread::yield are not deprecated. + */ +class Thread +{ + Thread( const Thread& ) SAL_DELETED_FUNCTION; + Thread& operator= ( const Thread& ) SAL_DELETED_FUNCTION; +public: + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete( void *, void * ) + {} + + Thread(): m_hThread(NULL){} + + virtual ~Thread() COVERITY_NOEXCEPT_FALSE + { + osl_destroyThread( m_hThread); + } + + bool SAL_CALL create() + { + assert(m_hThread == NULL); // only one running thread per instance + m_hThread = osl_createSuspendedThread( threadFunc, static_cast(this)); + if (m_hThread == NULL) + { + return false; + } + osl_resumeThread(m_hThread); + return true; + } + + bool SAL_CALL createSuspended() + { + assert(m_hThread == NULL); // only one running thread per instance + if( m_hThread) + return false; + m_hThread= osl_createSuspendedThread( threadFunc, + static_cast(this)); + return m_hThread != NULL; + } + + virtual void SAL_CALL suspend() + { + if( m_hThread ) + osl_suspendThread(m_hThread); + } + + virtual void SAL_CALL resume() + { + if( m_hThread ) + osl_resumeThread(m_hThread); + } + + virtual void SAL_CALL terminate() + { + if( m_hThread ) + osl_terminateThread(m_hThread); + } + + virtual void SAL_CALL join() + { + osl_joinWithThread(m_hThread); + } + + bool SAL_CALL isRunning() const + { + return osl_isThreadRunning(m_hThread); + } + + void SAL_CALL setPriority( oslThreadPriority Priority) + { + if( m_hThread ) + osl_setThreadPriority(m_hThread, Priority); + } + + oslThreadPriority SAL_CALL getPriority() const + { + return m_hThread ? osl_getThreadPriority(m_hThread) : osl_Thread_PriorityUnknown; + } + + oslThreadIdentifier SAL_CALL getIdentifier() const + { + return osl_getThreadIdentifier(m_hThread); + } + + static oslThreadIdentifier SAL_CALL getCurrentIdentifier() + { + return osl_getThreadIdentifier(NULL); + } + + static void SAL_CALL wait(const TimeValue& Delay) + { + osl_waitThread(&Delay); + } + + static void SAL_CALL yield() + { + osl_yieldThread(); + } + + static void setName(char const * name) SAL_NOEXCEPT { + osl_setThreadName(name); + } + + virtual bool SAL_CALL schedule() + { + return m_hThread && osl_scheduleThread(m_hThread); + } + + SAL_CALL operator oslThread() const + { + return m_hThread; + } + +protected: + + /** The thread functions calls the protected functions + run and onTerminated. + */ + friend void SAL_CALL threadFunc( void* param); + + virtual void SAL_CALL run() = 0; + + virtual void SAL_CALL onTerminated() + { + } + +private: + oslThread m_hThread; +}; + +extern "C" inline void SAL_CALL threadFunc( void* param) +{ + Thread* pObj= static_cast(param); + pObj->run(); + pObj->onTerminated(); +} + +class ThreadData +{ + ThreadData( const ThreadData& ) SAL_DELETED_FUNCTION; + ThreadData& operator= (const ThreadData& ) SAL_DELETED_FUNCTION; +public: + /// Create a thread specific local data key + ThreadData( oslThreadKeyCallbackFunction pCallback= NULL ) + { + m_hKey = osl_createThreadKey( pCallback ); + } + + /// Destroy a thread specific local data key + ~ThreadData() + { + osl_destroyThreadKey(m_hKey); + } + + /** Set the data associated with the data key. + @returns True if operation was successful + */ + bool SAL_CALL setData(void *pData) + { + return osl_setThreadKeyData(m_hKey, pData); + } + + /** Get the data associated with the data key. + @returns The data associated with the data key or + NULL if no data was set + */ + void* SAL_CALL getData() + { + return osl_getThreadKeyData(m_hKey); + } + + operator oslThreadKey() const + { + return m_hKey; + } + +private: + oslThreadKey m_hKey; +}; + +} // end namespace osl + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/osl/time.h b/include/osl/time.h new file mode 100644 index 000000000..5c5096cad --- /dev/null +++ b/include/osl/time.h @@ -0,0 +1,187 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_OSL_TIME_H +#define INCLUDED_OSL_TIME_H + +#include "sal/config.h" + +#if defined LIBO_INTERNAL_ONLY +#if defined __cplusplus +#include +#endif +#endif + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef _WIN32 +# pragma pack(push, 8) +#endif + +/* Time since Jan-01-1970 */ + +#if defined LIBO_INTERNAL_ONLY && defined __cplusplus + +struct TimeValue { + TimeValue() = default; + + constexpr TimeValue(sal_uInt32 seconds, sal_uInt32 nanoseconds): + Seconds(seconds), Nanosec(nanoseconds) {} + + template constexpr + TimeValue(std::chrono::duration const & duration): + Seconds( + std::chrono::duration_cast( + duration).count() / 1000000000), + Nanosec( + std::chrono::duration_cast( + duration).count() % 1000000000) + {} + + sal_uInt32 Seconds; + sal_uInt32 Nanosec; +}; + +#else + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + sal_uInt32 Seconds; + sal_uInt32 Nanosec; +} TimeValue; + +#ifdef __cplusplus +} +#endif + +#endif + +#if defined(_WIN32) +# pragma pack(pop) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _oslDateTime +{ + /** contains the nanoseconds + */ + sal_uInt32 NanoSeconds; + + /** contains the seconds (0-59). + */ + sal_uInt16 Seconds; + + /** contains the minutes (0-59). + */ + sal_uInt16 Minutes; + + /** contains the hour (0-23). + */ + sal_uInt16 Hours; + + /** is the day of month (1-31). + */ + sal_uInt16 Day; + + /** is the day of week (0-6 , 0 : Sunday). + */ + sal_uInt16 DayOfWeek; + + /** is the month of year (1-12). + */ + sal_uInt16 Month; + + /** is the year. + */ + sal_Int16 Year; + +} oslDateTime; + + +/** Get the current system time as TimeValue. + @retval false if any error occurs. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getSystemTime( + TimeValue* pTimeVal ); + + +/** Get the GMT from a TimeValue and fill a struct oslDateTime + @param[in] pTimeVal TimeValue + @param[out] pDateTime On success it receives a struct oslDateTime + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getDateTimeFromTimeValue( + const TimeValue* pTimeVal, oslDateTime* pDateTime ); + + +/** Get the GMT from a oslDateTime and fill a TimeValue + @param[in] pDateTime oslDateTime + @param[out] pTimeVal On success it receives a TimeValue + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getTimeValueFromDateTime( + const oslDateTime* pDateTime, TimeValue* pTimeVal ); + + +/** Convert GMT to local time + @param[in] pSystemTimeVal system time to convert + @param[out] pLocalTimeVal On success it receives the local time + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getLocalTimeFromSystemTime( + const TimeValue* pSystemTimeVal, TimeValue* pLocalTimeVal ); + + +/** Convert local time to GMT + @param[in] pLocalTimeVal local time to convert + @param[out] pSystemTimeVal On success it receives the system time + + @return sal_False if any error occurs else sal_True. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL osl_getSystemTimeFromLocalTime( + const TimeValue* pLocalTimeVal, TimeValue* pSystemTimeVal ); + + +/** Get the value of the global timer + @return current timer value in milliseconds + */ + +SAL_DLLPUBLIC sal_uInt32 SAL_CALL osl_getGlobalTimer(void); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_OSL_TIME_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/package/Deflater.hxx b/include/package/Deflater.hxx new file mode 100644 index 000000000..3cd528bf5 --- /dev/null +++ b/include/package/Deflater.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_PACKAGE_DEFLATER_HXX +#define INCLUDED_PACKAGE_DEFLATER_HXX + +#include +#include +#include + +struct z_stream_s; + +namespace ZipUtils { + +class DLLPUBLIC_PACKAGE Deflater final +{ + typedef struct z_stream_s z_stream; + + css::uno::Sequence< sal_Int8 > sInBuffer; + bool bFinish; + bool bFinished; + sal_Int64 nOffset, nLength; + std::unique_ptr pStream; + + void init (sal_Int32 nLevel, bool bNowrap); + sal_Int32 doDeflateBytes (css::uno::Sequence < sal_Int8 > &rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength); + +public: + ~Deflater(); + Deflater(sal_Int32 nSetLevel, bool bNowrap); + void setInputSegment( const css::uno::Sequence< sal_Int8 >& rBuffer ); + bool needsInput() const; + void finish( ); + bool finished() const { return bFinished;} + sal_Int32 doDeflateSegment( css::uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nNewLength ); + sal_Int64 getTotalIn() const; + sal_Int64 getTotalOut() const; + void reset( ); + void end( ); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/package/Inflater.hxx b/include/package/Inflater.hxx new file mode 100644 index 000000000..d8b36e175 --- /dev/null +++ b/include/package/Inflater.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_PACKAGE_INFLATER_HXX +#define INCLUDED_PACKAGE_INFLATER_HXX + +#include +#include +#include + +struct z_stream_s; + +namespace ZipUtils { + +class DLLPUBLIC_PACKAGE Inflater final +{ + typedef struct z_stream_s z_stream; + + bool bFinished, bNeedDict; + sal_Int32 nOffset, nLength, nLastInflateError; + std::unique_ptr pStream; + css::uno::Sequence < sal_Int8 > sInBuffer; + sal_Int32 doInflateBytes (css::uno::Sequence < sal_Int8 > &rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength); + +public: + Inflater(bool bNoWrap); + ~Inflater(); + void setInput( const css::uno::Sequence< sal_Int8 >& rBuffer ); + bool needsDictionary() const { return bNeedDict; } + bool finished() const { return bFinished; } + sal_Int32 doInflateSegment( css::uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength ); + void end( ); + + sal_Int32 getLastInflateError() const { return nLastInflateError; } +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/package/packagedllapi.hxx b/include/package/packagedllapi.hxx new file mode 100644 index 000000000..3db98fe34 --- /dev/null +++ b/include/package/packagedllapi.hxx @@ -0,0 +1,22 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_PACKAGE_PACKAGEDLLAPI_HXX +#define INCLUDED_PACKAGE_PACKAGEDLLAPI_HXX + +#include + +#if defined(DLLIMPLEMENTATION_PACKAGE) +#define DLLPUBLIC_PACKAGE SAL_DLLPUBLIC_EXPORT +#else +#define DLLPUBLIC_PACKAGE SAL_DLLPUBLIC_IMPORT +#endif + +#endif // INCLUDED_PACKAGE_PACKAGEDLLAPI_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/postmac.h b/include/postmac.h new file mode 100644 index 000000000..bfeb88dfd --- /dev/null +++ b/include/postmac.h @@ -0,0 +1,25 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#undef Point +#undef Size +#undef TimeValue +#undef TimeRecord + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/postwin.h b/include/postwin.h new file mode 100644 index 000000000..6b11c5827 --- /dev/null +++ b/include/postwin.h @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* not protected, do only include once! */ + +#undef ABSOLUTE +#undef CompareString +#undef CopyFile +#undef DELETE +#undef DocumentProperties +#undef DrawText +#undef FindWindow +#undef Folder +#undef GetCharWidth +#undef GetClassName +#undef GetGlyphOutline +#undef GetKerningPairs +#undef GetMetaFile +#undef GetNumberFormat +#undef GetObject +#undef GetPrinter +#undef GetTimeFormat +#undef GetUserName +#undef GradientStyle_RECT +#undef IGNORE +#undef IN +#undef OPAQUE // so it doesn't conflict with enum values +#undef OPTIONAL +#undef OUT +#undef PASSTHROUGH +#undef RELATIVE +#undef STRICT +#undef SetPort +#undef SetPrinter +#undef WB_LEFT +#undef WB_RIGHT +#undef Yield +#undef mciSetCommand + +#if !defined INCLUDED_POSTWIN_H && defined __cplusplus +#define INCLUDED_POSTWIN_H +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/premac.h b/include/premac.h new file mode 100644 index 000000000..5a2707d19 --- /dev/null +++ b/include/premac.h @@ -0,0 +1,25 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#define Point MacOSPoint +#define Size MacOSSize +#define TimeValue MacOSTimeValue +#define TimeRecord MacOSTimeRecord + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/prewin.h b/include/prewin.h new file mode 100644 index 000000000..d6f227445 --- /dev/null +++ b/include/prewin.h @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* not protected, do only include once! */ + +#if defined(_WIN32) + +#define Folder WIN_Folder +#define GradientStyle_RECT WIN_GradientStyle_RECT + +#ifndef IN +#define IN +#endif +#ifndef OUT +#define OUT +#endif + +#if !defined STRICT +#define STRICT +#endif + +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include +#include + +#include + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/reader.hxx b/include/registry/reader.hxx new file mode 100644 index 000000000..b804ba3ed --- /dev/null +++ b/include/registry/reader.hxx @@ -0,0 +1,606 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_READER_HXX +#define INCLUDED_REGISTRY_READER_HXX + +#include +#include +#include +#include + +#include +#include + +#include + +namespace typereg { + +/** + A type reader working on a binary blob that represents a UNOIDL type. + +

    Instances of this class are not multi-thread–safe.

    + + @since UDK 3.2.0 + */ +class Reader { +public: + /** + Creates a type reader. + +

    If the given binary blob is malformed, or of a version larger than + maxVersion, the created type reader is flagged as + invalid.

    + + @param buffer the binary blob representing the type; must point to at + least length bytes, and need only be byte-aligned + + @param length the size in bytes of the binary blob representing the type + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + Reader(void const * buffer, sal_uInt32 length) + { + if (!typereg_reader_create(buffer, length, &m_handle)) + { + throw std::bad_alloc(); + } + } + + /** + Shares a type reader between two Reader instances. + + @param other another Reader instance + */ + Reader(Reader const & other): m_handle(other.m_handle) { + typereg_reader_acquire(m_handle); + } + + /** + Destroys this Reader instance. + +

    The underlying type reader is only destroyed if this instance was its + last user.

    + */ + ~Reader() { + typereg_reader_release(m_handle); + } + + /** + Replaces the underlying type reader. + + @param other any Reader instance + + @return this Reader instance + */ + Reader & operator =(Reader const & other) { + Reader temp(other); + std::swap(m_handle, temp.m_handle); + return *this; + } + + /** + Returns whether this type reader is valid. + + @return true iff this type reader is valid + */ + bool isValid() const { + return m_handle != nullptr; + } + + /** + Returns the binary blob version of this type reader. + + @return the version of the binary blob from which this type reader was + constructed; if this type reader is invalid, + TYPEREG_VERSION_0 is returned + */ + typereg_Version getVersion() const { + return typereg_reader_getVersion(m_handle); + } + + /** + Returns the documentation of this type reader. + + @return the documentation of this type reader; if this type reader is + invalid, an empty string is returned + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getDocumentation() const { + rtl_uString * s = nullptr; + typereg_reader_getDocumentation(m_handle, &s); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the file name of this type reader. + + @return the file name of this type reader; if this type reader is + invalid, an empty string is returned + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + @deprecated + */ + OUString getFileName() const { + rtl_uString * s = nullptr; + typereg_reader_getFileName(m_handle, &s); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the type class of this type reader. + +

    This function will always return the type class without the internal + RT_TYPE_PUBLISHED flag set. Use isPublished to + determine whether this type reader is published.

    + + @return the type class of this type reader; if this type reader is + invalid, RT_TYPE_INVALID is returned + */ + RTTypeClass getTypeClass() const { + return typereg_reader_getTypeClass(m_handle); + } + + /** + Returns whether this type reader is published. + + @return whether this type reader is published; if this type reader is + invalid, false is returned + */ + bool isPublished() const { + return typereg_reader_isPublished(m_handle); + } + + /** + Returns the type name of this type reader. + + @return the type name of this type reader; if this type reader is + invalid, an empty string is returned + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getTypeName() const { + rtl_uString * s = nullptr; + typereg_reader_getTypeName(m_handle, &s); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the number of super types of this type reader. + + @return the number of super types of this type reader; if this type + reader is invalid, zero is returned + */ + sal_uInt16 getSuperTypeCount() const { + return typereg_reader_getSuperTypeCount(m_handle); + } + + /** + Returns the type name of a super type of this type reader. + + @param index a valid index into the range of super types of this type + reader + + @return the type name of the given super type + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getSuperTypeName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getSuperTypeName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the number of fields of this type reader. + + @return the number of fields of this type reader; if this type reader is + invalid, zero is returned + */ + sal_uInt16 getFieldCount() const { + return typereg_reader_getFieldCount(m_handle); + } + + /** + Returns the documentation of a field of this type reader. + + @param index a valid index into the range of fields of this type reader + + @return the documentation of the given field + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getFieldDocumentation(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getFieldDocumentation(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the file name of a field of this type reader. + + @param index a valid index into the range of fields of this type reader + + @return the file name of the given field + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + @deprecated + */ + OUString getFieldFileName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getFieldFileName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the flags of a field of this type reader. + + @param index a valid index into the range of fields of this type reader + + @return the flags of the given field + */ + RTFieldAccess getFieldFlags(sal_uInt16 index) const { + return typereg_reader_getFieldFlags(m_handle, index); + } + + /** + Returns the name of a field of this type reader. + + @param index a valid index into the range of fields of this type reader + + @return the name of the given field + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getFieldName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getFieldName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the type name of a field of this type reader. + + @param index a valid index into the range of fields of this type reader + + @return the type name of the given field + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getFieldTypeName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getFieldTypeName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the value of a field of this type reader. + + @param index a valid index into the range of fields of this type reader + + @return the value of the given field + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + RTConstValue getFieldValue(sal_uInt16 index) const { + RTConstValue v; + if (!typereg_reader_getFieldValue( + m_handle, index, &v.m_type, &v.m_value)) + { + throw std::bad_alloc(); + } + return v; + } + + /** + Returns the number of methods of this type reader. + + @return the number of methods of this type reader; if this type reader is + invalid, zero is returned + */ + sal_uInt16 getMethodCount() const { + return typereg_reader_getMethodCount(m_handle); + } + + /** + Returns the documentation of a method of this type reader. + + @param index a valid index into the range of methods of this type reader + + @return the documentation of the given method + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getMethodDocumentation(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getMethodDocumentation(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the flags of a method of this type reader. + + @param index a valid index into the range of methods of this type reader + + @return the flags of the given method + */ + RTMethodMode getMethodFlags(sal_uInt16 index) const { + return typereg_reader_getMethodFlags(m_handle, index); + } + + /** + Returns the name of a method of this type reader. + + @param index a valid index into the range of methods of this type reader + + @return the name of the given method + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getMethodName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getMethodName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the return type name of a method of this type reader. + + @param index a valid index into the range of methods of this type reader + + @return the return type name of the given method + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getMethodReturnTypeName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getMethodReturnTypeName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the number of parameters of a method of this type reader. + + @param index a valid index into the range of methods of this type reader + + @return the number of parameters of the given method + */ + sal_uInt16 getMethodParameterCount(sal_uInt16 index) const { + return typereg_reader_getMethodParameterCount(m_handle, index); + } + + /** + Returns the flags of a parameter of a method of this type reader. + + @param methodIndex a valid index into the range of methods of this type + reader + + @param parameterIndex a valid index into the range of parameters of the + given method + + @return the flags of the given method parameter + */ + RTParamMode getMethodParameterFlags( + sal_uInt16 methodIndex, sal_uInt16 parameterIndex) const + { + return typereg_reader_getMethodParameterFlags( + m_handle, methodIndex, parameterIndex); + } + + /** + Returns the name of a parameter of a method of this type reader. + + @param methodIndex a valid index into the range of methods of this type + reader + + @param parameterIndex a valid index into the range of parameters of the + given method + + @return the name of the given method parameter + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getMethodParameterName( + sal_uInt16 methodIndex, sal_uInt16 parameterIndex) const + { + rtl_uString * s = nullptr; + typereg_reader_getMethodParameterName( + m_handle, &s, methodIndex, parameterIndex); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the type name of a parameter of a method of this type reader. + + @param methodIndex a valid index into the range of methods of this type + reader + + @param parameterIndex a valid index into the range of parameters of the + given method + + @return the type name of the given method parameter + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getMethodParameterTypeName( + sal_uInt16 methodIndex, sal_uInt16 parameterIndex) const + { + rtl_uString * s = nullptr; + typereg_reader_getMethodParameterTypeName( + m_handle, &s, methodIndex, parameterIndex); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the number of exceptions of a method of this type reader. + + @param index a valid index into the range of methods of this type reader + + @return the number of exceptions of the given method + */ + sal_uInt16 getMethodExceptionCount(sal_uInt16 index) const { + return typereg_reader_getMethodExceptionCount(m_handle, index); + } + + /** + Returns the type name of an exception of a method of this type reader. + + @param methodIndex a valid index into the range of methods of this type + reader + + @param exceptionIndex a valid index into the range of exceptions of the + given method + + @return the type name of the given method exception + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getMethodExceptionTypeName( + sal_uInt16 methodIndex, sal_uInt16 exceptionIndex) const + { + rtl_uString * s = nullptr; + typereg_reader_getMethodExceptionTypeName( + m_handle, &s, methodIndex, exceptionIndex); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the number of references of this type reader. + + @return the number of references of this type reader; if this type reader + is invalid, zero is returned + */ + sal_uInt16 getReferenceCount() const { + return typereg_reader_getReferenceCount(m_handle); + } + + /** + Returns the documentation of a reference of this type reader. + + @param index a valid index into the range of references of this type + reader + + @return the documentation of the given reference + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getReferenceDocumentation(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getReferenceDocumentation(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns the flags of a reference of this type reader. + + @param index a valid index into the range of references of this type + reader + + @return the flags of the given reference + */ + RTFieldAccess getReferenceFlags(sal_uInt16 index) const { + return typereg_reader_getReferenceFlags(m_handle, index); + } + + /** + Returns the sort of a reference of this type reader. + + @param index a valid index into the range of references of this type + reader + + @return the sort of the given reference + */ + RTReferenceType getReferenceSort(sal_uInt16 index) const { + return typereg_reader_getReferenceSort(m_handle, index); + } + + /** + Returns the type name of a reference of this type reader. + + @param index a valid index into the range of references of this type + reader + + @return the type name of the given reference + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + OUString getReferenceTypeName(sal_uInt16 index) const { + rtl_uString * s = nullptr; + typereg_reader_getReferenceTypeName(m_handle, &s, index); + if (s == nullptr) { + throw std::bad_alloc(); + } + return OUString(s, SAL_NO_ACQUIRE); + } + +private: + void * m_handle; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/refltype.hxx b/include/registry/refltype.hxx new file mode 100644 index 000000000..0ca5803cd --- /dev/null +++ b/include/registry/refltype.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_REFLTYPE_HXX +#define INCLUDED_REGISTRY_REFLTYPE_HXX + +#include +#include + +/** specifies the type source of a binary type blob. + + Currently only RT_UNO_IDL type is used. + */ +enum RTTypeSource +{ + RT_UNO_IDL, + RT_CORBA_IDL, + RT_JAVA +}; + +/** specifies a helper class for const values. + + This class is used for easy handling of constants or enum values + as fields in binary type blob. + */ +class RTConstValue +{ +public: + /// stores the type of the constant value. + RTValueType m_type; + /// stores the value of the constant. + RTConstValueUnion m_value; + + /// Default constructor. + RTConstValue() + : m_type(RT_TYPE_NONE) + { + m_value.aDouble = 0.0; + } +}; + +/** deprecated. + + An earlier version of UNO used a unique identifier for interfaces. In the + current version of UNO this uik was eliminated and this type is no longer used. + */ +struct RTUik +{ + sal_uInt32 m_Data1; + sal_uInt16 m_Data2; + sal_uInt16 m_Data3; + sal_uInt32 m_Data4; + sal_uInt32 m_Data5; +}; + +/// specifies the calling convention for type reader/writer api +#define TYPEREG_CALLTYPE SAL_CALL + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/regdllapi.h b/include/registry/regdllapi.h new file mode 100644 index 000000000..603eea11d --- /dev/null +++ b/include/registry/regdllapi.h @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_REGDLLAPI_H +#define INCLUDED_REGISTRY_REGDLLAPI_H + +#include + +#if defined(REG_DLLIMPLEMENTATION) +#define REG_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define REG_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif // INCLUDED_REGISTRY_REGDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/registry.hxx b/include/registry/registry.hxx new file mode 100644 index 000000000..b98b1e936 --- /dev/null +++ b/include/registry/registry.hxx @@ -0,0 +1,1059 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +extern "C" { + +/** specifies a collection of function pointers which represents the complete registry C-API. + + These function pointers are used by the C++ wrapper to call the C-API. +*/ +struct Registry_Api +{ + void (REGISTRY_CALLTYPE *acquire) (RegHandle); + void (REGISTRY_CALLTYPE *release) (RegHandle); + sal_Bool (REGISTRY_CALLTYPE *isReadOnly) (RegHandle); + RegError (REGISTRY_CALLTYPE *openRootKey) (RegHandle, RegKeyHandle*); + RegError (REGISTRY_CALLTYPE *getName) (RegHandle, rtl_uString**); + RegError (REGISTRY_CALLTYPE *createRegistry) (rtl_uString*, RegHandle*); + RegError (REGISTRY_CALLTYPE *openRegistry) (rtl_uString*, RegHandle*, RegAccessMode); + RegError (REGISTRY_CALLTYPE *closeRegistry) (RegHandle); + RegError (REGISTRY_CALLTYPE *destroyRegistry) (RegHandle, rtl_uString*); + RegError (REGISTRY_CALLTYPE *mergeKey) (RegHandle, RegKeyHandle, rtl_uString*, rtl_uString*, sal_Bool, sal_Bool); + void (REGISTRY_CALLTYPE *acquireKey) (RegKeyHandle); + void (REGISTRY_CALLTYPE *releaseKey) (RegKeyHandle); + sal_Bool (REGISTRY_CALLTYPE *isKeyReadOnly) (RegKeyHandle); + RegError (REGISTRY_CALLTYPE *getKeyName) (RegKeyHandle, rtl_uString**); + RegError (REGISTRY_CALLTYPE *createKey) (RegKeyHandle, rtl_uString*, RegKeyHandle*); + RegError (REGISTRY_CALLTYPE *openKey) (RegKeyHandle, rtl_uString*, RegKeyHandle*); + RegError (REGISTRY_CALLTYPE *openSubKeys) (RegKeyHandle, rtl_uString*, RegKeyHandle**, sal_uInt32*); + RegError (REGISTRY_CALLTYPE *closeSubKeys) (RegKeyHandle*, sal_uInt32); + RegError (REGISTRY_CALLTYPE *deleteKey) (RegKeyHandle, rtl_uString*); + RegError (REGISTRY_CALLTYPE *closeKey) (RegKeyHandle); + RegError (REGISTRY_CALLTYPE *setValue) (RegKeyHandle, rtl_uString*, RegValueType, RegValue, sal_uInt32); + RegError (REGISTRY_CALLTYPE *setLongListValue) (RegKeyHandle, rtl_uString*, sal_Int32 const *, sal_uInt32); + RegError (REGISTRY_CALLTYPE *setStringListValue) (RegKeyHandle, rtl_uString*, char**, sal_uInt32); + RegError (REGISTRY_CALLTYPE *setUnicodeListValue)(RegKeyHandle, rtl_uString*, sal_Unicode**, sal_uInt32); + RegError (REGISTRY_CALLTYPE *getValueInfo) (RegKeyHandle, rtl_uString*, RegValueType*, sal_uInt32*); + RegError (REGISTRY_CALLTYPE *getValue) (RegKeyHandle, rtl_uString*, RegValue); + RegError (REGISTRY_CALLTYPE *getLongListValue) (RegKeyHandle, rtl_uString*, sal_Int32**, sal_uInt32*); + RegError (REGISTRY_CALLTYPE *getStringListValue) (RegKeyHandle, rtl_uString*, char***, sal_uInt32*); + RegError (REGISTRY_CALLTYPE *getUnicodeListValue)(RegKeyHandle, rtl_uString*, sal_Unicode***, sal_uInt32*); + RegError (REGISTRY_CALLTYPE *freeValueList) (RegValueType, RegValue, sal_uInt32); + RegError (REGISTRY_CALLTYPE *getResolvedKeyName) (RegKeyHandle, rtl_uString*, sal_Bool, rtl_uString**); + RegError (REGISTRY_CALLTYPE *getKeyNames) (RegKeyHandle, rtl_uString*, rtl_uString***, sal_uInt32*); + RegError (REGISTRY_CALLTYPE *freeKeyNames) (rtl_uString**, sal_uInt32); +}; + +/** the API initialization function. +*/ +REG_DLLPUBLIC Registry_Api* REGISTRY_CALLTYPE initRegistry_Api(); + +} + +class RegistryKey; + + +/** The Registry provides the functionality to read and write information in a registry file. + + The class is implemented inline and use a C-Api. +*/ +class Registry final +{ +public: + /** Default constructor. + */ + inline Registry(); + + /// Copy constructor + inline Registry(const Registry& toCopy); + + Registry(Registry && other) noexcept : m_pApi(other.m_pApi), m_hImpl(other.m_hImpl) + { other.m_hImpl = nullptr; } + + /// Destructor. The Destructor close the registry if it is open. + inline ~Registry(); + + /// Assign operator + inline Registry& operator = (const Registry& toAssign); + + Registry & operator =(Registry && other) { + if (m_hImpl != nullptr) { + m_pApi->release(m_hImpl); + } + m_hImpl = other.m_hImpl; + other.m_hImpl = nullptr; + return *this; + } + + /// checks if the registry points to a valid registry data file. + inline bool isValid() const; + + /** returns the access mode of the registry. + + @return TRUE if the access mode is readonly else FALSE. + */ + inline bool isReadOnly() const; + + /** opens the root key of the registry. + + @param rRootKey reference to a RegistryKey which is filled with the rootkey. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError openRootKey(RegistryKey& rRootKey); + + /// returns the name of the current registry data file. + inline OUString getName(); + + /** creates a new registry with the specified name and creates a root key. + + @param registryName specifies the name of the new registry. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError create(const OUString& registryName); + + /** opens a registry with the specified name. + + If the registry already points to a valid registry, the old registry will be closed. + @param registryName specifies a registry name. + @param accessMode specifies the access mode for the registry, RegAccessMode::READONLY or RegAccessMode::READWRITE. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError open(const OUString& registryName, + RegAccessMode accessMode); + + /// closes explicitly the current registry data file. + inline RegError close(); + + /** destroys a registry. + + @param registryName specifies a registry name, if the name is an empty string the registry + itself will be destroyed. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError destroy(const OUString& registryName); + + /** merges the registry information of the specified key with the registry + information of the specified file. + + All existing keys will be extended and existing key values will be overwritten. + @param rKey references a currently open key. The key which information is merged by this + function is a subkey of this key + @param keyName specifies the name of the key which will be merged. + If keyName is an empty string the registry information under the key specified + by rKey is merged with the information from the specified file. + @param regFileName specifies the file containing the registry information. + @param bReport if TRUE the function reports warnings on stdout if a key already exists. + @return RegError::NO_ERROR if succeeds else an error code. If it returns an error the registry will + restore the state before merging. + */ + inline RegError mergeKey(RegistryKey& rKey, + const OUString& keyName, + const OUString& regFileName, + bool bReport); + + friend class RegistryKey; + friend class RegistryKeyArray; + friend class RegistryKeyNames; + + /// returns the used registry Api. + const Registry_Api* getApi() const { return m_pApi; } + +private: + /// stores the used and initialized registry Api. + const Registry_Api* m_pApi; + /// stores the handle of the underlying registry file on which most of the functions work. + RegHandle m_hImpl; +}; + + +/** RegistryKeyArray represents an array of open keys. + + RegistryKeyArray is a helper class to work with an array of keys. +*/ +class RegistryKeyArray +{ +public: + /// Default constructor + inline RegistryKeyArray(); + + /// Destructor, all subkeys will be closed. + inline ~RegistryKeyArray(); + + /// returns the open key specified by index. + inline RegistryKey getElement(sal_uInt32 index); + + /// returns the length of the array. + inline sal_uInt32 getLength() const; + + friend class RegistryKey; + +private: + /** sets the data of the key array. + + @param registry specifies the registry files where the keys are located. + @param phKeys points to an array of open keys. + @param length specifies the length of the array specified by phKeys. + */ + inline void setKeyHandles(Registry const & registry, RegKeyHandle* phKeys, sal_uInt32 length); + + /// stores the number of open subkeys, the number of elements. + sal_uInt32 m_length; + /// stores an array of open subkeys. + RegKeyHandle* m_phKeys; + /// stores the handle to the registry file where the appropriate keys are located. + Registry m_registry; +}; + + +/** RegistryKeyNames represents an array of key names. + + RegistryKeyNames is a helper class to work with an array of key names. +*/ +class RegistryKeyNames +{ +public: + /// Default constructor + inline RegistryKeyNames(); + + /// Destructor, the internal array with key names will be deleted. + inline ~RegistryKeyNames(); + + /// returns the name of the key specified by index. + inline OUString getElement(sal_uInt32 index); + + /// returns the length of the array. + inline sal_uInt32 getLength() const; + + friend class RegistryKey; + +private: + /** sets the data of the array. + + @param registry specifies the registry files where the keys are located. + @param pKeyNames points to an array of key names. + @param length specifies the length of the array specified by pKeyNames. + */ + inline void setKeyNames(Registry const & registry, rtl_uString** pKeyNames, sal_uInt32 length); + + /// stores the number of key names, the number of elements. + sal_uInt32 m_length; + /// stores an array of key names. + rtl_uString** m_pKeyNames; + /// stores the handle to the registry file where the appropriate keys are located. + Registry m_registry; +}; + + +/** RegistryValueList represents a value list of the specified type. + + RegistryValueList is a helper class to work with a list value. +*/ +template +class RegistryValueList final +{ +public: + /// Default constructor + RegistryValueList() + : m_length(0) + , m_pValueList(nullptr) + , m_valueType(RegValueType::NOT_DEFINED) + {} + + /// Destructor, the internal value list will be freed. + ~RegistryValueList() + { + if (m_pValueList) + { + m_registry.getApi()->freeValueList(m_valueType, m_pValueList, m_length); + } + } + + /// returns the value of the list specified by index. + ValueType getElement(sal_uInt32 index) + { + if (m_registry.isValid() && index < m_length) + { + return m_pValueList[index]; + } else + { + return {}; + } + } + + /// returns the length of the list. + sal_uInt32 getLength() + { + return m_length; + } + + friend class RegistryKey; + +private: + /** sets the data of the value list. + + @param registry specifies the registry files where the appropriate key is located. + @param valueType specifies the type of the list values. + @param pValueList points to a value list. + @param length specifies the length of the list. + */ + void setValueList(const Registry& registry, RegValueType valueType, + ValueType* pValueList, sal_uInt32 length) + { + m_length = length; + m_pValueList = pValueList; + m_valueType = valueType; + m_registry = registry; + } + + /// stores the length of the list, the number of elements. + sal_uInt32 m_length; + /// stores the value list. + ValueType* m_pValueList; + /// stores the type of the list elements + RegValueType m_valueType; + /** stores the handle to the registry file where the appropriate key to this + value is located. + */ + Registry m_registry; +}; + + +/** RegistryKey reads or writes information of the underlying key in a registry. + + Class is inline and use a load on call C-Api. +*/ +class RegistryKey +{ +public: + /// Default constructor + inline RegistryKey(); + + /// Copy constructor + inline RegistryKey(const RegistryKey& toCopy); + + /// Destructor, close the key if it references an open one. + inline ~RegistryKey(); + + /// Assign operator + inline RegistryKey& operator = (const RegistryKey& toAssign); + + /// checks if the key points to a valid registry key. + inline bool isValid() const; + + /** returns the access mode of the key. + + @return TRUE if access mode is read only else FALSE. + */ + inline bool isReadOnly() const; + + /// returns the full qualified name of the key beginning with the rootkey. + inline OUString getName(); + + /** creates a new key or opens a key if the specified key already exists. + + The specified keyname is relative to this key. + @param keyName specifies the name of the key which will be opened or created. + @param rNewKey references a RegistryKey which will be filled with the new or open key. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError createKey(const OUString& keyName, + RegistryKey& rNewKey); + + /** opens the specified key. + + The specified keyname is relative to this key. + @param keyName specifies the name of the key which will be opened. + @param rOpenKey references a RegistryKey which will be filled with the open key. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError openKey(const OUString& keyName, + RegistryKey& rOpenKey); + + /** opens all subkeys of the specified key. + + The specified keyname is relative to this key. + @param keyName specifies the name of the key which subkeys will be opened. + @param rSubKeys reference a RegistryKeyArray which will be filled with the open subkeys. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError openSubKeys(const OUString& keyName, + RegistryKeyArray& rSubKeys); + + /** returns an array with the names of all subkeys of the specified key. + + The specified keyname is relative to this key. + @param keyName specifies the name of the key which subkey names will be returned. + @param rSubKeyNames reference a RegistryKeyNames array which will be filled with the subkey names. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getKeyNames(const OUString& keyName, + RegistryKeyNames& rSubKeyNames); + + /** deletes the specified key. + + @param keyName specifies the name of the key which will be deleted. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError deleteKey(const OUString& keyName); + + /// closes explicitly the current key + inline RegError closeKey(); + + /// releases the current key + inline void releaseKey(); + + /** sets a value of a key. + + @param keyName specifies the name of the key which value will be set. + If keyName is an empty string, the value will be set for the key + specified by hKey. + @param valueType specifies the type of the value. + @param pValue points to a memory block containing the data for the value. + @param valueSize specifies the size of pData in bytes + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError setValue(const OUString& keyName, + RegValueType valueType, + RegValue pValue, + sal_uInt32 valueSize); + + /** sets a long list value of a key. + + @param keyName specifies the name of the key which value will be set. + If keyName is an empty string, the value will be set for the key + specified by hKey. + @param pValueList points to an array of longs containing the data for the value. + @param len specifies the length of the list (the array referenced by pValueList). + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError setLongListValue(const OUString& keyName, + sal_Int32 const * pValueList, + sal_uInt32 len); + + /** sets an ascii list value of a key. + + @param keyName specifies the name of the key which value will be set. + If keyName is an empty string, the value will be set for the key + specified by hKey. + @param pValueList points to an array of char* containing the data for the value. + @param len specifies the length of the list (the array referenced by pValueList). + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError setStringListValue(const OUString& keyName, + char** pValueList, + sal_uInt32 len); + + /** sets a unicode string list value of a key. + + @param keyName specifies the name of the key which value will be set. + If keyName is an empty string, the value will be set for the key + specified by hKey. + @param pValueList points to an array of sal_Unicode* containing the data for the value. + @param len specifies the length of the list (the array referenced by pValueList). + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError setUnicodeListValue(const OUString& keyName, + sal_Unicode** pValueList, + sal_uInt32 len); + + /** gets info about type and size of a value. + + @param keyName specifies the name of the key which value info will be returned. + If keyName is an empty string, the value info of the key + specified by hKey will be returned. + @param pValueType returns the type of the value. + @param pValueSize returns the size of the value in bytes or the length of a list value. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getValueInfo(const OUString& keyName, + RegValueType* pValueType, + sal_uInt32* pValueSize); + + /** gets the value of a key. + + @param keyName specifies the name of the key which value will be returned. + If keyName is an empty string, the value is get from the key + specified by hKey. + @param pValue points to an allocated memory block receiving the data of the value. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getValue(const OUString& keyName, + RegValue pValue); + + /** gets a long list value of a key. + + @param keyName specifies the name of the key which value will be returned. + If keyName is an empty string, the value is get from the key + specified by hKey. + @param rValueList references a RegistryValueList which will be filled with the long values. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getLongListValue(const OUString& keyName, + RegistryValueList& rValueList); + + /** gets an ascii list value of a key. + + @param keyName specifies the name of the key which value will be returned. + If keyName is an empty string, the value is get from the key + specified by hKey. + @param rValueList references a RegistryValueList which will be filled with the ascii values. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getStringListValue(const OUString& keyName, + RegistryValueList& rValueList); + + /** gets a unicode value of a key. + + @param keyName specifies the name of the key which value will be returned. + If keyName is an empty string, the value is get from the key + specified by hKey. + @param rValueList reference a RegistryValueList which will be filled with the unicode values. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getUnicodeListValue(const OUString& keyName, + RegistryValueList& rValueList); + + /** resolves a keyname. + + @param[in] keyName specifies the name of the key which will be resolved relative to this key. + The resolved name will be prefixed with the name of this key. + @param[out] rResolvedName the resolved name. + @return RegError::NO_ERROR if succeeds else an error code. + */ + inline RegError getResolvedKeyName(const OUString& keyName, + OUString& rResolvedName) const; + + /// returns the name of the registry in which the key is defined. + inline OUString getRegistryName(); + + friend class Registry; +public: + /// @cond INTERNAL + + /** Constructor, which initialize a RegistryKey with registry and a valid key handle. + + This constructor is internal only. + */ + inline RegistryKey(Registry const & registry, + RegKeyHandle hKey); + +private: + /** sets the internal registry on which this key should work. + */ + inline void setRegistry(Registry const & registry); + + /// @endcond + + /// stores the registry on which this key works + Registry m_registry; + /// stores the current key handle of this key + RegKeyHandle m_hImpl; +}; + + +inline RegistryKeyArray::RegistryKeyArray() + : m_length(0) + , m_phKeys(nullptr) +{ +} + +inline RegistryKeyArray::~RegistryKeyArray() +{ + if (m_phKeys) + m_registry.m_pApi->closeSubKeys(m_phKeys, m_length); +} + +inline RegistryKey RegistryKeyArray::getElement(sal_uInt32 index) +{ + if (m_registry.isValid() && index < m_length) + return RegistryKey(m_registry, m_phKeys[index]); + else + return RegistryKey(); +} + +inline sal_uInt32 RegistryKeyArray::getLength() const +{ + return m_length; +} + +inline void RegistryKeyArray::setKeyHandles(Registry const & registry, + RegKeyHandle* phKeys, + sal_uInt32 length) +{ + m_phKeys = phKeys; + m_length = length; + m_registry = registry; +} + +inline RegistryKeyNames::RegistryKeyNames() + : m_length(0) + , m_pKeyNames(nullptr) +{ +} + +inline RegistryKeyNames::~RegistryKeyNames() +{ + if (m_pKeyNames) + m_registry.m_pApi->freeKeyNames(m_pKeyNames, m_length); +} + +inline OUString RegistryKeyNames::getElement(sal_uInt32 index) +{ + + if (m_pKeyNames && index < m_length) + return m_pKeyNames[index]; + else + return OUString(); +} + +inline sal_uInt32 RegistryKeyNames::getLength() const +{ + return m_length; +} + +inline void RegistryKeyNames::setKeyNames(Registry const & registry, + rtl_uString** pKeyNames, + sal_uInt32 length) +{ + m_pKeyNames = pKeyNames; + m_length = length; + m_registry = registry; +} + +inline RegistryKey::RegistryKey() + : m_hImpl(nullptr) + { } + +/// @cond INTERNAL +inline RegistryKey::RegistryKey(Registry const & registry, RegKeyHandle hKey) + : m_registry(registry) + , m_hImpl(hKey) + { + if (m_hImpl) + m_registry.m_pApi->acquireKey(m_hImpl); + } +/// @endcond + +inline RegistryKey::RegistryKey(const RegistryKey& toCopy) + : m_registry(toCopy.m_registry) + , m_hImpl(toCopy.m_hImpl) + { + if (m_hImpl) + m_registry.m_pApi->acquireKey(m_hImpl); + } + +/// @cond INTERNAL +inline void RegistryKey::setRegistry(Registry const & registry) + { + m_registry = registry; + } +/// @endcond + +inline RegistryKey::~RegistryKey() + { + if (m_hImpl) + m_registry.m_pApi->releaseKey(m_hImpl); + } + +inline RegistryKey& RegistryKey::operator = (const RegistryKey& toAssign) +{ + m_registry = toAssign.m_registry; + + if (toAssign.m_hImpl) + m_registry.m_pApi->acquireKey(toAssign.m_hImpl); + if (m_hImpl) + m_registry.m_pApi->releaseKey(m_hImpl); + m_hImpl = toAssign.m_hImpl; + + return *this; +} + +inline bool RegistryKey::isValid() const + { return (m_hImpl != nullptr); } + +inline bool RegistryKey::isReadOnly() const + { + if (m_registry.isValid()) + return m_registry.m_pApi->isKeyReadOnly(m_hImpl); + else + return false; + } + +inline OUString RegistryKey::getName() + { + OUString sRet; + if (m_registry.isValid()) + m_registry.m_pApi->getKeyName(m_hImpl, &sRet.pData); + return sRet; + } + +inline RegError RegistryKey::createKey(const OUString& keyName, + RegistryKey& rNewKey) + { + if (rNewKey.isValid()) rNewKey.closeKey(); + if (m_registry.isValid()) + { + RegError ret = m_registry.m_pApi->createKey(m_hImpl, keyName.pData, &rNewKey.m_hImpl); + if (ret == RegError::NO_ERROR) rNewKey.setRegistry(m_registry); + return ret; + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::openKey(const OUString& keyName, + RegistryKey& rOpenKey) + { + if (rOpenKey.isValid()) rOpenKey.closeKey(); + if (m_registry.isValid()) + { + RegError ret = m_registry.m_pApi->openKey(m_hImpl, keyName.pData, + &rOpenKey.m_hImpl); + if (ret == RegError::NO_ERROR) rOpenKey.setRegistry(m_registry); + return ret; + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::openSubKeys(const OUString& keyName, + RegistryKeyArray& rSubKeys) + { + if (m_registry.isValid()) + { + RegError ret = RegError::NO_ERROR; + RegKeyHandle* pSubKeys; + sal_uInt32 nSubKeys; + ret = m_registry.m_pApi->openSubKeys(m_hImpl, keyName.pData, + &pSubKeys, &nSubKeys); + if ( ret != RegError::NO_ERROR) + { + return ret; + } else + { + rSubKeys.setKeyHandles(m_registry, pSubKeys, nSubKeys); + return ret; + } + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getKeyNames(const OUString& keyName, + RegistryKeyNames& rSubKeyNames) + { + if (m_registry.isValid()) + { + RegError ret = RegError::NO_ERROR; + rtl_uString** pSubKeyNames; + sal_uInt32 nSubKeys; + ret = m_registry.m_pApi->getKeyNames(m_hImpl, keyName.pData, + &pSubKeyNames, &nSubKeys); + if ( ret != RegError::NO_ERROR) + { + return ret; + } else + { + rSubKeyNames.setKeyNames(m_registry, pSubKeyNames, nSubKeys); + return ret; + } + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::deleteKey(const OUString& keyName) + { + if (m_registry.isValid()) + return m_registry.m_pApi->deleteKey(m_hImpl, keyName.pData); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::closeKey() + { + if (m_registry.isValid()) + { + RegError ret = m_registry.m_pApi->closeKey(m_hImpl); + if (ret == RegError::NO_ERROR) + { + m_hImpl = nullptr; + m_registry = Registry(); + } + return ret; + } else + return RegError::INVALID_KEY; + } + +inline void RegistryKey::releaseKey() +{ + if (m_registry.isValid() && (m_hImpl != nullptr)) + { + m_registry.m_pApi->releaseKey(m_hImpl); + m_hImpl = nullptr; + } +} + +inline RegError RegistryKey::setValue(const OUString& keyName, + RegValueType valueType, + RegValue pValue, + sal_uInt32 valueSize) + { + if (m_registry.isValid()) + return m_registry.m_pApi->setValue(m_hImpl, keyName.pData, valueType, + pValue, valueSize); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::setLongListValue(const OUString& keyName, + sal_Int32 const * pValueList, + sal_uInt32 len) + { + if (m_registry.isValid()) + return m_registry.m_pApi->setLongListValue(m_hImpl, keyName.pData, + pValueList, len); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::setStringListValue(const OUString& keyName, + char** pValueList, + sal_uInt32 len) + { + if (m_registry.isValid()) + return m_registry.m_pApi->setStringListValue(m_hImpl, keyName.pData, + pValueList, len); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::setUnicodeListValue(const OUString& keyName, + sal_Unicode** pValueList, + sal_uInt32 len) + { + if (m_registry.isValid()) + return m_registry.m_pApi->setUnicodeListValue(m_hImpl, keyName.pData, + pValueList, len); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getValueInfo(const OUString& keyName, + RegValueType* pValueType, + sal_uInt32* pValueSize) + { + if (m_registry.isValid()) + return m_registry.m_pApi->getValueInfo(m_hImpl, keyName.pData, pValueType, pValueSize); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getValue(const OUString& keyName, + RegValue pValue) + { + if (m_registry.isValid()) + return m_registry.m_pApi->getValue(m_hImpl, keyName.pData, pValue); + else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getLongListValue(const OUString& keyName, + RegistryValueList& rValueList) + { + if (m_registry.isValid()) + { + RegError ret = RegError::NO_ERROR; + sal_Int32* pValueList; + sal_uInt32 length; + ret = m_registry.m_pApi->getLongListValue(m_hImpl, keyName.pData, + &pValueList, &length); + if ( ret != RegError::NO_ERROR) + { + return ret; + } else + { + rValueList.setValueList(m_registry, RegValueType::LONGLIST, + pValueList, length); + return ret; + } + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getStringListValue(const OUString& keyName, + RegistryValueList& rValueList) + { + if (m_registry.isValid()) + { + RegError ret = RegError::NO_ERROR; + char** pValueList; + sal_uInt32 length; + ret = m_registry.m_pApi->getStringListValue(m_hImpl, keyName.pData, + &pValueList, &length); + if ( ret != RegError::NO_ERROR ) + { + return ret; + } else + { + rValueList.setValueList(m_registry, RegValueType::STRINGLIST, + pValueList, length); + return ret; + } + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getUnicodeListValue(const OUString& keyName, + RegistryValueList& rValueList) + { + if (m_registry.isValid()) + { + RegError ret = RegError::NO_ERROR; + sal_Unicode** pValueList; + sal_uInt32 length; + ret = m_registry.m_pApi->getUnicodeListValue(m_hImpl, keyName.pData, + &pValueList, &length); + if ( ret != RegError::NO_ERROR ) + { + return ret; + } else + { + rValueList.setValueList(m_registry, RegValueType::UNICODELIST, + pValueList, length); + return ret; + } + } else + return RegError::INVALID_KEY; + } + +inline RegError RegistryKey::getResolvedKeyName(const OUString& keyName, + OUString& rResolvedName) const + { + if (m_registry.isValid()) + return m_registry.m_pApi->getResolvedKeyName(m_hImpl, + keyName.pData, + true, + &rResolvedName.pData); + else + return RegError::INVALID_KEY; + } + +inline OUString RegistryKey::getRegistryName() + { + if (m_registry.isValid()) + { + return m_registry.getName(); + } else + return OUString(); + } + + +inline Registry::Registry() + : m_pApi(initRegistry_Api()) + , m_hImpl(nullptr) + { } + +inline Registry::Registry(const Registry& toCopy) + : m_pApi(toCopy.m_pApi) + , m_hImpl(toCopy.m_hImpl) + { + if (m_hImpl) + m_pApi->acquire(m_hImpl); + } + + +inline Registry::~Registry() + { + if (m_hImpl) + m_pApi->release(m_hImpl); + } + +inline Registry& Registry::operator = (const Registry& toAssign) +{ + if (toAssign.m_hImpl) + toAssign.m_pApi->acquire(toAssign.m_hImpl); + if (m_hImpl) + m_pApi->release(m_hImpl); + + m_pApi = toAssign.m_pApi; + m_hImpl = toAssign.m_hImpl; + + return *this; +} + +inline bool Registry::isValid() const + { return ( m_hImpl != nullptr ); } + +inline bool Registry::isReadOnly() const + { return m_pApi->isReadOnly(m_hImpl); } + +inline RegError Registry::openRootKey(RegistryKey& rRootKey) + { + rRootKey.setRegistry(*this); + return m_pApi->openRootKey(m_hImpl, &rRootKey.m_hImpl); + } + +inline OUString Registry::getName() + { + OUString sRet; + m_pApi->getName(m_hImpl, &sRet.pData); + return sRet; + } + +inline RegError Registry::create(const OUString& registryName) + { + if (m_hImpl) + m_pApi->release(m_hImpl); + return m_pApi->createRegistry(registryName.pData, &m_hImpl); + } + +inline RegError Registry::open(const OUString& registryName, + RegAccessMode accessMode) + { + if (m_hImpl) + m_pApi->release(m_hImpl); + return m_pApi->openRegistry(registryName.pData, &m_hImpl, accessMode); + } + +inline RegError Registry::close() + { + RegError ret = m_pApi->closeRegistry(m_hImpl); + if (ret == RegError::NO_ERROR) + m_hImpl = nullptr; + return ret; + } + +inline RegError Registry::destroy(const OUString& registryName) + { + RegError ret = m_pApi->destroyRegistry(m_hImpl, registryName.pData); + if ( ret == RegError::NO_ERROR && registryName.isEmpty() ) + m_hImpl = nullptr; + return ret; + } + +inline RegError Registry::mergeKey(RegistryKey& rKey, + const OUString& keyName, + const OUString& regFileName, + bool bReport) + { return m_pApi->mergeKey(m_hImpl, rKey.m_hImpl, keyName.pData, regFileName.pData, false/*bWarnings*/, bReport); } + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/regtype.h b/include/registry/regtype.h new file mode 100644 index 000000000..89fdcc940 --- /dev/null +++ b/include/registry/regtype.h @@ -0,0 +1,141 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_REGTYPE_H +#define INCLUDED_REGISTRY_REGTYPE_H + +#include +#include + +/// defines the type of a registry handle used in the C API. +typedef void* RegHandle; + +/// defines the type of a registry key handle used in the C API. +typedef void* RegKeyHandle; + +/// defines the type of a registry key value handle used in the C API. +typedef void* RegValue; + +/** defines the open/access mode of the registry. + + Two modes are valid: + -READONLY allows readonly access + -READWRITE allows read and write access + */ +enum class RegAccessMode +{ + READONLY = 0x0001, /// This mode allows readonly access. + READWRITE = 0x0002 /// This mode allows read and write access. +}; +namespace o3tl +{ +template <> struct typed_flags : is_typed_flags +{ +}; +} + +/** defines the type of a key value. + + A registry key can contain a value which has one of seven different types. + Three simple types (long, ascii and unicode string) and a list type of + these simple types. Furthermore a binary type which provides the possibility + to define own data structures and store these types in the registry. The UNO + core reflection data is stored as a binary blob in the type registry. + */ +enum class SAL_DLLPUBLIC_RTTI RegValueType +{ + /// The key has no value or the value type is unknown. + NOT_DEFINED, + /// The key has a value of type long + LONG, + /// The key has a value of type ascii string + STRING, + /// The key has a value of type unicode string + UNICODE, + /// The key has a value of type binary + BINARY, + /// The key has a value of type long list + LONGLIST, + /// The key has a value of type ascii string list + STRINGLIST, + /// The key has a value of type unicode string list + UNICODELIST +}; + +/// specifies the possible error codes which can occur using the registry API. +enum class SAL_DLLPUBLIC_RTTI RegError +{ + /// no error. + NO_ERROR, + + /// registry is not open. + REGISTRY_NOT_OPEN, + /// registry does not exists. + REGISTRY_NOT_EXISTS, + /// registry is open with readonly access rights. + REGISTRY_READONLY, + /// destroy a registry failed. There are may be any open keys. + DESTROY_REGISTRY_FAILED, + /** registry cannot be opened with readwrite access because the registry is already + open with readwrite access anywhere. + */ + CANNOT_OPEN_FOR_READWRITE, + /** registry is in an invalid state or the registry does not point to + a valid registry data file. + */ + INVALID_REGISTRY, + + /// the key or key handle points to an invalid key or closed key. + KEY_NOT_OPEN, + /// the specified keyname points to a nonexisting key. + KEY_NOT_EXISTS, + /// the key with the specified keyname cannot be created. + CREATE_KEY_FAILED, + /// the specified key cannot be deleted. Maybe an open key handle exists to this key. + DELETE_KEY_FAILED, + /** the keyname is invalid. This error will return if the keyname + is NULL but should not be NULL in the context of a called function. + */ + INVALID_KEYNAME, + /// the key is not in a valid state. + INVALID_KEY, + + /// the key has no value + VALUE_NOT_EXISTS, + /// setting the specified value of a key failed. + SET_VALUE_FAILED, + /// deleting of the key value failed. + DELETE_VALUE_FAILED, + /// the key has an invalid value or the value type is unknown. + INVALID_VALUE, + + /// merging a key, the value and all subkeys failed. + MERGE_ERROR, + /** conflicts exists during the merge process of a key. This could happen if + the value of a key already exists and the merge process will replace it. + */ + MERGE_CONFLICT, +}; + +/// specify the calling convention for the registry API +#define REGISTRY_CALLTYPE SAL_CALL + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/typereg_reader.hxx b/include/registry/typereg_reader.hxx new file mode 100644 index 000000000..a0af800f0 --- /dev/null +++ b/include/registry/typereg_reader.hxx @@ -0,0 +1,565 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_READER_H +#define INCLUDED_REGISTRY_READER_H + +#include +#include +#include + +#include +#include + +/** + Creates a type reader working on a binary blob that represents a UNOIDL type. + +

    If a non-null handle is returned through result, its + reference count will be one. Operations on a non-null handle are not + multi-thread–safe.

    + + The type reader works directly on the given buffer, which must remain + available unmodified until the type reader is destroyed + + @param buffer the binary blob representing the type; must point to at least + length bytes, and need only be byte-aligned + + @param length the size in bytes of the binary blob representing the type + + @param result an out-parameter obtaining a handle on the type reader; must + not be null; if the given binary blob is malformed, or of a version larger + than maxVersion, null is returned + + @return false iff an out-of-memory condition occurred, in which case + result is left unchanged, and no type reader is created + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC bool typereg_reader_create( + void const * buffer, sal_uInt32 length, + void ** result); + +/** + Increments the reference count of a type reader. + + @param handle a handle on a type reader; may be null + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_acquire(void * handle); + +/** + Decrements the reference count of a type reader. + +

    If the reference count drops to zero, the type reader is destroyed.

    + + @param handle a handle on a type reader; may be null + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_release(void * handle); + +/** + Returns the binary blob version of a type reader. + + @param handle a handle on a type reader; may be null + + @return the version of the binary blob from which the type reader was + constructed; if handle is null, TYPEREG_VERSION_0 + is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC typereg_Version typereg_reader_getVersion(void const * handle); + +/** + Returns the documentation of a type reader. + + @param handle a handle on a type reader; may be null + + @param result an out-parameter obtaining the documentation string; must not + be null; if handle is null, an empty string is returned; if an + out-of-memory condition occurs, a pointer to a null pointer is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getDocumentation( + void * handle, rtl_uString ** result); + +/** + Returns the file name of a type reader. + + @param handle a handle on a type reader; may be null + + @param result an out-parameter obtaining the file name string; must not be + null; if handle is null, an empty string is returned; if an + out-of-memory condition occurs, a pointer to a null pointer is returned + + @since UDK 3.2.0 + @deprecated + */ +REG_DLLPUBLIC void typereg_reader_getFileName(void * handle, rtl_uString ** result); + +/** + Returns the type class of a type reader. + +

    This function will always return the type class without the internal + RT_TYPE_PUBLISHED flag set. Use + typereg_reader_isPublished to determine whether a type reader is + published.

    + + @param handle a handle on a type reader; may be null + + @return the type class of the type reader; if handle is null, + RT_TYPE_INVALID is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC RTTypeClass typereg_reader_getTypeClass(void * handle); + +/** + Returns whether a type reader is published. + + @param handle a handle on a type reader; may be null + + @return whether the type reader is published; if handle is null, + false is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC bool typereg_reader_isPublished(void * handle); + +/** + Returns the type name of a type reader. + + @param handle a handle on a type reader; may be null + + @param result an out-parameter obtaining the type name string; must not be + null; if handle is null, an empty string is returned; if an + out-of-memory condition occurs, a pointer to a null pointer is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getTypeName(void * handle, rtl_uString ** result); + +/** + Returns the number of super types of a type reader. + + @param handle a handle on a type reader; may be null + + @return the number of super types of the type reader; if handle + is null, zero is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_uInt16 typereg_reader_getSuperTypeCount(void * handle); + +/** + Returns the type name of a super type of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the super type's type name string; + must not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param index a valid index into the range of super types of the given type + reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getSuperTypeName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the number of fields of a type reader. + + @param handle a handle on a type reader; may be null + + @return the number of fields of the type reader; if handle is + null, zero is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_uInt16 typereg_reader_getFieldCount(void * handle); + +/** + Returns the documentation of a field of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the field's documentation string; + must not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param index a valid index into the range of fields of the given type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getFieldDocumentation( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the file name of a field of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the field's file name string; must + not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param index a valid index into the range of fields of the given type reader + + @since UDK 3.2.0 + @deprecated + */ +REG_DLLPUBLIC void typereg_reader_getFieldFileName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the flags of a field of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of fields of the given type reader + + @return the flags of the given field of the type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC RTFieldAccess typereg_reader_getFieldFlags( + void * handle, sal_uInt16 index); + +/** + Returns the name of a field of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the field's name string; must not be + null; if an out-of-memory condition occurs, a pointer to a null pointer is + returned + + @param index a valid index into the range of fields of the given type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getFieldName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the type name of a field of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the field's type name string; must + not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param index a valid index into the range of fields of the given type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getFieldTypeName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the value of a field of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of fields of the given type reader + + @param type an out-parameter obtaining the field value's type; must not be + null + + @param value an out-parameter obtaining the field value's value; must not be + null + + @return false iff an out-of-memory condition occurred, in which case + type and value are left unchanged + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC bool typereg_reader_getFieldValue( + void * handle, sal_uInt16 index, RTValueType * type, + union RTConstValueUnion * value); + +/** + Returns the number of methods of a type reader. + + @param handle a handle on a type reader; may be null + + @return the number of methods of the type reader; if handle is + null, zero is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_uInt16 typereg_reader_getMethodCount(void * handle); + +/** + Returns the documentation of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the methods's documentation string; + must not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param index a valid index into the range of methods of the given type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getMethodDocumentation( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the flags of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of methods of the given type reader + + @return the flags of the given method of the type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC RTMethodMode typereg_reader_getMethodFlags( + void * handle, sal_uInt16 index); + +/** + Returns the name of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the methods's name string; must not + be null; if an out-of-memory condition occurs, a pointer to a null pointer is + returned + + @param index a valid index into the range of methods of the given type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getMethodName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the return type name of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the methods's return type name + string; must not be null; if an out-of-memory condition occurs, a pointer to + a null pointer is returned + + @param index a valid index into the range of methods of the given type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getMethodReturnTypeName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the number of parameters of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of methods of the given type reader + + @return the number of parameters of the given method of the type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_uInt16 typereg_reader_getMethodParameterCount( + void * handle, sal_uInt16 index); + +/** + Returns the flags of a parameter of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param methodIndex a valid index into the range of methods of the given type + reader + + @param parameterIndex a valid index into the range of parameters of the given + method + + @return the flags of the given parameter of the given method of the type + reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC RTParamMode typereg_reader_getMethodParameterFlags( + void * handle, sal_uInt16 methodIndex, sal_uInt16 parameterIndex); + +/** + Returns the name of a parameter of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the parameter's name string; must + not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param methodIndex a valid index into the range of methods of the given type + reader + + @param parameterIndex a valid index into the range of parameters of the given + method + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getMethodParameterName( + void * handle, rtl_uString ** result, sal_uInt16 methodIndex, + sal_uInt16 parameterIndex); + +/** + Returns the type name of a parameter of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the parameter's type name string; + must not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param methodIndex a valid index into the range of methods of the given type + reader + + @param parameterIndex a valid index into the range of parameters of the given + method + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getMethodParameterTypeName( + void * handle, rtl_uString ** result, sal_uInt16 methodIndex, + sal_uInt16 parameterIndex); + +/** + Returns the number of exceptions of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of methods of the given type reader + + @return the number of exceptions of the given method of the type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_uInt16 typereg_reader_getMethodExceptionCount( + void * handle, sal_uInt16 index); + +/** + Returns the type name of an exception of a method of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the exception's type name string; + must not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param methodIndex a valid index into the range of methods of the given type + reader + + @param exceptionIndex a valid index into the range of exceptions of the given + method + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getMethodExceptionTypeName( + void * handle, rtl_uString ** result, sal_uInt16 methodIndex, + sal_uInt16 exceptionIndex); + +/** + Returns the number of references of a type reader. + + @param handle a handle on a type reader; may be null + + @return the number of references of the type reader; if handle + is null, zero is returned + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_uInt16 typereg_reader_getReferenceCount(void * handle); + +/** + Returns the documentation of a reference of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the reference's documentation + string; must not be null; if an out-of-memory condition occurs, a pointer to + a null pointer is returned + + @param index a valid index into the range of references of the given type + reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getReferenceDocumentation( + void * handle, rtl_uString ** result, sal_uInt16 index); + +/** + Returns the flags of a reference of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of references of the given type + reader + + @return the flags of the given reference of the type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC RTFieldAccess typereg_reader_getReferenceFlags( + void * handle, sal_uInt16 index); + +/** + Returns the sort of a reference of a type reader. + + @param handle a handle on a type reader; must not be null + + @param index a valid index into the range of references of the given type + reader + + @return the sort of the given reference of the type reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC RTReferenceType typereg_reader_getReferenceSort( + void * handle, sal_uInt16 index); + +/** + Returns the type name of a reference of a type reader. + + @param handle a handle on a type reader; must not be null + + @param result an out-parameter obtaining the reference's type name string; + must not be null; if an out-of-memory condition occurs, a pointer to a null + pointer is returned + + @param index a valid index into the range of references of the given type + reader + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_reader_getReferenceTypeName( + void * handle, rtl_uString ** result, sal_uInt16 index); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/types.hxx b/include/registry/types.hxx new file mode 100644 index 000000000..a9763f5ea --- /dev/null +++ b/include/registry/types.hxx @@ -0,0 +1,339 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_TYPES_H +#define INCLUDED_REGISTRY_TYPES_H + +#include +#include + +/** specifies the typeclass of a binary type blob. + + The general structure of a binary type blob is always the same. It depends + on the typeclass which parts of the blob are filled with data or not. + */ +enum RTTypeClass +{ + /** specifies that the structure of the given blob is unknown and can't be + read. + */ + RT_TYPE_INVALID, + + /** specifies that the blob represents an interface type. An interface blob + can contain a base interface, attributes and methods. + */ + RT_TYPE_INTERFACE, + + /** specifies that the blob represents a module type. A module blob can + contain a base module and constant members (fields). + */ + RT_TYPE_MODULE, + + /** specifies that the blob represents a struct type. A struct blob can + contain a base struct and members (fields). + */ + RT_TYPE_STRUCT, + + /** specifies that the blob represents an enum type. An enum blob can + contain enum values which are accessible as fields. + */ + RT_TYPE_ENUM, + + /** specifies that the blob represents an exception type. An exception blob + can contain a base exception and members (fields). + */ + RT_TYPE_EXCEPTION, + + /** specifies that the blob represents a typedef type. A typedef blob can + contain a base type. + */ + RT_TYPE_TYPEDEF, + + /** specifies that the blob represents a service type. A service blob can + contain a base service, properties (fields), references to services or + interfaces. + */ + RT_TYPE_SERVICE, + + /** specifies that the blob represents a singleton type (a named object) + which refers exactly one existing service. + */ + RT_TYPE_SINGLETON, + + /// deprecated, not used. + RT_TYPE_OBJECT, + + /** specifies that the blob represents a constants type. A constants blob + can contain constant types as fields. + */ + RT_TYPE_CONSTANTS, + + /** @deprecated + a union type was evaluated but currently not supported. + */ + RT_TYPE_UNION, + + /// @cond INTERNAL + /** + Flag for published entities. + + Used in combination with RT_TYPE_INTERFACE, RT_TYPE_STRUCT, RT_TYPE_ENUM, + RT_TYPE_EXCEPTION, RT_TYPE_TYPEDEF, RT_TYPE_SERVICE, RT_TYPE_SINGLETON, + or RT_TYPE_CONSTANTS to mark an entity as published. + + (The value of this enumerator is chosen so that it is unlikely that its + addition changes the underlying type of this enumeration for any C/C++ + compiler.) + + @since UDK 3.2.0 + */ + RT_TYPE_PUBLISHED = 0x4000 + /// @endcond +}; + +/** specifies the type for the field access. + + Fields in a type blob are used for different types. Among others they were + used for properties of services and these properties can have several flags. + + @see RTFieldAccess::INVALID + @see RTFieldAccess::READONLY + @see RTFieldAccess::OPTIONAL + @see RTFieldAccess::MAYBEVOID + @see RTFieldAccess::BOUND + @see RTFieldAccess::CONSTRAINED + @see RTFieldAccess::TRANSIENT + @see RTFieldAccess::MAYBEAMBIGUOUS + @see RTFieldAccess::MAYBEDEFAULT + @see RTFieldAccess::REMOVABLE + @see RTFieldAccess::ATTRIBUTE + @see RTFieldAccess::PROPERTY + @see RTFieldAccess::CONST + @see RTFieldAccess::READWRITE + @see RTFieldAccess::DEFAULT + @see RTFieldAccess::PARAMETERIZED_TYPE + @see RTFieldAccess::PUBLISHED + */ +enum class RTFieldAccess +{ + NONE = 0x0000, + /// specifies an unknown flag + INVALID = 0x0000, + /// specifies a readonly property/attribute + READONLY = 0x0001, + /// specifies a property as optional that means that it must not be implemented. + OPTIONAL = 0x0002, + /// @see com::sun::star::beans::PropertyAttribute + MAYBEVOID = 0x0004, + /// @see com::sun::star::beans::PropertyAttribute + BOUND = 0x0008, + /// @see com::sun::star::beans::PropertyAttribute + CONSTRAINED = 0x0010, + /// @see com::sun::star::beans::PropertyAttribute + TRANSIENT = 0x0020, + /// @see com::sun::star::beans::PropertyAttribute + MAYBEAMBIGUOUS = 0x0040, + /// @see com::sun::star::beans::PropertyAttribute + MAYBEDEFAULT = 0x0080, + /// @see com::sun::star::beans::PropertyAttribute + REMOVABLE = 0x0100, + /// @see com::sun::star::beans::PropertyAttribute + ATTRIBUTE = 0x0200, + /// specifies that the field is a property + PROPERTY = 0x0400, + /// specifies that the field is a constant or enum value + CONST = 0x0800, + /// specifies that the property/attribute has read/write access + READWRITE = 0x1000, + /// only to describe a union default label + DEFAULT = 0x2000, + /** + Indicates that a member of a polymorphic struct type template is of a + parameterized type. + + Only valid for fields that represent members of polymorphic struct type + templates. + + @since UDK 3.2.0 + */ + PARAMETERIZED_TYPE = 0x4000, + /** + Flag for published individual constants. + + Used in combination with RTFieldAccess::CONST for individual constants (which are + not members of constant groups). + + @since UDK 3.2.0 + */ + PUBLISHED = 0x8000, + +}; +namespace o3tl +{ +template <> struct typed_flags : is_typed_flags +{ +}; +} + +/** specifies the type of a field value. + + A field can have a value if it represents a constant or an enum value. + */ +enum RTValueType +{ + RT_TYPE_NONE, + RT_TYPE_BOOL, + RT_TYPE_BYTE, + RT_TYPE_INT16, + RT_TYPE_UINT16, + RT_TYPE_INT32, + RT_TYPE_UINT32, + RT_TYPE_INT64, + RT_TYPE_UINT64, + RT_TYPE_FLOAT, + RT_TYPE_DOUBLE, + RT_TYPE_STRING +}; + +/** specifies a variable container for field values. + */ +union RTConstValueUnion { + bool aBool; + sal_Int8 aByte; + sal_Int16 aShort; + sal_uInt16 aUShort; + sal_Int32 aLong; + sal_uInt32 aULong; + sal_Int64 aHyper; + sal_uInt64 aUHyper; + float aFloat; + double aDouble; + sal_Unicode const* aString; +}; + +/** specifies the mode of a method. + + A method can be synchron or asynchron (oneway). The const attribute for + methods was removed so that the const values are deprecated. + */ +enum class RTMethodMode +{ + /// indicates an invalid mode + INVALID, + + /// indicates the asynchronous mode of a method + ONEWAY, + + /// @deprecated + ONEWAY_CONST, + + /// indicated the synchronous mode of a method + TWOWAY, + + /// @deprecated + TWOWAY_CONST, + + /** + Indicates an extended attribute getter (that has a 'raises' clause) of an + interface type. + + @since UDK 3.2.0 + */ + ATTRIBUTE_GET, + + /** + Indicates an extended attribute setter (that has a 'raises' clause) of an + interface type. + + @since UDK 3.2.0 + */ + ATTRIBUTE_SET +}; + +/** specifies the mode of a parameter. + + There are three parameter modes which have impact of the handling of the + parameter in the UNO bridges and the UNO code generation. + */ +enum RTParamMode +{ + /// indicates an invalid parameter mode + RT_PARAM_INVALID = 0, + + /// indicates a pure in parameter which is used by value + RT_PARAM_IN = 1, + + /// indicates a pure out parameter which is used by reference + RT_PARAM_OUT = 2, + + /// indicates a in and out parameter which is used also by reference + RT_PARAM_INOUT = 3, + + /** + Indicates a rest parameter (currently only valid for service + constructors). + + This value can be combined with any of RT_PARAM_IN, RT_PARAM_OUT, and + RT_PARAM_INOUT (however, service constructors currently only allow + RT_PARAM_IN, anyway). + + @since UDK 3.2.0 + */ + RT_PARAM_REST = 4 +}; + +/** specifies the type of a reference used in a service description. + */ +enum class RTReferenceType +{ + /// the reference type is unknown + INVALID, + + /** the service support the interface that means an implementation of this + service must implement this interface. + */ + SUPPORTS, + + /** @deprecated + the service observes the interface. + */ + OBSERVES, + + /** the service exports the specified service that means this service + provides also the specified service. + */ + EXPORTS, + + /** @deprecated + the service needs the specified service that means in the context of + this service the specified service will be used or must be available. + */ + NEEDS, + + /** + Indicates a type parameter of a polymorphic struct type template. + + @since UDK 3.2.0 + */ + TYPE_PARAMETER +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/version.h b/include/registry/version.h new file mode 100644 index 000000000..b7c066d41 --- /dev/null +++ b/include/registry/version.h @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_VERSION_H +#define INCLUDED_REGISTRY_VERSION_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + The version of a binary blob that represents a UNOIDL type. + +

    All values between TYPEREG_VERSION_0 and + TYPEREG_MAX_VERSION are valid, where currently unallocated + values represent future versions. Negative values are not valid.

    + + @see typereg::Reader + @see typereg::Writer + + @since UDK 3.2.0 + */ +enum typereg_Version { + /** + Denotes the original version of UNOIDL type blobs. + */ + TYPEREG_VERSION_0, + + /** + Denotes the updated version of UNOIDL type blobs. + +

    This version added support for multiple-inheritance interface types, + extended interface type attributes, single-interface–based + services, interface-based singletons, polymorphic struct types, and + published entities.

    + */ + TYPEREG_VERSION_1, + + /** + Denotes the maximum future version of UNOIDL type blobs. + */ + TYPEREG_MAX_VERSION = SAL_MAX_INT32 +}; + +#ifdef __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/writer.h b/include/registry/writer.h new file mode 100644 index 000000000..8f07437c5 --- /dev/null +++ b/include/registry/writer.h @@ -0,0 +1,262 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_WRITER_H +#define INCLUDED_REGISTRY_WRITER_H + +#include +#include +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Creates a type writer working on a binary blob that represents a UNOIDL type. + +

    Operations on a returned handle are not multi-thread–safe.

    + + @param version the version of the created type writer; must not be negative + + @param documentation the documentation; must not be null + + @param fileName the file name; must not be null (deprecated, use an empty string) + + @param typeClass the type class of the created type writer + + @param published whether the created type writer is published; for a type + class that cannot be published, this should be false + + @param typeName the type name of the created type writer; must not be null + + @param superTypeCount the number of super types of the created type writer + + @param fieldCount the number of fields of the created type writer + + @param methodCount the number of methods of the created type writer + + @param referenceCount the number of references of the created type writer + + @return a handle on the type writer; if an out-of-memory condition occurs, + null is returned, and no type writer is created + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void * typereg_writer_create( + typereg_Version version, rtl_uString const * documentation, + rtl_uString const * fileName, RTTypeClass typeClass, sal_Bool published, + rtl_uString const * typeName, sal_uInt16 superTypeCount, + sal_uInt16 fieldCount, sal_uInt16 methodCount, sal_uInt16 referenceCount) + SAL_THROW_EXTERN_C(); + +/** + Destroys a type writer. + + @param handle a handle on a type writer obtained from a call to + typereg_writer_create; must not be null + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC void typereg_writer_destroy(void * handle) SAL_THROW_EXTERN_C(); + +/** + Sets the type name of a super type of a type writer. + + @param handle a handle on a type writer; must not be null + + @param index a valid index into the range of super types of the given type + writer + + @param typeName the super type name; must not be null + + @return false iff an out-of-memory condition occurred, in which case the type + writer is not modified + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_Bool typereg_writer_setSuperTypeName( + void const * handle, sal_uInt16 index, rtl_uString const * typeName) + SAL_THROW_EXTERN_C(); + +/** + Sets the data of a field of a type writer. + + @param handle a handle on a type writer; must not be null + + @param index a valid index into the range of fields of the given type writer + + @param documentation the documentation of the field; must not be null + + @param fileName the file name of the field; must not be null (deprecated, use an empty string) + + @param flags the flags of the field + + @param name the name of the field; must not be null + + @param typeName the type name of the field; must not be null + + @param valueType the type of the value of the field + + @param valueValue the value of the value of the field + + @return false iff an out-of-memory condition occurred, in which case the type + writer is not modified + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_Bool typereg_writer_setFieldData( + void * handle, sal_uInt16 index, rtl_uString const * documentation, + rtl_uString const * fileName, RTFieldAccess flags, rtl_uString const * name, + rtl_uString const * typeName, RTValueType valueType, + RTConstValueUnion valueValue) + SAL_THROW_EXTERN_C(); + +/** + Sets the data of a method of a type writer. + + @param handle a handle on a type writer; must not be null + + @param index a valid index into the range of methods of the given type writer + + @param documentation the documentation of the method; must not be null + + @param flags the flags of the method + + @param name the name of the method; must not be null + + @param returnTypeName the return type name of the method; must not be null + + @param parameterCount the number of parameters of the method + + @param exceptionCount the number of exceptions of the method + + @return false iff an out-of-memory condition occurred, in which case the type + writer is not modified + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_Bool typereg_writer_setMethodData( + void * handle, sal_uInt16 index, rtl_uString const * documentation, + RTMethodMode flags, rtl_uString const * name, + rtl_uString const * returnTypeName, sal_uInt16 parameterCount, + sal_uInt16 exceptionCount) + SAL_THROW_EXTERN_C(); + +/** + Sets the data of a parameter of a method of a type writer. + + @param handle a handle on a type writer; must not be null + + @param methodIndex a valid index into the range of methods of the given type + writer + + @param parameterIndex a valid index into the range of parameters of the given + method + + @param flags the flags of the parameter + + @param name the name of the parameter; must not be null + + @param typeName the type name of the parameter; must not be null + + @return false iff an out-of-memory condition occurred, in which case the type + writer is not modified + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_Bool typereg_writer_setMethodParameterData( + void const * handle, sal_uInt16 methodIndex, sal_uInt16 parameterIndex, + RTParamMode flags, rtl_uString const * name, rtl_uString const * typeName) + SAL_THROW_EXTERN_C(); + +/** + Sets an exception type name of a method of a type writer. + + @param handle a handle on a type writer; must not be null + + @param methodIndex a valid index into the range of methods of the given type + writer + + @param exceptionIndex a valid index into the range of exceptions of the given + method + + @param typeName the exception type name; must not be null + + @return false iff an out-of-memory condition occurred, in which case the type + writer is not modified + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_Bool typereg_writer_setMethodExceptionTypeName( + void const * handle, sal_uInt16 methodIndex, sal_uInt16 exceptionIndex, + rtl_uString const * typeName) + SAL_THROW_EXTERN_C(); + +/** + Sets the data of a reference of a type writer. + + @param handle a handle on a type writer; must not be null + + @param index a valid index into the range of references of the given type + writer + + @param documentation the documentation of the reference; must not be null + + @param sort the sort of the reference + + @param flags the flags of the reference + + @param typeName the type name of the reference; must not be null + + @return false iff an out-of-memory condition occurred, in which case the type + writer is not modified + + @since UDK 3.2.0 + */ +REG_DLLPUBLIC sal_Bool typereg_writer_setReferenceData( + void * handle, sal_uInt16 index, rtl_uString const * documentation, + RTReferenceType sort, RTFieldAccess flags, rtl_uString const * typeName) + SAL_THROW_EXTERN_C(); + +/** + Returns the blob of a type writer. + + @param handle a handle on a type writer; must not be null + + @param size an out-parameter obtaining the size of the blob; must not be null + + @return a (byte-aligned) pointer to the blob; the returned pointer and the + returned size remain valid until the next function is called on + the given type writer; if an out-of-memory condition occurs, null is returned + and size is not modified + */ +REG_DLLPUBLIC void const * typereg_writer_getBlob(void * handle, sal_uInt32 * size) + SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/registry/writer.hxx b/include/registry/writer.hxx new file mode 100644 index 000000000..4bf672461 --- /dev/null +++ b/include/registry/writer.hxx @@ -0,0 +1,291 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_REGISTRY_WRITER_HXX +#define INCLUDED_REGISTRY_WRITER_HXX + +#include +#include +#include +#include + +#include +#include + +#include + +namespace typereg { + +/** + A type writer working on a binary blob that represents a UNOIDL type. + +

    Instances of this class are not multi-thread–safe.

    + + @since UDK 3.2.0 + */ +class Writer { +public: + /** + Creates a type writer. + + @param version the version of the created type writer; must not be + negative + + @param documentation the documentation + + @param fileName the file name (deprecated, use an empty string) + + @param typeClass the type class of the created type writer + + @param published whether the created type writer is published; for a type + class that cannot be published, this should be false + + @param typeName the type name of the created type writer + + @param superTypeCount the number of super types of the created type + writer + + @param fieldCount the number of fields of the created type writer + + @param methodCount the number of methods of the created type writer + + @param referenceCount the number of references of the created type writer + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + Writer( + typereg_Version version, OUString const & documentation, + OUString const & fileName, RTTypeClass typeClass, bool published, + OUString const & typeName, sal_uInt16 superTypeCount, + sal_uInt16 fieldCount, sal_uInt16 methodCount, + sal_uInt16 referenceCount): + m_handle( + typereg_writer_create( + version, documentation.pData, fileName.pData, typeClass, + published, typeName.pData, superTypeCount, fieldCount, + methodCount, referenceCount)) + { + if (m_handle == nullptr) { + throw std::bad_alloc(); + } + } + + /** + Destroys this Writer instance. + */ + ~Writer() { + typereg_writer_destroy(m_handle); + } + + /** + Sets the type name of a super type of this type writer. + + @param index a valid index into the range of super types of this type + writer + + @param typeName the super type name + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + void setSuperTypeName(sal_uInt16 index, OUString const & typeName) { + if (!typereg_writer_setSuperTypeName(m_handle, index, typeName.pData)) { + throw std::bad_alloc(); + } + } + + /** + Sets the data of a field of this type writer. + + @param index a valid index into the range of fields of this type writer + + @param documentation the documentation of the field + + @param fileName the file name of the field (deprecated, use an empty string) + + @param flags the flags of the field + + @param name the name of the field + + @param typeName the type name of the field + + @param value the value of the field + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + void setFieldData( + sal_uInt16 index, OUString const & documentation, + OUString const & fileName, RTFieldAccess flags, OUString const & name, + OUString const & typeName, RTConstValue const & value) + { + if (!typereg_writer_setFieldData( + m_handle, index, documentation.pData, fileName.pData, flags, + name.pData, typeName.pData, value.m_type, value.m_value)) + { + throw std::bad_alloc(); + } + } + + /** + Sets the data of a method of this type writer. + + @param index a valid index into the range of methods of this type writer + + @param documentation the documentation of the method + + @param flags the flags of the method + + @param name the name of the method + + @param returnTypeName the return type name of the method + + @param parameterCount the number of parameters of the method + + @param exceptionCount the number of exceptions of the method + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + void setMethodData( + sal_uInt16 index, OUString const & documentation, + RTMethodMode flags, OUString const & name, + OUString const & returnTypeName, sal_uInt16 parameterCount, + sal_uInt16 exceptionCount) + { + if (!typereg_writer_setMethodData( + m_handle, index, documentation.pData, flags, name.pData, + returnTypeName.pData, parameterCount, exceptionCount)) + { + throw std::bad_alloc(); + } + } + + /** + Sets the data of a parameter of a method of this type writer. + + @param methodIndex a valid index into the range of methods of this type + writer + + @param parameterIndex a valid index into the range of parameters of the + given method + + @param flags the flags of the parameter + + @param name the name of the parameter + + @param typeName the type name of the parameter + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + void setMethodParameterData( + sal_uInt16 methodIndex, sal_uInt16 parameterIndex, + RTParamMode flags, OUString const & name, + OUString const & typeName) const + { + if (!typereg_writer_setMethodParameterData( + m_handle, methodIndex, parameterIndex, flags, name.pData, + typeName.pData)) + { + throw std::bad_alloc(); + } + } + + /** + Sets an exception type name of a method of this type writer. + + @param methodIndex a valid index into the range of methods of this type + writer + + @param exceptionIndex a valid index into the range of exceptions of the + given method + + @param typeName the exception type name + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + void setMethodExceptionTypeName( + sal_uInt16 methodIndex, sal_uInt16 exceptionIndex, + OUString const & typeName) + { + if (!typereg_writer_setMethodExceptionTypeName( + m_handle, methodIndex, exceptionIndex, typeName.pData)) + { + throw std::bad_alloc(); + } + } + + /** + Sets the data of a reference of this type writer. + + @param index a valid index into the range of references of this type + writer + + @param documentation the documentation of the reference + + @param sort the sort of the reference + + @param flags the flags of the reference + + @param typeName the type name of the reference + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + */ + void setReferenceData( + sal_uInt16 index, OUString const & documentation, + RTReferenceType sort, RTFieldAccess flags, + OUString const & typeName) + { + if (!typereg_writer_setReferenceData( + m_handle, index, documentation.pData, sort, flags, + typeName.pData)) + { + throw std::bad_alloc(); + } + } + + /** + Returns the blob of this type writer. + + @param size an out-parameter obtaining the size of the blob + + @return a (byte-aligned) pointer to the blob; the returned pointer and + the returned size remain valid until the next function is + called on this type writer + + @exception std::bad_alloc is raised if an out-of-memory condition occurs + (in which case size is not modified + */ + void const * getBlob(sal_uInt32 * size) { + void const * p = typereg_writer_getBlob(m_handle, size); + if (p == nullptr) { + throw std::bad_alloc(); + } + return p; + } + +private: + Writer(Writer const &) = delete; + Writer& operator =(Writer const &) = delete; + + void * m_handle; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/alloc.h b/include/rtl/alloc.h new file mode 100644 index 000000000..79a94704c --- /dev/null +++ b/include/rtl/alloc.h @@ -0,0 +1,336 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_ALLOC_H +#define INCLUDED_RTL_ALLOC_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** Allocate memory. + + A call to this function will return NULL upon the requested + memory size being either zero or larger than currently allocatable. + + @param[in] Bytes memory size. + @return pointer to the allocated memory. + */ +SAL_DLLPUBLIC void * SAL_CALL rtl_allocateMemory ( + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + + +/** Reallocate memory. + + A call to this function with parameter 'Ptr' being NULL + is equivalent to a rtl_allocateMemory() call. + A call to this function with parameter 'Bytes' being 0 + is equivalent to a rtl_freeMemory() call. + + @see rtl_allocateMemory() + @see rtl_freeMemory() + + @param[in] Ptr pointer to the previously allocated memory. + @param[in] Bytes new memory size. + @return pointer to the reallocated memory. May differ from Ptr. + */ +SAL_DLLPUBLIC void * SAL_CALL rtl_reallocateMemory ( + void * Ptr, + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + + +/** Free memory. + @param[in] Ptr pointer to the previously allocated memory. + @return none. Memory is released. Ptr is invalid. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_freeMemory ( + void * Ptr +) SAL_THROW_EXTERN_C(); + +/** Allocate and zero memory. + + A call to this function will return NULL upon the requested + memory size being either zero or larger than currently allocatable. + + @param[in] Bytes memory size. + @return pointer to the allocated and zero'ed memory. + */ +SAL_DLLPUBLIC void * SAL_CALL rtl_allocateZeroMemory ( + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + +/** Zero memory + + Fills a block of memory with zeros in a way that is guaranteed to be secure + + @param[in] Ptr pointer to the previously allocated memory. + @param[in] Bytes memory size. + + @since LibreOffice 5.0 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_secureZeroMemory ( + void * Ptr, + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + + +/** Zero and free memory. + @param[in] Ptr pointer to the previously allocated memory. + @param[in] Bytes memory size. + @return none. Memory is zero'ed with rtl_secureZeroMemory() and released. + Ptr is invalid. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_freeZeroMemory ( + void * Ptr, + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + +/** Allocate aligned memory. + + A call to this function will return NULL upon the requested + memory size being either zero or larger than currently allocatable. + + Memory obtained through this function must be freed with + rtl_freeAlignedMemory(). + + @param[in] Alignment alignment in bytes, must be a power of two multiple of + sizeof(void*). + @param[in] Bytes memory size. + @return pointer to the allocated memory. + + @since LibreOffice 4.3 + */ +SAL_DLLPUBLIC void* SAL_CALL rtl_allocateAlignedMemory ( + sal_Size Alignment, + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + + +/** Free memory allocated with rtl_allocateAlignedMemory(). + + @param[in] Ptr pointer to the previously allocated memory. + @return none. Memory is released. Ptr is invalid. + + @since LibreOffice 4.3 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_freeAlignedMemory ( + void * Ptr +) SAL_THROW_EXTERN_C(); + + +/** Opaque rtl_arena_type. + */ +typedef struct SAL_DLLPUBLIC_RTTI rtl_arena_st rtl_arena_type; + +#define RTL_ARENA_NAME_LENGTH 31 + + +/** + * @param[in] pName descriptive name; for debugging purposes. + * @param[in] quantum resource allocation unit / granularity; rounded up to next power of 2. + * @param[in] quantum_cache_max no longer used, should be 0. + * @param[in] source_arena passed as argument to source_alloc, source_free; usually NULL. + * @param[in] source_alloc function to allocate resources; usually rtl_arena_alloc. + * @param[in] source_free function to free resources; usually rtl_arena_free. + * @param[in] nFlags flags; usually 0. + * + * @return pointer to rtl_arena_type, or NULL upon failure. + * + * @see rtl_arena_destroy() + */ +SAL_DLLPUBLIC rtl_arena_type * SAL_CALL rtl_arena_create ( + const char * pName, + sal_Size quantum, + sal_Size quantum_cache_max, + rtl_arena_type * source_arena, + void * (SAL_CALL * source_alloc)(rtl_arena_type *, sal_Size *), + void (SAL_CALL * source_free) (rtl_arena_type *, void *, sal_Size), + int nFlags +) SAL_THROW_EXTERN_C(); + + +/** + * @param[in] pArena the arena to destroy. + * @return None + * + * @see rtl_arena_create() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_arena_destroy ( + rtl_arena_type * pArena +) SAL_THROW_EXTERN_C(); + + +/** + * @param[in] pArena arena from which resource is allocated. + * @param[in,out] pBytes size of resource to allocate. + * + * @return allocated resource, or NULL upon failure. + * + * @see rtl_arena_free() + */ +SAL_DLLPUBLIC void * SAL_CALL rtl_arena_alloc ( + rtl_arena_type * pArena, + sal_Size * pBytes +) SAL_THROW_EXTERN_C(); + + +/** + * @param[in] pArena arena from which resource was allocated. + * @param[in] pAddr resource to free. + * @param[in] nBytes size of resource. + * + * @return None. + * + * @see rtl_arena_alloc() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_arena_free ( + rtl_arena_type * pArena, + void * pAddr, + sal_Size nBytes +) SAL_THROW_EXTERN_C(); + + +/** Opaque rtl_cache_type. + */ +typedef struct rtl_cache_st rtl_cache_type; + +#define RTL_CACHE_NAME_LENGTH 31 + +#define RTL_CACHE_FLAG_BULKDESTROY 1 /* obsolete */ + +/** + * @param[in] pName descriptive name; for debugging purposes. + * @param[in] nObjSize object size. + * @param[in] nObjAlign object alignment; usually 0 for suitable default. + * @param[in] constructor object constructor callback function; returning 1 for success or 0 for failure. + * @param[in] destructor object destructor callback function. + * @param[in] reclaim reclaim callback function. + * @param[in] pUserArg opaque argument passed to callback functions. + * @param[in] pSource unused argument (should be null). + * @param[in] nFlags flags (unused). + * + * @return pointer to rtl_cache_type, or NULL upon failure. + * + * @see rtl_cache_destroy() + */ +SAL_DLLPUBLIC rtl_cache_type * SAL_CALL rtl_cache_create ( + const char * pName, + sal_Size nObjSize, + sal_Size nObjAlign, + int (SAL_CALL * constructor)(void * pObj, void * pUserArg), + void (SAL_CALL * destructor) (void * pObj, void * pUserArg), + void (SAL_CALL * reclaim) (void * pUserArg), + void * pUserArg, + rtl_arena_type * pSource, + int nFlags +) SAL_THROW_EXTERN_C(); + + +/** + * @param[in] pCache the cache to destroy. + * + * @return None. + * + * @see rtl_cache_create() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_cache_destroy ( + rtl_cache_type * pCache +) SAL_THROW_EXTERN_C(); + + +/** + * @param[in] pCache cache from which object is allocated. + * + * @return pointer to the allocated object, or NULL upon failure. + */ +SAL_DLLPUBLIC void * SAL_CALL rtl_cache_alloc ( + rtl_cache_type * pCache +) SAL_THROW_EXTERN_C(); + + +/** + * @param[in] pCache cache from which object was allocated. + * @param[in] pObj object to free. + * + * @return None. + * + * @see rtl_cache_alloc() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_cache_free ( + rtl_cache_type * pCache, + void * pObj +) SAL_THROW_EXTERN_C(); + + +#ifdef LIBO_INTERNAL_ONLY + +/** @cond INTERNAL */ +/** rtl_alloc_preInit + * + * This function, is called at the beginning and again + * at the end of LibreOfficeKit pre-initialization to enable + * various optimizations. + * + * Its function is to annotate a section @start = true + * to end (@start = false) via. two calls. Inside this + * section string allocators are replaced with ones which cause the + * strings to be staticized at the end of the section. + * + * This brings a number of constraints - in particular no + * string allocated outside the section should be freed + * inside it, practically this means starting the section + * as early as possible. No string allocated inside the + * section will be freed subsequently as they are + * staticized. + * + * This method is not thread-safe, nor intended for use in + * a threaded context, cf. previous constraints. + * + * It is almost certainly not the method that you want, + * use with extraordinary care referring to the + * implementation. + * + * @since LibreOffice 6.1 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_alloc_preInit ( + sal_Bool start +) SAL_THROW_EXTERN_C(); +/** @endcond */ + +#endif + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_ALLOC_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/bootstrap.h b/include/rtl/bootstrap.h new file mode 100644 index 000000000..e532cd0e3 --- /dev/null +++ b/include/rtl/bootstrap.h @@ -0,0 +1,224 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_BOOTSTRAP_H +#define INCLUDED_RTL_BOOTSTRAP_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + @file + + The described concept provides a platform independent way to access + minimum bootstrap settings for every application by explicitly or + implicitly passing the values to the application. + + MULTI-LEVEL STRATEGY FOR RETRIEVAL OF BOOTSTRAP VALUES: + + The 1st level is tried first. On failure, + the next level is tried. Every query starts at the first level again, so + that one setting may be taken from the 3rd and one from the 1st level. + + 1st level: explicitly set variables via rtl_bootstrap_set() + + 2nd level: command line arguments. A `-env:SETTINGNAME=value` is given on + command line. This allows giving an application a certain setting, even + if an ini-file exists (especially useful for e.g. daemons that want to + start an executable with dynamical changing settings). + + 3rd level: environment variables. The application tries to get the + setting from the environment. + + 4th level: executable ini-file. Every application looks for an ini-file. + The filename defaults to `/absolute/path/to/executable[rc|.ini]` + without .bin or .exe suffix. The ini-filename can be + set by the special command line parameter + `-env:INIFILENAME=/absolute/path/to/inifile` at runtime or it may + be set at compile time by an API-call. + + 5th level: URE_BOOTSTRAP ini-file. If the bootstrap variable URE_BOOTSTRAP + expands to the URL of an ini-file, that ini-file is searched. + + 6th level: default. An application can have some default settings decided + at compile time, which allow the application to run even with no + deployment settings. + + If neither of the above levels leads to a successful retrieval of the value + (no default possible), the application may fail to start. + + NAMING CONVENTIONS + + Naming conventions for names of bootstrap values: + Names may only include characters, that are allowed characters for + environment variables. This excludes '.', ' ', ';', ':' and any non-ascii + character. Names are case insensitive. + + An ini-file is only allowed to have one section, which must be named + `[Bootstrap]` with the square brackets. + The section may be omitted. + The section name does not appear in the name of the corresponding + environment variable or commandline arg. + Values may be arbitrary unicode strings, they must be encoded in UTF8. + + Example: + + in an ini-file: + + [Sectionname] + Name=value + + + as commandline arg: + -env:Name=value + + as environment: + - setenv Name value + - set Name=value + + SPECIAL VARIABLES: + + - INIFILENAME
    + This variable allows to set the inifilename. This makes only sense, if the filename + is different than the executable file name. It must be given on command line. If it is + given the executable ini-file is ignored. +*/ + +/** may be called by an application to set an ini-filename. + + Must be called before rtl_bootstrap_get(). May not be called twice. + If it is never called, the filename is based on the name of the executable, + with the suffix ".ini" on Windows or "rc" on Unix. + + @param pFileUri URL of the inifile with path but WITHOUT suffix (.ini or rc) +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_setIniFileName( rtl_uString *pFileUri ); + +/** + @param pName + The name of the bootstrap setting to be retrieved. + @param[out] ppValue + Contains always a valid rtl_uString pointer. + @param pDefault + maybe NULL. If once the default is + returned, successive calls always return this + default value, even when called with different + defaults. + + @retval sal_True when a value could be retrieved successfully. + When a pDefault value is given, + the function always returns sal_True. + @retval sal_False when none of the 4 methods gave a value. + ppValue then contains an empty string. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_bootstrap_get( + rtl_uString *pName, rtl_uString **ppValue, rtl_uString *pDefault ); + +/** Sets a bootstrap parameter. + + @param pName + name of bootstrap parameter + @param pValue + value of bootstrap parameter +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_set( + rtl_uString * pName, rtl_uString * pValue ); + + +typedef void * rtlBootstrapHandle; + +/** + Opens a bootstrap argument container. + @param[in] pIniName The name of the ini-file to use, if NULL defaults + to the executables name + @return Handle for a bootstrap argument container +*/ +SAL_DLLPUBLIC rtlBootstrapHandle SAL_CALL rtl_bootstrap_args_open(rtl_uString * pIniName); + +/** + Closes a bootstrap argument container. + @param[in] handle The handle got by rtl_bootstrap_args_open() +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_args_close(rtlBootstrapHandle handle) + SAL_THROW_EXTERN_C(); + +/** + @param[in] handle The handle got by rtl_bootstrap_args_open() + @param[in] pName The name of the variable to be retrieved + @param[out] ppValue The result of the retrieval. *ppValue may be null in case of failure. + @param[in] pDefault The default value for the retrieval, may be NULL + + @return The status of the retrieval, sal_True on success. +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_bootstrap_get_from_handle( + rtlBootstrapHandle handle, rtl_uString *pName, rtl_uString **ppValue, rtl_uString *pDefault); + + +/** Returns the name of the inifile associated with this handle. + + @param[in] handle The handle got by rtl_bootstrap_args_open() + @param[out] ppIniName contains after the call the name of the ini-filename. +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_get_iniName_from_handle( + rtlBootstrapHandle handle, rtl_uString ** ppIniName); + +/** Expands a macro using bootstrap variables. + + @param[in] handle The handle got by rtl_bootstrap_args_open() + @param[in,out] macro The macro to be expanded +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_expandMacros_from_handle( + rtlBootstrapHandle handle, rtl_uString ** macro ); + +/** Expands a macro using default bootstrap variables. + + @param[in,out] macro The macro to be expanded +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_expandMacros( + rtl_uString ** macro); + +/** Escapes special characters ("$" and "\"). + + @param value + an arbitrary, non-NULL value + + @param[out] encoded + the given value with all occurrences of special characters ("$" and "\") escaped + + @since UDK 3.2.9 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_bootstrap_encode( + rtl_uString const * value, rtl_uString ** encoded ); + +#ifdef __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/bootstrap.hxx b/include/rtl/bootstrap.hxx new file mode 100644 index 000000000..4d8db0690 --- /dev/null +++ b/include/rtl/bootstrap.hxx @@ -0,0 +1,231 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_BOOTSTRAP_HXX +#define INCLUDED_RTL_BOOTSTRAP_HXX + +#include "sal/config.h" + +#include + +#include "rtl/ustring.hxx" +#include "rtl/bootstrap.h" + +namespace rtl +{ + class Bootstrap + { + void * _handle; + + Bootstrap( Bootstrap const & ) SAL_DELETED_FUNCTION; + Bootstrap & operator = ( Bootstrap const & ) SAL_DELETED_FUNCTION; + + public: + /** + * @see rtl_bootstrap_setIniFileName() + */ + static inline void SAL_CALL setIniFilename( const ::rtl::OUString &sFileUri ); + + /** Retrieves a bootstrap parameter + @param sName name of the bootstrap value. case insensitive. + @param[out] outValue On success contains the value, otherwise + an empty string. + @return false, if no value could be retrieved, otherwise true + @see rtl_bootstrap_get() + */ + static inline bool get( + const ::rtl::OUString &sName, + ::rtl::OUString &outValue ); + + /** Retrieves a bootstrap parameter + + @param sName name of the bootstrap value. case insensitive. + @param[out] outValue Contains the value associated with sName. + @param aDefault if none of the other methods retrieved a value, + outValue is assigned to aDefault. + + @see rtl_bootstrap_get() + */ + static inline void get( + const ::rtl::OUString &sName, + ::rtl::OUString &outValue, + const ::rtl::OUString &aDefault ); + + /** Sets a bootstrap parameter. + + @param name + name of bootstrap parameter + @param value + value of bootstrap parameter + + @see rtl_bootstrap_set() + */ + static inline void set( ::rtl::OUString const & name, ::rtl::OUString const & value ); + + /** default ctor. + */ + inline Bootstrap(); + + /** Opens a bootstrap argument container + @see rtl_bootstrap_args_open() + */ + inline Bootstrap(const rtl::OUString & iniName); + + /** Closes a bootstrap argument container + @see rtl_bootstrap_args_close() + */ + inline ~Bootstrap(); + + /** Retrieves a bootstrap argument. + + It is first tried to retrieve the value via the global function + and second via the special bootstrap container. + @see rtl_bootstrap_get_from_handle() + */ + + inline bool getFrom(const ::rtl::OUString &sName, + ::rtl::OUString &outValue) const; + + /** Retrieves a bootstrap argument. + + It is first tried to retrieve the value via the global function + and second via the special bootstrap container. + @see rtl_bootstrap_get_from_handle() + */ + inline void getFrom(const ::rtl::OUString &sName, + ::rtl::OUString &outValue, + const ::rtl::OUString &aDefault) const; + + /** Retrieves the name of the underlying ini-file. + @see rtl_bootstrap_get_iniName_from_handle() + */ + inline void getIniName(::rtl::OUString & iniName) const; + + /** Expands a macro using bootstrap variables. + + @param[in,out] macro The macro to be expanded + */ + void expandMacrosFrom( ::rtl::OUString & macro ) const + { rtl_bootstrap_expandMacros_from_handle( _handle, ¯o.pData ); } + + /** Expands a macro using default bootstrap variables. + + @param[in,out] macro The macro to be expanded + */ + static void expandMacros( ::rtl::OUString & macro ) + { rtl_bootstrap_expandMacros( ¯o.pData ); } + + /** Provides the bootstrap internal handle. + + @return bootstrap handle + */ + rtlBootstrapHandle getHandle() const + { return _handle; } + + /** Escapes special characters ("$" and "\"). + + @param value + an arbitrary value + + @return + the given value, with all occurrences of special characters ("$" and + "\") escaped + + @since UDK 3.2.9 + */ + static inline ::rtl::OUString encode( ::rtl::OUString const & value ); + }; + + + // IMPLEMENTATION + + inline void Bootstrap::setIniFilename( const ::rtl::OUString &sFile ) + { + rtl_bootstrap_setIniFileName( sFile.pData ); + } + + inline bool Bootstrap::get( const ::rtl::OUString &sName, + ::rtl::OUString & outValue ) + { + return rtl_bootstrap_get( sName.pData , &(outValue.pData) , NULL ); + } + + inline void Bootstrap::get( const ::rtl::OUString &sName, + ::rtl::OUString & outValue, + const ::rtl::OUString & sDefault ) + { + rtl_bootstrap_get( sName.pData , &(outValue.pData) , sDefault.pData ); + } + + inline void Bootstrap::set( ::rtl::OUString const & name, ::rtl::OUString const & value ) + { + rtl_bootstrap_set( name.pData, value.pData ); + } + + inline Bootstrap::Bootstrap() + { + _handle = NULL; + } + + inline Bootstrap::Bootstrap(const rtl::OUString & iniName) + { + if(!iniName.isEmpty()) + _handle = rtl_bootstrap_args_open(iniName.pData); + + else + _handle = NULL; + } + + inline Bootstrap::~Bootstrap() + { + rtl_bootstrap_args_close(_handle); + } + + + inline bool Bootstrap::getFrom(const ::rtl::OUString &sName, + ::rtl::OUString &outValue) const + { + return rtl_bootstrap_get_from_handle(_handle, sName.pData, &outValue.pData, NULL); + } + + inline void Bootstrap::getFrom(const ::rtl::OUString &sName, + ::rtl::OUString &outValue, + const ::rtl::OUString &aDefault) const + { + rtl_bootstrap_get_from_handle(_handle, sName.pData, &outValue.pData, aDefault.pData); + } + + inline void Bootstrap::getIniName(::rtl::OUString & iniName) const + { + rtl_bootstrap_get_iniName_from_handle(_handle, &iniName.pData); + } + + inline ::rtl::OUString Bootstrap::encode( ::rtl::OUString const & value ) + { + ::rtl::OUString encoded; + rtl_bootstrap_encode(value.pData, &encoded.pData); + return encoded; + } +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/byteseq.h b/include/rtl/byteseq.h new file mode 100644 index 000000000..2acb9b745 --- /dev/null +++ b/include/rtl/byteseq.h @@ -0,0 +1,331 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_BYTESEQ_H +#define INCLUDED_RTL_BYTESEQ_H + +#include "sal/config.h" + +#include "rtl/alloc.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** Assures that the reference count of the given byte sequence is one. Otherwise a new copy + of the sequence is created with a reference count of one. + + @param ppSequence sequence +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_reference2One( + sal_Sequence ** ppSequence ) + SAL_THROW_EXTERN_C(); + +/** Reallocates length of byte sequence. + + @param ppSequence sequence + @param nSize new size of sequence +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_realloc( + sal_Sequence ** ppSequence, sal_Int32 nSize ) + SAL_THROW_EXTERN_C(); + +/** Acquires the byte sequence + + @param pSequence sequence, that is to be acquired +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_acquire( + sal_Sequence *pSequence ) + SAL_THROW_EXTERN_C(); + +/** Releases the byte sequence. If the refcount drops to zero, the sequence is freed. + + @param pSequence sequence, that is to be released; invalid after call +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_release( + sal_Sequence *pSequence ) + SAL_THROW_EXTERN_C(); + +/** Constructs a bytes sequence with length nLength. All bytes are set to zero. + + @param ppSequence inout sequence; on entry *ppSequence may be null, otherwise it is released; + after the call, *ppSequence contains the newly constructed sequence + @param nLength length of new sequence +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_construct( + sal_Sequence **ppSequence , sal_Int32 nLength ) + SAL_THROW_EXTERN_C(); + +/** Constructs a bytes sequence with length nLength. The data is not initialized. + + @param ppSequence inout sequence; on entry *ppSequence may be null, otherwise it is released; + after the call, *ppSequence contains the newly constructed sequence + @param nLength length of new sequence +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_constructNoDefault( + sal_Sequence **ppSequence , sal_Int32 nLength ) + SAL_THROW_EXTERN_C(); + +/** Constructs a byte sequence with length nLength and copies nLength bytes from pData. + + @param ppSequence inout sequence; on entry *ppSequence may be null, otherwise it is released; + after the call, *ppSequence contains the newly constructed sequence + @param pData initial data + @param nLength length of new sequence +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_constructFromArray( + sal_Sequence **ppSequence, const sal_Int8 *pData , sal_Int32 nLength ) + SAL_THROW_EXTERN_C(); + +/** Assigns the byte sequence pSequence to *ppSequence. + + @param ppSequence inout sequence; on entry *ppSequence may be null, otherwise it is released; + after the call, *ppSequence references pSequence + @param pSequence the source sequence +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_byte_sequence_assign( + sal_Sequence **ppSequence , sal_Sequence *pSequence ) + SAL_THROW_EXTERN_C(); + +/** Compares two byte sequences. + + @return true, if the data within the sequences are identical; false otherwise +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_byte_sequence_equals( + sal_Sequence *pSequence1 , sal_Sequence *pSequence2 ) + SAL_THROW_EXTERN_C(); + +/** Returns the data array pointer of the sequence. + + @return read-pointer to the data array of the sequence. If rtl_byte_sequence_reference2One() + has been called before, the pointer may be casted to a non const pointer and + the sequence may be modified +*/ +SAL_DLLPUBLIC const sal_Int8 *SAL_CALL rtl_byte_sequence_getConstArray( + sal_Sequence *pSequence ) + SAL_THROW_EXTERN_C(); + +/** Returns the length of the sequence + + @param pSequence sequence handle + @return length of the sequence +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_byte_sequence_getLength( + sal_Sequence *pSequence ) + SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +namespace rtl +{ + +enum __ByteSequence_NoDefault +{ + /** This enum value can be used to create a bytesequence with uninitialized data + */ + BYTESEQ_NODEFAULT = 0xcafe +}; + +enum __ByteSequence_NoAcquire +{ + /** This enum value can be used to create a bytesequence from a C-Handle without + acquiring the handle. + */ + BYTESEQ_NOACQUIRE = +#if defined _MSC_VER + int(0xcafebabe) +#else + 0xcafebabe +#endif +}; + +/** C++ class representing a SAL byte sequence. + C++ Sequences are reference counted and shared, so the sequence keeps a handle to its data. + To keep value semantics, copies are only generated if the sequence is to be modified + (new handle). +*/ +class SAL_WARN_UNUSED ByteSequence +{ + /** sequence handle + */ + sal_Sequence * _pSequence; + +public: + /// @cond INTERNAL + // these are here to force memory de/allocation to sal lib. + static void * SAL_CALL operator new ( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + static void SAL_CALL operator delete ( void * pMem ) + { ::rtl_freeMemory( pMem ); } + static void * SAL_CALL operator new ( size_t, void * pMem ) + { return pMem; } + static void SAL_CALL operator delete ( void *, void * ) + {} + /// @endcond + + /** Default constructor: Creates an empty sequence. + */ + inline ByteSequence(); + /** Copy constructor: Creates a copy of given sequence. + + @param rSeq another byte sequence + */ + inline ByteSequence( const ByteSequence & rSeq ); +#if defined LIBO_INTERNAL_ONLY + inline ByteSequence( ByteSequence && rSeq ) noexcept; +#endif + /** Copy constructor Creates a copy from the C-Handle. + + @param pSequence another byte sequence handle + */ + inline ByteSequence( sal_Sequence *pSequence ); + /** Constructor: Creates a copy of given data bytes. + + @param pElements an array of bytes + @param len number of bytes + */ + inline ByteSequence( const sal_Int8 * pElements, sal_Int32 len ); + /** Constructor: Creates sequence of given length and initializes all bytes to 0. + + @param len initial sequence length + */ + inline ByteSequence( sal_Int32 len ); + /** Constructor: Creates sequence of given length and does NOT initialize data. + Use this ctor for performance optimization only. + + @param len initial sequence length + @param nodefault dummy parameter forcing explicit BYTESEQ_NODEFAULT + */ + inline ByteSequence( sal_Int32 len , enum __ByteSequence_NoDefault nodefault ); + /** Constructor: + Creates a sequence from a C-Handle without acquiring the handle, thus taking + over ownership. Eitherway the handle is released by the destructor. + This ctor is useful, when working with a c-interface (it safes a pair of + acquire and release call and is thus a performance optimization only). + + @param pSequence sequence handle to be taken over + @param noacquire dummy parameter forcing explicit BYTESEQ_NOACQUIRE + */ + inline ByteSequence( sal_Sequence *pSequence , enum __ByteSequence_NoAcquire noacquire ); + /** Destructor: Releases sequence handle. Last handle will free memory. + */ + inline ~ByteSequence(); + + /** Assignment operator: Acquires given sequence handle and releases a previously set handle. + + @param rSeq another byte sequence + @return this sequence + */ + inline ByteSequence & SAL_CALL operator = ( const ByteSequence & rSeq ); +#if defined LIBO_INTERNAL_ONLY + inline ByteSequence & operator = ( ByteSequence && rSeq ) noexcept; +#endif + + /** Gets the length of sequence. + + @return length of sequence + */ + sal_Int32 SAL_CALL getLength() const + { return _pSequence->nElements; } + + /** Gets a pointer to byte array for READING. If the sequence has a length of 0, then the + returned pointer is undefined. + + @return pointer to byte array + */ + const sal_Int8 * SAL_CALL getConstArray() const + { return reinterpret_cast(_pSequence->elements); } + /** Gets a pointer to elements array for READING AND WRITING. In general if the sequence + has a handle acquired by other sequences (reference count > 1), then a new sequence is + created copying all bytes to keep value semantics! + If the sequence has a length of 0, then the returned pointer is undefined. + + @return pointer to elements array + */ + inline sal_Int8 * SAL_CALL getArray(); + + /** Non-const index operator: + Obtains a reference to byte indexed at given position. + In general if the sequence has a handle acquired by other + sequences (reference count > 1), then a new sequence is created + copying all bytes to keep value semantics! + + @attention + The implementation does NOT check for array bounds! + + @param nIndex index + @return non-const C++ reference to element at index nIndex + */ + inline sal_Int8 & SAL_CALL operator [] ( sal_Int32 nIndex ); + + /** Const index operator: Obtains a reference to byte indexed at given position. + The implementation does NOT check for array bounds! + + @param nIndex index + @return const C++ reference to byte at element of index nIndex + */ + const sal_Int8 & SAL_CALL operator [] ( sal_Int32 nIndex ) const + { return getConstArray()[ nIndex ]; } + + /** Equality operator: Compares two sequences. + + @param rSeq another byte sequence (right side) + @return true if both sequences are equal, false otherwise + */ + inline bool SAL_CALL operator == ( const ByteSequence & rSeq ) const; + /** Unequality operator: Compares two sequences. + + @param rSeq another byte sequence (right side) + @return false if both sequences are equal, true otherwise + */ + inline bool SAL_CALL operator != ( const ByteSequence & rSeq ) const; + + /** Reallocates sequence to new length. If the sequence has a handle acquired by other sequences + (reference count > 1), then the remaining elements are copied to a new sequence handle to + keep value semantics! + + @param nSize new size of sequence + */ + inline void SAL_CALL realloc( sal_Int32 nSize ); + + /** Returns the UNacquired C handle of the sequence + + @return UNacquired handle of the sequence + */ + sal_Sequence * SAL_CALL getHandle() const + { return _pSequence; } + /** Returns the UNacquired C handle of the sequence (for compatibility reasons) + + @return UNacquired handle of the sequence + */ + sal_Sequence * SAL_CALL get() const + { return _pSequence; } +}; + +} +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/byteseq.hxx b/include/rtl/byteseq.hxx new file mode 100644 index 000000000..33118cd8b --- /dev/null +++ b/include/rtl/byteseq.hxx @@ -0,0 +1,144 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_BYTESEQ_HXX +#define INCLUDED_RTL_BYTESEQ_HXX + +#include "rtl/byteseq.h" + +#include +#include + +namespace rtl +{ + + +inline ByteSequence::ByteSequence() + : _pSequence( NULL ) +{ + ::rtl_byte_sequence_construct( &_pSequence, 0 ); +} + +inline ByteSequence::ByteSequence( const ByteSequence & rSeq ) + : _pSequence( NULL ) +{ + ::rtl_byte_sequence_assign( &_pSequence, rSeq._pSequence ); +} + +#if defined LIBO_INTERNAL_ONLY +inline ByteSequence::ByteSequence( ByteSequence && rSeq ) noexcept + : _pSequence(rSeq._pSequence) +{ + rSeq._pSequence = nullptr; +} +#endif + +inline ByteSequence::ByteSequence( sal_Sequence *pSequence) + : _pSequence( pSequence ) +{ + ::rtl_byte_sequence_acquire( pSequence ); +} + +inline ByteSequence::ByteSequence( const sal_Int8 * pElements, sal_Int32 len ) + : _pSequence( NULL ) +{ + ::rtl_byte_sequence_constructFromArray( &_pSequence, pElements, len ); + if (_pSequence == NULL) + throw ::std::bad_alloc(); +} + +inline ByteSequence::ByteSequence( sal_Int32 len, enum __ByteSequence_NoDefault ) + : _pSequence( NULL ) +{ + ::rtl_byte_sequence_constructNoDefault( &_pSequence, len ); + if (_pSequence == NULL) + throw ::std::bad_alloc(); +} + +inline ByteSequence::ByteSequence( sal_Sequence *pSequence, enum __ByteSequence_NoAcquire ) + : _pSequence( pSequence ) +{ +} + +inline ByteSequence::ByteSequence( sal_Int32 len ) + : _pSequence( NULL ) +{ + ::rtl_byte_sequence_construct( &_pSequence, len ); + if (_pSequence == NULL) + throw ::std::bad_alloc(); +} + +inline ByteSequence::~ByteSequence() +{ + ::rtl_byte_sequence_release( _pSequence ); +} + +inline ByteSequence & ByteSequence::operator = ( const ByteSequence & rSeq ) +{ + ::rtl_byte_sequence_assign( &_pSequence, rSeq._pSequence ); + return *this; +} + +#if defined LIBO_INTERNAL_ONLY +inline ByteSequence & ByteSequence::operator = ( ByteSequence && rSeq ) noexcept +{ + ::rtl_byte_sequence_release(_pSequence); + _pSequence = rSeq._pSequence; + rSeq._pSequence = nullptr; + return *this; +} +#endif + +inline bool ByteSequence::operator == ( const ByteSequence & rSeq ) const +{ + return ::rtl_byte_sequence_equals( _pSequence, rSeq._pSequence ); +} + +inline sal_Int8 * ByteSequence::getArray() +{ + ::rtl_byte_sequence_reference2One( &_pSequence ); + if (_pSequence == NULL) + throw ::std::bad_alloc(); + return reinterpret_cast(_pSequence->elements); +} + +inline void ByteSequence::realloc( sal_Int32 nSize ) +{ + ::rtl_byte_sequence_realloc( &_pSequence, nSize ); + if (_pSequence == NULL) + throw ::std::bad_alloc(); +} + +inline sal_Int8 & ByteSequence::operator [] ( sal_Int32 nIndex ) +{ + return getArray()[ nIndex ]; +} + +inline bool ByteSequence::operator != ( const ByteSequence & rSeq ) const +{ + return (! operator == ( rSeq )); +} + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/character.hxx b/include/rtl/character.hxx new file mode 100644 index 000000000..580106353 --- /dev/null +++ b/include/rtl/character.hxx @@ -0,0 +1,526 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_CHARACTER_HXX +#define INCLUDED_RTL_CHARACTER_HXX + +#include "sal/config.h" + +#include +#include + +#include "sal/types.h" + +#if defined LIBO_INTERNAL_ONLY +#include +#endif + +namespace rtl +{ +/** Check for Unicode code point. + + @param code An integer. + + @return True if code is a Unicode code point. + + @since LibreOffice 5.2 +*/ +inline SAL_CONSTEXPR bool isUnicodeCodePoint(sal_uInt32 code) { return code <= 0x10FFFF; } + +/** Check for ASCII character. + + @param code A Unicode code point. + + @return True if code is an ASCII character (0x00--0x7F). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAscii(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code <= 0x7F; +} + +#if defined LIBO_INTERNAL_ONLY +bool isAscii(char) = delete; +bool isAscii(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAscii(T code) +{ + return isAscii(sal_uInt32(code)); +} +#endif + +/** Check for ASCII lower case character. + + @param code A Unicode code point. + + @return True if code is an ASCII lower case alphabetic character (ASCII + 'a'--'z'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiLowerCase(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= 'a' && code <= 'z'; +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiLowerCase(char) = delete; +bool isAsciiLowerCase(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiLowerCase(T code) +{ + return isAsciiLowerCase(sal_uInt32(code)); +} +#endif + +/** Check for ASCII upper case character. + + @param code A Unicode code point. + + @return True if code is an ASCII upper case alphabetic character (ASCII + 'A'--'Z'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiUpperCase(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= 'A' && code <= 'Z'; +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiUpperCase(char) = delete; +bool isAsciiUpperCase(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiUpperCase(T code) +{ + return isAsciiUpperCase(sal_uInt32(code)); +} +#endif + +/** Check for ASCII alphabetic character. + + @param code A Unicode code point. + + @return True if code is an ASCII alphabetic character (ASCII 'A'--'Z' or + 'a'--'z'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiAlpha(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return isAsciiLowerCase(code) || isAsciiUpperCase(code); +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiAlpha(char) = delete; +bool isAsciiAlpha(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiAlpha(T code) +{ + return isAsciiAlpha(sal_uInt32(code)); +} +#endif + +/** Check for ASCII digit character. + + @param code A Unicode code point. + + @return True if code is an ASCII (decimal) digit character (ASCII + '0'--'9'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiDigit(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= '0' && code <= '9'; +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiDigit(char) = delete; +bool isAsciiDigit(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiDigit(T code) +{ + return isAsciiDigit(sal_uInt32(code)); +} +#endif + +/** Check for ASCII alphanumeric character. + + @param code A Unicode code point. + + @return True if code is an ASCII alphanumeric character (ASCII '0'--'9', + 'A'--'Z', or 'a'--'z'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiAlphanumeric(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return isAsciiDigit(code) || isAsciiAlpha(code); +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiAlphanumeric(char) = delete; +bool isAsciiAlphanumeric(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiAlphanumeric(T code) +{ + return isAsciiAlphanumeric(sal_uInt32(code)); +} +#endif + +/** Check for ASCII canonic hexadecimal digit character. + + @param code A Unicode code point. + + @return True if code is an ASCII canonic (i.e., upper case) hexadecimal + digit character (ASCII '0'--'9' or 'A'--'F'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiCanonicHexDigit(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return isAsciiDigit(code) || (code >= 'A' && code <= 'F'); +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiCanonicHexDigit(char) = delete; +bool isAsciiCanonicHexDigit(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiCanonicHexDigit(T code) +{ + return isAsciiCanonicHexDigit(sal_uInt32(code)); +} +#endif + +/** Check for ASCII hexadecimal digit character. + + @param code A Unicode code point. + + @return True if code is an ASCII hexadecimal digit character (ASCII + '0'--'9', 'A'--'F', or 'a'--'f'). + + @since LibreOffice 4.1 + */ +inline SAL_CONSTEXPR bool isAsciiHexDigit(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return isAsciiCanonicHexDigit(code) || (code >= 'a' && code <= 'f'); +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiHexDigit(char) = delete; +bool isAsciiHexDigit(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiHexDigit(T code) +{ + return isAsciiHexDigit(sal_uInt32(code)); +} +#endif + +/** Check for ASCII octal digit character. + + @param code A Unicode code point. + + @return True if code is an ASCII octal digit character (ASCII '0'--'7'). + + @since LibreOffice 5.0 + */ +inline SAL_CONSTEXPR bool isAsciiOctalDigit(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= '0' && code <= '7'; +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiOctalDigit(char) = delete; +bool isAsciiOctalDigit(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiOctalDigit(T code) +{ + return isAsciiOctalDigit(sal_uInt32(code)); +} +#endif + +/** Check for ASCII white space character. + + @param code A Unicode code point. + + @return True if code is an ASCII white space character as defined by C for + isspace in the "C" locale (ASCII ' ', '\\f', '\\n', '\\r', '\\t' '\\v'). + + @since LibreOffice 5.4 +*/ +inline SAL_CONSTEXPR bool isAsciiWhiteSpace(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code == ' ' || code == '\f' || code == '\n' || code == '\r' || code == '\t' + || code == '\v'; +} + +#if defined LIBO_INTERNAL_ONLY +bool isAsciiWhiteSpace(char) = delete; +bool isAsciiWhiteSpace(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), bool> +isAsciiWhiteSpace(T code) +{ + return isAsciiWhiteSpace(sal_uInt32(code)); +} +#endif + +/** Convert a character, if ASCII, to upper case. + + @param code A Unicode code point. + + @return code converted to ASCII upper case. + + @since LibreOffice 4.2 +*/ +inline SAL_CONSTEXPR sal_uInt32 toAsciiUpperCase(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return isAsciiLowerCase(code) ? code - 32 : code; +} + +#if defined LIBO_INTERNAL_ONLY +sal_uInt32 toAsciiUpperCase(char) = delete; +sal_uInt32 toAsciiUpperCase(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), + sal_uInt32> +toAsciiUpperCase(T code) +{ + return toAsciiUpperCase(sal_uInt32(code)); +} +#endif + +/** Convert a character, if ASCII, to lower case. + + @param code A Unicode code point. + + @return code converted to ASCII lower case. + + @since LibreOffice 4.2 +*/ +inline SAL_CONSTEXPR sal_uInt32 toAsciiLowerCase(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return isAsciiUpperCase(code) ? code + 32 : code; +} + +#if defined LIBO_INTERNAL_ONLY +sal_uInt32 toAsciiLowerCase(char) = delete; +sal_uInt32 toAsciiLowerCase(signed char) = delete; +template +inline constexpr std::enable_if_t && sizeof(T) <= sizeof(sal_uInt32), + sal_uInt32> +toAsciiLowerCase(T code) +{ + return toAsciiLowerCase(sal_uInt32(code)); +} +#endif + +/** Compare two characters ignoring ASCII case. + + @param code1 A Unicode code point. + + @param code2 A unicode code point. + + @return 0 if both code points are equal, + < 0 if code1 is less than code2, + > 0 if code1 is greater than code2. + + @since LibreOffice 4.2 + */ +inline SAL_CONSTEXPR sal_Int32 compareIgnoreAsciiCase(sal_uInt32 code1, sal_uInt32 code2) +{ + assert(isUnicodeCodePoint(code1)); + assert(isUnicodeCodePoint(code2)); + return static_cast(toAsciiLowerCase(code1)) + - static_cast(toAsciiLowerCase(code2)); +} + +/// @cond INTERNAL +namespace detail +{ +sal_uInt32 const surrogatesHighFirst = 0xD800; +sal_uInt32 const surrogatesHighLast = 0xDBFF; +sal_uInt32 const surrogatesLowFirst = 0xDC00; +sal_uInt32 const surrogatesLowLast = 0xDFFF; +} +/// @endcond + +/** Check for surrogate. + + @param code A Unicode code point. + + @return True if code is a surrogate code point (0xD800--0xDFFF). + + @since LibreOffice 6.0 +*/ +inline SAL_CONSTEXPR bool isSurrogate(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= detail::surrogatesHighFirst && code <= detail::surrogatesLowLast; +} + +/** Check for high surrogate. + + @param code A Unicode code point. + + @return True if code is a high surrogate code point (0xD800--0xDBFF). + + @since LibreOffice 5.0 +*/ +inline SAL_CONSTEXPR bool isHighSurrogate(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= detail::surrogatesHighFirst && code <= detail::surrogatesHighLast; +} + +/** Check for low surrogate. + + @param code A Unicode code point. + + @return True if code is a low surrogate code point (0xDC00--0xDFFF). + + @since LibreOffice 5.0 +*/ +inline SAL_CONSTEXPR bool isLowSurrogate(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + return code >= detail::surrogatesLowFirst && code <= detail::surrogatesLowLast; +} + +/** Get high surrogate half of a non-BMP Unicode code point. + + @param code A non-BMP Unicode code point. + + @return The UTF-16 high surrogate half for the give code point. + + @since LibreOffice 5.0 + */ +inline SAL_CONSTEXPR sal_Unicode getHighSurrogate(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + assert(code >= 0x10000); + return static_cast(((code - 0x10000) >> 10) | detail::surrogatesHighFirst); +} + +/** Get low surrogate half of a non-BMP Unicode code point. + + @param code A non-BMP Unicode code point. + + @return The UTF-16 low surrogate half for the give code point. + + @since LibreOffice 5.0 + */ +inline SAL_CONSTEXPR sal_Unicode getLowSurrogate(sal_uInt32 code) +{ + assert(isUnicodeCodePoint(code)); + assert(code >= 0x10000); + return static_cast(((code - 0x10000) & 0x3FF) | detail::surrogatesLowFirst); +} + +/** Combine surrogates to form a code point. + + @param high A high surrogate code point. + + @param low A low surrogate code point. + + @return The code point represented by the surrogate pair. + + @since LibreOffice 5.0 +*/ +inline SAL_CONSTEXPR sal_uInt32 combineSurrogates(sal_uInt32 high, sal_uInt32 low) +{ + assert(isHighSurrogate(high)); + assert(isLowSurrogate(low)); + return ((high - detail::surrogatesHighFirst) << 10) + (low - detail::surrogatesLowFirst) + + 0x10000; +} + +/** Split a Unicode code point into UTF-16 code units. + + @param code A Unicode code point. + + @param output A non-null pointer to an array with space for at least two + sal_Unicode UTF-16 code units. + + @return The number of UTF-16 code units placed into the output (either one + or two). + + @since LibreOffice 5.3 +*/ +inline SAL_CONSTEXPR std::size_t splitSurrogates(sal_uInt32 code, sal_Unicode* output) +{ + assert(isUnicodeCodePoint(code)); + assert(output != NULL); + if (code < 0x10000) + { + output[0] = code; + return 1; + } + else + { + output[0] = getHighSurrogate(code); + output[1] = getLowSurrogate(code); + return 2; + } +} + +/** Check for Unicode scalar value. + + @param code An integer. + + @return True if code is a Unicode scalar value. + + @since LibreOffice 6.0 +*/ +inline SAL_CONSTEXPR bool isUnicodeScalarValue(sal_uInt32 code) +{ + return isUnicodeCodePoint(code) && !isSurrogate(code); +} +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/cipher.h b/include/rtl/cipher.h new file mode 100644 index 000000000..ed718166c --- /dev/null +++ b/include/rtl/cipher.h @@ -0,0 +1,282 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_CIPHER_H +#define INCLUDED_RTL_CIPHER_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Cipher Handle opaque type. + */ +typedef void* rtlCipher; + +/** Cipher Algorithm enumeration. + @see rtl_cipher_create() + */ +enum __rtl_CipherAlgorithm +{ + rtl_Cipher_AlgorithmBF, + rtl_Cipher_AlgorithmARCFOUR, + rtl_Cipher_AlgorithmInvalid, + rtl_Cipher_Algorithm_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Cipher Algorithm type. + */ +typedef enum __rtl_CipherAlgorithm rtlCipherAlgorithm; + +/** Cipher Mode enumeration. + @see rtl_cipher_create() + */ +enum __rtl_CipherMode +{ + rtl_Cipher_ModeECB, + rtl_Cipher_ModeCBC, + rtl_Cipher_ModeStream, + rtl_Cipher_ModeInvalid, + rtl_Cipher_Mode_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Cipher Mode type. + */ +typedef enum __rtl_CipherMode rtlCipherMode; + +/** Cipher Direction enumeration. + @see rtl_cipher_init() + */ +enum __rtl_CipherDirection +{ + rtl_Cipher_DirectionBoth, + rtl_Cipher_DirectionDecode, + rtl_Cipher_DirectionEncode, + rtl_Cipher_DirectionInvalid, + rtl_Cipher_Direction_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Cipher Direction type. + */ +typedef enum __rtl_CipherDirection rtlCipherDirection; + + +/** Error Code enumeration. + */ +enum __rtl_CipherError +{ + rtl_Cipher_E_None, + rtl_Cipher_E_Argument, + rtl_Cipher_E_Algorithm, + rtl_Cipher_E_Direction, + rtl_Cipher_E_Mode, + rtl_Cipher_E_BufferSize, + rtl_Cipher_E_Memory, + rtl_Cipher_E_Unknown, + rtl_Cipher_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Error Code type. + */ +typedef enum __rtl_CipherError rtlCipherError; + + +/** Create a cipher handle for the given algorithm and mode. + @see rtlCipherAlgorithm + @see rtlCipherMode + + @param[in] Algorithm cipher algorithm. + @param[in] Mode cipher mode. + @return Cipher handle, or 0 upon failure. + */ +SAL_DLLPUBLIC rtlCipher SAL_CALL rtl_cipher_create ( + rtlCipherAlgorithm Algorithm, + rtlCipherMode Mode +) SAL_THROW_EXTERN_C(); + +/** Inititialize a cipher for the given direction. + @see rtlCipherDirection + + @param[in] Cipher cipher handle. + @param[in] Direction cipher direction. + @param[in] pKeyData key material buffer. + @param[in] nKeyLen key material length in bytes. + @param[in] pArgData initialization vector buffer. + @param[in] nArgLen initialization vector length in bytes. + @retval rtl_Cipher_E_None upon success. + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_init ( + rtlCipher Cipher, + rtlCipherDirection Direction, + const sal_uInt8 *pKeyData, sal_Size nKeyLen, + const sal_uInt8 *pArgData, sal_Size nArgLen +) SAL_THROW_EXTERN_C(); + +/** Encode a buffer under a given cipher algorithm. + @pre Initialized for a compatible cipher direction. + @see rtl_cipher_init() + + @param[in] Cipher cipher handle. + @param[in] pData plaintext buffer. + @param[in] nDatLen plaintext length in bytes. + @param[out] pBuffer ciphertext buffer. + @param[in] nBufLen ciphertext length in bytes. + @retval rtl_Cipher_E_None upon success. + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_encode ( + rtlCipher Cipher, + const void *pData, sal_Size nDatLen, + sal_uInt8 *pBuffer, sal_Size nBufLen +) SAL_THROW_EXTERN_C(); + +/** Decode a buffer under a given cipher algorithm. + @pre Initialized for a compatible cipher direction. + @see rtl_cipher_init() + + @param[in] Cipher cipher handle. + @param[in] pData ciphertext buffer. + @param[in] nDatLen ciphertext length in bytes. + @param[out] pBuffer plaintext buffer. + @param[in] nBufLen plaintext length in bytes. + @retval rtl_Cipher_E_None upon success. + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_decode ( + rtlCipher Cipher, + const void *pData, sal_Size nDatLen, + sal_uInt8 *pBuffer, sal_Size nBufLen +) SAL_THROW_EXTERN_C(); + +/** Destroy a cipher handle. + @param[in] Cipher cipher handle to be destroyed. + @return None. Cipher handle destroyed and invalid. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_cipher_destroy ( + rtlCipher Cipher +) SAL_THROW_EXTERN_C(); + +/** Create a Blowfish cipher handle for the given mode. + + The Blowfish block cipher algorithm is specified in + Bruce Schneier: Applied Cryptography, 2nd edition, ch. 14.3 + + @see rtl_cipher_create() + */ +SAL_DLLPUBLIC rtlCipher SAL_CALL rtl_cipher_createBF ( + rtlCipherMode Mode +) SAL_THROW_EXTERN_C(); + +/** Inititialize a Blowfish cipher for the given direction. + @see rtl_cipher_init() + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_initBF ( + rtlCipher Cipher, + rtlCipherDirection Direction, + const sal_uInt8 *pKeyData, sal_Size nKeyLen, + const sal_uInt8 *pArgData, sal_Size nArgLen +) SAL_THROW_EXTERN_C(); + +/** Encode a buffer under the Blowfish cipher algorithm. + @see rtl_cipher_encode() + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_encodeBF ( + rtlCipher Cipher, + const void *pData, sal_Size nDatLen, + sal_uInt8 *pBuffer, sal_Size nBufLen +) SAL_THROW_EXTERN_C(); + +/** Decode a buffer under the Blowfish cipher algorithm. + @see rtl_cipher_decode() + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_decodeBF ( + rtlCipher Cipher, + const void *pData, sal_Size nDatLen, + sal_uInt8 *pBuffer, sal_Size nBufLen +) SAL_THROW_EXTERN_C(); + +/** Destroy a Blowfish cipher handle. + @see rtl_cipher_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_cipher_destroyBF ( + rtlCipher Cipher +) SAL_THROW_EXTERN_C(); + +/** Create a RC4 cipher handle for the given mode. + + The RC4 symmetric stream cipher algorithm is specified in + Bruce Schneier: Applied Cryptography, 2nd edition, ch. 17.1 + + @see rtl_cipher_create() + + @param[in] Mode cipher mode. Must be rtl_Cipher_ModeStream. + @return Cipher handle, or 0 upon failure. + */ +SAL_DLLPUBLIC rtlCipher SAL_CALL rtl_cipher_createARCFOUR ( + rtlCipherMode Mode +) SAL_THROW_EXTERN_C(); + +/** Inititialize a RC4 cipher for the given direction. + @see rtl_cipher_init() + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_initARCFOUR ( + rtlCipher Cipher, + rtlCipherDirection Direction, + const sal_uInt8 *pKeyData, sal_Size nKeyLen, + const sal_uInt8 *pArgData, sal_Size nArgLen +) SAL_THROW_EXTERN_C(); + +/** Encode a buffer under the RC4 cipher algorithm. + @see rtl_cipher_encode() + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_encodeARCFOUR ( + rtlCipher Cipher, + const void *pData, sal_Size nDatLen, + sal_uInt8 *pBuffer, sal_Size nBufLen +) SAL_THROW_EXTERN_C(); + +/** Decode a buffer under the RC4 cipher algorithm. + @see rtl_cipher_decode() + */ +SAL_DLLPUBLIC rtlCipherError SAL_CALL rtl_cipher_decodeARCFOUR ( + rtlCipher Cipher, + const void *pData, sal_Size nDatLen, + sal_uInt8 *pBuffer, sal_Size nBufLen +) SAL_THROW_EXTERN_C(); + +/** Destroy a RC4 cipher handle. + @see rtl_cipher_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_cipher_destroyARCFOUR ( + rtlCipher Cipher +) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif /* ! INCLUDED_RTL_CIPHER_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/crc.h b/include/rtl/crc.h new file mode 100644 index 000000000..d081140f5 --- /dev/null +++ b/include/rtl/crc.h @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_CRC_H +#define INCLUDED_RTL_CRC_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Evaluate CRC32 over given data. + + This function evaluates the CRC polynomial 0xEDB88320. + + @param[in] Crc CRC32 over previous data or zero. + @param[in] Data data buffer. + @param[in] DatLen data buffer length. + @return new CRC32 value. + */ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL rtl_crc32 ( + sal_uInt32 Crc, + const void *Data, sal_uInt32 DatLen +) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_CRC_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/digest.h b/include/rtl/digest.h new file mode 100644 index 000000000..bb2d4f8f0 --- /dev/null +++ b/include/rtl/digest.h @@ -0,0 +1,644 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_DIGEST_H +#define INCLUDED_RTL_DIGEST_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Digest Handle opaque type. + */ +typedef void* rtlDigest; + + +/** Digest Algorithm enumeration. + @see rtl_digest_create() + */ +enum __rtl_DigestAlgorithm +{ + rtl_Digest_AlgorithmMD2, + rtl_Digest_AlgorithmMD5, + rtl_Digest_AlgorithmSHA, + rtl_Digest_AlgorithmSHA1, + + rtl_Digest_AlgorithmHMAC_MD5, + rtl_Digest_AlgorithmHMAC_SHA1, + + rtl_Digest_AlgorithmInvalid, + rtl_Digest_Algorithm_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Digest Algorithm type. + */ +typedef enum __rtl_DigestAlgorithm rtlDigestAlgorithm; + + +/** Error Code enumeration. + */ +enum __rtl_DigestError +{ + rtl_Digest_E_None, + rtl_Digest_E_Argument, + rtl_Digest_E_Algorithm, + rtl_Digest_E_BufferSize, + rtl_Digest_E_Memory, + rtl_Digest_E_Unknown, + rtl_Digest_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Error Code type. + */ +typedef enum __rtl_DigestError rtlDigestError; + + +/** Create a digest handle for the given algorithm. + @see rtlDigestAlgorithm + + @param[in] Algorithm digest algorithm. + @return Digest handle, or 0 upon failure. + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_create ( + rtlDigestAlgorithm Algorithm +) SAL_THROW_EXTERN_C(); + + +/** Destroy a digest handle. + @post Digest handle destroyed and invalid. + @param[in] Digest digest handle to be destroyed. + @return None. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroy ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + + +/** Query the algorithm of a given digest. + @param[in] Digest digest handle. + @return digest algorithm, or rtl_Digest_AlgorithmInvalid upon failure. + */ +SAL_DLLPUBLIC rtlDigestAlgorithm SAL_CALL rtl_digest_queryAlgorithm ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + + +/** Query the length of a given digest. + @param[in] Digest digest handle. + @return digest length, or 0 upon failure. + */ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL rtl_digest_queryLength ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + + +/** Initialize a digest with given data. + @param[in] Digest digest handle. + @param[in] pData data buffer. + @param[in] nDatLen data length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_init ( + rtlDigest Digest, + const sal_uInt8 *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + + +/** Update a digest with given data. + @param[in] Digest digest handle. + @param[in] pData data buffer. + @param[in] nDatLen data length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_update ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + + +/** Finalize a digest and retrieve the digest value. + @pre Digest value length must not be less than digest length. + @post Digest initialized to accept another update sequence. + @see rtl_digest_queryLength() + @see rtl_digest_update() + + @param[in] Digest digest handle. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_get ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +#define RTL_DIGEST_LENGTH_MD2 16 + +/** Create a MD2 digest handle. + + The MD2 digest algorithm is specified in + RFC 1319 (Informational) + The MD2 Message-Digest Algorithm + + @see rtl_digest_create() + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_createMD2 (void) SAL_THROW_EXTERN_C(); + + +/** Destroy a MD2 digest handle. + @see rtl_digest_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroyMD2 ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + +/** Update a MD2 digest with given data. + @see rtl_digest_update() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_updateMD2 ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + +/** Finalize a MD2 digest and retrieve the digest value. + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_getMD2 ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Evaluate a MD2 digest value from given data. + + This function performs an optimized call sequence on a + single data buffer, avoiding digest creation and destruction. + + @see rtl_digest_updateMD2() + @see rtl_digest_getMD2() + + @param[in] pData data buffer. + @param[in] nDatLen data length. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_MD2 ( + const void *pData, sal_uInt32 nDatLen, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +#define RTL_DIGEST_LENGTH_MD5 16 + +/** Create a MD5 digest handle. + + The MD5 digest algorithm is specified in + RFC 1321 (Informational) + The MD5 Message-Digest Algorithm + + @see rtl_digest_create() + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_createMD5 (void) SAL_THROW_EXTERN_C(); + +/** Destroy a MD5 digest handle. + @see rtl_digest_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroyMD5 ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + +/** Update a MD5 digest with given data. + @see rtl_digest_update() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_updateMD5 ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + +/** Finalize a MD5 digest and retrieve the digest value. + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_getMD5 ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Retrieve the raw (not finalized) MD5 digest value. + + This function is a non-standard replacement for + rtl_digest_getMD5() and must be used with caution. + + @post Digest initialized to accept another update sequence. + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_rawMD5 ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Evaluate a MD5 digest value from given data. + + This function performs an optimized call sequence on a + single data buffer, avoiding digest creation and destruction. + + @see rtl_digest_updateMD5() + @see rtl_digest_getMD5() + + @param[in] pData data buffer. + @param[in] nDatLen data length. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_MD5 ( + const void *pData, sal_uInt32 nDatLen, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +#define RTL_DIGEST_LENGTH_SHA 20 + +/** Create a SHA digest handle. + + The SHA digest algorithm is specified in + FIPS PUB 180 (Superseded by FIPS PUB 180-1) + Secure Hash Standard + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_create() + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_createSHA (void) SAL_THROW_EXTERN_C(); + +/** Destroy a SHA digest handle. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroySHA ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + + +/** Update a SHA digest with given data. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_update() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_updateSHA ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + +/** Finalize a SHA digest and retrieve the digest value. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_getSHA ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Evaluate a SHA digest value from given data. + + This function performs an optimized call sequence on a + single data buffer, avoiding digest creation and destruction. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_updateSHA() + @see rtl_digest_getSHA() + + @param[in] pData data buffer. + @param[in] nDatLen data length. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_SHA ( + const void *pData, sal_uInt32 nDatLen, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/*======================================================================== + * + * rtl_digest_SHA1 interface. + * + *======================================================================*/ +#define RTL_DIGEST_LENGTH_SHA1 20 + +/** Create a SHA1 digest handle. + + The SHA1 digest algorithm is specified in + FIPS PUB 180-1 (Supersedes FIPS PUB 180) + Secure Hash Standard + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_create() + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_createSHA1 (void) SAL_THROW_EXTERN_C(); + +/** Destroy a SHA1 digest handle. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroySHA1 ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + +/** Update a SHA1 digest with given data. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_update() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_updateSHA1 ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + +/** Finalize a SHA1 digest and retrieve the digest value. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_getSHA1 ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Evaluate a SHA1 digest value from given data. + + This function performs an optimized call sequence on a + single data buffer, avoiding digest creation and destruction. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_updateSHA1() + @see rtl_digest_getSHA1() + + @param[in] pData data buffer. + @param[in] nDatLen data length. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_SHA1 ( + const void *pData, sal_uInt32 nDatLen, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +#define RTL_DIGEST_LENGTH_HMAC_MD5 RTL_DIGEST_LENGTH_MD5 + +/** Create a HMAC_MD5 digest handle. + + The HMAC_MD5 digest algorithm is specified in + + RFC 2104 (Informational) + HMAC: Keyed-Hashing for Message Authentication + + @see rtl_digest_create() + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_createHMAC_MD5 (void) SAL_THROW_EXTERN_C(); + +/** Destroy a HMAC_MD5 digest handle. + @see rtl_digest_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroyHMAC_MD5 ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + +/** Initialize a HMAC_MD5 digest. + @see rtl_digest_init() + + @param[in] Digest digest handle. + @param[in] pKeyData key material buffer. + @param[in] nKeyLen key material length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_initHMAC_MD5 ( + rtlDigest Digest, + const sal_uInt8 *pKeyData, sal_uInt32 nKeyLen +) SAL_THROW_EXTERN_C(); + +/** Update a HMAC_MD5 digest with given data. + @see rtl_digest_update() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_updateHMAC_MD5 ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + +/** Finalize a HMAC_MD5 digest and retrieve the digest value. + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_getHMAC_MD5 ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Evaluate a HMAC_MD5 digest value from given data. + + This function performs an optimized call sequence on a + single data buffer, avoiding digest creation and destruction. + + @see rtl_digest_initHMAC_MD5() + @see rtl_digest_updateHMAC_MD5() + @see rtl_digest_getHMAC_MD5() + + @param[in] pKeyData key material buffer. + @param[in] nKeyLen key material length. + @param[in] pData data buffer. + @param[in] nDatLen data length. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_HMAC_MD5 ( + const sal_uInt8 *pKeyData, sal_uInt32 nKeyLen, + const void *pData, sal_uInt32 nDatLen, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +#define RTL_DIGEST_LENGTH_HMAC_SHA1 RTL_DIGEST_LENGTH_SHA1 + +/** Create a HMAC_SHA1 digest handle. + + The HMAC_SHA1 digest algorithm is specified in + RFC 2104 (Informational) + HMAC: Keyed-Hashing for Message Authentication + RFC 2898 (Informational) + PKCS #5: Password-Based Cryptography Specification Version 2.0 + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_create() + */ +SAL_DLLPUBLIC rtlDigest SAL_CALL rtl_digest_createHMAC_SHA1 (void) SAL_THROW_EXTERN_C(); + +/** Destroy a HMAC_SHA1 digest handle. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_destroy() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_digest_destroyHMAC_SHA1 ( + rtlDigest Digest +) SAL_THROW_EXTERN_C(); + +/** Initialize a HMAC_SHA1 digest. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_init() + + @param[in] Digest digest handle. + @param[in] pKeyData key material buffer. + @param[in] nKeyLen key material length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_initHMAC_SHA1 ( + rtlDigest Digest, + const sal_uInt8 *pKeyData, sal_uInt32 nKeyLen +) SAL_THROW_EXTERN_C(); + +/** Update a HMAC_SHA1 digest with given data. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_update() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_updateHMAC_SHA1 ( + rtlDigest Digest, + const void *pData, sal_uInt32 nDatLen +) SAL_THROW_EXTERN_C(); + +/** Finalize a HMAC_SHA1 digest and retrieve the digest value. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_get() + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_getHMAC_SHA1 ( + rtlDigest Digest, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Evaluate a HMAC_SHA1 digest value from given data. + + This function performs an optimized call sequence on a + single data buffer, avoiding digest creation and destruction. + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility. + + @see rtl_digest_initHMAC_SHA1() + @see rtl_digest_updateHMAC_SHA1() + @see rtl_digest_getHMAC_SHA1() + + @param[in] pKeyData key material buffer. + @param[in] nKeyLen key material length. + @param[in] pData data buffer. + @param[in] nDatLen data length. + @param[in] pBuffer digest value buffer. + @param[in] nBufLen digest value length. + + @retval rtl_Digest_E_None upon success. + */ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_HMAC_SHA1 ( + const sal_uInt8 *pKeyData, sal_uInt32 nKeyLen, + const void *pData, sal_uInt32 nDatLen, + sal_uInt8 *pBuffer, sal_uInt32 nBufLen +) SAL_THROW_EXTERN_C(); + +/** Password-Based Key Derivation Function. + + The PBKDF2 key derivation function is specified in + RFC 2898 (Informational) + PKCS #5: Password-Based Cryptography Specification Version 2.0 + + @deprecated The implementation is buggy and generates incorrect results + for 52 <= (len % 64) <= 55; use only for bug-compatibility + or if the input is guaranteed to have a good length + by a start-key derivation round. + + @param[out] pKeyData derived key + @param[in] nKeyLen derived key length + @param[in] pPassData password + @param[in] nPassLen password length + @param[in] pSaltData salt + @param[in] nSaltLen salt length + @param[in] nCount iteration count + + @retval rtl_Digest_E_None upon success. +*/ +SAL_DLLPUBLIC rtlDigestError SAL_CALL rtl_digest_PBKDF2 ( + sal_uInt8 *pKeyData , sal_uInt32 nKeyLen, + const sal_uInt8 *pPassData, sal_uInt32 nPassLen, + const sal_uInt8 *pSaltData, sal_uInt32 nSaltLen, + sal_uInt32 nCount +) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_DIGEST_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/instance.hxx b/include/rtl/instance.hxx new file mode 100644 index 000000000..0d7d8f3fc --- /dev/null +++ b/include/rtl/instance.hxx @@ -0,0 +1,643 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_INSTANCE_HXX +#define INCLUDED_RTL_INSTANCE_HXX + +#include "sal/config.h" + +#include + +#include "osl/doublecheckedlocking.h" +#include "osl/getglobalmutex.hxx" + +namespace { + +/** A non-broken version of the double-checked locking pattern. + + See + + for a description of double-checked locking, why it is broken, and how it + can be fixed. Always use this template instead of spelling out the + double-checked locking pattern explicitly, and only in those rare cases + where that is not possible and you have to spell it out explicitly, at + least call OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER() at the right + places. That way, all platform-dependent code to make double-checked + locking work can be kept in one place. + + Usage scenarios: + + 1 Static instance (most common case) + + Pattern: + + T * getInstance() + { + static T * pInstance = 0; + if (!pInstance) + { + ::osl::MutexGuard aGuard(::osl::Mutex::getGlobalMutex()); + if (!pInstance) + { + static T aInstance; + pInstance = &aInstance; + } + } + return pInstance; + } + + Code: + + #include + #include + + namespace { + struct Init + { + T * operator()() + { + static T aInstance; + return &aInstance; + } + }; + } + + T * getInstance() + { + return rtl_Instance< T, Init, ::osl::MutexGuard, + ::osl::GetGlobalMutex >::create( + Init(), ::osl::GetGlobalMutex()); + } + + 2 Dynamic instance + + Pattern: + + T * getInstance() + { + static T * pInstance = 0; + if (!pInstance) + { + ::osl::MutexGuard aGuard(::osl::Mutex::getGlobalMutex()); + if (!pInstance) + pInstance = new T; + } + return pInstance; + } + + Code: + + #include + #include + + namespace { + struct Init + { + T * operator()() + { + return new T; + } + }; + } + + T * getInstance() + { + return rtl_Instance< T, Init, ::osl::MutexGuard, + ::osl::GetGlobalMutex >::create( + Init(), ::osl::GetGlobalMutex()); + } + + 3 Other guard/mutex + + Pattern: + + T * getInstance() + { + static T * pInstance = 0; + if (!pInstance) + { + SomeGuard aGuard(pSomeMutex); + if (!pInstance) + { + static T aInstance; + pInstance = &aInstance; + } + } + return pInstance; + } + + Code: + + #include + + namespace { + struct InitInstance + { + T * operator()() + { + static T aInstance; + return &aInstance; + } + }; + + struct InitGuard + { + SomeMutex * operator()() + { + return pSomeMutex; + } + }; + } + + T * getInstance() + { + return rtl_Instance< T, InitInstance, + SomeGuard, InitGuard >::create( + InitInstance(), InitMutex()); + } + + 4 Calculate extra data + + Pattern: + + T * getInstance() + { + static T * pInstance = 0; + if (!pInstance) + { + Data aData(...); + ::osl::MutexGuard aGuard(::osl::Mutex::getGlobalMutex()); + if (!pInstance) + { + static T aInstance(aData); + pInstance = &aInstance; + } + } + return pInstance; + } + + Code: + + #include + #include + + namespace { + struct InitInstance + { + T * operator()() + { + static T aInstance; + return &aInstance; + } + } + + struct InitData + { + Data const & operator()() + { + return ...; + } + } + } + + T * getInstance() + { + return rtl_Instance< T, InitInstance, + ::osl::MutexGuard, ::osl::GetGlobalMutex, + Data, InitData >::create( + InitInstance(), ::osl::GetGlobalMutex(), InitData()); + } + + Some comments: + + For any instantiation of rtl_Instance, at most one call to a create method + may occur in the program code: Each occurrence of a create method within + the program code is supposed to return a fresh object instance on the + first call, and that same object instance on subsequent calls; but + independent occurrences of create methods are supposed to return + independent object instances. Since there is a one-to-one correspondence + between object instances and instantiations of rtl_Instance, the + requirement should be clear. One measure to enforce the requirement is + that rtl_Instance lives in an unnamed namespace, so that instantiations of + rtl_Instance in different translation units will definitely be different + instantiations. A drawback of that measure is that the name of the class + needs a funny "hand coded" prefix "rtl_" instead of a proper namespace + prefix like "::rtl::". + + A known problem with this template is when two occurrences of calls to + create methods with identical template arguments appear in one translation + unit. Those two places will share a single object instance. This can be + avoided by using different Init structs (see the above code samples) in + the two places. + + There is no need to make m_pInstance volatile, in order to avoid usage of + stale copies of m_pInstance: At the first check, a thread will see that + m_pInstance contains either 0 or a valid pointer. If it contains a valid + pointer, it cannot be stale, and that pointer is used. If it contains 0, + acquiring the mutex will ensure that the second check sees a non-stale + value in all cases. + + On some compilers, the create methods would not be inlined if they + contained any static variables, so m_pInstance is made a class member + instead (and the create methods are inlined). But on MSC, the definition + of the class member m_pInstance would cause compilation to fail with an + internal compiler error. Since MSC is able to inline methods containing + static variables, m_pInstance is moved into the methods there. Note that + this only works well because for any instantiation of rtl_Instance at most + one call to a create method should be present, anyway. + */ +template< typename Inst, typename InstCtor, + typename Guard, typename GuardCtor, + typename Data = int, typename DataCtor = int > +class rtl_Instance +{ +public: + static Inst * create(InstCtor aInstCtor, GuardCtor aGuardCtor) + { +#if defined _MSC_VER + static Inst * m_pInstance = NULL; +#endif // _MSC_VER + Inst * p = m_pInstance; + if (!p) + { + Guard aGuard(aGuardCtor()); + p = m_pInstance; + if (!p) + { + p = aInstCtor(); + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + m_pInstance = p; + } + } + else + { + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + } + return p; + } + + static Inst * create(InstCtor aInstCtor, GuardCtor aGuardCtor, + DataCtor aDataCtor) + { +#if defined _MSC_VER + static Inst * m_pInstance = NULL; +#endif // _MSC_VER + Inst * p = m_pInstance; + if (!p) + { + Data aData(aDataCtor()); + Guard aGuard(aGuardCtor()); + p = m_pInstance; + if (!p) + { + p = aInstCtor(aData); + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + m_pInstance = p; + } + } + else + { + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + } + return p; + } + + static Inst * create(InstCtor aInstCtor, GuardCtor aGuardCtor, + const Data &rData) + { +#if defined _MSC_VER + static Inst * m_pInstance = 0; +#endif // _MSC_VER + Inst * p = m_pInstance; + if (!p) + { + Guard aGuard(aGuardCtor()); + p = m_pInstance; + if (!p) + { + p = aInstCtor(rData); + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + m_pInstance = p; + } + } + else + { + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + } + return p; + } + +private: +#if !defined _MSC_VER + static Inst * m_pInstance; +#endif // _MSC_VER +}; + +#if !defined _MSC_VER +template< typename Inst, typename InstCtor, + typename Guard, typename GuardCtor, + typename Data, typename DataCtor > +Inst * +rtl_Instance< Inst, InstCtor, Guard, GuardCtor, Data, DataCtor >::m_pInstance += NULL; +#endif // _MSC_VER + +} + +namespace rtl { + +/** Helper base class for a late-initialized (default-constructed) + static variable, implementing the double-checked locking pattern correctly. + + @derive + Derive from this class (common practice), e.g. +
    +    struct MyStatic : public rtl::Static {};
    +    ...
    +    MyType & rStatic = MyStatic::get();
    +    ...
    +    
    + + @tparam T + variable's type + @tparam Unique + Implementation trick to make the inner static holder unique, + using the outer class + (the one that derives from this base class) +*/ +#if defined LIBO_INTERNAL_ONLY +template +class Static { +public: + /** Gets the static. Mutual exclusion is implied by a functional + -fthreadsafe-statics + + @return + static variable + */ + static T & get() { + static T instance; + return instance; + } +}; +#else +template +class Static { +public: + /** Gets the static. Mutual exclusion is performed using the + osl global mutex. + + @return + static variable + */ + static T & get() { + return *rtl_Instance< + T, StaticInstance, + ::osl::MutexGuard, ::osl::GetGlobalMutex >::create( + StaticInstance(), ::osl::GetGlobalMutex() ); + } +private: + struct StaticInstance { + T * operator () () { + static T instance; + return &instance; + } + }; +}; +#endif + +/** Helper base class for a late-initialized (default-constructed) + static variable, implementing the double-checked locking pattern correctly. + + @derive + Derive from this class (common practice), e.g. +
    +    struct MyStatic : public rtl::Static {};
    +    ...
    +    MyType & rStatic = MyStatic::get();
    +    ...
    +    
    + + @tparam T + variable's type + @tparam Unique + Implementation trick to make the inner static holder unique, + using the outer class + (the one that derives from this base class) +*/ +#if defined LIBO_INTERNAL_ONLY +template +class StaticWithArg { +public: + /** Gets the static. Mutual exclusion is implied by a functional + -fthreadsafe-statics + + @return + static variable + */ + static T & get(const Data& rData) { + static T instance(rData); + return instance; + } + + /** Gets the static. Mutual exclusion is implied by a functional + -fthreadsafe-statics + + @return + static variable + */ + static T & get(Data& rData) { + static T instance(rData); + return instance; + } +}; +#else +template +class StaticWithArg { +public: + /** Gets the static. Mutual exclusion is performed using the + osl global mutex. + + @return + static variable + */ + static T & get(const Data& rData) { + return *rtl_Instance< + T, StaticInstanceWithArg, + ::osl::MutexGuard, ::osl::GetGlobalMutex, + Data >::create( StaticInstanceWithArg(), + ::osl::GetGlobalMutex(), + rData ); + } + + /** Gets the static. Mutual exclusion is performed using the + osl global mutex. + + @return + static variable + */ + static T & get(Data& rData) { + return *rtl_Instance< + T, StaticInstanceWithArg, + ::osl::MutexGuard, ::osl::GetGlobalMutex, + Data >::create( StaticInstanceWithArg(), + ::osl::GetGlobalMutex(), + rData ); + } +private: + struct StaticInstanceWithArg { + T * operator () (const Data& rData) { + static T instance(rData); + return &instance; + } + + T * operator () (Data& rData) { + static T instance(rData); + return &instance; + } + }; +}; +#endif + +/** Helper class for a late-initialized static aggregate, e.g. an array, + implementing the double-checked locking pattern correctly. + + @tparam T + aggregate's element type + @tparam InitAggregate + initializer functor class +*/ +#if defined LIBO_INTERNAL_ONLY +template +class StaticAggregate { +public: + /** Gets the static aggregate, late-initializing. + Mutual exclusion is implied by a functional + -fthreadsafe-statics + + @return + aggregate + */ + static T * get() { + static T *instance = InitAggregate()(); + return instance; + } +}; +#else +template +class StaticAggregate { +public: + /** Gets the static aggregate, late-initializing. + Mutual exclusion is performed using the osl global mutex. + + @return + aggregate + */ + static T * get() { + return rtl_Instance< + T, InitAggregate, + ::osl::MutexGuard, ::osl::GetGlobalMutex >::create( + InitAggregate(), ::osl::GetGlobalMutex() ); + } +}; +#endif +/** Helper base class for a late-initialized static variable, + implementing the double-checked locking pattern correctly. + + @derive + Derive from this class (common practice), + providing an initializer functor class, e.g. +
    +    struct MyStatic : public rtl::StaticWithInit {
    +        MyType operator () () {
    +            ...
    +            return MyType( ... );
    +        }
    +    };
    +    ...
    +    MyType & rStatic = MyStatic::get();
    +    ...
    +    
    + + @tparam T + variable's type + @tparam InitData + initializer functor class + @tparam Unique + Implementation trick to make the inner static holder unique, + using the outer class + (the one that derives from this base class). + Default is InitData (common practice). + @tparam Data + Initializer functor's return type. + Default is T (common practice). +*/ +#if defined LIBO_INTERNAL_ONLY +template +class StaticWithInit { +public: + /** Gets the static. Mutual exclusion is implied by a functional + -fthreadsafe-statics + + @return + static variable + */ + static T & get() { + static T instance = InitData()(); + return instance; + } +}; +#else +template +class StaticWithInit { +public: + /** Gets the static. Mutual exclusion is performed using the + osl global mutex. + + @return + static variable + */ + static T & get() { + return *rtl_Instance< + T, StaticInstanceWithInit, + ::osl::MutexGuard, ::osl::GetGlobalMutex, + Data, InitData >::create( StaticInstanceWithInit(), + ::osl::GetGlobalMutex(), + InitData() ); + } +private: + struct StaticInstanceWithInit { + T * operator () ( Data d ) { + static T instance(d); + return &instance; + } + }; +}; +#endif +} // namespace rtl + +#endif // INCLUDED_RTL_INSTANCE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/locale.h b/include/rtl/locale.h new file mode 100644 index 000000000..141ff8768 --- /dev/null +++ b/include/rtl/locale.h @@ -0,0 +1,139 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_LOCALE_H +#define INCLUDED_RTL_LOCALE_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +# pragma pack(push, 8) +#endif + +/** + The implementation structure of a locale. Do not create this structure + direct. Only use the functions rtl_locale_register and + rtl_locale_setDefault. The strings Language, Country and Variant + are constants, so it is not necessary to acquire and release them. + */ +typedef struct _rtl_Locale +{ + /** + Lowercase two-letter ISO 639-1 or three-letter ISO 639-3 code. + */ + rtl_uString * Language; + /** + uppercase two-letter ISO-3166 code. + */ + rtl_uString * Country; + /** + Lowercase vendor and browser specific code. + */ + rtl_uString * Variant; + /** + The merged hash value of the Language, Country and Variant strings. + */ + sal_Int32 HashCode; +} rtl_Locale; + +#if defined( _WIN32) +#pragma pack(pop) +#endif + +/** + Register a locale from language, country and variant. + @param language lowercase two-letter ISO 639-1 or three-letter ISO 639-3 code. + @param country uppercase two-letter ISO-3166 code. May be null. + @param variant vendor and browser specific code. May be null. + */ +SAL_DLLPUBLIC rtl_Locale * SAL_CALL rtl_locale_register( + const sal_Unicode * language, const sal_Unicode * country, const sal_Unicode * variant ); + +/** + Common method of getting the current default Locale. + + @deprecated LibreOffice itself does not use this anymore, and client code + should not have good use for it either. It may eventually be removed. + */ +SAL_DLLPUBLIC rtl_Locale * SAL_CALL rtl_locale_getDefault(void); + +/** + Sets the default. + + setDefault does not reset the host locale. + + @param language lowercase two-letter ISO 639-1 or three-letter ISO 639-3 code. + @param country uppercase two-letter ISO-3166 code. + @param variant vendor and browser specific code. See class description. + + @deprecated LibreOffice itself does not use this anymore, and client code + should not have good use for it either. It may eventually be removed. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_locale_setDefault( + const sal_Unicode * language, const sal_Unicode * country, const sal_Unicode * variant ); + +/** + Getter for programmatic name of field, + a lowercase two-letter ISO 639-1 or three-letter ISO 639-3 code. + @see getDisplayLanguage + */ +SAL_DLLPUBLIC rtl_uString * SAL_CALL rtl_locale_getLanguage( rtl_Locale * This ); + +/** + Getter for programmatic name of field, + an uppercased two-letter ISO-3166 code. + @see getDisplayCountry + */ +SAL_DLLPUBLIC rtl_uString * SAL_CALL rtl_locale_getCountry( rtl_Locale * This ); + +/** + Getter for programmatic name of field. + @see getDisplayVariant + */ +SAL_DLLPUBLIC rtl_uString * SAL_CALL rtl_locale_getVariant( rtl_Locale * This ); + +/** + Returns the hash code of the locale This. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_locale_hashCode( rtl_Locale * This ); + +/** + Returns true if the locals are equal, otherwise false. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_locale_equals( rtl_Locale * This, rtl_Locale * obj ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_LOCALE_H + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/malformeduriexception.hxx b/include/rtl/malformeduriexception.hxx new file mode 100644 index 000000000..718656311 --- /dev/null +++ b/include/rtl/malformeduriexception.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_MALFORMEDURIEXCEPTION_HXX +#define INCLUDED_RTL_MALFORMEDURIEXCEPTION_HXX + +#include "rtl/ustring.hxx" + +namespace rtl { + +/** An exception indicating a malformed URI. + +

    Used when parsing (part of) a URI fails for syntactical reasons.

    + */ +class SAL_EXCEPTION_DLLPUBLIC_EXPORT MalformedUriException +{ +public: + /** Create a MalformedUriException. + + @param rMessage + A message containing any details about the exception. + */ + SAL_EXCEPTION_DLLPRIVATE MalformedUriException( + rtl::OUString const & rMessage): m_aMessage(rMessage) {} + + SAL_EXCEPTION_DLLPRIVATE MalformedUriException( + MalformedUriException const & other): m_aMessage(other.m_aMessage) {} + + SAL_EXCEPTION_DLLPRIVATE ~MalformedUriException() {} + + SAL_EXCEPTION_DLLPRIVATE MalformedUriException operator =( + MalformedUriException const & rOther) + { m_aMessage = rOther.m_aMessage; return *this; } + + /** Get the message. + + @return + A reference to the message. The reference is valid for the lifetime of + this MalformedUriException. + */ + SAL_EXCEPTION_DLLPRIVATE rtl::OUString const & getMessage() const + { return m_aMessage; } + +private: + rtl::OUString m_aMessage; +}; + +} + +#endif // INCLUDED_RTL_MALFORMEDURIEXCEPTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/math.h b/include/rtl/math.h new file mode 100644 index 000000000..1938f037c --- /dev/null +++ b/include/rtl/math.h @@ -0,0 +1,509 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_MATH_H +#define INCLUDED_RTL_MATH_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#if defined __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Formatting modes for rtl_math_doubleToString and rtl_math_doubleToUString + and rtl_math_doubleToUStringBuffer. + */ +enum rtl_math_StringFormat +{ + /** Like sprintf() %E. + */ + rtl_math_StringFormat_E, + + /** Like sprintf() %f. + */ + rtl_math_StringFormat_F, + + /** Like sprintf() %G, 'F' or 'E' format is used depending on which one is + more compact. + */ + rtl_math_StringFormat_G, + + /** Automatic, 'F' or 'E' format is used depending on the numeric value to + be formatted. + */ + rtl_math_StringFormat_Automatic, + + /** Same 'E', but with only 1 minimum digits in exponent. + @since LibreOffice 5.0 + */ + rtl_math_StringFormat_E1, + + /** Same 'E', but with only 2 minimum digits in exponent. + @since LibreOffice 5.0 + */ + rtl_math_StringFormat_E2, + + /** Same 'G', but with only 1 minimum digits in exponent. + @since LibreOffice 5.0 + */ + rtl_math_StringFormat_G1, + + /** Same 'G', but with only 2 minimum digits in exponent. + @since LibreOffice 5.0 + */ + rtl_math_StringFormat_G2, + + /** @cond INTERNAL */ + rtl_math_StringFormat_FORCE_EQUAL_SIZE = SAL_MAX_ENUM + /** @endcond */ +}; + +/** Status for rtl_math_stringToDouble and rtl_math_uStringToDouble. + */ +enum rtl_math_ConversionStatus +{ + /** Conversion was successful. + */ + rtl_math_ConversionStatus_Ok, + + /** Conversion caused overflow or underflow. + */ + rtl_math_ConversionStatus_OutOfRange, + + /** @cond INTERNAL */ + rtl_math_ConversionStatus_FORCE_EQUAL_SIZE = SAL_MAX_ENUM + /** @endcond */ +}; + +/** Rounding modes for rtl_math_round. + */ +enum rtl_math_RoundingMode +{ + /** Like HalfUp, but corrects roundoff errors, preferred. + */ + rtl_math_RoundingMode_Corrected, + + /** Floor of absolute value, signed return (commercial). + */ + rtl_math_RoundingMode_Down, + + /** Ceil of absolute value, signed return (commercial). + */ + rtl_math_RoundingMode_Up, + + /** Floor of signed value. + */ + rtl_math_RoundingMode_Floor, + + /** Ceil of signed value. + */ + rtl_math_RoundingMode_Ceiling, + + /** Frac <= 0.5 ? floor of abs : ceil of abs, signed return. + */ + rtl_math_RoundingMode_HalfDown, + + /** Frac < 0.5 ? floor of abs : ceil of abs, signed return (mathematical). + */ + rtl_math_RoundingMode_HalfUp, + + /** IEEE rounding mode (statistical). + */ + rtl_math_RoundingMode_HalfEven, + + /** @cond INTERNAL */ + rtl_math_RoundingMode_FORCE_EQUAL_SIZE = SAL_MAX_ENUM + /** @endcond */ +}; + +/** Special decimal places constants for rtl_math_doubleToString and + rtl_math_doubleToUString and rtl_math_doubleToUStringBuffer. + */ +enum rtl_math_DecimalPlaces +{ + /** Value to be used with rtl_math_StringFormat_Automatic. + */ + rtl_math_DecimalPlaces_Max = 0x7ffffff, + + /** Value to be used with rtl_math_StringFormat_G. + In fact the same value as rtl_math_DecimalPlaces_Max, just an alias for + better understanding. + */ + rtl_math_DecimalPlaces_DefaultSignificance = rtl_math_DecimalPlaces_Max +}; + + +/** Conversions analogous to sprintf() using internal rounding. + + +/-HUGE_VAL are converted to "INF" and "-INF", NAN values are + converted to "NaN". + + @param pResult + Returns the resulting byte string. Must itself not be null, and must point + to either null or a valid string. + + @param pResultCapacity + If null, pResult is considered to point to immutable strings, and a new + string will be allocated in pResult. + If non-null, it points to the current capacity of pResult, which is + considered to point to a string buffer (pResult must not itself be null in + this case, and must point to a string that has room for the given capacity). + The string representation of the given double value is inserted into pResult + at position nResultOffset. If pResult's current capacity is too small, a + new string buffer will be allocated in pResult as necessary, and + pResultCapacity will contain the new capacity on return. + + @param nResultOffset + If pResult is used as a string buffer (i.e., pResultCapacity is non-null), + nResultOffset specifies the insertion offset within the buffer. Ignored + otherwise. + + @param fValue + The value to convert. + + @param eFormat + The format to use, one of rtl_math_StringFormat. + + @param nDecPlaces + The number of decimals to be generated. Effectively fValue is rounded at + this position, specifying nDecPlaces <= 0 accordingly rounds the value + before the decimal point and fills with zeros. + If eFormat == rtl_math_StringFormat_Automatic and nDecPlaces == + rtl_math_DecimalPlaces_Max, the highest number of significant decimals + possible is generated. + If eFormat == rtl_math_StringFormat_G, nDecPlaces specifies the number of + significant digits instead. If nDecPlaces == + rtl_math_DecimalPlaces_DefaultSignificance, the default number (currently 6 + as implemented by most libraries) of significant digits is generated. + According to the ANSI C90 standard the E style will be used only if the + exponent resulting from the conversion is less than -4 or greater than or + equal to the precision. However, as opposed to the ANSI standard, trailing + zeros are not necessarily removed from the fractional portion of the result + unless bEraseTrailingDecZeros == true was specified. + + @param cDecSeparator + The decimal separator. + + @param pGroups + Either null (no grouping is used), or a null-terminated list of group + lengths. Each group length must be strictly positive. If the number of + digits in a conversion exceeds the specified range, the last (highest) group + length is repeated as needed. Values are applied from right to left, for a + grouping of 1,00,00,000 you'd have to specify pGroups={3,2,0}. + + @param cGroupSeparator + The group separator. Ignored if pGroups is null. + + @param bEraseTrailingDecZeros + Trailing zeros in decimal places are erased. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_math_doubleToString(rtl_String ** pResult, + sal_Int32 * pResultCapacity, + sal_Int32 nResultOffset, double fValue, + enum rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + char cDecSeparator, + sal_Int32 const * pGroups, + char cGroupSeparator, + sal_Bool bEraseTrailingDecZeros) + SAL_THROW_EXTERN_C(); + +/** Conversions analogous to sprintf() using internal rounding. + + +/-HUGE_VAL are converted to "INF" and "-INF", NAN values are + converted to "NaN". + + @param pResult + Returns the resulting Unicode string. Must itself not be null, and must + point to either null or a valid string. + + @param pResultCapacity + If null, pResult is considered to point to immutable strings, and a new + string will be allocated in pResult. + If non-null, it points to the current capacity of pResult, which is + considered to point to a string buffer (pResult must not itself be null in + this case, and must point to a string that has room for the given capacity). + The string representation of the given double value is inserted into pResult + at position nResultOffset. If pResult's current capacity is too small, a + new string buffer will be allocated in pResult as necessary, and + pResultCapacity will contain the new capacity on return. + + @param nResultOffset + If pResult is used as a string buffer (i.e., pResultCapacity is non-null), + nResultOffset specifies the insertion offset within the buffer. Ignored + otherwise. + + @param fValue + The value to convert. + + @param eFormat + The format to use, one of rtl_math_StringFormat. + + @param nDecPlaces + The number of decimals to be generated. Effectively fValue is rounded at + this position, specifying nDecPlaces <= 0 accordingly rounds the value + before the decimal point and fills with zeros. + If eFormat == rtl_math_StringFormat_Automatic and nDecPlaces == + rtl_math_DecimalPlaces_Max, the highest number of significant decimals + possible is generated. + If eFormat == rtl_math_StringFormat_G, nDecPlaces specifies the number of + significant digits instead. If nDecPlaces == + rtl_math_DecimalPlaces_DefaultSignificance, the default number (currently 6 + as implemented by most libraries) of significant digits is generated. + According to the ANSI C90 standard the E style will be used only if the + exponent resulting from the conversion is less than -4 or greater than or + equal to the precision. However, as opposed to the ANSI standard, trailing + zeros are not necessarily removed from the fractional portion of the result + unless bEraseTrailingDecZeros == true was specified. + + @param cDecSeparator + The decimal separator. + + @param pGroups + Either null (no grouping is used), or a null-terminated list of group + lengths. Each group length must be strictly positive. If the number of + digits in a conversion exceeds the specified range, the last (highest) group + length is repeated as needed. Values are applied from right to left, for a + grouping of 1,00,00,000 you'd have to specify pGroups={3,2,0}. + + @param cGroupSeparator + The group separator. Ignored if pGroups is null. + + @param bEraseTrailingDecZeros + Trailing zeros in decimal places are erased. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_math_doubleToUString(rtl_uString ** pResult, + sal_Int32 * pResultCapacity, + sal_Int32 nResultOffset, double fValue, + enum rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + sal_Unicode cDecSeparator, + sal_Int32 const * pGroups, + sal_Unicode cGroupSeparator, + sal_Bool bEraseTrailingDecZeros) + SAL_THROW_EXTERN_C(); + +/** Conversion analogous to strtod(), convert a string representing a + decimal number into a double value. + + Leading tabs (0x09) and spaces (0x20) are eaten. Overflow returns + +/-HUGE_VAL, underflow 0. In both cases pStatus is set to + rtl_math_ConversionStatus_OutOfRange, otherwise to + rtl_math_ConversionStatus_Ok. "INF", "-INF" and "+/-1.#INF" are + recognized as +/-HUGE_VAL, pStatus is set to + rtl_math_ConversionStatus_OutOfRange. "NaN" and "+/-1.#NAN" are + recognized and the value is set to +/-NAN, pStatus is set to + rtl_math_ConversionStatus_Ok. + + @param pBegin + Points to the start of the byte string to convert. Must not be null. + + @param pEnd + Points one past the end of the byte string to convert. The condition + pEnd >= pBegin must hold. + + @param cDecSeparator + The decimal separator. + + @param cGroupSeparator + The group (aka thousands) separator. + + @param pStatus + If non-null, returns the status of the conversion. + + @param pParsedEnd + If non-null, returns one past the position of the last character parsed + away. Thus if [pBegin..pEnd) only contains the numerical string to be + parsed, *pParsedEnd == pEnd on return. If no numerical (sub-)string is + found, *pParsedEnd == pBegin on return, even if there was leading + whitespace. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_stringToDouble( + char const * pBegin, char const * pEnd, char cDecSeparator, + char cGroupSeparator, enum rtl_math_ConversionStatus * pStatus, + char const ** pParsedEnd) SAL_THROW_EXTERN_C(); + +/** Conversion analogous to strtod(), convert a string representing a + decimal number into a double value. + + Leading tabs (U+0009) and spaces (U+0020) are eaten. Overflow returns + +/-HUGE_VAL, underflow 0. In both cases pStatus is set to + rtl_math_ConversionStatus_OutOfRange, otherwise to + rtl_math_ConversionStatus_Ok. "INF", "-INF" and "+/-1.#INF" are + recognized as +/-HUGE_VAL, pStatus is set to + rtl_math_ConversionStatus_OutOfRange. "NaN" and "+/-1.#NAN" are + recognized and the value is set to +/-NAN, pStatus is set to + rtl_math_ConversionStatus_Ok. + + @param pBegin + Points to the start of the Unicode string to convert. Must not be null. + + @param pEnd + Points one past the end of the Unicode string to convert. The condition + pEnd >= pBegin must hold. + + @param cDecSeparator + The decimal separator. + + @param cGroupSeparator + The group (aka thousands) separator. + + @param pStatus + If non-null, returns the status of the conversion. + + @param pParsedEnd + If non-null, returns one past the position of the last character parsed + away. Thus if [pBegin..pEnd) only contains the numerical string to be + parsed, *pParsedEnd == pEnd on return. If no numerical (sub-)string is + found, *pParsedEnd == pBegin on return, even if there was leading + whitespace. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_uStringToDouble( + sal_Unicode const * pBegin, sal_Unicode const * pEnd, + sal_Unicode cDecSeparator, sal_Unicode cGroupSeparator, + enum rtl_math_ConversionStatus * pStatus, sal_Unicode const ** pParsedEnd) + SAL_THROW_EXTERN_C(); + +/** Rounds a double value. + + @param fValue + Specifies the value to be rounded. + + @param nDecPlaces + Specifies the decimal place where rounding occurs. Must be in the range + -20 to +20, inclusive. Negative if rounding occurs before the decimal + point. + + @param eMode + Specifies the rounding mode. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_round(double fValue, int nDecPlaces, + enum rtl_math_RoundingMode eMode) + SAL_THROW_EXTERN_C(); + +/** Scales fVal to a power of 10 without calling pow() or div() for nExp values + between -16 and +16, providing a faster method. + + @param fValue + The value to be raised. + + @param nExp + The exponent. + + @return + fVal * pow(10.0, nExp) + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_pow10Exp(double fValue, int nExp) SAL_THROW_EXTERN_C(); + +/** Rounds value to 15 significant decimal digits. + + @param fValue + The value to be rounded. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_approxValue(double fValue) SAL_THROW_EXTERN_C(); + +/** Test equality of two values with an accuracy of the magnitude of the + given values scaled by 2^-48 (4 bits roundoff stripped). + + @attention + approxEqual( value!=0.0, 0.0 ) _never_ yields true. + + @since LibreOffice 5.3 + */ +SAL_DLLPUBLIC bool SAL_CALL rtl_math_approxEqual(double a, double b) SAL_THROW_EXTERN_C(); + +/** Returns more accurate e^x-1 for x near 0 than calculating directly. + + expm1 is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term e^x-1. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_expm1(double fValue) SAL_THROW_EXTERN_C(); + +/** Returns more accurate log(1+x) for x near 0 than calculating directly. + + log1p is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term log(1+x). + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_log1p(double fValue) SAL_THROW_EXTERN_C(); + +/** Returns more accurate atanh(x) for x near 0 than calculating + 0.5*log((1+x)/(1-x)). + + atanh is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term atanh(x). + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_atanh(double fValue) SAL_THROW_EXTERN_C(); + +/** Returns values of the Errorfunction erf. + + erf is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term erf(x). + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_erf(double fValue) SAL_THROW_EXTERN_C(); + +/** Returns values of the complement Errorfunction erfc. + + erfc is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term erfc(x). + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_erfc(double fValue) SAL_THROW_EXTERN_C(); + +/** Returns values of the inverse hyperbolic sine. + + asinh is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term asinh(x). + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_asinh(double fValue) SAL_THROW_EXTERN_C(); + +/** Returns values of the inverse hyperbolic cosine. + + acosh is part of the C99 standard, but not provided by some compilers. + + @param fValue + The value x in the term acosh(x). + */ +SAL_DLLPUBLIC double SAL_CALL rtl_math_acosh(double fValue) SAL_THROW_EXTERN_C(); + +#if defined __cplusplus +} +#endif /* __cplusplus */ + +#endif /* INCLUDED_RTL_MATH_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/math.hxx b/include/rtl/math.hxx new file mode 100644 index 000000000..661ddf1d1 --- /dev/null +++ b/include/rtl/math.hxx @@ -0,0 +1,511 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_MATH_HXX +#define INCLUDED_RTL_MATH_HXX + +#include "rtl/math.h" +#include "rtl/strbuf.hxx" +#include "rtl/string.hxx" +#include "rtl/ustring.hxx" +#include "rtl/ustrbuf.hxx" +#include "sal/mathconf.h" +#include "sal/types.h" + +#include +#include + +namespace rtl { + +namespace math { + +/** A wrapper around rtl_math_doubleToString. + */ +inline rtl::OString doubleToString(double fValue, rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + char cDecSeparator, + sal_Int32 const * pGroups, + char cGroupSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl::OString aResult; + rtl_math_doubleToString(&aResult.pData, NULL, 0, fValue, eFormat, nDecPlaces, + cDecSeparator, pGroups, cGroupSeparator, + bEraseTrailingDecZeros); + return aResult; +} + +/** A wrapper around rtl_math_doubleToString, with no grouping. + */ +inline rtl::OString doubleToString(double fValue, rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + char cDecSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl::OString aResult; + rtl_math_doubleToString(&aResult.pData, NULL, 0, fValue, eFormat, nDecPlaces, + cDecSeparator, NULL, 0, bEraseTrailingDecZeros); + return aResult; +} + +/** A wrapper around rtl_math_doubleToString that appends to an + rtl::OStringBuffer. + + @since LibreOffice 5.4 +*/ +inline void doubleToStringBuffer( + rtl::OStringBuffer& rBuffer, double fValue, rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, char cDecSeparator, sal_Int32 const * pGroups, + char cGroupSeparator, bool bEraseTrailingDecZeros = false) +{ + rtl_String ** pData; + sal_Int32 * pCapacity; + rBuffer.accessInternals(&pData, &pCapacity); + rtl_math_doubleToString( + pData, pCapacity, rBuffer.getLength(), fValue, eFormat, nDecPlaces, + cDecSeparator, pGroups, cGroupSeparator, bEraseTrailingDecZeros); +} + +/** A wrapper around rtl_math_doubleToString that appends to an + rtl::OStringBuffer, with no grouping. + + @since LibreOffice 5.4 +*/ +inline void doubleToStringBuffer( + rtl::OStringBuffer& rBuffer, double fValue, rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, char cDecSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl_String ** pData; + sal_Int32 * pCapacity; + rBuffer.accessInternals(&pData, &pCapacity); + rtl_math_doubleToString( + pData, pCapacity, rBuffer.getLength(), fValue, eFormat, nDecPlaces, + cDecSeparator, NULL, 0, bEraseTrailingDecZeros); +} + +/** A wrapper around rtl_math_doubleToUString. + */ +inline rtl::OUString doubleToUString(double fValue, + rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + sal_Unicode cDecSeparator, + sal_Int32 const * pGroups, + sal_Unicode cGroupSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl::OUString aResult; + rtl_math_doubleToUString(&aResult.pData, NULL, 0, fValue, eFormat, nDecPlaces, + cDecSeparator, pGroups, cGroupSeparator, + bEraseTrailingDecZeros); + return aResult; +} + +/** A wrapper around rtl_math_doubleToUString, with no grouping. + */ +inline rtl::OUString doubleToUString(double fValue, + rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + sal_Unicode cDecSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl::OUString aResult; + rtl_math_doubleToUString(&aResult.pData, NULL, 0, fValue, eFormat, nDecPlaces, + cDecSeparator, NULL, 0, bEraseTrailingDecZeros); + return aResult; +} + +/** A wrapper around rtl_math_doubleToUString that appends to an + rtl::OUStringBuffer. + */ +inline void doubleToUStringBuffer( rtl::OUStringBuffer& rBuffer, double fValue, + rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + sal_Unicode cDecSeparator, + sal_Int32 const * pGroups, + sal_Unicode cGroupSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl_uString ** pData; + sal_Int32 * pCapacity; + rBuffer.accessInternals( &pData, &pCapacity ); + rtl_math_doubleToUString( pData, pCapacity, rBuffer.getLength(), fValue, + eFormat, nDecPlaces, cDecSeparator, pGroups, + cGroupSeparator, bEraseTrailingDecZeros); +} + +/** A wrapper around rtl_math_doubleToUString that appends to an + rtl::OUStringBuffer, with no grouping. + */ +inline void doubleToUStringBuffer( rtl::OUStringBuffer& rBuffer, double fValue, + rtl_math_StringFormat eFormat, + sal_Int32 nDecPlaces, + sal_Unicode cDecSeparator, + bool bEraseTrailingDecZeros = false) +{ + rtl_uString ** pData; + sal_Int32 * pCapacity; + rBuffer.accessInternals( &pData, &pCapacity ); + rtl_math_doubleToUString( pData, pCapacity, rBuffer.getLength(), fValue, + eFormat, nDecPlaces, cDecSeparator, NULL, 0, + bEraseTrailingDecZeros); +} + +/** A wrapper around rtl_math_stringToDouble. + */ +#ifdef LIBO_INTERNAL_ONLY +inline double stringToDouble(std::string_view aString, + char cDecSeparator, char cGroupSeparator, + rtl_math_ConversionStatus * pStatus = NULL, + sal_Int32 * pParsedEnd = NULL) +{ + char const * pBegin = aString.data(); + char const * pEnd; + double fResult = rtl_math_stringToDouble(pBegin, + pBegin + aString.size(), + cDecSeparator, cGroupSeparator, + pStatus, &pEnd); + if (pParsedEnd != NULL) + *pParsedEnd = static_cast(pEnd - pBegin); + return fResult; +} +#else +inline double stringToDouble(rtl::OString const & rString, + char cDecSeparator, char cGroupSeparator, + rtl_math_ConversionStatus * pStatus = NULL, + sal_Int32 * pParsedEnd = NULL) +{ + char const * pBegin = rString.getStr(); + char const * pEnd; + double fResult = rtl_math_stringToDouble(pBegin, + pBegin + rString.getLength(), + cDecSeparator, cGroupSeparator, + pStatus, &pEnd); + if (pParsedEnd != NULL) + *pParsedEnd = static_cast(pEnd - pBegin); + return fResult; +} +#endif + + +/** A wrapper around rtl_math_uStringToDouble. + */ +#ifdef LIBO_INTERNAL_ONLY +inline double stringToDouble(std::u16string_view aString, + sal_Unicode cDecSeparator, + sal_Unicode cGroupSeparator, + rtl_math_ConversionStatus * pStatus = NULL, + sal_Int32 * pParsedEnd = NULL) +{ + sal_Unicode const * pBegin = aString.data(); + sal_Unicode const * pEnd; + double fResult = rtl_math_uStringToDouble(pBegin, + pBegin + aString.size(), + cDecSeparator, cGroupSeparator, + pStatus, &pEnd); + if (pParsedEnd != NULL) + *pParsedEnd = static_cast(pEnd - pBegin); + return fResult; +} +#else +inline double stringToDouble(rtl::OUString const & rString, + sal_Unicode cDecSeparator, + sal_Unicode cGroupSeparator, + rtl_math_ConversionStatus * pStatus = NULL, + sal_Int32 * pParsedEnd = NULL) +{ + sal_Unicode const * pBegin = rString.getStr(); + sal_Unicode const * pEnd; + double fResult = rtl_math_uStringToDouble(pBegin, + pBegin + rString.getLength(), + cDecSeparator, cGroupSeparator, + pStatus, &pEnd); + if (pParsedEnd != NULL) + *pParsedEnd = static_cast(pEnd - pBegin); + return fResult; +} +#endif + +/** A wrapper around rtl_math_round. + */ +inline double round( + double fValue, int nDecPlaces = 0, + rtl_math_RoundingMode eMode = rtl_math_RoundingMode_Corrected) +{ + return rtl_math_round(fValue, nDecPlaces, eMode); +} + +/** A wrapper around rtl_math_pow10Exp. + */ +inline double pow10Exp(double fValue, int nExp) +{ + return rtl_math_pow10Exp(fValue, nExp); +} + +/** A wrapper around rtl_math_approxValue. + */ +inline double approxValue(double fValue) +{ + return rtl_math_approxValue(fValue); +} + +/** A wrapper around rtl_math_expm1. + */ +inline double expm1(double fValue) +{ + return rtl_math_expm1(fValue); +} + +/** A wrapper around rtl_math_log1p. + */ +inline double log1p(double fValue) +{ + return rtl_math_log1p(fValue); +} + +/** A wrapper around rtl_math_atanh. + */ +inline double atanh(double fValue) +{ + return rtl_math_atanh(fValue); +} + +/** A wrapper around rtl_math_erf. + */ +inline double erf(double fValue) +{ + return rtl_math_erf(fValue); +} + +/** A wrapper around rtl_math_erfc. + */ +inline double erfc(double fValue) +{ + return rtl_math_erfc(fValue); +} + +/** A wrapper around rtl_math_asinh. + */ +inline double asinh(double fValue) +{ + return rtl_math_asinh(fValue); +} + +/** A wrapper around rtl_math_acosh. + */ +inline double acosh(double fValue) +{ + return rtl_math_acosh(fValue); +} + +/** A wrapper around rtl_math_approxEqual. + */ +inline bool approxEqual(double a, double b) +{ + return rtl_math_approxEqual( a, b ); +} + +/** Test equality of two values with an accuracy defined by nPrec + + @attention + approxEqual( value!=0.0, 0.0 ) _never_ yields true. + */ +inline bool approxEqual(double a, double b, sal_Int16 nPrec) +{ + if ( a == b ) + return true; + double x = a - b; + return (x < 0.0 ? -x : x) + < ((a < 0.0 ? -a : a) * (1.0 / (pow(2.0, nPrec)))); +} + +/** Add two values. + + If signs differ and the absolute values are equal according to approxEqual() + the method returns 0.0 instead of calculating the sum. + + If you wanted to sum up multiple values it would be convenient not to call + approxAdd() for each value but instead remember the first value not equal to + 0.0, add all other values using normal + operator, and with the result and + the remembered value call approxAdd(). + */ +inline double approxAdd(double a, double b) +{ + if ( ((a < 0.0 && b > 0.0) || (b < 0.0 && a > 0.0)) + && approxEqual( a, -b ) ) + return 0.0; + return a + b; +} + +/** Subtract two values (a-b). + + If signs are identical and the values are equal according to approxEqual() + the method returns 0.0 instead of calculating the subtraction. + */ +inline double approxSub(double a, double b) +{ + if ( ((a < 0.0 && b < 0.0) || (a > 0.0 && b > 0.0)) && approxEqual( a, b ) ) + return 0.0; + return a - b; +} + +/** floor() method taking approxValue() into account. + + Use for expected integer values being calculated by double functions. + */ +inline double approxFloor(double a) +{ + return floor( approxValue( a )); +} + +/** ceil() method taking approxValue() into account. + + Use for expected integer values being calculated by double functions. + */ +inline double approxCeil(double a) +{ + return ceil( approxValue( a )); +} + +/** Tests whether a value is neither INF nor NAN. + */ +inline bool isFinite(double d) +{ + return SAL_MATH_FINITE(d); +} + +/** If a value represents +INF or -INF. + + The sign bit may be queried with isSignBitSet(). + + If isFinite(d)==false and isInf(d)==false then NAN. + */ +inline bool isInf(double d) +{ + // exponent==0x7ff fraction==0 + return !SAL_MATH_FINITE(d) && + (reinterpret_cast< sal_math_Double * >(&d)->inf_parts.fraction_hi == 0) + && (reinterpret_cast< sal_math_Double * >(&d)->inf_parts.fraction_lo + == 0); +} + +/** Test on any QNAN or SNAN. + */ +inline bool isNan(double d) +{ + // exponent==0x7ff fraction!=0 + return !SAL_MATH_FINITE(d) && ( + (reinterpret_cast< sal_math_Double * >(&d)->inf_parts.fraction_hi != 0) + || (reinterpret_cast< sal_math_Double * >(&d)->inf_parts.fraction_lo + != 0) ); +} + +/** If the sign bit is set. + */ +inline bool isSignBitSet(double d) +{ + return reinterpret_cast< sal_math_Double * >(&d)->inf_parts.sign != 0; +} + +/** Set to +INF if bNegative==false or -INF if bNegative==true. + */ +inline void setInf(double * pd, bool bNegative) +{ + union + { + double sd; + sal_math_Double md; + }; + md.w32_parts.msw = bNegative ? 0xFFF00000 : 0x7FF00000; + md.w32_parts.lsw = 0; + *pd = sd; +} + +/** Set a QNAN. + */ +inline void setNan(double * pd) +{ + union + { + double sd; + sal_math_Double md; + }; + md.w32_parts.msw = 0x7FFFFFFF; + md.w32_parts.lsw = 0xFFFFFFFF; + *pd = sd; +} + +/** If a value is a valid argument for sin(), cos(), tan(). + + IEEE 754 specifies that absolute values up to 2^64 (=1.844e19) for the + radian must be supported by trigonometric functions. Unfortunately, at + least on x86 architectures, the FPU doesn't generate an error pattern for + values >2^64 but produces erroneous results instead and sets only the + "invalid operation" (IM) flag in the status word :-( Thus the application + has to handle it itself. + */ +inline bool isValidArcArg(double d) +{ + return fabs(d) + <= (static_cast< double >(static_cast< unsigned long >(0x80000000)) + * static_cast< double >(static_cast< unsigned long >(0x80000000)) + * 4); +} + +/** Safe sin(), returns NAN if not valid. + */ +inline double sin(double d) +{ + if ( isValidArcArg( d ) ) + return ::sin( d ); + setNan( &d ); + return d; +} + +/** Safe cos(), returns NAN if not valid. + */ +inline double cos(double d) +{ + if ( isValidArcArg( d ) ) + return ::cos( d ); + setNan( &d ); + return d; +} + +/** Safe tan(), returns NAN if not valid. + */ +inline double tan(double d) +{ + if ( isValidArcArg( d ) ) + return ::tan( d ); + setNan( &d ); + return d; +} + +} + +} + +#endif // INCLUDED_RTL_MATH_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/process.h b/include/rtl/process.h new file mode 100644 index 000000000..0a2833863 --- /dev/null +++ b/include/rtl/process.h @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_PROCESS_H +#define INCLUDED_RTL_PROCESS_H + +#include "sal/config.h" + +#include "osl/process.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + gets a 16-byte fixed size identifier which is guaranteed not to change + during the current process. + + The current implementation creates a 16-byte uuid without using + the ethernet address of system. Thus the + identifier is different from identifiers created + in other processes with a very probability. + + @param pTargetUUID 16 byte of memory + @see rtl_createUuid() + */ +SAL_DLLPUBLIC void SAL_CALL rtl_getGlobalProcessId( sal_uInt8 *pTargetUUID ); + +/** Get the nArg-th command-line argument passed to the main-function of this process. + + This function differs from osl_getCommandArg() in filtering any bootstrap values + given by command args, that means that all arguments starting with "-env:" will be + ignored by this function. + + @param[in] nArg The number of the argument to return. + @param[out] strCommandArg The string receives the nArg-th command-line argument. + @retval osl_Process_E_None or does not return. + @see osl_getCommandArg() + @see rtl_getAppCommandArgCount() +*/ +SAL_DLLPUBLIC oslProcessError SAL_CALL rtl_getAppCommandArg(sal_uInt32 nArg, rtl_uString **strCommandArg); + +/** Returns the number of command line arguments at process start. + + This function differs from osl_getCommandArg() in filtering any bootstrap values + given by command args, that means that all arguments starting with "-env:" will be + ignored by this function. + + @return the number of commandline arguments passed to the main-function of this process. + @see osl_getCommandArgCount() + @see rtl_getAppCommandArg() +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL rtl_getAppCommandArgCount(void); + +#ifdef __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/random.h b/include/rtl/random.h new file mode 100644 index 000000000..af21139de --- /dev/null +++ b/include/rtl/random.h @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_RANDOM_H +#define INCLUDED_RTL_RANDOM_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Random Pool opaque type. + */ +typedef void* rtlRandomPool; + + +/** Error Code enumeration. + */ +enum __rtl_RandomError +{ + rtl_Random_E_None, + rtl_Random_E_Argument, + rtl_Random_E_Memory, + rtl_Random_E_Unknown, + rtl_Random_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + +/** Error Code type. + */ +typedef enum __rtl_RandomError rtlRandomError; + + +/** Create a Random Pool. + @return initialized Random Pool, or NULL upon failure. + */ +SAL_DLLPUBLIC rtlRandomPool SAL_CALL rtl_random_createPool (void) SAL_THROW_EXTERN_C(); + + +/** Destroy a Random Pool. + @param[in] Pool a Random Pool. + @return none. Pool is invalid. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_random_destroyPool ( + rtlRandomPool Pool +) SAL_THROW_EXTERN_C(); + + +/** Add bytes to a Random Pool. + @param[in] Pool a Random Pool. + @param[in] Buffer a buffer containing the bytes to add. + @param[in] Bytes the number of bytes to read from the buffer. + @retval rtl_Random_E_None upon success. + */ +SAL_DLLPUBLIC rtlRandomError SAL_CALL rtl_random_addBytes ( + rtlRandomPool Pool, + const void *Buffer, + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + + +/** Retrieve bytes from a Random Pool. + @param[in] Pool a Random Pool. + @param[in,out] Buffer a buffer to receive the random bytes. + @param[in] Bytes the number of bytes to write to the buffer. + @retval rtl_Random_E_None upon success. + */ +SAL_DLLPUBLIC rtlRandomError SAL_CALL rtl_random_getBytes ( + rtlRandomPool Pool, + void *Buffer, + sal_Size Bytes +) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_RANDOM_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/ref.hxx b/include/rtl/ref.hxx new file mode 100644 index 000000000..38dfe3769 --- /dev/null +++ b/include/rtl/ref.hxx @@ -0,0 +1,316 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_REF_HXX +#define INCLUDED_RTL_REF_HXX + +#include "sal/config.h" + +#include +#include +#include +#ifdef LIBO_INTERNAL_ONLY +#include +#include "com/sun/star/uno/Reference.h" +#endif + +#include "sal/types.h" + +namespace rtl +{ + +/** Template reference class for reference type. +*/ +template +class Reference +{ + /** The reference_type body pointer. + */ + reference_type * m_pBody; + + +public: + /** Constructor... + */ + Reference() + : m_pBody (NULL) + {} + + + /** Constructor... + */ + Reference (reference_type * pBody, __sal_NoAcquire) + : m_pBody (pBody) + { + } + + /** Constructor... + */ + Reference (reference_type * pBody) + : m_pBody (pBody) + { + if (m_pBody) + m_pBody->acquire(); + } + + /** Copy constructor... + */ + Reference (const Reference & handle) + : m_pBody (handle.m_pBody) + { + if (m_pBody) + m_pBody->acquire(); + } + +#ifdef LIBO_INTERNAL_ONLY + /** Move constructor... + */ + Reference (Reference && handle) noexcept + : m_pBody (handle.m_pBody) + { + handle.m_pBody = nullptr; + } +#endif + +#if defined LIBO_INTERNAL_ONLY + /** Up-casting conversion constructor: Copies interface reference. + + Does not work for up-casts to ambiguous bases. + + @param rRef another reference + */ + template< class derived_type > + inline Reference( + const Reference< derived_type > & rRef, + std::enable_if_t, int> = 0 ) + : m_pBody (rRef.get()) + { + if (m_pBody) + m_pBody->acquire(); + } + + /** Up-casting conversion operator to convert to css::uno::Interface + + Does not work for up-casts to ambiguous bases. + */ + template< class super_type, + std::enable_if_t, int> = 0 > + inline operator css::uno::Reference() const + { + return css::uno::Reference(m_pBody); + } +#endif + + /** Destructor... + */ + ~Reference() COVERITY_NOEXCEPT_FALSE + { + if (m_pBody) + m_pBody->release(); + } + + /** Set... + Similar to assignment. + */ + Reference & + SAL_CALL set (reference_type * pBody) + { + if (pBody) + pBody->acquire(); + reference_type * const pOld = m_pBody; + m_pBody = pBody; + if (pOld) + pOld->release(); + return *this; + } + + /** Assignment. + Unbinds this instance from its body (if bound) and + bind it to the body represented by the handle. + */ + Reference & + SAL_CALL operator= (const Reference & handle) + { + return set( handle.m_pBody ); + } + +#ifdef LIBO_INTERNAL_ONLY + /** Assignment. + * Unbinds this instance from its body (if bound), + * bind it to the body represented by the handle, and + * set the body represented by the handle to nullptr. + */ + Reference & + operator= (Reference && handle) + { + // self-movement guts ourself + if (m_pBody) + m_pBody->release(); + m_pBody = handle.m_pBody; + handle.m_pBody = nullptr; + return *this; + } +#endif + + /** Assignment... + */ + Reference & + SAL_CALL operator= (reference_type * pBody) + { + return set( pBody ); + } + + /** Unbind the body from this handle. + Note that for a handle representing a large body, + "handle.clear().set(new body());" _might_ + perform a little bit better than "handle.set(new body());", + since in the second case two large objects exist in memory + (the old body and the new body). + */ + Reference & SAL_CALL clear() + { + if (m_pBody) + { + reference_type * const pOld = m_pBody; + m_pBody = NULL; + pOld->release(); + } + return *this; + } + + + /** Get the body. Can be used instead of operator->(). + I.e. handle->someBodyOp() and handle.get()->someBodyOp() + are the same. + */ + reference_type * SAL_CALL get() const + { + return m_pBody; + } + + + /** Probably most common used: handle->someBodyOp(). + */ + reference_type * SAL_CALL operator->() const + { + assert(m_pBody != NULL); + return m_pBody; + } + + + /** Allows (*handle).someBodyOp(). + */ + reference_type & SAL_CALL operator*() const + { + assert(m_pBody != NULL); + return *m_pBody; + } + + + /** Returns True if the handle does point to a valid body. + */ + bool SAL_CALL is() const + { + return (m_pBody != NULL); + } + +#if defined LIBO_INTERNAL_ONLY + /** Returns True if the handle does point to a valid body. + */ + explicit operator bool() const + { + return is(); + } +#endif + + /** Returns True if this points to pBody. + */ + bool SAL_CALL operator== (const reference_type * pBody) const + { + return (m_pBody == pBody); + } + + + /** Returns True if handle points to the same body. + */ + bool + SAL_CALL operator== (const Reference & handle) const + { + return (m_pBody == handle.m_pBody); + } + + + /** Needed to place References into STL collection. + */ + bool + SAL_CALL operator!= (const Reference & handle) const + { + return (m_pBody != handle.m_pBody); + } + + + /** Needed to place References into STL collection. + */ + bool + SAL_CALL operator< (const Reference & handle) const + { + return (m_pBody < handle.m_pBody); + } + + + /** Needed to place References into STL collection. + */ + bool + SAL_CALL operator> (const Reference & handle) const + { + return (m_pBody > handle.m_pBody); + } +}; + +} // namespace rtl + +#if defined LIBO_INTERNAL_ONLY +namespace std +{ + +/// @cond INTERNAL +/** + Make rtl::Reference hashable by default for use in STL containers. + + @since LibreOffice 6.3 +*/ +template +struct hash<::rtl::Reference> +{ + std::size_t operator()(::rtl::Reference const & s) const + { return std::size_t(s.get()); } +}; +/// @endcond + +} + +#endif + +#endif /* ! INCLUDED_RTL_REF_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/strbuf.h b/include/rtl/strbuf.h new file mode 100644 index 000000000..0c6eea1de --- /dev/null +++ b/include/rtl/strbuf.h @@ -0,0 +1,143 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_STRBUF_H +#define INCLUDED_RTL_STRBUF_H + +#include "sal/config.h" + +#include "rtl/string.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Allocates a new String that contains characters from + the character array argument. + + The count argument specifies + the length of the array. The initial capacity of the string buffer is + 16 plus the length of the string argument. + + @param newStr out parameter, contains the new string. The reference count is 1. + @param value the initial value of the string. + @param count the length of value. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_stringbuffer_newFromStr_WithLength( + rtl_String ** newStr, + const char * value, + sal_Int32 count); + +/** + Allocates a new String that contains the same sequence of + characters as the string argument. + + The initial capacity is the larger of: +
      +
    • The bufferLen argument. +
    • The length of the string argument. +
    + + @param newStr out parameter, contains the new string. The reference count is 1. + @param capacity the initial len of the string buffer. + @param oldStr the initial value of the string. + @return the new capacity of the string buffer + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_stringbuffer_newFromStringBuffer( + rtl_String ** newStr, + sal_Int32 capacity, + rtl_String * oldStr ); + +/** + Ensures that the capacity of the buffer is at least equal to the + specified minimum. + + If the current capacity of this string buffer is less than the + argument, then a new internal buffer is allocated with greater + capacity. The new capacity is the larger of: +
      +
    • The minimumCapacity argument. +
    • Twice the old capacity, plus 2. +
    + If the minimumCapacity argument is nonpositive, this + method takes no action and simply returns. + + @param[in,out] This the String to operate on. + @param[in,out] capacity in: old capacity, out: new capacity. + @param[in] minimumCapacity the minimum desired capacity. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_stringbuffer_ensureCapacity( + rtl_String ** This, + sal_Int32* capacity, + sal_Int32 minimumCapacity); + + +/** + Inserts the string representation of the char array + argument into this string buffer. + + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. + + @param[in,out] This the String to operate on. + @param[in,out] capacity the capacity of the string buffer + @param[in] offset the offset. + @param[in] str a character array. Since LibreOffice 4.4, as a + special case, if str is null then the len added + characters are left uninitialized. + @param[in] len the number of characters to append. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_stringbuffer_insert( + rtl_String ** This, + sal_Int32 * capacity, + sal_Int32 offset, + const char * str, + sal_Int32 len); + +/** + Removes the characters in a substring of this sequence. + + The substring begins at the specified start and + is len characters long. + + start must be >= 0 && <= This->length + + @param[in,out] This The String to operate on. + @param[in] start The beginning index, inclusive + @param[in] len The substring length + */ +SAL_DLLPUBLIC void SAL_CALL rtl_stringbuffer_remove( + rtl_String ** This, + sal_Int32 start, + sal_Int32 len ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_STRBUF_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/strbuf.hxx b/include/rtl/strbuf.hxx new file mode 100644 index 000000000..098e8b0bb --- /dev/null +++ b/include/rtl/strbuf.hxx @@ -0,0 +1,1131 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#pragma once + +#include "sal/config.h" + +#include +#include +#include + +#include "rtl/strbuf.h" +#include "rtl/string.hxx" +#include "rtl/stringutils.hxx" + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +#include "rtl/stringconcat.hxx" +#include +#include +#endif + +#ifdef RTL_STRING_UNITTEST +extern bool rtl_string_unittest_const_literal; +extern bool rtl_string_unittest_const_literal_function; +#endif + +// The unittest uses slightly different code to help check that the proper +// calls are made. The class is put into a different namespace to make +// sure the compiler generates a different (if generating also non-inline) +// copy of the function and does not merge them together. The class +// is "brought" into the proper rtl namespace by a typedef below. +#ifdef RTL_STRING_UNITTEST +#define rtl rtlunittest +#endif + +namespace rtl +{ + +/// @cond INTERNAL +#ifdef RTL_STRING_UNITTEST +#undef rtl +// helper macro to make functions appear more readable +#define RTL_STRING_CONST_FUNCTION rtl_string_unittest_const_literal_function = true; +#else +#define RTL_STRING_CONST_FUNCTION +#endif +/// @endcond + +/** A string buffer implements a mutable sequence of characters. + */ +class SAL_WARN_UNUSED OStringBuffer +{ +public: + /** + Constructs a string buffer with no characters in it and an + initial capacity of 16 characters. + */ + OStringBuffer() + : pData(NULL) + , nCapacity( 16 ) + { + rtl_string_new_WithLength( &pData, nCapacity ); + } + + /** + Allocates a new string buffer that contains the same sequence of + characters as the string buffer argument. + + @param value a OStringBuffer. + */ + OStringBuffer( const OStringBuffer & value ) + : pData(NULL) + , nCapacity( value.nCapacity ) + { + rtl_stringbuffer_newFromStringBuffer( &pData, value.nCapacity, value.pData ); + } + + /** + Constructs a string buffer with no characters in it and an + initial capacity specified by the length argument. + + @param length the initial capacity. + */ + explicit OStringBuffer(sal_Int32 length) + : pData(NULL) + , nCapacity( length ) + { + rtl_string_new_WithLength( &pData, length ); + } +#if defined LIBO_INTERNAL_ONLY + template + explicit OStringBuffer(T length, std::enable_if_t, int> = 0) + : OStringBuffer(static_cast(length)) + { + assert( + length >= 0 + && static_cast>(length) + <= static_cast>( + std::numeric_limits::max())); + } + // avoid (obvious) bugs + explicit OStringBuffer(bool) = delete; + explicit OStringBuffer(char) = delete; + explicit OStringBuffer(wchar_t) = delete; +#if defined __cpp_char8_t + explicit OStringBuffer(char8_t) = delete; +#endif + explicit OStringBuffer(char16_t) = delete; + explicit OStringBuffer(char32_t) = delete; +#endif + + /** + Constructs a string buffer so that it represents the same + sequence of characters as the string argument. + + The initial + capacity of the string buffer is 16 plus the length + of the string argument. + + @param value the initial string value. + */ +#if defined LIBO_INTERNAL_ONLY + OStringBuffer(std::string_view sv) + : pData(nullptr) + , nCapacity( sv.length() + 16 ) + { + if (sv.size() > sal_uInt32(std::numeric_limits::max())) { + throw std::bad_alloc(); + } + rtl_stringbuffer_newFromStr_WithLength( &pData, sv.data(), sv.length() ); + } +#else + OStringBuffer(const OString& value) + : pData(NULL) + , nCapacity( value.getLength() + 16 ) + { + rtl_stringbuffer_newFromStr_WithLength( &pData, value.getStr(), value.getLength() ); + } +#endif + + /** + @overload + @since LibreOffice 3.6 + */ + template< typename T > + OStringBuffer( const T& value, typename libreoffice_internal::CharPtrDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy()) + : pData(NULL) + { + sal_Int32 length = rtl_str_getLength( value ); + nCapacity = length + 16; + rtl_stringbuffer_newFromStr_WithLength( &pData, value, length ); + } + + template< typename T > + OStringBuffer( T& value, typename libreoffice_internal::NonConstCharArrayDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy()) + : pData(NULL) + { + sal_Int32 length = rtl_str_getLength( value ); + nCapacity = length + 16; + rtl_stringbuffer_newFromStr_WithLength( &pData, value, length ); + } + + /** + Constructs a string buffer so that it represents the same + sequence of characters as the string literal. + + If there are any embedded \0's in the string literal, the result is undefined. + Use the overload that explicitly accepts length. + + @since LibreOffice 3.6 + + @param literal a string literal + */ + template< typename T > + OStringBuffer( T& literal, typename libreoffice_internal::ConstCharArrayDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy()) + : pData(NULL) + , nCapacity( libreoffice_internal::ConstCharArrayDetector::length + 16 ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + rtl_string_newFromLiteral( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length, 16); +#ifdef RTL_STRING_UNITTEST + rtl_string_unittest_const_literal = true; +#endif + } + + /** + Constructs a string buffer so that it represents the same + sequence of characters as the string argument. + + The initial + capacity of the string buffer is 16 plus length + + @param value a character array. + @param length the number of character which should be copied. + The character array length must be greater or + equal than this value. + */ + OStringBuffer(const char * value, sal_Int32 length) + : pData(NULL) + , nCapacity( length + 16 ) + { + rtl_stringbuffer_newFromStr_WithLength( &pData, value, length ); + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OStringBuffer( OStringConcat< T1, T2 >&& c ) + { + const sal_Int32 l = c.length(); + nCapacity = l + 16; + pData = rtl_string_alloc( nCapacity ); + char* end = c.addData( pData->buffer ); + *end = '\0'; + pData->length = l; + } + + /** + @overload + @internal + */ + template< typename T > + OStringBuffer( OStringNumber< T >&& n ) + : OStringBuffer( OString( n )) + {} +#endif + +#if defined LIBO_INTERNAL_ONLY + operator std::string_view() const { return {getStr(), sal_uInt32(getLength())}; } +#endif + + /** Assign to this a copy of value. + */ + OStringBuffer& operator = ( const OStringBuffer& value ) + { + if (this != &value) + { + rtl_stringbuffer_newFromStringBuffer(&pData, + value.nCapacity, + value.pData); + nCapacity = value.nCapacity; + } + return *this; + } + + /** Assign from a string. + + @since LibreOffice 5.3 + */ +#if defined LIBO_INTERNAL_ONLY + OStringBuffer & operator =(std::string_view string) { + sal_Int32 n = string.length(); + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + std::memcpy(pData->buffer, string.data(), n); + pData->buffer[n] = '\0'; + pData->length = n; + return *this; + } +#else + OStringBuffer & operator =(OString const & string) { + sal_Int32 n = string.getLength(); + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + std::memcpy(pData->buffer, string.pData->buffer, n + 1); + pData->length = n; + return *this; + } +#endif + + /** Assign from a string literal. + + @since LibreOffice 5.3 + */ + template + typename + libreoffice_internal::ConstCharArrayDetector::Type + operator =(T & literal) { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + sal_Int32 const n + = libreoffice_internal::ConstCharArrayDetector::length; + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + std::memcpy( + pData->buffer, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + n + 1); + pData->length = n; + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + OStringBuffer & operator =(OStringConcat && concat) { + sal_Int32 const n = concat.length(); + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + *concat.addData(pData->buffer) = 0; + pData->length = n; + return *this; + } + + /** @overload @internal */ + template + OStringBuffer & operator =(OStringNumber && n) + { + *this = OStringBuffer( std::move ( n )); + return *this; + } +#endif + + /** + Release the string data. + */ + ~OStringBuffer() + { + rtl_string_release( pData ); + } + + /** + Fill the string data in the new string and clear the buffer. + + This method is more efficient than the constructor of the string. It does + not copy the buffer. + + @return the string previously contained in the buffer. + */ + SAL_WARN_UNUSED_RESULT OString makeStringAndClear() + { + OString aRet( pData ); + rtl_string_new(&pData); + nCapacity = 0; + return aRet; + } + + /** + Returns the length (character count) of this string buffer. + + @return the number of characters in this string buffer. + */ + sal_Int32 getLength() const + { + return pData->length; + } + + /** + Checks if a string buffer is empty. + + @return true if the string buffer is empty; + false, otherwise. + + @since LibreOffice 4.1 + */ + bool isEmpty() const + { + return pData->length == 0; + } + + /** + Returns the current capacity of the String buffer. + + The capacity + is the amount of storage available for newly inserted + characters. The real buffer size is 2 bytes longer, because + all strings are 0 terminated. + + @return the current capacity of this string buffer. + */ + sal_Int32 getCapacity() const + { + return nCapacity; + } + + /** + Ensures that the capacity of the buffer is at least equal to the + specified minimum. + + The new capacity will be at least as large as the maximum of the current + length (so that no contents of the buffer is destroyed) and the given + minimumCapacity. If the given minimumCapacity is negative, nothing is + changed. + + @param minimumCapacity the minimum desired capacity. + */ + void ensureCapacity(sal_Int32 minimumCapacity) + { + rtl_stringbuffer_ensureCapacity( &pData, &nCapacity, minimumCapacity ); + } + + /** + Sets the length of this String buffer. + + If the newLength argument is less than the current + length of the string buffer, the string buffer is truncated to + contain exactly the number of characters given by the + newLength argument. +

    + If the newLength argument is greater than or equal + to the current length, sufficient null characters + ('\u0000') are appended to the string buffer so that + length becomes the newLength argument. +

    + The newLength argument must be greater than or equal + to 0. + + @param newLength the new length of the buffer. + */ + void setLength(sal_Int32 newLength) + { + assert(newLength >= 0); + // Avoid modifications if pData points to const empty string: + if( newLength != pData->length ) + { + if( newLength > nCapacity ) + rtl_stringbuffer_ensureCapacity(&pData, &nCapacity, newLength); + else + pData->buffer[newLength] = '\0'; + pData->length = newLength; + } + } + + /** + Returns the character at a specific index in this string buffer. + + The first character of a string buffer is at index + 0, the next at index 1, and so on, for + array indexing. +

    + The index argument must be greater than or equal to + 0, and less than the length of this string buffer. + + @param index the index of the desired character. + @return the character at the specified index of this string buffer. + */ + SAL_DEPRECATED("use rtl::OStringBuffer::operator [] instead") + char charAt( sal_Int32 index ) + { + assert(index >= 0 && index < pData->length); + return pData->buffer[ index ]; + } + + /** + The character at the specified index of this string buffer is set + to ch. + + The index argument must be greater than or equal to + 0, and less than the length of this string buffer. + + @param index the index of the character to modify. + @param ch the new character. + */ + SAL_DEPRECATED("use rtl::OStringBuffer::operator [] instead") + OStringBuffer & setCharAt(sal_Int32 index, char ch) + { + assert(index >= 0 && index < pData->length); + pData->buffer[ index ] = ch; + return *this; + } + + /** + Return a null terminated character array. + */ + const char* getStr() const SAL_RETURNS_NONNULL { return pData->buffer; } + + /** + Access to individual characters. + + @param index must be non-negative and less than length. + + @return a reference to the character at the given index. + + @since LibreOffice 3.5 + */ + char & operator [](sal_Int32 index) + { + assert(index >= 0 && index < pData->length); + return pData->buffer[index]; + } + + /** + Return an OString instance reflecting the current content + of this OStringBuffer. + */ + OString toString() const + { + return OString(pData->buffer, pData->length); + } + +#if !defined LIBO_INTERNAL_ONLY + /** + Appends the string to this string buffer. + + The characters of the String argument are appended, in + order, to the contents of this string buffer, increasing the + length of this string buffer by the length of the argument. + + @param str a string. + @return this string buffer. + */ + OStringBuffer & append(const OString &str) + { + return append( str.getStr(), str.getLength() ); + } +#endif + + /** + Appends the string representation of the char array + argument to this string buffer. + + The characters of the array argument are appended, in order, to + the contents of this string buffer. The length of this string + buffer increases by the length of the argument. + + @param str the characters to be appended. + @return this string buffer. + */ + template< typename T > + typename libreoffice_internal::CharPtrDetector< T, OStringBuffer& >::Type append( const T& str ) + { + return append( str, rtl_str_getLength( str ) ); + } + + template< typename T > + typename libreoffice_internal::NonConstCharArrayDetector< T, OStringBuffer& >::Type append( T& str ) + { + return append( str, rtl_str_getLength( str ) ); + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, OStringBuffer& >::Type append( T& literal ) + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return append( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + + /** + Appends the string representation of the char array + argument to this string buffer. + + Characters of the character array str are appended, + in order, to the contents of this string buffer. The length of this + string buffer increases by the value of len. + + @param str the characters to be appended; must be non-null, and must + point to at least len characters + @param len the number of characters to append; must be non-negative + @return this string buffer. + */ + OStringBuffer & append( const char * str, sal_Int32 len) + { + assert( len == 0 || str != NULL ); // cannot assert that in rtl_stringbuffer_insert + rtl_stringbuffer_insert( &pData, &nCapacity, getLength(), str, len ); + return *this; + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OStringBuffer& append( OStringConcat< T1, T2 >&& c ) + { + sal_Int32 l = c.length(); + if( l == 0 ) + return *this; + l += pData->length; + rtl_stringbuffer_ensureCapacity( &pData, &nCapacity, l ); + char* end = c.addData( pData->buffer + pData->length ); + *end = '\0'; + pData->length = l; + return *this; + } + + /** + @overload + @internal + */ + template< typename T > + OStringBuffer& append( OStringNumber< T >&& c ) + { + return append( c.buf, c.length ); + } + + /** + @overload + @internal + */ + OStringBuffer& append( std::string_view s ) + { + return append( s.data(), s.size() ); + } + +#endif + + /** + Appends the string representation of the sal_Bool + argument to the string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param b a sal_Bool. + @return this string buffer. + */ + OStringBuffer & append(sal_Bool b) + { + char sz[RTL_STR_MAX_VALUEOFBOOLEAN]; + return append( sz, rtl_str_valueOfBoolean( sz, b ) ); + } + + /** + Appends the string representation of the bool + argument to the string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param b a bool. + @return this string buffer. + + @since LibreOffice 4.3 + */ + OStringBuffer & append(bool b) + { + char sz[RTL_STR_MAX_VALUEOFBOOLEAN]; + return append( sz, rtl_str_valueOfBoolean( sz, b ) ); + } + + /// @cond INTERNAL + // Pointer can be automatically converted to bool, which is unwanted here. + // Explicitly delete all pointer append() overloads to prevent this + // (except for char* overload, which is handled elsewhere). + template< typename T > + typename libreoffice_internal::Enable< void, + !libreoffice_internal::CharPtrDetector< T* >::ok >::Type + append( T* ) SAL_DELETED_FUNCTION; + /// @endcond + + /** + Appends the string representation of the char + argument to this string buffer. + + The argument is appended to the contents of this string buffer. + The length of this string buffer increases by 1. + + @param c a char. + @return this string buffer. + */ + OStringBuffer & append(char c) + { + return append( &c, 1 ); + } + + /** + Appends the string representation of the sal_Int32 + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param i an sal_Int32. + @param radix the radix + @return this string buffer. + */ + OStringBuffer & append(sal_Int32 i, sal_Int16 radix = 10 ) + { + char sz[RTL_STR_MAX_VALUEOFINT32]; + return append( sz, rtl_str_valueOfInt32( sz, i, radix ) ); + } + + /** + Appends the string representation of the long + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param l a long. + @param radix the radix + @return this string buffer. + */ + OStringBuffer & append(sal_Int64 l, sal_Int16 radix = 10 ) + { + char sz[RTL_STR_MAX_VALUEOFINT64]; + return append( sz, rtl_str_valueOfInt64( sz, l, radix ) ); + } + + /** + Appends the string representation of the float + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param f a float. + @return this string buffer. + */ + OStringBuffer & append(float f) + { + char sz[RTL_STR_MAX_VALUEOFFLOAT]; + return append( sz, rtl_str_valueOfFloat( sz, f ) ); + } + + /** + Appends the string representation of the double + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param d a double. + @return this string buffer. + */ + OStringBuffer & append(double d) + { + char sz[RTL_STR_MAX_VALUEOFDOUBLE]; + return append( sz, rtl_str_valueOfDouble( sz, d ) ); + } + + /** + Unsafe way to make space for a fixed amount of characters to be appended + into this OStringBuffer. + + A call to this function must immediately be followed by code that + completely fills the uninitialized block pointed to by the return value. + + @param length the length of the uninitialized block of char entities; + must be non-negative + + @return a pointer to the start of the uninitialized block; only valid + until this OStringBuffer's capacity changes + + @since LibreOffice 4.4 + */ + char * appendUninitialized(sal_Int32 length) SAL_RETURNS_NONNULL { + sal_Int32 n = getLength(); + rtl_stringbuffer_insert(&pData, &nCapacity, n, NULL, length); + return pData->buffer + n; + } + + /** + Inserts the string into this string buffer. + + The characters of the String argument are inserted, in + order, into this string buffer at the indicated offset. The length + of this string buffer is increased by the length of the argument. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param str a string. + @return this string buffer. + */ +#if defined LIBO_INTERNAL_ONLY + OStringBuffer & insert(sal_Int32 offset, std::string_view str) + { + return insert( offset, str.data(), str.length() ); + } +#else + OStringBuffer & insert(sal_Int32 offset, const OString & str) + { + return insert( offset, str.getStr(), str.getLength() ); + } +#endif + + /** + Inserts the string representation of the char array + argument into this string buffer. + + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param str a character array. + @return this string buffer. + */ + template< typename T > + typename libreoffice_internal::CharPtrDetector< T, OStringBuffer& >::Type insert( sal_Int32 offset, const T& str ) + { + return insert( offset, str, rtl_str_getLength( str ) ); + } + + template< typename T > + typename libreoffice_internal::NonConstCharArrayDetector< T, OStringBuffer& >::Type insert( sal_Int32 offset, T& str ) + { + return insert( offset, str, rtl_str_getLength( str ) ); + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, OStringBuffer& >::Type insert( sal_Int32 offset, T& literal ) + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return insert( + offset, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + + /** + Inserts the string representation of the char array + argument into this string buffer. + + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param str a character array. + @param len the number of characters to append. + @return this string buffer. + */ + OStringBuffer & insert( sal_Int32 offset, const char * str, sal_Int32 len) + { + assert( len == 0 || str != NULL ); // cannot assert that in rtl_stringbuffer_insert + rtl_stringbuffer_insert( &pData, &nCapacity, offset, str, len ); + return *this; + } + + /** + Inserts the string representation of the sal_Bool + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param b a sal_Bool. + @return this string buffer. + */ + OStringBuffer & insert(sal_Int32 offset, sal_Bool b) + { + char sz[RTL_STR_MAX_VALUEOFBOOLEAN]; + return insert( offset, sz, rtl_str_valueOfBoolean( sz, b ) ); + } + + /** + Inserts the string representation of the bool + argument into this string buffer. + + The second argument is converted to a string as if by the method + OString::boolean, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param b a bool. + @return this string buffer. + + @since LibreOffice 4.3 + */ + OStringBuffer & insert(sal_Int32 offset, bool b) + { + char sz[RTL_STR_MAX_VALUEOFBOOLEAN]; + return insert( offset, sz, rtl_str_valueOfBoolean( sz, b ) ); + } + + /** + Inserts the string representation of the char + argument into this string buffer. + + The second argument is inserted into the contents of this string + buffer at the position indicated by offset. The length + of this string buffer increases by one. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param c a char. + @return this string buffer. + */ + OStringBuffer & insert(sal_Int32 offset, char c) + { + return insert( offset, &c, 1 ); + } + + /** + Inserts the string representation of the second sal_Int32 + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param i an sal_Int32. + @param radix the radix + @return this string buffer. + */ + OStringBuffer & insert(sal_Int32 offset, sal_Int32 i, sal_Int16 radix = 10 ) + { + char sz[RTL_STR_MAX_VALUEOFINT32]; + return insert( offset, sz, rtl_str_valueOfInt32( sz, i, radix ) ); + } + + /** + Inserts the string representation of the long + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param l a long. + @param radix the radix + @return this string buffer. + */ + OStringBuffer & insert(sal_Int32 offset, sal_Int64 l, sal_Int16 radix = 10 ) + { + char sz[RTL_STR_MAX_VALUEOFINT64]; + return insert( offset, sz, rtl_str_valueOfInt64( sz, l, radix ) ); + } + + /** + Inserts the string representation of the float + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param f a float. + @return this string buffer. + */ + OStringBuffer insert(sal_Int32 offset, float f) + { + char sz[RTL_STR_MAX_VALUEOFFLOAT]; + return insert( offset, sz, rtl_str_valueOfFloat( sz, f ) ); + } + + /** + Inserts the string representation of the double + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param d a double. + @return this string buffer. + */ + OStringBuffer & insert(sal_Int32 offset, double d) + { + char sz[RTL_STR_MAX_VALUEOFDOUBLE]; + return insert( offset, sz, rtl_str_valueOfDouble( sz, d ) ); + } + + /** + Removes the characters in a substring of this sequence. + + The substring begins at the specified start and + is len characters long. + + start must be >= 0 && <= getLength() && <= end + + @param start The beginning index, inclusive + @param len The substring length + @return this string buffer. + */ + OStringBuffer & remove( sal_Int32 start, sal_Int32 len ) + { + rtl_stringbuffer_remove( &pData, start, len ); + return *this; + } + + /** Allows access to the internal data of this OStringBuffer, for effective + manipulation. + + This function should be used with care. After you have called this + function, you may use the returned pInternalData and pInternalCapacity + only as long as you make no other calls on this OStringBuffer. + + @param pInternalData + This output parameter receives a pointer to the internal data + (rtl_String pointer). pInternalData itself must not be null. + + @param pInternalCapacity + This output parameter receives a pointer to the internal capacity. + pInternalCapacity itself must not be null. + + @since LibreOffice 5.4 + */ + void accessInternals( + rtl_String *** pInternalData, sal_Int32 ** pInternalCapacity) + { + *pInternalData = &pData; + *pInternalCapacity = &nCapacity; + } + +private: + /** + A pointer to the data structure which contains the data. + */ + rtl_String * pData; + + /** + The len of the pData->buffer. + */ + sal_Int32 nCapacity; +}; + +#if defined LIBO_INTERNAL_ONLY +template<> struct ToStringHelper { + static std::size_t length(OStringBuffer const & s) { return s.getLength(); } + + static char * addData(char * buffer, OStringBuffer const & s) SAL_RETURNS_NONNULL + { return addDataHelper(buffer, s.getStr(), s.getLength()); } + + static constexpr bool allowOStringConcat = true; + static constexpr bool allowOUStringConcat = false; +}; +#endif + +} + +#ifdef RTL_STRING_UNITTEST +namespace rtl +{ +typedef rtlunittest::OStringBuffer OStringBuffer; +} +#undef RTL_STRING_CONST_FUNCTION +#endif + +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST +using ::rtl::OStringBuffer; +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/string.h b/include/rtl/string.h new file mode 100644 index 000000000..f80bef02c --- /dev/null +++ b/include/rtl/string.h @@ -0,0 +1,1462 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_STRING_H +#define INCLUDED_RTL_STRING_H + +#include "sal/config.h" + +#include "osl/interlck.h" +#include "rtl/textcvt.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* ======================================================================= */ + +/** Return the length of a string. + + The length is equal to the number of 8-bit characters in the string, + without the terminating NUL character. + + @param str + a null-terminated string. + + @return + the length of the sequence of characters represented by this string, + excluding the terminating NUL character. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_getLength( + const char * str ) SAL_THROW_EXTERN_C(); + +/** Compare two strings. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. Both strings must be + null-terminated. + + @param first + the first null-terminated string to be compared. + + @param second + the second null-terminated string which is compared with the first one. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_compare( + const char * first, const char * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_compare_WithLength( + const char * first, sal_Int32 firstLen, const char * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings with a maximum count of characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @param shortenedLen + the maximum number of characters to compare. This length can be greater + or smaller than the lengths of the two strings. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_shortenedCompare_WithLength( + const char * first, sal_Int32 firstLen, const char * second, sal_Int32 secondLen, sal_Int32 shortenedLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings from back to front. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string + compares less than the second string, and a value greater than 0 if the + first string compares greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_reverseCompare_WithLength( + const char * first, sal_Int32 firstLen, const char * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. Both strings must be null-terminated. + + @param first + the first null-terminated string to be compared. + + @param second + the second null-terminated string which is compared with the first one. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_compareIgnoreAsciiCase( + const char * first, const char * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_compareIgnoreAsciiCase_WithLength( + const char * first, sal_Int32 firstLen, const char * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings with a maximum count of characters, ignoring the case + of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @param shortenedLen + the maximum number of characters to compare. This length can be greater + or smaller than the lengths of the two strings. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_shortenedCompareIgnoreAsciiCase_WithLength( + const char * first, sal_Int32 firstLen, const char * second, sal_Int32 secondLen, sal_Int32 shortenedLen ) SAL_THROW_EXTERN_C(); + +/** Return a hash code for a string. + + It is not allowed to store the hash code persistently, because later + versions could return other hash codes. The string must be + null-terminated. + + @param str + a null-terminated string. + + @return + a hash code for the given string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_hashCode( + const char * str ) SAL_THROW_EXTERN_C(); + +/** Return a hash code for a string. + + It is not allowed to store the hash code persistently, because later + versions could return other hash codes. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @return + a hash code for the given string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_hashCode_WithLength( + const char * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a character within a string. + + The string must be null-terminated. + + @param str + a null-terminated string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the first occurrence of the character in the + string, or -1 if the character does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_indexOfChar( + const char * str, char ch ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a character within a string. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the first occurrence of the character in the + string, or -1 if the character does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_indexOfChar_WithLength( + const char * str, sal_Int32 len, char ch ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a character within a string. + + The string must be null-terminated. + + @param str + a null-terminated string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the last occurrence of the character in the + string, or -1 if the character does not occur. The returned value is + always smaller than the string length. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_lastIndexOfChar( + const char * str, char ch ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a character within a string. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the last occurrence of the character in the + string, or -1 if the character does not occur. The returned value is + always smaller than the string length. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_lastIndexOfChar_WithLength( + const char * str, sal_Int32 len, char ch ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + Both strings must be null-terminated. + + @param str + a null-terminated string. + + @param subStr + the null-terminated substring to be searched for. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_indexOfStr( + const char * str, const char * subStr ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param subStr + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified subLen. + + @param subLen + the length of the substring. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_indexOfStr_WithLength( + const char * str, sal_Int32 len, const char * subStr, sal_Int32 subLen ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + Both strings must be null-terminated. + + @param str + a null-terminated string. + + @param subStr + the null-terminated substring to be searched for. + + @return + the index (starting at 0) of the first character of the last occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_lastIndexOfStr( + const char * str, const char * subStr ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param subStr + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified subLen. + + @param subLen + the length of the substring. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_lastIndexOfStr_WithLength( + const char * str, sal_Int32 len, const char * subStr, sal_Int32 subLen ) SAL_THROW_EXTERN_C(); + +/** Replace all occurrences of a single character within a string. + + If oldChar does not occur within str, then the string is not modified. + The string must be null-terminated. + + @param str + a null-terminated string. + + @param oldChar + the old character. + + @param newChar + the new character. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_str_replaceChar( + char * str, char oldChar, char newChar ) SAL_THROW_EXTERN_C(); + +/** Replace all occurrences of a single character within a string. + + If oldChar does not occur within str, then the string is not modified. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param oldChar + the old character. + + @param newChar + the new character. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_str_replaceChar_WithLength( + char * str, sal_Int32 len, char oldChar, char newChar ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII uppercase letters to lowercase within a string. + + The characters with values between 65 and 90 (ASCII A--Z) are replaced + with values between 97 and 122 (ASCII a--z). The string must be + null-terminated. + + @param str + a null-terminated string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_str_toAsciiLowerCase( + char * str ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII uppercase letters to lowercase within a string. + + The characters with values between 65 and 90 (ASCII A--Z) are replaced + with values between 97 and 122 (ASCII a--z). + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_str_toAsciiLowerCase_WithLength( + char * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII lowercase letters to uppercase within a string. + + The characters with values between 97 and 122 (ASCII a--z) are replaced + with values between 65 and 90 (ASCII A--Z). The string must be + null-terminated. + + @param str + a null-terminated string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_str_toAsciiUpperCase( + char * str ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII lowercase letters to uppercase within a string. + + The characters with values between 97 and 122 (ASCII a--z) are replaced + with values between 65 and 90 (ASCII A--Z). + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_str_toAsciiUpperCase_WithLength( + char * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Remove white space from both ends of a string. + + All characters with values less than or equal to 32 (the space character) + are considered to be white space. This function cannot be used for + language-specific operations. The string must be null-terminated. + + @param str + a null-terminated string. + + @return + the new length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_trim( + char * str ) SAL_THROW_EXTERN_C(); + +/** Remove white space from both ends of the string. + + All characters with values less than or equal to 32 (the space character) + are considered to be white space. This function cannot be used for + language-specific operations. The string must be null-terminated. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the original length of the string. + + @return + the new length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_trim_WithLength( + char * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Create the string representation of a boolean. + + If b is true, the buffer is filled with the string "true" and 5 is + returned. If b is false, the buffer is filled with the string "false" and + 6 is returned. This function cannot be used for language-specific + operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFBOOLEAN define to create + a buffer that is big enough. + + @param b + a boolean value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfBoolean( + char * str, sal_Bool b ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MAX_VALUEOFBOOLEAN 6 + +/** Create the string representation of a character. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFCHAR define to create a + buffer that is big enough. + + @param ch + a character value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfChar( + char * str, char ch ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MAX_VALUEOFCHAR 2 + +/** Create the string representation of an integer. + + This function cannot be used for language-specific operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFINT32 define to create a + buffer that is big enough. + + @param i + an integer value. + + @param radix + the radix. Must be between RTL_STR_MIN_RADIX (2) and RTL_STR_MAX_RADIX + (36), inclusive. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfInt32( + char * str, sal_Int32 i, sal_Int16 radix ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MIN_RADIX 2 +#define RTL_STR_MAX_RADIX 36 +#define RTL_STR_MAX_VALUEOFINT32 33 + +/** Create the string representation of a long integer. + + This function cannot be used for language-specific operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFINT64 define to create a + buffer that is big enough. + + @param l + a long integer value. + + @param radix + the radix. Must be between RTL_STR_MIN_RADIX (2) and RTL_STR_MAX_RADIX + (36), inclusive. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfInt64( + char * str, sal_Int64 l, sal_Int16 radix ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MAX_VALUEOFINT64 65 + +/** Create the string representation of an unsigned long integer. + + This function cannot be used for language-specific operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFUINT64 define to create a + buffer that is big enough. + + @param l + a long integer value. + + @param radix + the radix. Must be between RTL_STR_MIN_RADIX (2) and RTL_STR_MAX_RADIX + (36), inclusive. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfUInt64( + char * str, sal_uInt64 l, sal_Int16 radix ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MAX_VALUEOFUINT64 65 + +/** Create the string representation of a float. + + This function cannot be used for language-specific conversion. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFFLOAT define to create a + buffer that is big enough. + + @param f + a float value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfFloat( + char * str, float f ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MAX_VALUEOFFLOAT 15 + +/** Create the string representation of a double. + + This function cannot be used for language-specific conversion. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_STR_MAX_VALUEOFDOUBLE define to create + a buffer that is big enough. + + @param d + a double value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_valueOfDouble( + char * str, double d ) SAL_THROW_EXTERN_C(); +#define RTL_STR_MAX_VALUEOFDOUBLE 25 + +/** Interpret a string as a boolean. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @return + true if the string is "1" or "true" in any ASCII case, false otherwise. + */ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_str_toBoolean( + const char * str ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as an integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_STR_MIN_RADIX (2) and RTL_STR_MAX_RADIX + (36), inclusive. + + @return + the integer value represented by the string, or 0 if the string does not + represent an integer. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_str_toInt32( + const char * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as an unsigned integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the unsigned integer value represented by the string, or 0 if the string + does not represent an unsigned integer. + + @since LibreOffice 4.2 + */ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL rtl_str_toUInt32( + const char * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a long integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_STR_MIN_RADIX (2) and RTL_STR_MAX_RADIX + (36), inclusive. + + @return + the long integer value represented by the string, or 0 if the string does + not represent a long integer. + */ +SAL_DLLPUBLIC sal_Int64 SAL_CALL rtl_str_toInt64( + const char * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a long integer. + + This function cannot be used for language-specific conversion. + + @param str + a string. + + @param radix + the radix. Must be between RTL_STR_MIN_RADIX (2) and RTL_STR_MAX_RADIX + (36), inclusive. + + @param nStrLength + number of chars to process + + @return + the long integer value represented by the string, or 0 if the string does + not represent a long integer. + + @internal + @since LibreOffice 6.4 +*/ +SAL_DLLPUBLIC sal_Int64 SAL_CALL rtl_str_toInt64_WithLength( + const char * str, sal_Int16 radix, sal_Int32 nStrLength ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as an unsigned long integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the unsigned long integer value represented by the string, or 0 if the + string does not represent an unsigned long integer. + + @since LibreOffice 4.1 + */ +SAL_DLLPUBLIC sal_uInt64 SAL_CALL rtl_str_toUInt64( + const char * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a float. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @return + the float value represented by the string, or 0.0 if the string does not + represent a float. + */ +SAL_DLLPUBLIC float SAL_CALL rtl_str_toFloat( + const char * str ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a double. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @return + the float value represented by the string, or 0.0 if the string does not + represent a double. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_str_toDouble( + const char * str ) SAL_THROW_EXTERN_C(); + +/* ======================================================================= */ + +#ifdef _WIN32 +# pragma pack(push, 8) +#endif + +/** @cond INTERNAL */ +/** The implementation of a byte string. + */ +typedef struct _rtl_String +{ + oslInterlockedCount refCount; /* opaque */ + sal_Int32 length; + char buffer[1]; +} rtl_String; +/** @endcond */ + +#if defined(_WIN32) +#pragma pack(pop) +#endif + +/* ----------------------------------------------------------------------- */ + +/** Increment the reference count of a string. + + @param str + a string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_acquire( rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Decrement the reference count of a string. + + If the count goes to zero than the string data is deleted. + + @param str + a string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_release( rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string containing no characters. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_new( rtl_String ** newStr ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string containing space for a given number of characters. + + The reference count of the new string will be 1. The length of the string + will be nLen. This function does not handle out-of-memory conditions. + + For failed allocation this method returns NULL. + + The characters of the capacity are not cleared, and the length is set to + nLen, unlike the similar method of rtl_String_new_WithLength which + zeros out the buffer, and sets the length to 0. So should be somewhat + more efficient for allocating a new string. + + call rtl_String_release to release the string + alternatively pass ownership to an OUString with + rtl::OUString(newStr, SAL_NO_ACQUIRE); + + @param[out] nLen the number of characters. Must be >= 0. + + @return pointer to the new string. + + @since LibreOffice 4.1 + */ +SAL_DLLPUBLIC rtl_String * SAL_CALL rtl_string_alloc(sal_Int32 nLen) SAL_THROW_EXTERN_C(); + +/** Allocate a new string containing space for a given number of characters. + + If len is greater than zero, the reference count of the new string will be + 1. The values of all characters are set to 0 and the length of the string + is 0. This function does not handle out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param len + the number of characters. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_new_WithLength( rtl_String ** newStr, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of another string. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newFromString( rtl_String ** newStr, const rtl_String * value ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of a character array. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a null-terminated character array. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newFromStr( rtl_String ** newStr, const char * value ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of a character array. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a character array. Need not be null-terminated, but must be at least as + long as the specified len. + + @param len + the length of the character array. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newFromStr_WithLength( rtl_String ** newStr, const char * value, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that is a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. Meaningless combinations such as negative beginIndex, + or beginIndex + count greater than the length of the string have + undefined behaviour. + + @param[out] newStr the specified substring. + @param[in] from the String to take the substring from. + @param[in] beginIndex the beginning index, inclusive. + @param[in] count the number of characters. + + @since LibreOffice 4.0 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newFromSubString( + rtl_String ** newStr, const rtl_String * from, + sal_Int32 beginIndex, sal_Int32 count ) SAL_THROW_EXTERN_C(); + +/** + @internal + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newFromLiteral( rtl_String ** newStr, const char * value, sal_Int32 len, sal_Int32 allocExtra ) SAL_THROW_EXTERN_C(); + +/** Assign a new value to a string. + + First releases any value str might currently hold, then acquires + rightValue. + + @param str + pointer to the string. The pointed-to data must be null or a valid + string. + + @param rightValue + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_assign( rtl_String ** str, rtl_String * rightValue ) SAL_THROW_EXTERN_C(); + +/** Return the length of a string. + + The length is equal to the number of characters in the string. + + @param str + a valid string. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_string_getLength( const rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Return a pointer to the underlying character array of a string. + + @param str + a valid string. + + @return + a pointer to the null-terminated character array. + */ +SAL_DLLPUBLIC char * SAL_CALL rtl_string_getStr( rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string that is the concatenation of two other strings. + + The new string does not necessarily have a reference count of 1 (in cases + where one of the two other strings is empty), so it must not be modified + without checking the reference count. This function does not handle + out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param left + a valid string. + + @param right + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newConcat( rtl_String ** newStr, rtl_String * left, rtl_String * right ) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing a substring of another string. + + The new string results from replacing a number of characters (count), + starting at the specified position (index) in the original string (str), + with some new substring (subStr). If subStr is null, then only a number + of characters is deleted. + + The new string does not necessarily have a reference count of 1, so it + must not be modified without checking the reference count. This function + does not handle out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + + @param idx + the index into str at which to start replacement. Must be between 0 and + the length of str, inclusive. + + @param count + the number of characters to remove. Must not be negative, and the sum of + index and count must not exceed the length of str. + + @param subStr + either null or a valid string to be inserted. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newReplaceStrAt( + rtl_String ** newStr, rtl_String * str, sal_Int32 idx, sal_Int32 count, rtl_String * subStr ) SAL_THROW_EXTERN_C(); + +#ifdef LIBO_INTERNAL_ONLY +SAL_DLLPUBLIC void SAL_CALL rtl_string_newReplaceStrAt_WithLength ( + rtl_String ** newStr, rtl_String * str, sal_Int32 idx, sal_Int32 count, char const * subStr, sal_Int32 substrLen ) SAL_THROW_EXTERN_C(); +#endif + +/** Create a new string by replacing all occurrences of a single character + within another string. + + The new string results from replacing all occurrences of oldChar in str + with newChar. + + The new string does not necessarily have a reference count of 1 (in cases + where oldChar does not occur in str), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + + @param oldChar + the old character. + + @param newChar + the new character. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newReplace( + rtl_String ** newStr, rtl_String * str, char oldChar, char newChar ) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_String + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the replacing substring; must not be null and must + point to memory of at least \p toLength bytes + + @param toLength the length of the \p to substring; must be non-negative + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place or -1 if no replacement took place + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newReplaceFirst( + rtl_String ** newStr, rtl_String * str, char const * from, + sal_Int32 fromLength, char const * to, sal_Int32 toLength, + sal_Int32 * index) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_String + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the replacing substring; must not be null and must + point to memory of at least \p toLength bytes + + @param toLength the length of the \p to substring; must be non-negative + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newReplaceAll( + rtl_String ** newStr, rtl_String * str, char const * from, + sal_Int32 fromLength, char const * to, sal_Int32 toLength) + SAL_THROW_EXTERN_C(); + +/** Create a new string by converting all ASCII uppercase letters to lowercase + within another string. + + The new string results from replacing all characters with values between + 65 and 90 (ASCII A--Z) by values between 97 and 122 (ASCII a--z). + + This function cannot be used for language-specific conversion. The new + string does not necessarily have a reference count of 1 (in cases where + no characters need to be converted), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newToAsciiLowerCase( + rtl_String ** newStr, rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string by converting all ASCII lowercase letters to uppercase + within another string. + + The new string results from replacing all characters with values between + 97 and 122 (ASCII a--z) by values between 65 and 90 (ASCII A--Z). + + This function cannot be used for language-specific conversion. The new + string does not necessarily have a reference count of 1 (in cases where + no characters need to be converted), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newToAsciiUpperCase( + rtl_String ** newStr, rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string by removing white space from both ends of another + string. + + The new string results from removing all characters with values less than + or equal to 32 (the space character) form both ends of str. + + This function cannot be used for language-specific conversion. The new + string does not necessarily have a reference count of 1 (in cases where + no characters need to be removed), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_newTrim( + rtl_String ** newStr, rtl_String * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string by extracting a single token from another string. + + Starting at index, the next token is searched for. If there is no + such token, the result is an empty string. Otherwise, all characters from + the start of that token and up to, but not including the next occurrence + of cTok make up the resulting token. The return value is the position of + the next token, or -1 if no more tokens follow. + + Example code could look like + rtl_String * pToken = NULL; + sal_Int32 nIndex = 0; + do + { + ... + nIndex = rtl_string_getToken(&pToken, pStr, 0, ';', nIndex); + ... + } + while (nIndex >= 0); + + The new string does not necessarily have a reference count of 1, so it + must not be modified without checking the reference count. This function + does not handle out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. If either token or index is negative, an empty token is stored in + newStr (and -1 is returned). + + @param str + a valid string. + + @param token + the number of the token to return, starting at index. + + @param cTok + the character that separates the tokens. + + @param idx + the position at which searching for the token starts. Must not be greater + than the length of str. + + @return + the index of the next token, or -1 if no more tokens follow. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_string_getToken( + rtl_String ** newStr , rtl_String * str, sal_Int32 token, char cTok, sal_Int32 idx ) SAL_THROW_EXTERN_C(); + +/* ======================================================================= */ + +/** Supply an ASCII string literal together with its length. + + This macro can be used to compute (some of) the arguments in function calls + like rtl::OString(RTL_CONSTASCII_STRINGPARAM("foo")) or + rtl::OUString::equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("foo")). + + @param constAsciiStr + must be an expression of type "(possibly cv-qualified reference to) array of + (possibly cv-qualified) char." Each element of the referenced array must + represent an ASCII value in the range 0x00--0x7F. The last element of the + referenced array is not considered part of the represented ASCII string, and + its value should be 0x00. Depending on where this macro is used, the nature + of the supplied expression might be further restricted. +*/ +// The &foo[0] trick is intentional, it makes sure the type is char* or const char* +// (plain cast to const char* would not work with non-const char foo[]="a", which seems to be allowed). +// This is to avoid mistaken use with functions that accept string literals +// (i.e. const char (&)[N]) where usage of this macro otherwise could match +// the argument and a following int argument with a default value (e.g. OString::match()). +#define RTL_CONSTASCII_STRINGPARAM( constAsciiStr ) (&(constAsciiStr)[0]), \ + ((sal_Int32)SAL_N_ELEMENTS(constAsciiStr)-1) + +/** Supply the length of an ASCII string literal. + + This macro can be used to compute arguments in function calls like + rtl::OUString::match(other, RTL_CONSTASCII_LENGTH("prefix")). + + @param constAsciiStr + must be an expression of type "(possibly cv-qualified reference to) array of + (possibly cv-qualified) char." Each element of the referenced array must + represent an ASCII value in the range 0x00--0x7F. The last element of the + referenced array is not considered part of the represented ASCII string, and + its value should be 0x00. Depending on where this macro is used, the nature + of the supplied expression might be further restricted. +*/ +#define RTL_CONSTASCII_LENGTH( constAsciiStr ) ((sal_Int32)(SAL_N_ELEMENTS(constAsciiStr)-1)) + +/* ======================================================================= */ + +/* predefined constants for String-Conversion */ +#define OUSTRING_TO_OSTRING_CVTFLAGS (RTL_UNICODETOTEXT_FLAGS_UNDEFINED_DEFAULT |\ + RTL_UNICODETOTEXT_FLAGS_INVALID_DEFAULT |\ + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |\ + RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0) + +/* ----------------------------------------------------------------------- */ + +/** Create a new byte string by converting a Unicode string, using a specific + text encoding. + + The lengths of the byte string and the Unicode string may differ (e.g., + for double-byte encodings, UTF-7, UTF-8). + + If the length of the Unicode string is greater than zero, the reference + count of the new string will be 1. + + If an out-of-memory condition occurs, newStr will point to a null pointer + upon return. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a Unicode character array. Need not be null-terminated, but must be at + least as long as the specified len. + + @param len + the length of the Unicode character array. + + @param encoding + the text encoding to use for conversion. + + @param convertFlags + flags which control the conversion. Either use + OUSTRING_TO_OSTRING_CVTFLAGS, or see + for more + details. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString2String( + rtl_String ** newStr, const sal_Unicode * str, sal_Int32 len, rtl_TextEncoding encoding, sal_uInt32 convertFlags ) SAL_THROW_EXTERN_C(); + +/** + Converts a Unicode string to a byte string, signalling failure. + + @param pTarget + An out parameter receiving the converted string. Must not be null itself, and + must contain either null or a pointer to a valid rtl_String; the contents are + not modified if conversion fails (rtl_convertUStringToString returns false). + + @param pSource + The Unicode string. May only be null if nLength is zero. + + @param nLength + The length of the Unicode string. Must be non-negative. + + @param nEncoding + The text encoding to convert into. Must be an octet encoding (i.e., + rtl_isOctetTextEncoding(nEncoding) must return true). + + @param nFlags + A combination of RTL_UNICODETOTEXT_FLAGS that detail how to do the conversion + (see rtl_convertUnicodeToText). RTL_UNICODETOTEXT_FLAGS_FLUSH need not be + included, it is implicitly assumed. Typical uses are either + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR | + RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR (fail if a Unicode character cannot be + converted to the target nEncoding) or OUSTRING_TO_OSTRING_CVTFLAGS (make a + best efforts conversion). + + @return + True if the conversion succeeded, false otherwise. + */ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_convertUStringToString( + rtl_String ** pTarget, + sal_Unicode const * pSource, + sal_Int32 nLength, + rtl_TextEncoding nEncoding, + sal_uInt32 nFlags) + SAL_THROW_EXTERN_C(); + +/** Ensure a string has enough space for a given number of characters. + + If the given string is large enough and has refcount of 1, it is not altered in any way. + Otherwise it is replaced by a copy that has enough space for the given number of characters, + data from the source string is copied to the beginning of it, the content of the remaining + capacity undefined, the string has refcount of 1, and refcount of the original string is decreased. + + @param str + pointer to the string. The pointed-to data must be a valid string. + + @param size + the number of characters + + @since LibreOffice 4.1 + @internal + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string_ensureCapacity( rtl_String ** str, sal_Int32 size ) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_STRING_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/string.hxx b/include/rtl/string.hxx new file mode 100644 index 000000000..0e3dad692 --- /dev/null +++ b/include/rtl/string.hxx @@ -0,0 +1,2314 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_STRING_HXX +#define INCLUDED_RTL_STRING_HXX + +#include "sal/config.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined LIBO_INTERNAL_ONLY +#include +#include +#endif + +#include "rtl/textenc.h" +#include "rtl/string.h" +#include "rtl/stringutils.hxx" + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +#include "config_global.h" +#include "rtl/stringconcat.hxx" +#endif + +#ifdef RTL_STRING_UNITTEST +extern bool rtl_string_unittest_const_literal; +extern bool rtl_string_unittest_const_literal_function; +#endif + +// The unittest uses slightly different code to help check that the proper +// calls are made. The class is put into a different namespace to make +// sure the compiler generates a different (if generating also non-inline) +// copy of the function and does not merge them together. The class +// is "brought" into the proper rtl namespace by a typedef below. +#ifdef RTL_STRING_UNITTEST +#define rtl rtlunittest +#endif + +namespace rtl +{ + +/// @cond INTERNAL +#ifdef RTL_STRING_UNITTEST +#undef rtl +// helper macro to make functions appear more readable +#define RTL_STRING_CONST_FUNCTION rtl_string_unittest_const_literal_function = true; +#else +#define RTL_STRING_CONST_FUNCTION +#endif +/// @endcond + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +/** +A wrapper dressing a string literal as a static-refcount rtl_String. + +This class is not part of public API and is meant to be used only in LibreOffice code. +@since LibreOffice 4.0 +*/ +template class SAL_WARN_UNUSED OStringLiteral { + static_assert(N != 0); + static_assert(N - 1 <= std::numeric_limits::max(), "literal too long"); + friend class OString; + +public: +#if HAVE_CPP_CONSTEVAL + consteval +#else + constexpr +#endif + OStringLiteral(char const (&literal)[N]) { + assertLayout(); + assert(literal[N - 1] == '\0'); + //TODO: Use C++20 constexpr std::copy_n (P0202R3): + for (std::size_t i = 0; i != N; ++i) { + more.buffer[i] = literal[i]; + } + } + +#if defined __cpp_char8_t +#if HAVE_CPP_CONSTEVAL + consteval +#else + constexpr +#endif + explicit OStringLiteral(char8_t const (&literal)[N]) { + assertLayout(); + assert(literal[N - 1] == '\0'); + //TODO: Use C++20 constexpr std::copy_n (P0202R3): + for (std::size_t i = 0; i != N; ++i) { + more.buffer[i] = literal[i]; + } + } +#endif + + constexpr sal_Int32 getLength() const { return more.length; } + + constexpr char const * getStr() const SAL_RETURNS_NONNULL { return more.buffer; } + + constexpr operator std::string_view() const { return {more.buffer, sal_uInt32(more.length)}; } + +private: + static constexpr void assertLayout() { + // These static_asserts verifying the layout compatibility with rtl_String cannot be class + // member declarations, as offsetof requires a complete type, so defer them to here: + static_assert(std::is_standard_layout_v); + static_assert(offsetof(OStringLiteral, str.refCount) == offsetof(OStringLiteral, more.refCount)); + static_assert(offsetof(OStringLiteral, str.length) == offsetof(OStringLiteral, more.length)); + static_assert(offsetof(OStringLiteral, str.buffer) == offsetof(OStringLiteral, more.buffer)); + } + + struct Data { + Data() = default; + + oslInterlockedCount refCount = 0x40000000; // SAL_STRING_STATIC_FLAG (sal/rtl/strimp.hxx) + sal_Int32 length = N - 1; + char buffer[N] = {}; //TODO: drop initialization for C++20 (P1331R2) + }; + + union { + rtl_String str; + Data more = {}; + }; +}; +#endif + +/* ======================================================================= */ + +/** + This String class provide base functionality for C++ like 8-Bit + character array handling. The advantage of this class is, that it + handle all the memory management for you - and it do it + more efficient. If you assign a string to another string, the + data of both strings are shared (without any copy operation or + memory allocation) as long as you do not change the string. This class + stores also the length of the string, so that many operations are + faster as the C-str-functions. + + This class provides only readonly string handling. So you could create + a string and you could only query the content from this string. + It provides also functionality to change the string, but this results + in every case in a new string instance (in the most cases with an + memory allocation). You don't have functionality to change the + content of the string. If you want to change the string content, then + you should use the OStringBuffer class, which provides these + functionalities and avoid too much memory allocation. + + The design of this class is similar to the string classes in Java + and so more people should have fewer understanding problems when they + use this class. +*/ + +class SAL_WARN_UNUSED SAL_DLLPUBLIC_RTTI OString +{ +public: + /// @cond INTERNAL + rtl_String * pData; + /// @endcond + + /** + New string containing no characters. + */ + OString() + { + pData = NULL; + rtl_string_new( &pData ); + } + + /** + New string from OString. + + @param str an OString. + */ + OString( const OString & str ) + { + pData = str.pData; + rtl_string_acquire( pData ); + } + +#if defined LIBO_INTERNAL_ONLY + /** + Move constructor. + + @param str an OString. + @since LibreOffice 5.2 + */ + OString( OString && str ) noexcept + { + pData = str.pData; + str.pData = nullptr; + rtl_string_new( &str.pData ); + } +#endif + + /** + New string from OString data. + + @param str an OString data. + */ + OString( rtl_String * str ) + { + pData = str; + rtl_string_acquire( pData ); + } + + /** New string from OString data without acquiring it. Takeover of ownership. + + The SAL_NO_ACQUIRE dummy parameter is only there to distinguish this + from other constructors. + + @param str an OString data. + */ + OString( rtl_String * str, __sal_NoAcquire ) + { + pData = str; + } + + /** + New string from a single character. + + @param value a character. + */ + explicit OString( char value ) + : pData (NULL) + { + rtl_string_newFromStr_WithLength( &pData, &value, 1 ); + } + +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST_CONCAT + // Catch inadvertent conversions to the above ctor (e.g., from sal_[u]Int8, aka [un]signed + // char): + OString(int) = delete; +#endif + + /** + New string from a character buffer array. + + Note: The argument type is always either char* or const char*. The template is + used only for technical reasons, as is the second argument. + + @param value a NULL-terminated character array. + */ + template< typename T > + OString( const T& value, typename libreoffice_internal::CharPtrDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy() ) + { + pData = NULL; + rtl_string_newFromStr( &pData, value ); + } + + template< typename T > + OString( T& value, typename libreoffice_internal::NonConstCharArrayDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy() ) + { + pData = NULL; + rtl_string_newFromStr( &pData, value ); + } + + /** + New string from a string literal. + + If there are any embedded \0's in the string literal, the result is undefined. + Use the overload that explicitly accepts length. + + @since LibreOffice 3.6 + + @param literal a string literal + */ + template< typename T > + OString( T& literal, typename libreoffice_internal::ConstCharArrayDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy() ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + pData = NULL; + if (libreoffice_internal::ConstCharArrayDetector::length == 0) { + rtl_string_new(&pData); + } else { + rtl_string_newFromLiteral( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, 0); + } +#ifdef RTL_STRING_UNITTEST + rtl_string_unittest_const_literal = true; +#endif + } + + /** + New string from a character buffer array. + + @param value a character array. + @param length the number of character which should be copied. + The character array length must be greater or + equal than this value. + */ + OString( const char * value, sal_Int32 length ) + { + pData = NULL; + rtl_string_newFromStr_WithLength( &pData, value, length ); + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /// @cond INTERNAL + /** + New string from an 8-Bit string literal. + + @since LibreOffice 7.1 + */ + template constexpr OString(OStringLiteral const & literal): + pData(const_cast(&literal.str)) {} + template OString(OStringLiteral &&) = delete; + /// @endcond +#endif + +#if defined LIBO_INTERNAL_ONLY + explicit OString(std::string_view sv) { + if (sv.size() > sal_uInt32(std::numeric_limits::max())) { + throw std::bad_alloc(); + } + pData = nullptr; + rtl_string_newFromStr_WithLength(&pData, sv.data(), sv.size()); + } +#endif + + /** + New string from a Unicode character buffer array. + + @param value a Unicode character array. + @param length the number of character which should be converted. + The Unicode character array length must be + greater or equal than this value. + @param encoding the text encoding in which the Unicode character + sequence should be converted. + @param convertFlags flags which controls the conversion. + see RTL_UNICODETOTEXT_FLAGS_... + + @exception std::bad_alloc is thrown if an out-of-memory condition occurs + */ + OString( const sal_Unicode * value, sal_Int32 length, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OUSTRING_TO_OSTRING_CVTFLAGS ) + { + pData = NULL; + rtl_uString2String( &pData, value, length, encoding, convertFlags ); + if (pData == NULL) { + throw std::bad_alloc(); + } + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OString( OStringConcat< T1, T2 >&& c ) + { + const sal_Int32 l = c.length(); + pData = rtl_string_alloc( l ); + if (l != 0) + { + char* end = c.addData( pData->buffer ); + pData->length = l; + *end = '\0'; + } + } + + /** + @overload + @internal + */ + template< typename T > + OString( OStringNumber< T >&& n ) + : OString( n.buf, n.length ) + {} +#endif + +#ifdef LIBO_INTERNAL_ONLY + OString(std::nullptr_t) = delete; +#endif + + /** + Release the string data. + */ + ~OString() + { + rtl_string_release( pData ); + } + + /** + Assign a new string. + + @param str an OString. + */ + OString & operator=( const OString & str ) + { + rtl_string_assign( &pData, str.pData ); + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** + Move assign a new string. + + @param str an OString. + @since LibreOffice 5.2 + */ + OString & operator=( OString && str ) noexcept + { + rtl_string_release( pData ); + pData = str.pData; + str.pData = nullptr; + rtl_string_new( &str.pData ); + return *this; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, OString& >::Type operator=( T& literal ) + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + if (libreoffice_internal::ConstCharArrayDetector::length == 0) { + rtl_string_new(&pData); + } else { + rtl_string_newFromLiteral( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, 0); + } + return *this; + } + + /** + Append a string to this string. + + @param str an OString. + */ + OString & operator+=( const OString & str ) +#if defined LIBO_INTERNAL_ONLY + & +#endif + { + rtl_string_newConcat( &pData, pData, str.pData ); + return *this; + } +#if defined LIBO_INTERNAL_ONLY + void operator+=(OString const &) && = delete; +#endif + +#if defined LIBO_INTERNAL_ONLY + template typename libreoffice_internal::CharPtrDetector::Type + operator +=(T const & value) & { return operator +=(std::string_view(value)); } + template typename libreoffice_internal::CharPtrDetector::Type + operator +=(T const &) && = delete; + + template + typename libreoffice_internal::NonConstCharArrayDetector::Type + operator +=(T & value) & { return operator +=(std::string_view(value)); } + template + typename libreoffice_internal::NonConstCharArrayDetector::Type operator +=(T &) && + = delete; + + template typename libreoffice_internal::ConstCharArrayDetector::Type + operator +=(T & literal) & { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return operator +=( + std::string_view( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length)); + } + template typename libreoffice_internal::ConstCharArrayDetector::Type + operator +=(T &) && = delete; + + template OString & operator +=(OStringLiteral const & literal) & + { return operator +=(std::string_view(literal.getStr(), literal.getLength())); } + template void operator +=(OStringLiteral const &) && = delete; + + OString & operator +=(std::string_view sv) & { + if (sv.empty()) { + return *this; + } + if (sv.size() > sal_uInt32(std::numeric_limits::max() - pData->length)) { + throw std::bad_alloc(); + } + auto const l = pData->length + sv.size(); + rtl_string_ensureCapacity(&pData, l); + *addDataHelper(pData->buffer + pData->length, sv.data(), sv.size()) = '\0'; + pData->length = l; + return *this; + } + void operator +=(std::string_view) && = delete; +#endif + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OString& operator+=( OStringConcat< T1, T2 >&& c ) & { + sal_Int32 l = c.length(); + if( l == 0 ) + return *this; + l += pData->length; + rtl_string_ensureCapacity( &pData, l ); + char* end = c.addData( pData->buffer + pData->length ); + *end = '\0'; + pData->length = l; + return *this; + } + template void operator +=( + OStringConcat &&) && = delete; + + /** + @overload + @internal + */ + template< typename T > + OString& operator+=( OStringNumber< T >&& n ) & { + return operator +=(std::string_view(n.buf, n.length)); + } + template void operator +=( + OStringNumber &&) && = delete; +#endif + + /** + Clears the string, i.e, makes a zero-character string + @since LibreOffice 4.4 + */ + void clear() + { + rtl_string_new( &pData ); + } + + /** + Returns the length of this string. + + The length is equal to the number of characters in this string. + + @return the length of the sequence of characters represented by this + object. + */ + sal_Int32 getLength() const { return pData->length; } + + /** + Checks if a string is empty. + + @return true if the string is empty; + false, otherwise. + + @since LibreOffice 3.4 + */ + bool isEmpty() const + { + return pData->length == 0; + } + + /** + Returns a pointer to the characters of this string. + +

    The returned pointer is guaranteed to point to a null-terminated byte + string. But note that this string object may contain embedded null + characters, which will thus also be embedded in the returned + null-terminated byte string.

    + + @return a pointer to a null-terminated byte string representing the + characters of this string object. + */ + const char * getStr() const SAL_RETURNS_NONNULL { return pData->buffer; } + + /** + Access to individual characters. + + @param index must be non-negative and less than length. + + @return the character at the given index. + + @since LibreOffice 3.5 + */ + char operator [](sal_Int32 index) const { + // silence spurious -Werror=strict-overflow warnings from GCC 4.8.2 + assert(index >= 0 && static_cast(index) < static_cast(getLength())); + return getStr()[index]; + } + + /** + Compares two strings. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + This function can't be used for language specific sorting. + + @param str the object to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ + sal_Int32 compareTo( const OString & str ) const + { + return rtl_str_compare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } + + /** + Compares two strings with an maximum count of characters. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + This function can't be used for language specific sorting. + + @param rObj the object to be compared. + @param maxLength the maximum count of characters to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ + sal_Int32 compareTo( const OString & rObj, sal_Int32 maxLength ) const + { + return rtl_str_shortenedCompare_WithLength( pData->buffer, pData->length, + rObj.pData->buffer, rObj.pData->length, maxLength ); + } + + /** + Compares two strings in reverse order. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + This function can't be used for language specific sorting. + + @param str the object to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ + sal_Int32 reverseCompareTo( const OString & str ) const + { + return rtl_str_reverseCompare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } + + /** + Perform a comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string. + This function can't be used for language specific comparison. + + @param str the object to be compared. + @return true if the strings are equal; + false, otherwise. + */ + bool equals( const OString & str ) const + { + if ( pData->length != str.pData->length ) + return false; + if ( pData == str.pData ) + return true; + return rtl_str_reverseCompare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ) == 0; + } + + /** + Perform a comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string. + The ASCII string must be NULL-terminated and must be greater or + equal as length. + This function can't be used for language specific comparison. + + + @param value a character array. + @param length the length of the character array. + @return true if the strings are equal; + false, otherwise. + */ + bool equalsL( const char* value, sal_Int32 length ) const + { + if ( pData->length != length ) + return false; + + return rtl_str_reverseCompare_WithLength( pData->buffer, pData->length, + value, length ) == 0; + } + + /** + Perform an ASCII lowercase comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string, + ignoring the case. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the object to be compared. + @return true if the strings are equal; + false, otherwise. + */ +#if defined LIBO_INTERNAL_ONLY + bool equalsIgnoreAsciiCase( std::string_view str ) const + { + if ( sal_uInt32(pData->length) != str.size() ) + return false; + if ( pData->buffer == str.data() ) + return true; + return rtl_str_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, + str.data(), str.size() ) == 0; + } +#else + bool equalsIgnoreAsciiCase( const OString & str ) const + { + if ( pData->length != str.pData->length ) + return false; + if ( pData == str.pData ) + return true; + return rtl_str_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ) == 0; + } +#endif + + /** + Perform an ASCII lowercase comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string, + ignoring the case. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and + 127. The ASCII string must be NULL-terminated. + This function can't be used for language specific comparison. + + Note: The argument type is always either char* or const char*, the return type is bool. + The template is used only for technical reasons. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @return true if the strings are equal; + false, otherwise. + */ + template< typename T > + typename libreoffice_internal::CharPtrDetector< T, bool >::Type equalsIgnoreAsciiCase( const T& asciiStr ) const + { + return rtl_str_compareIgnoreAsciiCase( pData->buffer, asciiStr ) == 0; + } + + template< typename T > + typename libreoffice_internal::NonConstCharArrayDetector< T, bool >::Type equalsIgnoreAsciiCase( T& asciiStr ) const + { + return rtl_str_compareIgnoreAsciiCase( pData->buffer, asciiStr ) == 0; + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type equalsIgnoreAsciiCase( T& literal ) const + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + (pData->length + == libreoffice_internal::ConstCharArrayDetector::length) + && (rtl_str_compareIgnoreAsciiCase_WithLength( + pData->buffer, pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0); + } + + /** + Perform an ASCII lowercase comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string, + ignoring the case. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and + 127. The ASCII string must be greater or equal in length as asciiStrLength. + This function can't be used for language specific comparison. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @param asciiStrLength the length of the ascii string + @return true if the strings are equal; + false, otherwise. + */ + bool equalsIgnoreAsciiCaseL( const char * asciiStr, sal_Int32 asciiStrLength ) const + { + if ( pData->length != asciiStrLength ) + return false; + + return rtl_str_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, + asciiStr, asciiStrLength ) == 0; + } + + /** + Match against a substring appearing in this string. + + The result is true if and only if the second string appears as a substring + of this string, at the given position. + This function can't be used for language specific comparison. + + @param str the object (substring) to be compared. + @param fromIndex the index to start the comparison from. + The index must be greater or equal than 0 + and less or equal as the string length. + @return true if str match with the characters in the string + at the given position; + false, otherwise. + */ +#if defined LIBO_INTERNAL_ONLY + bool match( std::string_view str, sal_Int32 fromIndex = 0 ) const + { + return rtl_str_shortenedCompare_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.data(), str.size(), str.size() ) == 0; + } +#else + bool match( const OString & str, sal_Int32 fromIndex = 0 ) const + { + return rtl_str_shortenedCompare_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length, str.pData->length ) == 0; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type match( T& literal, sal_Int32 fromIndex = 0 ) const + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + rtl_str_shortenedCompare_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, + libreoffice_internal::ConstCharArrayDetector::length) + == 0; + } + + /** + Match against a substring appearing in this string. + + @param str the substring to be compared; must not be null and must point + to memory of at least strLength bytes + + @param strLength the length of the substring; must be non-negative + + @param fromIndex the index into this string to start the comparison at; + must be non-negative and not greater than this string's length + + @return true if and only if the given str is contained as a substring of + this string at the given fromIndex + + @since LibreOffice 3.6 + */ + bool matchL( + char const * str, sal_Int32 strLength, sal_Int32 fromIndex = 0) + const + { + return rtl_str_shortenedCompare_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, + str, strLength, strLength) == 0; + } + + // This overload is left undefined, to detect calls of matchL that + // erroneously use RTL_CONSTASCII_USTRINGPARAM instead of + // RTL_CONSTASCII_STRINGPARAM (but would lead to ambiguities on 32 bit + // platforms): +#if SAL_TYPES_SIZEOFLONG == 8 + void matchL(char const *, sal_Int32, rtl_TextEncoding) const; +#endif + + /** + Match against a substring appearing in this string, ignoring the case of + ASCII letters. + + The result is true if and only if the second string appears as a substring + of this string, at the given position. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the object (substring) to be compared. + @param fromIndex the index to start the comparison from. + The index must be greater or equal than 0 + and less or equal as the string length. + @return true if str match with the characters in the string + at the given position; + false, otherwise. + */ +#if defined LIBO_INTERNAL_ONLY + bool matchIgnoreAsciiCase( std::string_view str, sal_Int32 fromIndex = 0 ) const + { + return rtl_str_shortenedCompareIgnoreAsciiCase_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.data(), str.size(), + str.size() ) == 0; + } +#else + bool matchIgnoreAsciiCase( const OString & str, sal_Int32 fromIndex = 0 ) const + { + return rtl_str_shortenedCompareIgnoreAsciiCase_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length, + str.pData->length ) == 0; + } +#endif + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type matchIgnoreAsciiCase( T& literal, sal_Int32 fromIndex = 0 ) const + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + rtl_str_shortenedCompareIgnoreAsciiCase_WithLength( + pData->buffer+fromIndex, pData->length-fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, + libreoffice_internal::ConstCharArrayDetector::length) + == 0; + } + + /** + Check whether this string starts with a given substring. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. Available since + LibreOffice 4.2 + + @return true if and only if the given str appears as a substring at the + start of this string + + @since LibreOffice 4.0 + */ +#if defined LIBO_INTERNAL_ONLY + bool startsWith(std::string_view str, OString * rest = NULL) const { + bool b = match(str); + if (b && rest != NULL) { + *rest = copy(str.size()); + } + return b; + } +#else + bool startsWith(OString const & str, OString * rest = NULL) const { + bool b = match(str); + if (b && rest != NULL) { + *rest = copy(str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 4.0 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type startsWith( + T & literal, OString * rest = NULL) const + { + RTL_STRING_CONST_FUNCTION + bool b = match(literal, 0); + if (b && rest != NULL) { + *rest = copy( + libreoffice_internal::ConstCharArrayDetector::length); + } + return b; + } + + /** + Check whether this string starts with a given string, ignoring the case of + ASCII letters. + + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. + + @return true if and only if the given str appears as a substring at the + start of this string, ignoring the case of ASCII letters ("A"--"Z" and + "a"--"z") + + @since LibreOffice 5.1 + */ +#if defined LIBO_INTERNAL_ONLY + bool startsWithIgnoreAsciiCase(std::string_view str, OString * rest = NULL) + const + { + bool b = matchIgnoreAsciiCase(str); + if (b && rest != NULL) { + *rest = copy(str.size()); + } + return b; + } +#else + bool startsWithIgnoreAsciiCase(OString const & str, OString * rest = NULL) + const + { + bool b = matchIgnoreAsciiCase(str); + if (b && rest != NULL) { + *rest = copy(str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 5.1 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type + startsWithIgnoreAsciiCase(T & literal, OString * rest = NULL) const + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + bool b = matchIgnoreAsciiCase(literal); + if (b && rest != NULL) { + *rest = copy( + libreoffice_internal::ConstCharArrayDetector::length); + } + return b; + } + + /** + Check whether this string ends with a given substring. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. Available since + LibreOffice 4.2 + + @return true if and only if the given str appears as a substring at the + end of this string + + @since LibreOffice 3.6 + */ +#if defined LIBO_INTERNAL_ONLY + bool endsWith(std::string_view str, OString * rest = NULL) const { + bool b = str.size() <= sal_uInt32(getLength()) + && match(str, getLength() - str.size()); + if (b && rest != NULL) { + *rest = copy(0, getLength() - str.size()); + } + return b; + } +#else + bool endsWith(OString const & str, OString * rest = NULL) const { + bool b = str.getLength() <= getLength() + && match(str, getLength() - str.getLength()); + if (b && rest != NULL) { + *rest = copy(0, getLength() - str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type endsWith( + T & literal, OString * rest = NULL) const + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + bool b + = (libreoffice_internal::ConstCharArrayDetector::length + <= sal_uInt32(getLength())) + && match( + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + (getLength() + - libreoffice_internal::ConstCharArrayDetector::length)); + if (b && rest != NULL) { + *rest = copy( + 0, + (getLength() + - libreoffice_internal::ConstCharArrayDetector::length)); + } + return b; + } + + /** + Check whether this string ends with a given substring. + + @param str the substring to be compared; must not be null and must point + to memory of at least strLength bytes + + @param strLength the length of the substring; must be non-negative + + @return true if and only if the given str appears as a substring at the + end of this string + + @since LibreOffice 3.6 + */ + bool endsWithL(char const * str, sal_Int32 strLength) const { + return strLength <= getLength() + && matchL(str, strLength, getLength() - strLength); + } + + friend bool operator == ( const OString& rStr1, const OString& rStr2 ) + { return rStr1.equals(rStr2); } + friend bool operator != ( const OString& rStr1, const OString& rStr2 ) + { return !(operator == ( rStr1, rStr2 )); } + friend bool operator < ( const OString& rStr1, const OString& rStr2 ) + { return rStr1.compareTo( rStr2 ) < 0; } + friend bool operator > ( const OString& rStr1, const OString& rStr2 ) + { return rStr1.compareTo( rStr2 ) > 0; } + friend bool operator <= ( const OString& rStr1, const OString& rStr2 ) + { return rStr1.compareTo( rStr2 ) <= 0; } + friend bool operator >= ( const OString& rStr1, const OString& rStr2 ) + { return rStr1.compareTo( rStr2 ) >= 0; } + + template< typename T > + friend typename libreoffice_internal::CharPtrDetector< T, bool >::Type operator==( const OString& rStr1, const T& value ) + { + return + rtl_str_compare_WithLength( + rStr1.getStr(), rStr1.getLength(), value, rtl_str_getLength(value)) + == 0; + } + + template< typename T > + friend typename libreoffice_internal::NonConstCharArrayDetector< T, bool >::Type operator==( const OString& rStr1, T& value ) + { + return + rtl_str_compare_WithLength( + rStr1.getStr(), rStr1.getLength(), value, rtl_str_getLength(value)) + == 0; + } + + template< typename T > + friend typename libreoffice_internal::CharPtrDetector< T, bool >::Type operator==( const T& value, const OString& rStr2 ) + { + return + rtl_str_compare_WithLength( + value, rtl_str_getLength(value), rStr2.getStr(), rStr2.getLength()) + == 0; + } + + template< typename T > + friend typename libreoffice_internal::NonConstCharArrayDetector< T, bool >::Type operator==( T& value, const OString& rStr2 ) + { + return + rtl_str_compare_WithLength( + value, rtl_str_getLength(value), rStr2.getStr(), rStr2.getLength()) + == 0; + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator==( const OString& rStr, T& literal ) + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + (rStr.getLength() + == libreoffice_internal::ConstCharArrayDetector::length) + && (rtl_str_compare_WithLength( + rStr.pData->buffer, rStr.pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0); + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator==( T& literal, const OString& rStr ) + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + (rStr.getLength() + == libreoffice_internal::ConstCharArrayDetector::length) + && (rtl_str_compare_WithLength( + rStr.pData->buffer, rStr.pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0); + } + + template< typename T > + friend typename libreoffice_internal::CharPtrDetector< T, bool >::Type operator!=( const OString& rStr1, const T& value ) + { + return !(operator == ( rStr1, value )); + } + + template< typename T > + friend typename libreoffice_internal::NonConstCharArrayDetector< T, bool >::Type operator!=( const OString& rStr1, T& value ) + { + return !(operator == ( rStr1, value )); + } + + template< typename T > + friend typename libreoffice_internal::CharPtrDetector< T, bool >::Type operator!=( const T& value, const OString& rStr2 ) + { + return !(operator == ( value, rStr2 )); + } + + template< typename T > + friend typename libreoffice_internal::NonConstCharArrayDetector< T, bool >::Type operator!=( T& value, const OString& rStr2 ) + { + return !(operator == ( value, rStr2 )); + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator!=( const OString& rStr, T& literal ) + { + return !( rStr == literal ); + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator!=( T& literal, const OString& rStr ) + { + return !( literal == rStr ); + } + + /** + Returns a hashcode for this string. + + @return a hash code value for this object. + + @see rtl::OStringHash for convenient use of std::unordered_map + */ + sal_Int32 hashCode() const + { + return rtl_str_hashCode_WithLength( pData->buffer, pData->length ); + } + + /** + Returns the index within this string of the first occurrence of the + specified character, starting the search at the specified index. + + @param ch character to be located. + @param fromIndex the index to start the search from. + The index must be greater or equal than 0 + and less or equal as the string length. + @return the index of the first occurrence of the character in the + character sequence represented by this string that is + greater than or equal to fromIndex, or + -1 if the character does not occur. + */ + sal_Int32 indexOf( char ch, sal_Int32 fromIndex = 0 ) const + { + sal_Int32 ret = rtl_str_indexOfChar_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, ch ); + return (ret < 0 ? ret : ret+fromIndex); + } + + /** + Returns the index within this string of the last occurrence of the + specified character, searching backward starting at the end. + + @param ch character to be located. + @return the index of the last occurrence of the character in the + character sequence represented by this string, or + -1 if the character does not occur. + */ + sal_Int32 lastIndexOf( char ch ) const + { + return rtl_str_lastIndexOfChar_WithLength( pData->buffer, pData->length, ch ); + } + + /** + Returns the index within this string of the last occurrence of the + specified character, searching backward starting before the specified + index. + + @param ch character to be located. + @param fromIndex the index before which to start the search. + @return the index of the last occurrence of the character in the + character sequence represented by this string that + is less than fromIndex, or -1 + if the character does not occur before that point. + */ + sal_Int32 lastIndexOf( char ch, sal_Int32 fromIndex ) const + { + return rtl_str_lastIndexOfChar_WithLength( pData->buffer, fromIndex, ch ); + } + + /** + Returns the index within this string of the first occurrence of the + specified substring, starting at the specified index. + + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @param fromIndex the index to start the search from. + @return If the string argument occurs one or more times as a substring + within this string at the starting index, then the index + of the first character of the first such substring is + returned. If it does not occur as a substring starting + at fromIndex or beyond, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 indexOf( std::string_view str, sal_Int32 fromIndex = 0 ) const + { + sal_Int32 ret = rtl_str_indexOfStr_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.data(), str.size() ); + return (ret < 0 ? ret : ret+fromIndex); + } +#else + sal_Int32 indexOf( const OString & str, sal_Int32 fromIndex = 0 ) const + { + sal_Int32 ret = rtl_str_indexOfStr_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length ); + return (ret < 0 ? ret : ret+fromIndex); + } +#endif + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, sal_Int32 >::Type indexOf( T& literal, sal_Int32 fromIndex = 0 ) const + { + RTL_STRING_CONST_FUNCTION + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + sal_Int32 n = rtl_str_indexOfStr_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return n < 0 ? n : n + fromIndex; + } + + /** + Returns the index within this string of the first occurrence of the + specified substring, starting at the specified index. + + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @param len the length of the substring. + @param fromIndex the index to start the search from. + @return If the string argument occurs one or more times as a substring + within this string at the starting index, then the index + of the first character of the first such substring is + returned. If it does not occur as a substring starting + at fromIndex or beyond, -1 is returned. + + @since LibreOffice 3.6 + */ + sal_Int32 indexOfL(char const * str, sal_Int32 len, sal_Int32 fromIndex = 0) + const + { + sal_Int32 n = rtl_str_indexOfStr_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, str, len); + return n < 0 ? n : n + fromIndex; + } + + // This overload is left undefined, to detect calls of indexOfL that + // erroneously use RTL_CONSTASCII_USTRINGPARAM instead of + // RTL_CONSTASCII_STRINGPARAM (but would lead to ambiguities on 32 bit + // platforms): +#if SAL_TYPES_SIZEOFLONG == 8 + void indexOfL(char const *, sal_Int32, rtl_TextEncoding) const; +#endif + + /** + Returns the index within this string of the last occurrence of + the specified substring, searching backward starting at the end. + + The returned index indicates the starting index of the substring + in this string. + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @return If the string argument occurs one or more times as a substring + within this string, then the index of the first character of + the last such substring is returned. If it does not occur as + a substring, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 lastIndexOf( std::string_view str ) const + { + return rtl_str_lastIndexOfStr_WithLength( pData->buffer, pData->length, + str.data(), str.size() ); + } +#else + sal_Int32 lastIndexOf( const OString & str ) const + { + return rtl_str_lastIndexOfStr_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + Returns the index within this string of the last occurrence of + the specified substring, searching backward starting before the specified + index. + + The returned index indicates the starting index of the substring + in this string. + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @param fromIndex the index before which to start the search. + @return If the string argument occurs one or more times as a substring + within this string before the starting index, then the index + of the first character of the last such substring is + returned. Otherwise, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 lastIndexOf( std::string_view str, sal_Int32 fromIndex ) const + { + return rtl_str_lastIndexOfStr_WithLength( pData->buffer, fromIndex, + str.data(), str.size() ); + } +#else + sal_Int32 lastIndexOf( const OString & str, sal_Int32 fromIndex ) const + { + return rtl_str_lastIndexOfStr_WithLength( pData->buffer, fromIndex, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + Returns a new string that is a substring of this string. + + The substring begins at the specified beginIndex. If + beginIndex is negative or be greater than the length of + this string, behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT OString copy( sal_Int32 beginIndex ) const + { + return copy(beginIndex, getLength() - beginIndex); + } + + /** + Returns a new string that is a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. If either beginIndex or count are negative, + or beginIndex + count are greater than the length of this string + then behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @param count the number of characters. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT OString copy( sal_Int32 beginIndex, sal_Int32 count ) const + { + rtl_String *pNew = NULL; + rtl_string_newFromSubString( &pNew, pData, beginIndex, count ); + return OString( pNew, SAL_NO_ACQUIRE ); + } + +#if defined LIBO_INTERNAL_ONLY + /** + Returns a std::string_view that is a view of a substring of this string. + + The substring begins at the specified beginIndex. If + beginIndex is negative or be greater than the length of + this string, behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT std::string_view subView( sal_Int32 beginIndex ) const + { + assert(beginIndex >= 0); + assert(beginIndex <= getLength()); + return subView(beginIndex, getLength() - beginIndex); + } + + /** + Returns a std::string_view that is a view of a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. If either beginIndex or count are negative, + or beginIndex + count are greater than the length of this string + then behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @param count the number of characters. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT std::string_view subView( sal_Int32 beginIndex, sal_Int32 count ) const + { + assert(beginIndex >= 0); + assert(count >= 0); + assert(beginIndex <= getLength()); + assert(count <= getLength() - beginIndex); + return std::string_view(*this).substr(beginIndex, count); + } +#endif + +#ifndef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + Concatenates the specified string to the end of this string. + + @param str the string that is concatenated to the end + of this string. + @return a string that represents the concatenation of this string + followed by the string argument. + */ + SAL_WARN_UNUSED_RESULT OString concat( const OString & str ) const + { + rtl_String* pNew = NULL; + rtl_string_newConcat( &pNew, pData, str.pData ); + return OString( pNew, SAL_NO_ACQUIRE ); + } +#endif + +#ifndef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + friend OString operator+( const OString & str1, const OString & str2 ) + { + return str1.concat( str2 ); + } +#endif + +// hide this from internal code to avoid ambiguous lookup error +#ifndef LIBO_INTERNAL_ONLY + /** + Returns a new string resulting from replacing n = count characters + from position index in this string with newStr. + + @param index the replacing index in str. + The index must be greater or equal as 0 and + less or equal as the length of the string. + @param count the count of characters that will replaced + The count must be greater or equal as 0 and + less or equal as the length of the string minus index. + @param newStr the new substring. + @return the new string. + */ + SAL_WARN_UNUSED_RESULT OString replaceAt( sal_Int32 index, sal_Int32 count, const OString& newStr ) const + { + rtl_String* pNew = NULL; + rtl_string_newReplaceStrAt( &pNew, pData, index, count, newStr.pData ); + return OString( pNew, SAL_NO_ACQUIRE ); + } +#endif + +#ifdef LIBO_INTERNAL_ONLY + SAL_WARN_UNUSED_RESULT OString replaceAt( sal_Int32 index, sal_Int32 count, std::string_view newStr ) const + { + rtl_String* pNew = NULL; + rtl_string_newReplaceStrAt_WithLength ( &pNew, pData, index, count, newStr.data(), newStr.size() ); + return OString( pNew, SAL_NO_ACQUIRE ); + } +#endif + + /** + Returns a new string resulting from replacing all occurrences of + oldChar in this string with newChar. + + If the character oldChar does not occur in the character sequence + represented by this object, then the string is assigned with + str. + + @param oldChar the old character. + @param newChar the new character. + @return a string derived from this string by replacing every + occurrence of oldChar with newChar. + */ + SAL_WARN_UNUSED_RESULT OString replace( char oldChar, char newChar ) const + { + rtl_String* pNew = NULL; + rtl_string_newReplace( &pNew, pData, oldChar, newChar ); + return OString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a new string resulting from replacing the first occurrence of a + given substring with another substring. + + @param from the substring to be replaced + + @param to the replacing substring + + @param[in,out] index pointer to a start index; if the pointer is + non-null: upon entry to the function, its value is the index into the this + string at which to start searching for the \p from substring, the value + must be non-negative and not greater than this string's length; upon exit + from the function its value is the index into this string at which the + replacement took place or -1 if no replacement took place; if the pointer + is null, searching always starts at index 0 + + @since LibreOffice 3.6 + */ + SAL_WARN_UNUSED_RESULT OString replaceFirst( + OString const & from, OString const & to, sal_Int32 * index = NULL) const + { + rtl_String * s = NULL; + sal_Int32 i = 0; + rtl_string_newReplaceFirst( + &s, pData, from.pData->buffer, from.pData->length, + to.pData->buffer, to.pData->length, index == NULL ? &i : index); + return OString(s, SAL_NO_ACQUIRE); + } + + /** + Returns a new string resulting from replacing all occurrences of a given + substring with another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param from the substring to be replaced + + @param to the replacing substring + + @since LibreOffice 3.6 + */ + SAL_WARN_UNUSED_RESULT OString replaceAll(OString const & from, OString const & to) const { + rtl_String * s = NULL; + rtl_string_newReplaceAll( + &s, pData, from.pData->buffer, from.pData->length, + to.pData->buffer, to.pData->length); + return OString(s, SAL_NO_ACQUIRE); + } + + /** + Converts from this string all ASCII uppercase characters (65-90) + to ASCII lowercase characters (97-122). + + This function can't be used for language specific conversion. + If the string doesn't contain characters which must be converted, + then the new string is assigned with str. + + @return the string, converted to ASCII lowercase. + */ + SAL_WARN_UNUSED_RESULT OString toAsciiLowerCase() const + { + rtl_String* pNew = NULL; + rtl_string_newToAsciiLowerCase( &pNew, pData ); + return OString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Converts from this string all ASCII lowercase characters (97-122) + to ASCII uppercase characters (65-90). + + This function can't be used for language specific conversion. + If the string doesn't contain characters which must be converted, + then the new string is assigned with str. + + @return the string, converted to ASCII uppercase. + */ + SAL_WARN_UNUSED_RESULT OString toAsciiUpperCase() const + { + rtl_String* pNew = NULL; + rtl_string_newToAsciiUpperCase( &pNew, pData ); + return OString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a new string resulting from removing white space from both ends + of the string. + + All characters that have codes less than or equal to + 32 (the space character) are considered to be white space. + If the string doesn't contain white spaces at both ends, + then the new string is assigned with str. + + @return the string, with white space removed from the front and end. + */ + SAL_WARN_UNUSED_RESULT OString trim() const + { + rtl_String* pNew = NULL; + rtl_string_newTrim( &pNew, pData ); + return OString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a token in the string. + + Example: + sal_Int32 nIndex = 0; + do + { + ... + OString aToken = aStr.getToken( 0, ';', nIndex ); + ... + } + while ( nIndex >= 0 ); + + @param token the number of the token to return. + @param cTok the character which separate the tokens. + @param index the position at which the token is searched in the + string. + The index must not be greater than the length of the + string. + This param is set to the position of the + next token or to -1, if it is the last token. + @return the token; if either token or index is negative, an empty token + is returned (and index is set to -1) + */ + OString getToken( sal_Int32 token, char cTok, sal_Int32& index ) const + { + rtl_String * pNew = NULL; + index = rtl_string_getToken( &pNew, pData, token, cTok, index ); + return OString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a token from the string. + + The same as getToken(sal_Int32, char, sal_Int32 &), but always passing + in 0 as the start index in the third argument. + + @param count the number of the token to return, starting with 0 + @param separator the character which separates the tokens + + @return the given token, or an empty string + + @since LibreOffice 3.6 + */ + OString getToken(sal_Int32 count, char separator) const { + sal_Int32 n = 0; + return getToken(count, separator, n); + } + + /** + Returns the Boolean value from this string. + + This function can't be used for language specific conversion. + + @return true, if the string is 1 or "True" in any ASCII case. + false in any other case. + */ + bool toBoolean() const + { + return rtl_str_toBoolean( pData->buffer ); + } + + /** + Returns the first character from this string. + + @return the first character from this string or 0, if this string + is empty. + */ + char toChar() const + { + return pData->buffer[0]; + } + + /** + Returns the int32 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the int32 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + */ + sal_Int32 toInt32( sal_Int16 radix = 10 ) const + { + return rtl_str_toInt32( pData->buffer, radix ); + } + + /** + Returns the uint32 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the uint32 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + + @since LibreOffice 4.2 + */ + sal_uInt32 toUInt32( sal_Int16 radix = 10 ) const + { + return rtl_str_toUInt32( pData->buffer, radix ); + } + + /** + Returns the int64 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the int64 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + */ + sal_Int64 toInt64( sal_Int16 radix = 10 ) const + { + return rtl_str_toInt64( pData->buffer, radix ); + } + + /** + Returns the uint64 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the uint64 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + + @since LibreOffice 4.1 + */ + sal_uInt64 toUInt64( sal_Int16 radix = 10 ) const + { + return rtl_str_toUInt64( pData->buffer, radix ); + } + + /** + Returns the float value from this string. + + This function can't be used for language specific conversion. + + @return the float represented from this string. + 0.0 if this string represents no number. + */ + float toFloat() const + { + return rtl_str_toFloat( pData->buffer ); + } + + /** + Returns the double value from this string. + + This function can't be used for language specific conversion. + + @return the double represented from this string. + 0.0 if this string represents no number. + */ + double toDouble() const + { + return rtl_str_toDouble( pData->buffer ); + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + + static OStringNumber< int > number( int i, sal_Int16 radix = 10 ) + { + return OStringNumber< int >( i, radix ); + } + static OStringNumber< long long > number( long long ll, sal_Int16 radix = 10 ) + { + return OStringNumber< long long >( ll, radix ); + } + static OStringNumber< unsigned long long > number( unsigned long long ll, sal_Int16 radix = 10 ) + { + return OStringNumber< unsigned long long >( ll, radix ); + } + static OStringNumber< unsigned long long > number( unsigned int i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + static OStringNumber< long long > number( long i, sal_Int16 radix = 10) + { + return number( static_cast< long long >( i ), radix ); + } + static OStringNumber< unsigned long long > number( unsigned long i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + static OStringNumber< float > number( float f ) + { + return OStringNumber< float >( f ); + } + static OStringNumber< double > number( double d ) + { + return OStringNumber< double >( d ); + } +#else + /** + Returns the string representation of the integer argument. + + This function can't be used for language specific conversion. + + @param i an integer value + @param radix the radix (between 2 and 36) + @return a string with the string representation of the argument. + @since LibreOffice 4.1 + */ + static OString number( int i, sal_Int16 radix = 10 ) + { + char aBuf[RTL_STR_MAX_VALUEOFINT32]; + return OString(aBuf, rtl_str_valueOfInt32(aBuf, i, radix)); + } + /// @overload + /// @since LibreOffice 4.1 + static OString number( unsigned int i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + /// @overload + /// @since LibreOffice 4.1 + static OString number( long i, sal_Int16 radix = 10 ) + { + return number( static_cast< long long >( i ), radix ); + } + /// @overload + /// @since LibreOffice 4.1 + static OString number( unsigned long i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + /// @overload + /// @since LibreOffice 4.1 + static OString number( long long ll, sal_Int16 radix = 10 ) + { + char aBuf[RTL_STR_MAX_VALUEOFINT64]; + return OString(aBuf, rtl_str_valueOfInt64(aBuf, ll, radix)); + } + /// @overload + /// @since LibreOffice 4.1 + static OString number( unsigned long long ll, sal_Int16 radix = 10 ) + { + char aBuf[RTL_STR_MAX_VALUEOFUINT64]; + return OString(aBuf, rtl_str_valueOfUInt64(aBuf, ll, radix)); + } + + /** + Returns the string representation of the float argument. + + This function can't be used for language specific conversion. + + @param f a float. + @return a string with the decimal representation of the argument. + @since LibreOffice 4.1 + */ + static OString number( float f ) + { + char aBuf[RTL_STR_MAX_VALUEOFFLOAT]; + return OString(aBuf, rtl_str_valueOfFloat(aBuf, f)); + } + + /** + Returns the string representation of the double argument. + + This function can't be used for language specific conversion. + + @param d a double. + @return a string with the decimal representation of the argument. + @since LibreOffice 4.1 + */ + static OString number( double d ) + { + char aBuf[RTL_STR_MAX_VALUEOFDOUBLE]; + return OString(aBuf, rtl_str_valueOfDouble(aBuf, d)); + } +#endif + + /** + Returns the string representation of the sal_Bool argument. + + If the sal_Bool is true, the string "true" is returned. + If the sal_Bool is false, the string "false" is returned. + This function can't be used for language specific conversion. + + @param b a sal_Bool. + @return a string with the string representation of the argument. + @deprecated use boolean() + */ + SAL_DEPRECATED("use boolean()") static OString valueOf( sal_Bool b ) + { + return boolean(b); + } + + /** + Returns the string representation of the boolean argument. + + If the argument is true, the string "true" is returned. + If the argument is false, the string "false" is returned. + This function can't be used for language specific conversion. + + @param b a bool. + @return a string with the string representation of the argument. + @since LibreOffice 4.1 + */ + static OString boolean( bool b ) + { + char aBuf[RTL_STR_MAX_VALUEOFBOOLEAN]; + return OString(aBuf, rtl_str_valueOfBoolean(aBuf, b)); + } + + /** + Returns the string representation of the char argument. + + @param c a character. + @return a string with the string representation of the argument. + @deprecated use operator, function or constructor taking char or sal_Unicode argument + */ + SAL_DEPRECATED("convert to OString or use directly") static OString valueOf( char c ) + { + return OString( &c, 1 ); + } + + /** + Returns the string representation of the int argument. + + This function can't be used for language specific conversion. + + @param i a int32. + @param radix the radix (between 2 and 36) + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OString valueOf( sal_Int32 i, sal_Int16 radix = 10 ) + { + return number( i, radix ); + } + + /** + Returns the string representation of the long argument. + + This function can't be used for language specific conversion. + + @param ll a int64. + @param radix the radix (between 2 and 36) + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OString valueOf( sal_Int64 ll, sal_Int16 radix = 10 ) + { + return number( ll, radix ); + } + + /** + Returns the string representation of the float argument. + + This function can't be used for language specific conversion. + + @param f a float. + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OString valueOf( float f ) + { + return number(f); + } + + /** + Returns the string representation of the double argument. + + This function can't be used for language specific conversion. + + @param d a double. + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OString valueOf( double d ) + { + return number(d); + } + +#if defined LIBO_INTERNAL_ONLY + operator std::string_view() const { return {getStr(), sal_uInt32(getLength())}; } +#endif + +#if defined LIBO_INTERNAL_ONLY + // A wrapper for the first expression in an + // + // OString::Concat(e1) + e2 + ... + // + // concatenation chain, when neither of the first two e1, e2 is one of our rtl string-related + // classes (so something like + // + // OString s = "a" + (b ? std::string_view("c") : std::string_view("dd")); + // + // would not compile): + template [[nodiscard]] static + typename std::enable_if_t< + ToStringHelper::allowOStringConcat, OStringConcat> + Concat(T const & value) { return OStringConcat({}, value); } + + // This overload is needed so that an argument of type 'char const[N]' ends up as + // 'OStringConcat' rather than as + // 'OStringConcat': + template [[nodiscard]] static + typename std::enable_if_t< + ToStringHelper::allowOStringConcat, OStringConcat> + Concat(T (& value)[N]) { return OStringConcat({}, value); } +#endif +}; + +#if defined LIBO_INTERNAL_ONLY +inline bool operator ==(OString const & lhs, OStringConcatenation const & rhs) +{ return lhs == std::string_view(rhs); } +inline bool operator !=(OString const & lhs, OStringConcatenation const & rhs) +{ return lhs != std::string_view(rhs); } +inline bool operator ==(OStringConcatenation const & lhs, OString const & rhs) +{ return std::string_view(lhs) == rhs; } +inline bool operator !=(OStringConcatenation const & lhs, OString const & rhs) +{ return std::string_view(lhs) != rhs; } +#endif + +/* ======================================================================= */ + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + +/** + @internal +*/ +template<> +struct ToStringHelper< OString > + { + static std::size_t length( const OString& s ) { return s.getLength(); } + static char* addData( char* buffer, const OString& s ) { return addDataHelper( buffer, s.getStr(), s.getLength()); } + static const bool allowOStringConcat = true; + static const bool allowOUStringConcat = false; + }; + +/** + @internal +*/ +template +struct ToStringHelper< OStringLiteral > + { + static constexpr std::size_t length( const OStringLiteral& str ) { return str.getLength(); } + static char* addData( char* buffer, const OStringLiteral& str ) { return addDataHelper( buffer, str.getStr(), str.getLength() ); } + static const bool allowOStringConcat = true; + static const bool allowOUStringConcat = false; + }; + +/** + @internal +*/ +template< typename charT, typename traits, typename T1, typename T2 > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, OStringConcat< T1, T2 >&& concat) +{ + return stream << OString( std::move(concat) ); +} +#endif + + +/** A helper to use OStrings with hash maps. + + Instances of this class are unary function objects that can be used as + hash function arguments to std::unordered_map and similar constructs. + */ +struct OStringHash +{ + /** Compute a hash code for a string. + + @param rString + a string. + + @return + a hash code for the string. This hash code should not be stored + persistently, as its computation may change in later revisions. + */ + size_t operator()( const OString& rString ) const + { return static_cast(rString.hashCode()); } +}; + +/** Equality functor for classic c-strings (i.e., null-terminated char* strings). */ +struct CStringEqual +{ + bool operator()( const char* p1, const char* p2) const + { return rtl_str_compare(p1, p2) == 0; } +}; + +/** Hashing functor for classic c-strings (i.e., null-terminated char* strings). */ +struct CStringHash +{ + size_t operator()(const char* p) const + { return rtl_str_hashCode(p); } +}; + +/* ======================================================================= */ + +/** + Support for rtl::OString in std::ostream (and thus in + CPPUNIT_ASSERT or SAL_INFO macros, for example). + + @since LibreOffice 4.0 + */ +template< typename charT, typename traits > std::basic_ostream & +operator <<( + std::basic_ostream & stream, OString const & rString) +{ + return stream << rString.getStr(); + // best effort; potentially loses data due to embedded null characters +} + +} /* Namespace */ + +#ifdef RTL_STRING_UNITTEST +namespace rtl +{ +typedef rtlunittest::OString OString; +} +#undef RTL_STRING_CONST_FUNCTION +#endif + +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST +using ::rtl::OString; +using ::rtl::OStringChar; +using ::rtl::OStringConcatenation; +using ::rtl::OStringHash; +using ::rtl::OStringLiteral; +#endif + +/// @cond INTERNAL +/** + Make OString hashable by default for use in STL containers. + + @since LibreOffice 6.0 +*/ +#if defined LIBO_INTERNAL_ONLY +namespace std { + +template<> +struct hash<::rtl::OString> +{ + std::size_t operator()(::rtl::OString const & s) const + { return std::size_t(s.hashCode()); } +}; + +} + +#endif +/// @endcond + +#endif // INCLUDED_RTL_STRING_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/stringconcat.hxx b/include/rtl/stringconcat.hxx new file mode 100644 index 000000000..51605d073 --- /dev/null +++ b/include/rtl/stringconcat.hxx @@ -0,0 +1,588 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_RTL_STRINGCONCAT_HXX +#define INCLUDED_RTL_STRINGCONCAT_HXX + +// This file is only included from LIBO_INTERNAL_ONLY + +#include "rtl/stringutils.hxx" +#include "rtl/string.h" +#include "rtl/ustring.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#if defined RTL_STRING_UNITTEST_CONCAT +extern bool rtl_string_unittest_invalid_concat; +#endif + +#ifdef RTL_STRING_UNITTEST +#define rtl rtlunittest +#endif +namespace rtl +{ +#ifdef RTL_STRING_UNITTEST +#undef rtl +#endif + +/* +Implementation of efficient string concatenation. + +The whole system is built around two basic template classes: +- ToStringHelper< T > - for each T it can give the length of the resulting string representation and can write + this string representation to a buffer +- O(U)StringConcat< T1, T2 > - operator+ now, instead of creating O(U)String object, returns only this helper object, + that keeps a reference to both operator+ operands; only when converted to O(U)String it will actually create + the resulting string object using ToStringHelper, creating directly the resulting object without any string + intermediate objects +As all the code is inline methods, it allows for extensive optimization and will usually result in very effective code +(even surpassing strlen/strcat and equalling handwritten), while allowing for very easy and intuitive syntax. +*/ + +/** +@internal + +Helper class for converting a given type to a string representation. +*/ +template< typename T > +struct ToStringHelper + { + /// Return length of the string representation of the given object. + static std::size_t length( const T& ); + /// Add 8-bit representation of the given object to the given buffer and return position right after the added data. + static char* addData( char* buffer, const T& ) SAL_RETURNS_NONNULL; + /// Add Unicode representation of the given object to the given buffer and return position right after the added data. + static sal_Unicode* addData( sal_Unicode* buffer, const T& ) SAL_RETURNS_NONNULL; + /// If true, T can be used in concatenation resulting in OString. + static const bool allowOStringConcat = false; + /// If true, T can be used in concatenation resulting in OUString. + static const bool allowOUStringConcat = false; + }; + +inline +char* addDataHelper( char* buffer, const char* data, std::size_t length ) + { + if (length != 0) { + memcpy( buffer, data, length ); + } + return buffer + length; + } + +inline +sal_Unicode* addDataHelper( sal_Unicode* buffer, const sal_Unicode* data, std::size_t length ) + { + if (length != 0) { + memcpy( buffer, data, length * sizeof( sal_Unicode )); + } + return buffer + length; + } + +inline +sal_Unicode* addDataLiteral( sal_Unicode* buffer, const char* data, std::size_t length ) + { + for( std::size_t i = 0; i != length; ++i ) + *buffer++ = *data++; + return buffer; + } + +inline +char* addDataCString( char* buffer, const char* str ) + { + while( *str != '\0' ) + *buffer++ = *str++; + return buffer; + } + +inline +sal_Unicode* addDataUString( sal_Unicode* buffer, const sal_Unicode* str ) + { + while( *str != '\0' ) + *buffer++ = *str++; + return buffer; + } + +template<> +struct ToStringHelper< const char* > + { + static std::size_t length( const char* str ) { + return str ? strlen( str ) : 0; + } + static char* addData( char* buffer, const char* str ) { + return str ? addDataCString( buffer, str ) : buffer; + } + static const bool allowOStringConcat = true; + static const bool allowOUStringConcat = false; + }; + +template<> +struct ToStringHelper< char* > : public ToStringHelper< const char* > {}; + +template< std::size_t N > +struct ToStringHelper< char[ N ] > + { + static std::size_t length( const char str[ N ] ) { + return strlen( str ); + } + static char* addData( char* buffer, const char str[ N ] ) { return addDataCString( buffer, str ); } + static const bool allowOStringConcat = true; + static const bool allowOUStringConcat = false; + }; + +template< std::size_t N > +struct ToStringHelper< const char[ N ] > + { + static std::size_t length( const char str[ N ] ) { (void)str; assert( strlen( str ) == N - 1 ); return N - 1; } + static char* addData( char* buffer, const char str[ N ] ) { return addDataHelper( buffer, str, N - 1 ); } + static sal_Unicode* addData( sal_Unicode* buffer, const char str[ N ] ) { return addDataLiteral( buffer, str, N - 1 ); } + static const bool allowOStringConcat = true; + static const bool allowOUStringConcat = true; + }; + +template<> +struct ToStringHelper + { + static std::size_t length(OStringChar) { return 1; } + static char* addData(char* buffer, OStringChar data) + { return addDataHelper(buffer, &data.c, 1); } + static bool const allowOStringConcat = true; + static bool const allowOUStringConcat = false; + }; + +template<> +struct ToStringHelper< const sal_Unicode* > + { + static std::size_t length( const sal_Unicode* str ) { + return str ? std::char_traits::length( str ) : 0; + } + static sal_Unicode* addData( sal_Unicode* buffer, const sal_Unicode* str ) { + return str ? addDataUString( buffer, str ) : buffer; + } + static const bool allowOStringConcat = false; + static const bool allowOUStringConcat = true; + }; + +template<> +struct ToStringHelper< sal_Unicode* > : public ToStringHelper< const sal_Unicode* > {}; + +template +struct ToStringHelper + { + static std::size_t length( const sal_Unicode str[ N ] ) { + return std::char_traits::length( str ); + } + static sal_Unicode * addData(sal_Unicode * buffer, sal_Unicode const str[N]) + { return addDataHelper(buffer, str, N - 1); } + static bool const allowOStringConcat = false; + static bool const allowOUStringConcat = true; + }; + +template +struct ToStringHelper + { + static std::size_t length( const sal_Unicode str[ N ] ) { (void)str; assert( std::char_traits::length( str ) == N - 1 ); return N - 1; } + static sal_Unicode * addData(sal_Unicode * buffer, sal_Unicode const str[N]) + { return addDataHelper(buffer, str, N - 1); } + static bool const allowOStringConcat = false; + static bool const allowOUStringConcat = true; + }; + +template<> +struct ToStringHelper + { + static std::size_t length(OUStringChar_) { return 1; } + static sal_Unicode * addData(sal_Unicode * buffer, OUStringChar_ literal) + { return addDataHelper(buffer, &literal.c, 1); } + static bool const allowOStringConcat = false; + static bool const allowOUStringConcat = true; + }; + +/** +@internal + +Objects returned by operator+, instead of OString. These objects (possibly recursively) keep a representation of the whole +concatenation operation. + +If you get a build error related to this class, you most probably need to explicitly convert the result of a string +concatenation to OString. +*/ +template< typename T1, typename T2 > +struct OStringConcat + { + public: + OStringConcat( const T1& left_, const T2& right_ ) : left( left_ ), right( right_ ) {} + std::size_t length() const { return ToStringHelper< T1 >::length( left ) + ToStringHelper< T2 >::length( right ); } + char* addData( char* buffer ) const SAL_RETURNS_NONNULL { return ToStringHelper< T2 >::addData( ToStringHelper< T1 >::addData( buffer, left ), right ); } + // NOTE here could be functions that would forward to the "real" temporary OString. Note however that e.g. getStr() + // is not so simple, as the OString temporary must live long enough (i.e. can't be created here in a function, a wrapper + // temporary object containing it must be returned instead). + private: + const T1& left; + const T2& right; + }; + +/** +@internal + +Objects returned by operator+, instead of OUString. These objects (possibly recursively) keep a representation of the whole +concatenation operation. + +If you get a build error related to this class, you most probably need to explicitly convert the result of a string +concatenation to OUString. +*/ +template< typename T1, typename T2 > +struct OUStringConcat + { + public: + OUStringConcat( const T1& left_, const T2& right_ ) : left( left_ ), right( right_ ) {} + std::size_t length() const { return ToStringHelper< T1 >::length( left ) + ToStringHelper< T2 >::length( right ); } + sal_Unicode* addData( sal_Unicode* buffer ) const SAL_RETURNS_NONNULL { return ToStringHelper< T2 >::addData( ToStringHelper< T1 >::addData( buffer, left ), right ); } + private: + const T1& left; + const T2& right; + }; + +template< typename T1, typename T2 > +struct ToStringHelper< OStringConcat< T1, T2 > > + { + static std::size_t length( const OStringConcat< T1, T2 >& c ) { return c.length(); } + static char* addData( char* buffer, const OStringConcat< T1, T2 >& c ) SAL_RETURNS_NONNULL { return c.addData( buffer ); } + static const bool allowOStringConcat = ToStringHelper< T1 >::allowOStringConcat && ToStringHelper< T2 >::allowOStringConcat; + static const bool allowOUStringConcat = false; + }; + +template< typename T1, typename T2 > +struct ToStringHelper< OUStringConcat< T1, T2 > > + { + static std::size_t length( const OUStringConcat< T1, T2 >& c ) { return c.length(); } + static sal_Unicode* addData( sal_Unicode* buffer, const OUStringConcat< T1, T2 >& c ) SAL_RETURNS_NONNULL { return c.addData( buffer ); } + static const bool allowOStringConcat = false; + static const bool allowOUStringConcat = ToStringHelper< T1 >::allowOUStringConcat && ToStringHelper< T2 >::allowOUStringConcat; + }; + +template< typename T1, typename T2 > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T1 >::allowOStringConcat && ToStringHelper< T2 >::allowOStringConcat, OStringConcat< T1, T2 > > operator+( const T1& left, const T2& right ) + { + return OStringConcat< T1, T2 >( left, right ); + } + +// char[N] and const char[N] need to be done explicitly, otherwise the compiler likes to treat them the same way for some reason +template< typename T, std::size_t N > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T >::allowOStringConcat, OStringConcat< T, const char[ N ] > > operator+( const T& left, const char (&right)[ N ] ) + { + return OStringConcat< T, const char[ N ] >( left, right ); + } + +template< typename T, std::size_t N > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T >::allowOStringConcat, OStringConcat< const char[ N ], T > > operator+( const char (&left)[ N ], const T& right ) + { + return OStringConcat< const char[ N ], T >( left, right ); + } + +template< typename T, std::size_t N > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T >::allowOStringConcat, OStringConcat< T, char[ N ] > > operator+( const T& left, char (&right)[ N ] ) + { + return OStringConcat< T, char[ N ] >( left, right ); + } + +template< typename T, std::size_t N > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T >::allowOStringConcat, OStringConcat< char[ N ], T > > operator+( char (&left)[ N ], const T& right ) + { + return OStringConcat< char[ N ], T >( left, right ); + } + +template< typename T1, typename T2 > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T1 >::allowOUStringConcat && ToStringHelper< T2 >::allowOUStringConcat, OUStringConcat< T1, T2 > > operator+( const T1& left, const T2& right ) + { + return OUStringConcat< T1, T2 >( left, right ); + } + +template< typename T1, typename T2 > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T1 >::allowOUStringConcat && ToStringHelper< T2 >::allowOUStringConcat && libreoffice_internal::ConstCharArrayDetector< T1, void >::ok, OUStringConcat< T1, T2 > > operator+( T1& left, const T2& right ) + { + return OUStringConcat< T1, T2 >( left, right ); + } + +template< typename T1, typename T2 > +[[nodiscard]] +inline +typename std::enable_if_t< ToStringHelper< T1 >::allowOUStringConcat && ToStringHelper< T2 >::allowOUStringConcat && libreoffice_internal::ConstCharArrayDetector< T2, void >::ok, OUStringConcat< T1, T2 > > operator+( const T1& left, T2& right ) + { + return OUStringConcat< T1, T2 >( left, right ); + } + +#ifdef RTL_STRING_UNITTEST_CONCAT +// Special overload to catch the remaining invalid combinations. The helper struct must +// be used to make this operator+ overload a worse choice than all the existing overloads above. +struct StringConcatInvalid + { + template< typename T > + StringConcatInvalid( const T& ) {} + }; +template< typename T > +inline +int operator+( const StringConcatInvalid&, const T& ) + { + rtl_string_unittest_invalid_concat = true; + return 0; // doesn't matter + } +#endif + +// Lightweight alternative to OString when a (temporary) object is needed to hold an OStringConcat +// result that can then be used as a std::string_view: +class OStringConcatenation { +public: + template + explicit OStringConcatenation(OStringConcat const & c): + length_(c.length()), + buffer_(new char[length_]) + { + auto const end = c.addData(buffer_.get()); + assert(end == buffer_.get() + length_); (void)end; + } + + operator std::string_view() const { return {buffer_.get(), length_}; } + +private: + std::size_t length_; + std::unique_ptr buffer_; +}; + +// Lightweight alternative to OUString when a (temporary) object is needed to hold an +// OUStringConcat result that can then be used as a std::u16string_view: +class OUStringConcatenation { +public: + template + explicit OUStringConcatenation(OUStringConcat const & c): + length_(c.length()), + buffer_(new char16_t[length_]) + { + auto const end = c.addData(buffer_.get()); + assert(end == buffer_.get() + length_); (void)end; + } + + operator std::u16string_view() const { return {buffer_.get(), length_}; } + +private: + std::size_t length_; + std::unique_ptr buffer_; +}; + +/** + @internal + +Objects returned by OString::number(), instead of OString. These objects keep a representation of the number() operation. + +If you get a build error related to this class, you most probably need to explicitly convert the result of calling +OString::number() to OString. +*/ +template< typename T > +struct OStringNumber; + +template struct OStringNumberBase +{ + using number_t = Number; + // OString::number(value).getStr() is very common (writing xml code, ...), + // so implement that one also here, to avoid having to explicitly to convert + // to OString in all such places + const char * getStr() const SAL_RETURNS_NONNULL { return buf; } + OStringNumber&& toAsciiUpperCase() + { + rtl_str_toAsciiUpperCase_WithLength(buf, length); + return std::move(*static_cast*>(this)); + } + operator std::string_view() const { return std::string_view(buf, length); } + char buf[nBufSize]; + sal_Int32 length; +}; + +template<> +struct OStringNumber< int > + : public OStringNumberBase +{ + OStringNumber(number_t i, sal_Int16 radix) { length = rtl_str_valueOfInt32(buf, i, radix); } +}; + +template<> +struct OStringNumber< long long > + : public OStringNumberBase +{ + OStringNumber(number_t i, sal_Int16 radix) { length = rtl_str_valueOfInt64(buf, i, radix); } +}; + +template<> +struct OStringNumber< unsigned long long > + : public OStringNumberBase +{ + OStringNumber(number_t i, sal_Int16 radix) { length = rtl_str_valueOfUInt64(buf, i, radix); } +}; + +template<> +struct OStringNumber< float > + : public OStringNumberBase +{ + OStringNumber(number_t f) { length = rtl_str_valueOfFloat(buf, f); } +}; + +template<> +struct OStringNumber< double > + : public OStringNumberBase +{ + OStringNumber(number_t d) { length = rtl_str_valueOfDouble(buf, d); } +}; + +template< typename T > +struct ToStringHelper< OStringNumber< T > > + { + static std::size_t length( const OStringNumber< T >& n ) { return n.length; } + static char* addData( char* buffer, const OStringNumber< T >& n ) SAL_RETURNS_NONNULL { return addDataHelper( buffer, n.buf, n.length ); } + static const bool allowOStringConcat = true; + static const bool allowOUStringConcat = false; + }; + + +/** + @internal + +Objects returned by OUString::number(), instead of OUString. These objects keep a representation of the number() operation. + +If you get a build error related to this class, you most probably need to explicitly convert the result of calling +OUString::number() to OUString. +*/ +template< typename T > +struct OUStringNumber; + +template struct OUStringNumberBase +{ + using number_t = Number; + OUStringNumber&& toAsciiUpperCase() + { + rtl_ustr_toAsciiUpperCase_WithLength(buf, length); + return std::move(*static_cast*>(this)); + } + operator std::u16string_view() const { return std::u16string_view(buf, length); } + sal_Unicode buf[nBufSize]; + sal_Int32 length; +}; + +template<> +struct OUStringNumber< int > + : public OUStringNumberBase +{ + OUStringNumber(number_t i, sal_Int16 radix) { length = rtl_ustr_valueOfInt32(buf, i, radix); } +}; + +template<> +struct OUStringNumber< long long > + : public OUStringNumberBase +{ + OUStringNumber(number_t i, sal_Int16 radix) { length = rtl_ustr_valueOfInt64(buf, i, radix); } +}; + +template<> +struct OUStringNumber< unsigned long long > + : public OUStringNumberBase +{ + OUStringNumber(number_t i, sal_Int16 radix) { length = rtl_ustr_valueOfUInt64(buf, i, radix); } +}; + +template<> +struct OUStringNumber< float > + : public OUStringNumberBase +{ + OUStringNumber(number_t f) { length = rtl_ustr_valueOfFloat(buf, f); } +}; + +template<> +struct OUStringNumber< double > + : public OUStringNumberBase +{ + OUStringNumber(number_t d) { length = rtl_ustr_valueOfDouble(buf, d); } +}; + +template< typename T > +struct ToStringHelper< OUStringNumber< T > > + { + static std::size_t length( const OUStringNumber< T >& n ) { return n.length; } + static sal_Unicode* addData( sal_Unicode* buffer, const OUStringNumber< T >& n ) SAL_RETURNS_NONNULL { return addDataHelper( buffer, n.buf, n.length ); } + static const bool allowOStringConcat = false; + static const bool allowOUStringConcat = true; + }; + +template<> struct ToStringHelper { + static constexpr std::size_t length(std::string_view s) { return s.size(); } + + static char * addData(char * buffer, std::string_view s) SAL_RETURNS_NONNULL + { return addDataHelper(buffer, s.data(), s.size()); } + + static constexpr bool allowOStringConcat = true; + static constexpr bool allowOUStringConcat = false; +}; + +template<> struct ToStringHelper { + static constexpr std::size_t length(std::u16string_view s) { return s.size(); } + + static sal_Unicode * addData(sal_Unicode * buffer, std::u16string_view s) SAL_RETURNS_NONNULL + { return addDataHelper(buffer, s.data(), s.size()); } + + static constexpr bool allowOStringConcat = false; + static constexpr bool allowOUStringConcat = true; +}; + +// An internal marker class used by OString::Concat: +struct OStringConcatMarker {}; + +template<> struct ToStringHelper { + static constexpr std::size_t length(OStringConcatMarker) { return 0; } + + static constexpr char * addData(char * buffer, OStringConcatMarker) SAL_RETURNS_NONNULL + { return buffer; } + + static constexpr bool allowOStringConcat = true; + static constexpr bool allowOUStringConcat = false; +}; + +// An internal marker class used by OUString::Concat: +struct OUStringConcatMarker {}; + +template<> struct ToStringHelper { + static constexpr std::size_t length(OUStringConcatMarker) { return 0; } + + static constexpr sal_Unicode * addData(sal_Unicode * buffer, OUStringConcatMarker) + SAL_RETURNS_NONNULL + { return buffer; } + + static constexpr bool allowOStringConcat = false; + static constexpr bool allowOUStringConcat = true; +}; + +} // namespace + +#endif diff --git a/include/rtl/stringutils.hxx b/include/rtl/stringutils.hxx new file mode 100644 index 000000000..58781973f --- /dev/null +++ b/include/rtl/stringutils.hxx @@ -0,0 +1,391 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_STRINGUTILS_HXX +#define INCLUDED_RTL_STRINGUTILS_HXX + +#include "sal/config.h" + +#include +#include + +#include "sal/types.h" + +// The unittest uses slightly different code to help check that the proper +// calls are made. The class is put into a different namespace to make +// sure the compiler generates a different (if generating also non-inline) +// copy of the function and does not merge them together. The class +// is "brought" into the proper rtl namespace by a typedef below. +#ifdef RTL_STRING_UNITTEST +#define rtl rtlunittest +#endif + +namespace rtl +{ + +#ifdef RTL_STRING_UNITTEST +#undef rtl +#endif + +#if defined LIBO_INTERNAL_ONLY +/// @cond INTERNAL + +// A simple wrapper around a single char. Can be useful in string concatenation contexts, like in +// +// OString s = ...; +// char c = ...; +// s += OStringChar(c); +// +struct SAL_WARN_UNUSED OStringChar { + constexpr OStringChar(char theC): c(theC) {} + template OStringChar(T &&) = delete; + constexpr operator std::string_view() const { return {&c, 1}; } + char const c; +}; + +/** A simple wrapper around a single sal_Unicode character. + + Can be useful to pass a sal_Unicode constant into an OUString-related + function that is optimized for UTF-16 string literal arguments. That is, + instead of + + sal_Unicode const WILDCARD = '%'; + ... + if (s[i] == WILDCARD) ... + ... + if (s.endsWith(OUString(WILDCARD))) ... + + use + + sal_Unicode const WILDCARD = '%'; + ... + if (s[i] == WILDCARD) ... + ... + if (s.endsWith(OUStringChar(WILDCARD))) ... + + to avoid creating a temporary OUString instance, and instead pick the + endsWith overload actually designed to take an argument of type + sal_Unicode const[N]. + + (Because of the above use case, + instances of OUStringChar need to be const, as those literal-optimized + functions take the literal argument by non-const lvalue reference, for + technical reasons. + + For actual arrays, it is important to distinguish string literals from other char or sal_Unicode + arrays, which may contain junk after the first NUL character or may be non-ASCII in the case of + char arrays. This is not so much a concern for single char and sal_Unicode values, where NUL is + assumed to always be meant as an actual character.) + + Can also be useful in string concatenation contexts, like in + + sal_Unicode const * s = ...; + sal_Unicode c = ...; + OUString t = s + OUStringChar(c); + + @since LibreOffice 5.0 +*/ +struct SAL_WARN_UNUSED OUStringChar_ { + constexpr OUStringChar_(sal_Unicode theC): c(theC) {} + constexpr OUStringChar_(char theC): c(theC) { assert(c <= 0x7F); } + template OUStringChar_(T &&) = delete; + constexpr operator std::u16string_view() const { return {&c, 1}; } + sal_Unicode const c; +}; +using OUStringChar = OUStringChar_ const; + +/// @endcond +#endif + +namespace libreoffice_internal +{ +/* +These templates use SFINAE (Substitution failure is not an error) to help distinguish the various +plain C string types: char*, const char*, char[N], const char[N], char[] and const char[]. +There are 2 cases: +1) Only string literal (i.e. const char[N]) is wanted, not any of the others. + In this case it is necessary to distinguish between const char[N] and char[N], as the latter + would be automatically converted to the const variant, which is not wanted (not a string literal + with known size of the content). In this case ConstCharArrayDetector is used to ensure the function + is called only with const char[N] arguments. There's no other plain C string type overload. + (Note that OUStringChar is also covered by ConstCharArrayDetector's TypeUtf16 check, but + provides a pointer to a string that is not NUL-terminated, unlike the char16_t const[N] arrays + normally covered by that check, and which are assumed to represent NUL-terminated string + literals.) +2) All plain C string types are wanted, and const char[N] needs to be handled differently. + In this case const char[N] would match const char* argument type (not exactly sure why, but it's + consistent in all of gcc, clang and msvc). Using a template with a reference to const of the type + avoids this problem, and CharPtrDetector ensures that the function is called only with char pointer + arguments. The const in the argument is necessary to handle the case when something is explicitly + cast to const char*. Additionally (non-const) char[N] needs to be handled, but with the reference + being const, it would also match const char[N], so another overload with a reference to non-const + and NonConstCharArrayDetector are used to ensure the function is called only with (non-const) char[N]. +Additionally, char[] and const char[] (i.e. size unknown) are rather tricky. Their usage with 'T&' would +mean it would be 'char(&)[]', which seems to be invalid. But gcc and clang somehow manage when it is +a template. while msvc complains about no conversion from char[] to char[1]. And the reference cannot +be avoided, because 'const char[]' as argument type would match also 'const char[N]' +So char[] and const char[] should always be used with their contents specified (which automatically +turns them into char[N] or const char[N]), or char* and const char* should be used. +*/ +struct Dummy {}; +template< typename T1, typename T2 = void > +struct CharPtrDetector +{ + static const bool ok = false; +}; +template< typename T > +struct CharPtrDetector< const char*, T > +{ + typedef T Type; + static const bool ok = true; +}; +template< typename T > +struct CharPtrDetector< char*, T > +{ + typedef T Type; + static const bool ok = true; +}; +#if defined LIBO_INTERNAL_ONLY +template struct CharPtrDetector { using TypeUtf16 = T; }; +template struct CharPtrDetector { using TypeUtf16 = T; }; +template struct CharPtrDetector { using TypeUtf16 = T; }; +template struct CharPtrDetector { using TypeUtf16 = T; }; +#endif + +template< typename T1, typename T2 > +struct NonConstCharArrayDetector +{ +}; +template< typename T, int N > +struct NonConstCharArrayDetector< char[ N ], T > +{ + typedef T Type; +}; +#ifdef RTL_STRING_UNITTEST +// never use, until all compilers handle this +template< typename T > +struct NonConstCharArrayDetector< char[], T > +{ + typedef T Type; +}; +template< typename T > +struct NonConstCharArrayDetector< const char[], T > +{ + typedef T Type; +}; +#endif +#if defined LIBO_INTERNAL_ONLY +template struct NonConstCharArrayDetector { + using TypeUtf16 = T; +}; +#endif + +template< typename T1, typename T2 = void > +struct ConstCharArrayDetector +{ + static const bool ok = false; +}; +template< std::size_t N, typename T > +struct ConstCharArrayDetector< const char[ N ], T > +{ + typedef T Type; + static const std::size_t length = N - 1; + static const bool ok = true; +#if defined LIBO_INTERNAL_ONLY + constexpr +#endif + static bool isValid(char const (& literal)[N]) { + for (std::size_t i = 0; i != N - 1; ++i) { + if (literal[i] == '\0') { + return false; + } + } + return literal[N - 1] == '\0'; + } +#if defined LIBO_INTERNAL_ONLY + constexpr +#endif + static char const * toPointer(char const (& literal)[N]) { return literal; } +}; + +#if defined(__COVERITY__) +//to silence over zealous warnings that the loop is logically dead +//for the single char case +template< typename T > +struct ConstCharArrayDetector< const char[ 1 ], T > +{ + typedef T Type; + static const std::size_t length = 0; + static const bool ok = true; +#if defined LIBO_INTERNAL_ONLY + constexpr +#endif + static bool isValid(char const (& literal)[1]) { + return literal[0] == '\0'; + } +#if defined LIBO_INTERNAL_ONLY + constexpr +#endif + static char const * toPointer(char const (& literal)[1]) { return literal; } +}; +#endif + +#if defined LIBO_INTERNAL_ONLY && defined __cpp_char8_t +template +struct ConstCharArrayDetector { + using Type = T; + static constexpr bool const ok = true; + static constexpr std::size_t const length = N - 1; + static constexpr bool isValid(char8_t const (& literal)[N]) { + for (std::size_t i = 0; i != N - 1; ++i) { + if (literal[i] == u8'\0') { + return false; + } + } + return literal[N - 1] == u8'\0'; + } + static constexpr char const * toPointer(char8_t const (& literal)[N]) + { return reinterpret_cast(literal); } +}; +#endif + +#if defined LIBO_INTERNAL_ONLY +template +struct ConstCharArrayDetector { + using TypeUtf16 = T; + static constexpr bool const ok = true; + static constexpr std::size_t const length = N - 1; + static constexpr bool isValid(sal_Unicode const (& literal)[N]) { + for (std::size_t i = 0; i != N - 1; ++i) { + if (literal[i] == '\0') { + return false; + } + } + return literal[N - 1] == '\0'; + } + static constexpr sal_Unicode const * toPointer( + sal_Unicode const (& literal)[N]) + { return literal; } +}; + +#if defined(__COVERITY__) +//to silence over zealous warnings that the loop is logically dead +//for the single char case +template +struct ConstCharArrayDetector { + using TypeUtf16 = T; + static constexpr bool const ok = true; + static constexpr std::size_t const length = 0; + static constexpr bool isValid(sal_Unicode const (& literal)[1]) { + return literal[0] == '\0'; + } + static constexpr sal_Unicode const * toPointer( + sal_Unicode const (& literal)[1]) + { return literal; } +}; +#endif + +template struct ConstCharArrayDetector< + OUStringChar, + T> +{ + using TypeUtf16 = T; + static constexpr bool const ok = true; + static constexpr std::size_t const length = 1; + static constexpr bool isValid(OUStringChar) { return true; } + static constexpr sal_Unicode const * toPointer( + OUStringChar_ const & literal) + { return &literal.c; } +}; +#endif + +#if defined LIBO_INTERNAL_ONLY && defined RTL_STRING_UNITTEST + +// this one is used to rule out only const char[N] +template< typename T > +struct ExceptConstCharArrayDetector +{ + typedef Dummy Type; +}; +template< int N > +struct ExceptConstCharArrayDetector< const char[ N ] > +{ +}; +template +struct ExceptConstCharArrayDetector {}; +template<> struct ExceptConstCharArrayDetector< + OUStringChar + > +{}; + +// this one is used to rule out only const char[N] +// (const will be brought in by 'const T&' in the function call) +// msvc needs const char[N] here (not sure whether gcc or msvc +// are right, it doesn't matter). +template< typename T > +struct ExceptCharArrayDetector +{ + typedef Dummy Type; +}; +template< int N > +struct ExceptCharArrayDetector< char[ N ] > +{ +}; +template< int N > +struct ExceptCharArrayDetector< const char[ N ] > +{ +}; +template struct ExceptCharArrayDetector {}; +template struct ExceptCharArrayDetector {}; +template<> struct ExceptCharArrayDetector {}; + +#endif + +template< typename T1, typename T2 = void > +struct SalUnicodePtrDetector +{ + static const bool ok = false; +}; +template< typename T > +struct SalUnicodePtrDetector< const sal_Unicode*, T > +{ + typedef T Type; + static const bool ok = true; +}; +template< typename T > +struct SalUnicodePtrDetector< sal_Unicode*, T > +{ + typedef T Type; + static const bool ok = true; +}; + +// SFINAE helper class +template< typename T, bool > +struct Enable + { + }; + +template< typename T > +struct Enable< T, true > + { + typedef T Type; + }; + + +} /* Namespace */ + +} /* Namespace */ + +#endif // INCLUDED_RTL_STRINGUTILS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/tencinfo.h b/include/rtl/tencinfo.h new file mode 100644 index 000000000..6154a9128 --- /dev/null +++ b/include/rtl/tencinfo.h @@ -0,0 +1,284 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_TENCINFO_H +#define INCLUDED_RTL_TENCINFO_H + +#include "sal/config.h" + +#include "rtl/textenc.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// See rtl_TextEncodingInfo.Flags below for documentation on these values: +#define RTL_TEXTENCODING_INFO_CONTEXT ((sal_uInt32)0x00000001) +#define RTL_TEXTENCODING_INFO_ASCII ((sal_uInt32)0x00000002) +#define RTL_TEXTENCODING_INFO_UNICODE ((sal_uInt32)0x00000004) +#define RTL_TEXTENCODING_INFO_MULTIBYTE ((sal_uInt32)0x00000008) +#define RTL_TEXTENCODING_INFO_R2L ((sal_uInt32)0x00000010) +#define RTL_TEXTENCODING_INFO_7BIT ((sal_uInt32)0x00000020) +#define RTL_TEXTENCODING_INFO_SYMBOL ((sal_uInt32)0x00000040) +#define RTL_TEXTENCODING_INFO_MIME ((sal_uInt32)0x00000080) + +/** Information about a text encoding. + */ +typedef struct _rtl_TextEncodingInfo +{ + /** The size (in bytes) of this structure. Should be 12. + */ + sal_uInt32 StructSize; + + /** The minimum number of bytes needed to encode any character in the + given encoding. + + Can be rather meaningless for encodings that encode global state along + with the characters (e.g., ISO-2022 encodings). + */ + sal_uInt8 MinimumCharSize; + + /** The maximum number of bytes needed to encode any character in the + given encoding. + + Can be rather meaningless for encodings that encode global state along + with the characters (e.g., ISO-2022 encodings). + */ + sal_uInt8 MaximumCharSize; + + /** The average number of bytes needed to encode a character in the given + encoding. + */ + sal_uInt8 AverageCharSize; + + /** An unused byte, for padding. + */ + sal_uInt8 Reserved; + + /** Any combination of the RTL_TEXTENCODING_INFO flags. + + RTL_TEXTENCODING_INFO_CONTEXT: The encoding uses some mechanism (like + state-changing byte sequences) to switch between different modes (e.g., + to encode multiple character repertoires within the same byte ranges). + + Even if an encoding does not have the CONTEXT property, interpretation + of certain byte values within that encoding can depend on context (e.g., + a certain byte value could be either a single-byte character or a + subsequent byte of a multi-byte character). Likewise, the single shift + characters (SS2 and SS3) used by some of the EUC encodings (to denote + that the following bytes constitute a character from another character + repertoire) do not imply that encodings making use of these characters + have the CONTEXT property. Examples of encodings that do have the + CONTEXT property are the ISO-2022 encodings and UTF-7. + + RTL_TEXTENCODING_INFO_ASCII: The encoding is a superset of ASCII. More + specifically, any appearance of a byte in the range 0x20--7F denotes the + corresponding ASCII character (from SPACE to DELETE); in particular, + such a byte cannot be part of a multi-byte character. Note that the + ASCII control codes 0x00--1F are not included here, as they are used for + special purposes in some encodings. + + If an encoding has this property, it is easy to search for occurrences of + ASCII characters within strings of this encoding---you do not need to + keep track whether a byte in the range 0x20--7F really represents an + ASCII character or rather is part of some multi-byte character. + + The guarantees when mapping between Unicode and a given encoding with + the ASCII property are as follows: When mapping from Unicode to the + given encoding, U+0020--007F map to 0x20--7F (but there can also be + other Unicode characters mapping into the range 0x20--7F), and when + mapping from the given encoding to Unicode, 0x20--7F map to U+0020--007F + (again, there can also be other characters mapping into the range + U+0020--007F). In particular, this ensures round-trip conversion for + the ASCII range. + + In principle, the ASCII property is orthogonal to the CONTEXT property. + In practice, however, an encoding that has the ASCII property will most + likely not also have the CONTEXT property. + + RTL_TEXTENCODING_INFO_UNICODE: The encoding is based on the Unicode + character repertoire. + + RTL_TEXTENCODING_INFO_MULTIBYTE: A multi-byte encoding. + + RTL_TEXTENCODING_INFO_R2L: An encoding used mainly or exclusively for + languages written from right to left. + + RTL_TEXTENCODING_INFO_7BIT: A 7-bit instead of an 8-bit encoding. + + RTL_TEXTENCODING_INFO_SYMBOL: A (generic) encoding for symbol character + sets. + + RTL_TEXTENCODING_INFO_MIME: The encoding is registered as a MIME + charset. + */ + sal_uInt32 Flags; +} rtl_TextEncodingInfo; + +/** Determine whether a text encoding uses single octets as basic units of + information (and can thus be used with the conversion routines in + rtl/textcvt.h). + + @param nEncoding + Any rtl_TextEncoding value. + + @return + True if the given encoding uses single octets as basic units of + information, false otherwise. + */ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_isOctetTextEncoding(rtl_TextEncoding nEncoding); + +/** Return information about a text encoding. + + @param eTextEncoding + Any rtl_TextEncoding value. + + @param pEncInfo + Returns information about the given encoding. Must not be null, and the + StructSize member must be set correctly. + + @return + True if information about the given encoding is available, false + otherwise. + */ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_getTextEncodingInfo( + rtl_TextEncoding eTextEncoding, rtl_TextEncodingInfo* pEncInfo ); + +/** Map from a numeric Windows charset to a text encoding. + + @param nWinCharset + Any numeric Windows charset. + + @return + The corresponding rtl_TextEncoding value, or RTL_TEXTENCODING_DONTKNOW if + no mapping is applicable. + If nWinCharset is 255 (OEM_CHARSET), then return value is RTL_TEXTENCODING_IBM_850, + regardless of current locale. + */ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL rtl_getTextEncodingFromWindowsCharset( + sal_uInt8 nWinCharset ); + +/** Map from a MIME charset to a text encoding. + + @param pMimeCharset + Any MIME charset string. Must not be null. + + @return + The corresponding rtl_TextEncoding value, or RTL_TEXTENCODING_DONTKNOW if + no mapping is applicable. + */ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL rtl_getTextEncodingFromMimeCharset( + const char* pMimeCharset ); + +/** Map from a Unix charset to a text encoding. + + @param pUnixCharset + Any Unix charset string. Must not be null. + + @return + The corresponding rtl_TextEncoding value, or RTL_TEXTENCODING_DONTKNOW if + no mapping is applicable. + */ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL rtl_getTextEncodingFromUnixCharset( + const char* pUnixCharset ); + +/** Map from a text encoding to the best matching numeric Windows charset. + + @param eTextEncoding + Any rtl_TextEncoding value. + + @return + The best matching numeric Windows charset, or 1 if none matches. + */ +SAL_DLLPUBLIC sal_uInt8 SAL_CALL rtl_getBestWindowsCharsetFromTextEncoding( + rtl_TextEncoding eTextEncoding ); + +/** Map from a text encoding to a corresponding MIME charset name, if + available (see ). + + @param nEncoding + Any rtl_TextEncoding value. + + @return + The (preferred) MIME charset name corresponding to the given encoding, or + NULL if none is available. + */ +SAL_DLLPUBLIC char const * SAL_CALL rtl_getMimeCharsetFromTextEncoding( + rtl_TextEncoding nEncoding ); + +/** Map from a text encoding to the best matching MIME charset. + + @param eTextEncoding + Any rtl_TextEncoding value. + + @return + The best matching MIME charset string, or null if none matches. + */ +SAL_DLLPUBLIC const char* SAL_CALL rtl_getBestMimeCharsetFromTextEncoding( + rtl_TextEncoding eTextEncoding ); + +/** Map from a text encoding to the best matching Unix charset. + + @param eTextEncoding + Any rtl_TextEncoding value. + + @return + The best matching Unix charset string, or null if none matches. + */ +SAL_DLLPUBLIC const char* SAL_CALL rtl_getBestUnixCharsetFromTextEncoding( + rtl_TextEncoding eTextEncoding ); + +/** Map from a Windows code page to a text encoding. + + @param nCodePage + Any Windows code page number. + + @return + The corresponding rtl_TextEncoding value (which will be an octet text + encoding, see rtl_isOctetTextEncoding), or RTL_TEXTENCODING_DONTKNOW if no + mapping is applicable. + */ +SAL_DLLPUBLIC rtl_TextEncoding SAL_CALL +rtl_getTextEncodingFromWindowsCodePage(sal_uInt32 nCodePage); + +/** Map from a text encoding to a Windows code page. + + @param nEncoding + Any rtl_TextEncoding value. + + @return + The corresponding Windows code page number, or 0 if no mapping is + applicable. + */ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL +rtl_getWindowsCodePageFromTextEncoding(rtl_TextEncoding nEncoding); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_TENCINFO_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/textcvt.h b/include/rtl/textcvt.h new file mode 100644 index 000000000..14d374c16 --- /dev/null +++ b/include/rtl/textcvt.h @@ -0,0 +1,194 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_TEXTCVT_H +#define INCLUDED_RTL_TEXTCVT_H + +#include "sal/config.h" + +#include "rtl/textenc.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Documentation about this file can be found at + . */ + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +typedef void* rtl_TextToUnicodeConverter; + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +typedef void* rtl_TextToUnicodeContext; + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC rtl_TextToUnicodeConverter SAL_CALL rtl_createTextToUnicodeConverter( rtl_TextEncoding eTextEncoding ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC void SAL_CALL rtl_destroyTextToUnicodeConverter( rtl_TextToUnicodeConverter hConverter ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC rtl_TextToUnicodeContext SAL_CALL rtl_createTextToUnicodeContext( rtl_TextToUnicodeConverter hConverter ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC void SAL_CALL rtl_destroyTextToUnicodeContext( rtl_TextToUnicodeConverter hConverter, rtl_TextToUnicodeContext hContext ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC void SAL_CALL rtl_resetTextToUnicodeContext( rtl_TextToUnicodeConverter hConverter, rtl_TextToUnicodeContext hContext ); + +#define RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR ((sal_uInt32)0x0001) +#define RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_IGNORE ((sal_uInt32)0x0002) +#define RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_MAPTOPRIVATE ((sal_uInt32)0x0003) +#define RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_DEFAULT ((sal_uInt32)0x0004) +#define RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR ((sal_uInt32)0x0010) +#define RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_IGNORE ((sal_uInt32)0x0020) +#define RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT ((sal_uInt32)0x0030) +#define RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR ((sal_uInt32)0x0100) +#define RTL_TEXTTOUNICODE_FLAGS_INVALID_IGNORE ((sal_uInt32)0x0200) +#define RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT ((sal_uInt32)0x0300) +#define RTL_TEXTTOUNICODE_FLAGS_FLUSH ((sal_uInt32)0x8000) +#define RTL_TEXTTOUNICODE_FLAGS_GLOBAL_SIGNATURE 0x10000 + /* Accept any global document signatures (for example, in UTF-8, a leading + EF BB BF encoding the Byte Order Mark U+FEFF) */ + +#define RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_MASK ((sal_uInt32)0x000F) +#define RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_MASK ((sal_uInt32)0x00F0) +#define RTL_TEXTTOUNICODE_FLAGS_INVALID_MASK ((sal_uInt32)0x0F00) + +#define RTL_TEXTTOUNICODE_INFO_ERROR ((sal_uInt32)0x0001) +// Misspelled constant, kept for backwards compatibility: +#define RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOSMALL ((sal_uInt32)0x0002) +#define RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL ((sal_uInt32)0x0002) +// Misspelled constant, kept for backwards compatibility: +#define RTL_TEXTTOUNICODE_INFO_DESTBUFFERTOSMALL ((sal_uInt32)0x0004) +#define RTL_TEXTTOUNICODE_INFO_DESTBUFFERTOOSMALL ((sal_uInt32)0x0004) +#define RTL_TEXTTOUNICODE_INFO_UNDEFINED ((sal_uInt32)0x0008) +#define RTL_TEXTTOUNICODE_INFO_MBUNDEFINED ((sal_uInt32)0x0010) +#define RTL_TEXTTOUNICODE_INFO_INVALID ((sal_uInt32)0x0020) + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + + Deviating from the linked specification, the behavior of + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR, RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR, and + RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR is as follows: When RTL_TEXTTOUNICODE_FLAGS_FLUSH is not + set, the erroneous input bytes are consumed as required by the linked specification. But if + RTL_TEXTTOUNICODE_FLAGS_FLUSH is set, any of those erroneous input bytes that would have been + consumed by this invocation of rtl_convertTextToUnicode (i.e., which had not already been + captured in hContext from a previous invocation with RTL_TEXTTOUNICODE_FLAGS_FLUSH unset) are + not consumed. + */ +SAL_DLLPUBLIC sal_Size SAL_CALL rtl_convertTextToUnicode( + rtl_TextToUnicodeConverter hConverter, + rtl_TextToUnicodeContext hContext, + const char* pSrcBuf, sal_Size nSrcBytes, + sal_Unicode* pDestBuf, sal_Size nDestChars, + sal_uInt32 nFlags, sal_uInt32* pInfo, + sal_Size* pSrcCvtBytes ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +typedef void* rtl_UnicodeToTextConverter; + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +typedef void* rtl_UnicodeToTextContext; + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC rtl_UnicodeToTextConverter SAL_CALL rtl_createUnicodeToTextConverter( rtl_TextEncoding eTextEncoding ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC void SAL_CALL rtl_destroyUnicodeToTextConverter( rtl_UnicodeToTextConverter hConverter ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC rtl_UnicodeToTextContext SAL_CALL rtl_createUnicodeToTextContext( rtl_UnicodeToTextConverter hConverter ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC void SAL_CALL rtl_destroyUnicodeToTextContext( rtl_UnicodeToTextConverter hConverter, rtl_UnicodeToTextContext hContext ); + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC void SAL_CALL rtl_resetUnicodeToTextContext( rtl_UnicodeToTextConverter hConverter, rtl_UnicodeToTextContext hContext ); + +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR ((sal_uInt32)0x0001) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_IGNORE ((sal_uInt32)0x0002) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_0 ((sal_uInt32)0x0003) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_QUESTIONMARK ((sal_uInt32)0x0004) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_UNDERLINE ((sal_uInt32)0x0005) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_DEFAULT ((sal_uInt32)0x0006) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR ((sal_uInt32)0x0010) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_IGNORE ((sal_uInt32)0x0020) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_0 ((sal_uInt32)0x0030) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_QUESTIONMARK ((sal_uInt32)0x0040) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_UNDERLINE ((sal_uInt32)0x0050) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_DEFAULT ((sal_uInt32)0x0060) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE ((sal_uInt32)0x0100) +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACESTR ((sal_uInt32)0x0200) +#define RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 ((sal_uInt32)0x0400) +#define RTL_UNICODETOTEXT_FLAGS_NONSPACING_IGNORE ((sal_uInt32)0x0800) +#define RTL_UNICODETOTEXT_FLAGS_CONTROL_IGNORE ((sal_uInt32)0x1000) +#define RTL_UNICODETOTEXT_FLAGS_PRIVATE_IGNORE ((sal_uInt32)0x2000) +#define RTL_UNICODETOTEXT_FLAGS_NOCOMPOSITE ((sal_uInt32)0x4000) ///< has no effect @deprecated +#define RTL_UNICODETOTEXT_FLAGS_FLUSH ((sal_uInt32)0x8000) +#define RTL_UNICODETOTEXT_FLAGS_GLOBAL_SIGNATURE 0x10000 + /* Write any global document signatures (for example, in UTF-8, a leading + EF BB BF encoding the Byte Order Mark U+FEFF) */ + +#define RTL_UNICODETOTEXT_FLAGS_UNDEFINED_MASK ((sal_uInt32)0x000F) +#define RTL_UNICODETOTEXT_FLAGS_INVALID_MASK ((sal_uInt32)0x00F0) + +#define RTL_UNICODETOTEXT_INFO_ERROR ((sal_uInt32)0x0001) +#define RTL_UNICODETOTEXT_INFO_SRCBUFFERTOSMALL ((sal_uInt32)0x0002) +#define RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL ((sal_uInt32)0x0004) +#define RTL_UNICODETOTEXT_INFO_UNDEFINED ((sal_uInt32)0x0008) +#define RTL_UNICODETOTEXT_INFO_INVALID ((sal_uInt32)0x0010) + +/** see http://udk.openoffice.org/cpp/man/spec/textconversion.html + */ +SAL_DLLPUBLIC sal_Size SAL_CALL rtl_convertUnicodeToText( + rtl_UnicodeToTextConverter hConverter, + rtl_UnicodeToTextContext hContext, + const sal_Unicode* pSrcBuf, sal_Size nSrcChars, + char* pDestBuf, sal_Size nDestBytes, + sal_uInt32 nFlags, sal_uInt32* pInfo, + sal_Size* pSrcCvtChars ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_TEXTCVT_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/textenc.h b/include/rtl/textenc.h new file mode 100644 index 000000000..1a675e1be --- /dev/null +++ b/include/rtl/textenc.h @@ -0,0 +1,266 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_TEXTENC_H +#define INCLUDED_RTL_TEXTENC_H + +#include "sal/types.h" + +/** The various supported text encodings. + + Possible values include a wide range of single- and multi-byte encodings + (ranging from RTL_TEXTENCODING_MS_1252 to RTL_TEXTENCODING_GB_18030), + the ISO 10646 (Unicode) specific encodings RTL_TEXTENCODING_UCS4 and + RTL_TEXTENCODING_UCS2 (aka RTL_TEXTENCODING_UNICODE), and + RTL_TEXTENCODING_DONTKNOW to indicate an unknown or missing encoding. + */ +typedef sal_uInt16 rtl_TextEncoding; + +#define RTL_TEXTENC_CAST( val ) ((rtl_TextEncoding) val) + +#define RTL_TEXTENCODING_DONTKNOW (RTL_TEXTENC_CAST( 0 )) +#define RTL_TEXTENCODING_MS_1252 (RTL_TEXTENC_CAST( 1 )) +#define RTL_TEXTENCODING_APPLE_ROMAN (RTL_TEXTENC_CAST( 2 )) +#define RTL_TEXTENCODING_IBM_437 (RTL_TEXTENC_CAST( 3 )) +#define RTL_TEXTENCODING_IBM_850 (RTL_TEXTENC_CAST( 4 )) +#define RTL_TEXTENCODING_IBM_860 (RTL_TEXTENC_CAST( 5 )) +#define RTL_TEXTENCODING_IBM_861 (RTL_TEXTENC_CAST( 6 )) +#define RTL_TEXTENCODING_IBM_863 (RTL_TEXTENC_CAST( 7 )) +#define RTL_TEXTENCODING_IBM_865 (RTL_TEXTENC_CAST( 8 )) +/* Reserved: RTL_TEXTENCODING_SYSTEM (RTL_TEXTENC_CAST( 9 )) */ +#define RTL_TEXTENCODING_SYMBOL (RTL_TEXTENC_CAST( 10 )) +#define RTL_TEXTENCODING_ASCII_US (RTL_TEXTENC_CAST( 11 )) +#define RTL_TEXTENCODING_ISO_8859_1 (RTL_TEXTENC_CAST( 12 )) +#define RTL_TEXTENCODING_ISO_8859_2 (RTL_TEXTENC_CAST( 13 )) +#define RTL_TEXTENCODING_ISO_8859_3 (RTL_TEXTENC_CAST( 14 )) +#define RTL_TEXTENCODING_ISO_8859_4 (RTL_TEXTENC_CAST( 15 )) +#define RTL_TEXTENCODING_ISO_8859_5 (RTL_TEXTENC_CAST( 16 )) +#define RTL_TEXTENCODING_ISO_8859_6 (RTL_TEXTENC_CAST( 17 )) +#define RTL_TEXTENCODING_ISO_8859_7 (RTL_TEXTENC_CAST( 18 )) +#define RTL_TEXTENCODING_ISO_8859_8 (RTL_TEXTENC_CAST( 19 )) +#define RTL_TEXTENCODING_ISO_8859_9 (RTL_TEXTENC_CAST( 20 )) +#define RTL_TEXTENCODING_ISO_8859_14 (RTL_TEXTENC_CAST( 21 )) +#define RTL_TEXTENCODING_ISO_8859_15 (RTL_TEXTENC_CAST( 22 )) +#define RTL_TEXTENCODING_IBM_737 (RTL_TEXTENC_CAST( 23 )) +#define RTL_TEXTENCODING_IBM_775 (RTL_TEXTENC_CAST( 24 )) +#define RTL_TEXTENCODING_IBM_852 (RTL_TEXTENC_CAST( 25 )) +#define RTL_TEXTENCODING_IBM_855 (RTL_TEXTENC_CAST( 26 )) +#define RTL_TEXTENCODING_IBM_857 (RTL_TEXTENC_CAST( 27 )) +#define RTL_TEXTENCODING_IBM_862 (RTL_TEXTENC_CAST( 28 )) +#define RTL_TEXTENCODING_IBM_864 (RTL_TEXTENC_CAST( 29 )) +#define RTL_TEXTENCODING_IBM_866 (RTL_TEXTENC_CAST( 30 )) +#define RTL_TEXTENCODING_IBM_869 (RTL_TEXTENC_CAST( 31 )) +#define RTL_TEXTENCODING_MS_874 (RTL_TEXTENC_CAST( 32 )) +#define RTL_TEXTENCODING_MS_1250 (RTL_TEXTENC_CAST( 33 )) +#define RTL_TEXTENCODING_MS_1251 (RTL_TEXTENC_CAST( 34 )) +#define RTL_TEXTENCODING_MS_1253 (RTL_TEXTENC_CAST( 35 )) +#define RTL_TEXTENCODING_MS_1254 (RTL_TEXTENC_CAST( 36 )) +#define RTL_TEXTENCODING_MS_1255 (RTL_TEXTENC_CAST( 37 )) +#define RTL_TEXTENCODING_MS_1256 (RTL_TEXTENC_CAST( 38 )) +#define RTL_TEXTENCODING_MS_1257 (RTL_TEXTENC_CAST( 39 )) +#define RTL_TEXTENCODING_MS_1258 (RTL_TEXTENC_CAST( 40 )) +#define RTL_TEXTENCODING_APPLE_ARABIC (RTL_TEXTENC_CAST( 41 )) +#define RTL_TEXTENCODING_APPLE_CENTEURO (RTL_TEXTENC_CAST( 42 )) +#define RTL_TEXTENCODING_APPLE_CROATIAN (RTL_TEXTENC_CAST( 43 )) +#define RTL_TEXTENCODING_APPLE_CYRILLIC (RTL_TEXTENC_CAST( 44 )) +#define RTL_TEXTENCODING_APPLE_DEVANAGARI (RTL_TEXTENC_CAST( 45 )) +#define RTL_TEXTENCODING_APPLE_FARSI (RTL_TEXTENC_CAST( 46 )) +#define RTL_TEXTENCODING_APPLE_GREEK (RTL_TEXTENC_CAST( 47 )) +#define RTL_TEXTENCODING_APPLE_GUJARATI (RTL_TEXTENC_CAST( 48 )) +#define RTL_TEXTENCODING_APPLE_GURMUKHI (RTL_TEXTENC_CAST( 49 )) +#define RTL_TEXTENCODING_APPLE_HEBREW (RTL_TEXTENC_CAST( 50 )) +#define RTL_TEXTENCODING_APPLE_ICELAND (RTL_TEXTENC_CAST( 51 )) +#define RTL_TEXTENCODING_APPLE_ROMANIAN (RTL_TEXTENC_CAST( 52 )) +#define RTL_TEXTENCODING_APPLE_THAI (RTL_TEXTENC_CAST( 53 )) +#define RTL_TEXTENCODING_APPLE_TURKISH (RTL_TEXTENC_CAST( 54 )) +#define RTL_TEXTENCODING_APPLE_UKRAINIAN (RTL_TEXTENC_CAST( 55 )) +#define RTL_TEXTENCODING_APPLE_CHINSIMP (RTL_TEXTENC_CAST( 56 )) +#define RTL_TEXTENCODING_APPLE_CHINTRAD (RTL_TEXTENC_CAST( 57 )) +#define RTL_TEXTENCODING_APPLE_JAPANESE (RTL_TEXTENC_CAST( 58 )) +#define RTL_TEXTENCODING_APPLE_KOREAN (RTL_TEXTENC_CAST( 59 )) +#define RTL_TEXTENCODING_MS_932 (RTL_TEXTENC_CAST( 60 )) +#define RTL_TEXTENCODING_MS_936 (RTL_TEXTENC_CAST( 61 )) +#define RTL_TEXTENCODING_MS_949 (RTL_TEXTENC_CAST( 62 )) +#define RTL_TEXTENCODING_MS_950 (RTL_TEXTENC_CAST( 63 )) +#define RTL_TEXTENCODING_SHIFT_JIS (RTL_TEXTENC_CAST( 64 )) +#define RTL_TEXTENCODING_GB_2312 (RTL_TEXTENC_CAST( 65 )) +#define RTL_TEXTENCODING_GBT_12345 (RTL_TEXTENC_CAST( 66 )) +#define RTL_TEXTENCODING_GBK (RTL_TEXTENC_CAST( 67 )) +#define RTL_TEXTENCODING_BIG5 (RTL_TEXTENC_CAST( 68 )) +#define RTL_TEXTENCODING_EUC_JP (RTL_TEXTENC_CAST( 69 )) +#define RTL_TEXTENCODING_EUC_CN (RTL_TEXTENC_CAST( 70 )) +#define RTL_TEXTENCODING_EUC_TW (RTL_TEXTENC_CAST( 71 )) +#define RTL_TEXTENCODING_ISO_2022_JP (RTL_TEXTENC_CAST( 72 )) +#define RTL_TEXTENCODING_ISO_2022_CN (RTL_TEXTENC_CAST( 73 )) +#define RTL_TEXTENCODING_KOI8_R (RTL_TEXTENC_CAST( 74 )) +#define RTL_TEXTENCODING_UTF7 (RTL_TEXTENC_CAST( 75 )) +#define RTL_TEXTENCODING_UTF8 (RTL_TEXTENC_CAST( 76 )) +#define RTL_TEXTENCODING_ISO_8859_10 (RTL_TEXTENC_CAST( 77 )) +#define RTL_TEXTENCODING_ISO_8859_13 (RTL_TEXTENC_CAST( 78 )) +#define RTL_TEXTENCODING_EUC_KR (RTL_TEXTENC_CAST( 79 )) +#define RTL_TEXTENCODING_ISO_2022_KR (RTL_TEXTENC_CAST( 80 )) +#define RTL_TEXTENCODING_JIS_X_0201 (RTL_TEXTENC_CAST( 81 )) +#define RTL_TEXTENCODING_JIS_X_0208 (RTL_TEXTENC_CAST( 82 )) +#define RTL_TEXTENCODING_JIS_X_0212 (RTL_TEXTENC_CAST( 83 )) +#define RTL_TEXTENCODING_MS_1361 (RTL_TEXTENC_CAST( 84 )) +#define RTL_TEXTENCODING_GB_18030 (RTL_TEXTENC_CAST( 85 )) +#define RTL_TEXTENCODING_BIG5_HKSCS (RTL_TEXTENC_CAST( 86 )) +#define RTL_TEXTENCODING_TIS_620 (RTL_TEXTENC_CAST( 87 )) +#define RTL_TEXTENCODING_KOI8_U (RTL_TEXTENC_CAST( 88 )) +#define RTL_TEXTENCODING_ISCII_DEVANAGARI (RTL_TEXTENC_CAST( 89 )) +#define RTL_TEXTENCODING_JAVA_UTF8 (RTL_TEXTENC_CAST( 90 )) +#define RTL_TEXTENCODING_ADOBE_STANDARD (RTL_TEXTENC_CAST( 91 )) +#define RTL_TEXTENCODING_ADOBE_SYMBOL (RTL_TEXTENC_CAST( 92 )) +#define RTL_TEXTENCODING_PT154 (RTL_TEXTENC_CAST( 93 )) +#define RTL_TEXTENCODING_ADOBE_DINGBATS (RTL_TEXTENC_CAST( 94 )) +/* ATTENTION! Whenever some encoding is added here, make sure to update + * rtl_isOctetTextEncoding in tencinfo.c. + */ + +#define RTL_TEXTENCODING_USER_START (RTL_TEXTENC_CAST( 0x8000 )) +#define RTL_TEXTENCODING_USER_END (RTL_TEXTENC_CAST( 0xEFFF )) + +#define RTL_TEXTENCODING_UCS4 (RTL_TEXTENC_CAST( 0xFFFE )) +#define RTL_TEXTENCODING_UCS2 (RTL_TEXTENC_CAST( 0xFFFF )) +#define RTL_TEXTENCODING_UNICODE RTL_TEXTENCODING_UCS2 + +/****** Overview over the TextEncodings ***** +# Arabic (Apple Macintosh) RTL_TEXTENCODING_APPLE_ARABIC +Arabic (DOS/OS2-864) RTL_TEXTENCODING_IBM_864 +Arabic (ISO-8859-6) RTL_TEXTENCODING_ISO_8859_6 +Arabic (Windows-1256) RTL_TEXTENCODING_MS_1256 + +Baltic (DOS/OS2-775) RTL_TEXTENCODING_IBM_775 +Baltic (ISO-8859-4) RTL_TEXTENCODING_ISO_8859_4 +Baltic (Windows-1257) RTL_TEXTENCODING_MS_1257 + +Central European (Apple Macintosh) RTL_TEXTENCODING_APPLE_CENTEURO +Central European (Apple Macintosh/Croatian) RTL_TEXTENCODING_APPLE_CROATIAN +Central European (Apple Macintosh/Romanian) RTL_TEXTENCODING_APPLE_ROMANIAN +Central European (DOS/OS2-852) RTL_TEXTENCODING_IBM_852 +Central European (ISO-8859-2) RTL_TEXTENCODING_ISO_8859_2 +Central European (ISO-8859-10) RTL_TEXTENCODING_ISO_8859_10 +Central European (ISO-8859-13) RTL_TEXTENCODING_ISO_8859_13 +Central European (Windows-1250/WinLatin 2) RTL_TEXTENCODING_MS_1250 + +Chinese Simplified (Apple Macintosh) RTL_TEXTENCODING_APPLE_CHINSIMP +Chinese Simplified (EUC-CN) RTL_TEXTENCODING_EUC_CN +Chinese Simplified (GB-2312) RTL_TEXTENCODING_GB_2312 +Chinese Simplified (GBK/GB-2312-80) RTL_TEXTENCODING_GBK +# Chinese Simplified (ISO-2022-CN) RTL_TEXTENCODING_ISO_2022_CN +Chinese Simplified (Windows-936) RTL_TEXTENCODING_MS_936 +# Chinese Simplified (GB-18030) RTL_TEXTENCODING_GB_18030 + +Chinese Traditional (Apple Macintosh) RTL_TEXTENCODING_APPLE_CHINTRAD +Chinese Traditional (BIG5) RTL_TEXTENCODING_BIG5 +# Chinese Traditional (EUC-TW) RTL_TEXTENCODING_EUC_TW +Chinese Traditional (GBT-12345) RTL_TEXTENCODING_GBT_12345 +Chinese Traditional (Windows-950) RTL_TEXTENCODING_MS_950 +Chinese Traditional (BIG5-HKSCS) RTL_TEXTENCODING_BIG5_HKSCS + +Cyrillic (Apple Macintosh) RTL_TEXTENCODING_APPLE_CYRILLIC +Cyrillic (Apple Macintosh/Ukrainian) RTL_TEXTENCODING_APPLE_UKRAINIAN +Cyrillic (DOS/OS2-855) RTL_TEXTENCODING_IBM_855 +Cyrillic (DOS/OS2-866/Russian) RTL_TEXTENCODING_IBM_866 +Cyrillic (ISO-8859-5) RTL_TEXTENCODING_ISO_8859_5 +Cyrillic (KOI8-R) RTL_TEXTENCODING_KOI8_R +Cyrillic (KOI8-U) RTL_TEXTENCODING_KOI8_U +Cyrillic (Windows-1251) RTL_TEXTENCODING_MS_1251 + +Greek (Apple Macintosh) RTL_TEXTENCODING_APPLE_GREEK +Greek (DOS/OS2-737) RTL_TEXTENCODING_IBM_737 +Greek (DOS/OS2-869/Modern) RTL_TEXTENCODING_IBM_869 +Greek (ISO-8859-7) RTL_TEXTENCODING_ISO_8859_7 +Greek (Windows-1253) RTL_TEXTENCODING_MS_1253 + +# Hebrew (Apple Macintosh) RTL_TEXTENCODING_APPLE_HEBREW +Hebrew (DOS/OS2-862) RTL_TEXTENCODING_IBM_862 +Hebrew (ISO-8859-8) RTL_TEXTENCODING_ISO_8859_8 +Hebrew (Windows-1255) RTL_TEXTENCODING_MS_1255 + +Korean (Apple Macintosh) RTL_TEXTENCODING_APPLE_KOREAN +Korean (EUC-KR) RTL_TEXTENCODING_EUC_KR +# Korean (ISO-2022-KR) RTL_TEXTENCODING_ISO_2022_KR +Korean (Windows-Wansung-949) RTL_TEXTENCODING_MS_949 +Korean (Windows-Johab-1361) RTL_TEXTENCODING_MS_1361 + +Latin 3 (ISO-8859-3) RTL_TEXTENCODING_ISO_8859_3 + +Indian (ISCII Devanagari) RTL_TEXTENCODING_ISCII_DEVANAGARI + +Japanese (Apple Macintosh) RTL_TEXTENCODING_APPLE_JAPANESE +Japanese (EUC-JP) RTL_TEXTENCODING_EUC_JP +# Japanese (ISO-2022-JP) RTL_TEXTENCODING_ISO_2022_JP +Japanese (Shift-JIS) RTL_TEXTENCODING_SHIFT_JIS +Japanese (Windows-932) RTL_TEXTENCODING_MS_932 + +Symbol RTL_TEXTENCODING_SYMBOL + +# Thai (Apple Macintosh) RTL_TEXTENCODING_APPLE_THAI +Thai (Dos/Windows-874) RTL_TEXTENCODING_MS_874 +Thai (TIS 620) RTL_TEXTENCODING_TIS_620 + +Turkish (Apple Macintosh) RTL_TEXTENCODING_APPLE_TURKISH +Turkish (DOS/OS2-857) RTL_TEXTENCODING_IBM_857 +Turkish (ISO-8859-9) RTL_TEXTENCODING_ISO_8859_9 +Turkish (Windows-1254) RTL_TEXTENCODING_MS_1254 + +Unicode (UTF-7) RTL_TEXTENCODING_UTF7 +Unicode (UTF-8) RTL_TEXTENCODING_UTF8 +Unicode (Java's modified UTF-8) RTL_TEXTENCODING_JAVA_UTF8 + +Vietnamese (Windows-1258) RTL_TEXTENCODING_MS_1258 + +Western (Apple Macintosh) RTL_TEXTENCODING_APPLE_ROMAN +Western (Apple Macintosh/Icelandic) RTL_TEXTENCODING_APPLE_ICELAND +Western (ASCII/US) RTL_TEXTENCODING_ASCII_US +Western (DOS/OS2-437/US) RTL_TEXTENCODING_IBM_437 +Western (DOS/OS2-850/International) RTL_TEXTENCODING_IBM_850 +Western (DOS/OS2-860/Portuguese) RTL_TEXTENCODING_IBM_860 +Western (DOS/OS2-861/Icelandic) RTL_TEXTENCODING_IBM_861 +Western (DOS/OS2-863/Canadian-French) RTL_TEXTENCODING_IBM_863 +Western (DOS/OS2-865/Nordic) RTL_TEXTENCODING_IBM_865 +Western (ISO-8859-1) RTL_TEXTENCODING_ISO_8859_1 +Western (ISO-8859-14) RTL_TEXTENCODING_ISO_8859_14 +Western (ISO-8859-15/EURO) RTL_TEXTENCODING_ISO_8859_15 +Western (Window-1252/WinLatin 1) RTL_TEXTENCODING_MS_1252 + +Not known and currently not supported +# RTL_TEXTENCODING_APPLE_DEVANAGARI +# RTL_TEXTENCODING_APPLE_FARSI +# RTL_TEXTENCODING_APPLE_GUJARATI +# RTL_TEXTENCODING_APPLE_GURMUKHI + +Only for internal implementations and not useful for user interface. +These encodings are not used for text encodings, only used for +font-/textoutput encodings. +Japanese (JIS 0201) RTL_TEXTENCODING_JISX_0201 +Japanese (JIS 0208) RTL_TEXTENCODING_JISX_0208 +Japanese (JIS 0212) RTL_TEXTENCODING_JISX_0212 + +# Currently not implemented +*/ + +#endif // INCLUDED_RTL_TEXTENC_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/unload.h b/include/rtl/unload.h new file mode 100644 index 000000000..23cd2fa74 --- /dev/null +++ b/include/rtl/unload.h @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_UNLOAD_H +#define INCLUDED_RTL_UNLOAD_H + +#include "sal/config.h" + +#include "osl/interlck.h" +#include "osl/time.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +/** @file + Backwards-compatibility remainders of a removed library unloading feature. +*/ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** Backwards-compatibility remainder of a removed library unloading feature. + + @deprecated Do not use. +*/ +typedef struct SAL_DLLPUBLIC_RTTI _rtl_ModuleCount +{ + void ( SAL_CALL * acquire ) ( struct _rtl_ModuleCount * that ); + void ( SAL_CALL * release ) ( struct _rtl_ModuleCount * that ); +}rtl_ModuleCount; + +/** Backwards-compatibility remainder of a removed library unloading feature. + + @deprecated Do not use. +*/ +#define MODULE_COUNT_INIT \ +{ {rtl_moduleCount_acquire,rtl_moduleCount_release}, rtl_moduleCount_canUnload, 0, {0, 0}} + +/** Backwards-compatibility remainder of a removed library unloading feature. + + @deprecated Do not use. +*/ +typedef struct _rtl_StandardModuleCount +{ + rtl_ModuleCount modCnt; + sal_Bool ( *canUnload ) ( struct _rtl_StandardModuleCount* a, TimeValue* libUnused); + oslInterlockedCount counter; + TimeValue unusedSince; +} rtl_StandardModuleCount; + +/** Backwards-compatibility remainder of a removed library unloading feature. + + @deprecated Do not use. +*/ +SAL_DLLPUBLIC void rtl_moduleCount_acquire(rtl_ModuleCount * that ) SAL_COLD; + +/** Backwards-compatibility remainder of a removed library unloading feature. + + @deprecated Do not use. +*/ +SAL_DLLPUBLIC void rtl_moduleCount_release( rtl_ModuleCount * that ) SAL_COLD; + +/** Backwards-compatibility remainder of a removed library unloading feature. + + @deprecated Do not use. +*/ +SAL_DLLPUBLIC sal_Bool rtl_moduleCount_canUnload( rtl_StandardModuleCount * that, TimeValue* libUnused) SAL_COLD; + +#ifdef __cplusplus +} +#endif + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/uri.h b/include/rtl/uri.h new file mode 100644 index 000000000..1fbd0128a --- /dev/null +++ b/include/rtl/uri.h @@ -0,0 +1,357 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_URI_H +#define INCLUDED_RTL_URI_H + +#include "sal/config.h" + +#include "rtl/textenc.h" +#include "rtl/ustring.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#if defined __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Various predefined URI 'char classes.' + + A 'char class' defines which (ASCII) characters can be written 'as they + are' in a part of a Uri, and which characters have to be written using + escape sequences ('%' followed by two hex digits). Characters outside + the ASCII range are always written using escape sequences. + + If there are other frequently used char classes, they can be added to + this enumeration; the function rtl_getUriCharClass() has to be adapted + then, too. + */ +typedef enum +{ + /** The empty char class. + + All characters are written using escape sequences. + */ + rtl_UriCharClassNone, + + /** The RFC 2732 @ char class. + + @verbatim + The 'valid' characters are !$&'()*+,-./:;=?@[]_~ plus digits and + letters. + + This differs from RFC 3986 @ in additionally allowing [] + @endverbatim + */ + rtl_UriCharClassUric, + + /** The RFC 2396 @ char class. + + @verbatim + The 'valid' characters are !$&'()*+,-.:;=?@_~ plus digits and letters. + + This differs from RFC 3986 @ in additionally encoding / + This differs from RFC 3986 @ in additionally allowing ? + @endverbatim + */ + rtl_UriCharClassUricNoSlash, + + /** The RFC 2396 @ char class. + + @verbatim + The 'valid' characters are !$&'()*+,-.;=@_~ plus digits and letters. + + This is the same as RFC 3986 @ + @endverbatim + */ + rtl_UriCharClassRelSegment, + + /** The RFC 2396 @ char class. + + @verbatim + The 'valid' characters are !$&'()*+,-.:;=@_~ plus digits and letters. + + This differs from RFC 3986 @ in additionally allowing @ + @endverbatim + */ + rtl_UriCharClassRegName, + + /** The RFC 2396 @ char class. + + @verbatim + The 'valid' characters are !$&'()*+,-.:;=_~ plus digits and letters. + + This is the same as RFC 3986 @ + @endverbatim + */ + rtl_UriCharClassUserinfo, + + /** The RFC 2396 @ char class. + + @verbatim + The 'valid' characters are !$&'()*+,-.:=@_~ plus digits and letters. + + This differs from RFC 3986 @ in additionally encoding ; + @endverbatim + */ + rtl_UriCharClassPchar, + + /** The char class for the values of uno URL parameters. + + @verbatim + The 'valid' characters are !$&'()*+-./:?@_~ plus digits and letters. + @endverbatim + */ + rtl_UriCharClassUnoParamValue, + + rtl_UriCharClass_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} +rtl_UriCharClass; + +/** The mechanism describing how escape sequences in the input of + rtl_uriEncode() are handled. + */ +typedef enum +{ + /** The special meaning of '%' is ignored (i.e., there are by definition + no escape sequences in the input). + + This mechanism is useful to encode user input as part of a URI (e.g., + the user-supplied password in an ftp URL---'%20abcde' is a valid + password, so do not assume that the '%20' is an escaped space). + */ + rtl_UriEncodeIgnoreEscapes, + + /** All escape sequences ('%' followed by two hex digits) are kept intact, + even if they represent characters that need not be escaped or if they + do not even map to characters in the given charset. + + This mechanism is useful when passing on complete URIs more or less + unmodified (e.g., within an HTTP proxy): missing escape sequences are + added, but existing escape sequences are not touched (except that any + lower case hex digits are replaced by upper case hex digits). + */ + rtl_UriEncodeKeepEscapes, + + /** All escape sequences ('%' followed by two hex digits) are resolved in + a first step; only those that represent characters that need to be + escaped are kept intact. + + This mechanism is useful to properly encode complete URIs entered by + the user: the URI is brought into a 'canonic form,' but care is taken + not to damage (valid) escape sequences the (careful) user already + entered as such. + */ + rtl_UriEncodeCheckEscapes, + + /** Like rtl_UriEncodeIgnoreEscapes, but indicating failure when converting + unmappable characters. + + @since UDK 3.2.0 + */ + rtl_UriEncodeStrict, + + /** Like rtl_UriEncodeKeepEscapes, but indicating failure when converting + unmappable characters. + + @since UDK 3.2.7 + */ + rtl_UriEncodeStrictKeepEscapes, + + rtl_UriEncode_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} +rtl_UriEncodeMechanism; + +/** The mechanism describing how rtl_uriDecode() translates (part of) a URI + into a Unicode string. + */ +typedef enum +{ + /** The text is returned completely unmodified. + */ + rtl_UriDecodeNone, + + /** The text is returned in the form of an IURI (cf. + draft-masinter-url-i18n-05.txt). + + All escape sequences representing ASCII characters (%00--%7F) are + kept, all other escape sequences are interpreted as UTF-8 characters + and translated to Unicode, if possible. + */ + rtl_UriDecodeToIuri, + + /** The text is decoded. + + All escape sequences representing characters from the given charset + are decoded and translated to Unicode, if possible. + */ + rtl_UriDecodeWithCharset, + + /** Like rtl_UriDecodeWithCharset, but indicating failure when converting + unmappable characters. + + @since UDK 3.2.0 + */ + rtl_UriDecodeStrict, + + rtl_UriDecode_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} +rtl_UriDecodeMechanism; + +/** Map a predefined rtl_UriCharClass to a form usable by rtl_uriEncode(). + + The function rtl_uriEncode() expects an array of 128 booleans, and this + function maps rtl_UriCharClass enumeration members to such arrays. + + @param eCharClass + Any valid member of rtl_UriCharClass. + + @return + An array of 128 booleans, to be used in calls to rtl_uriEncode(). + */ +SAL_DLLPUBLIC sal_Bool const * SAL_CALL rtl_getUriCharClass(rtl_UriCharClass eCharClass) + SAL_THROW_EXTERN_C(); + +/** Encode a text as (part of) a URI. + + @param pText + Any Unicode string. Must not be null. + + @param pCharClass + A char class, represented as an array of 128 booleans (true means keep the + corresponding ASCII character unencoded, false means encode it). Must not + be null, and the boolean corresponding to the percent sign (0x25) must be + false. (See rtl_getUriCharClass() for a function mapping from + rtl_UriCharClass to such arrays.) + + @param eMechanism + The mechanism describing how escape sequences in the input text are + handled. + + @param eCharset + When Unicode characters from the input text have to be written using + escape sequences (because they are either outside the ASCII range or do + not belong to the given char class), they are first translated into this + charset before being encoded using escape sequences. + + Also, if the encode mechanism is rtl_UriEncodeCheckEscapes, all escape + sequences already present in the input text are interpreted as characters + from this charset. + + @param pResult + Returns an encoded representation of the input text. Must itself not be + null, and must point to either null or a valid string. + + If the encode mechanism is rtl_UriEncodeStrict, and pText cannot be + converted to eCharset because it contains unmappable characters (which + implies that pText is not empty), then an empty string is returned. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uriEncode( + rtl_uString * pText, + sal_Bool const * pCharClass, + rtl_UriEncodeMechanism eMechanism, + rtl_TextEncoding eCharset, + rtl_uString ** pResult) + SAL_THROW_EXTERN_C(); + +/** Decode (a part of) a URI. + + @param pText + Any Unicode string. Must not be null. (If the input is indeed part of a + valid URI, this string will only contain a subset of the ASCII characters, + but this function also handles other Unicode characters properly.) + + @param eMechanism + The mechanism describing how the input text is translated into a Unicode + string. + + @param eCharset + When the decode mechanism is rtl_UriDecodeWithCharset, all escape + sequences in the input text are interpreted as characters from this + charset. Those characters are translated to Unicode characters in the + resulting output, if possible. + + When the decode mechanism is rtl_UriDecodeNone or rtl_UriDecodeToIuri, + this parameter is ignored (and is best specified as + RTL_TEXTENCODING_UTF8). + + @param pResult + Returns a decoded representation of the input text. Must itself not be + null, and must point to either null or a valid string. + + If the decode mechanism is rtl_UriDecodeStrict, and pText cannot be + converted to eCharset because it contains (encodings of) unmappable + characters (which implies that pText is not empty), then an empty string is + returned. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uriDecode( + rtl_uString * pText, + rtl_UriDecodeMechanism eMechanism, + rtl_TextEncoding eCharset, + rtl_uString ** pResult) + SAL_THROW_EXTERN_C(); + +/** Convert a relative URI reference into an absolute URI. + + This function uses the strict parser algorithm described in RFC 3986, + section 5.2. + + This function signals exceptions by returning false and letting pException + point to a message explaining the exception. + + @param pBaseUriRef + An absolute URI that serves as the base URI. If it has to be inspected + (i.e., pRelUriRef is not an absolute URI already), and it is not an absolute + URI (i.e., does not begin with a @ part), an exception will be + signaled. + + @param pRelUriRef + A URI reference that may be either absolute or relative. If it is + absolute, it will be returned unmodified. + + @param pResult + Returns an absolute URI. Must itself not be null, and must point to either + null or a valid string. If an exception is signalled, it is left unchanged. + + @param pException + Returns an explanatory message in case an exception is signalled. Must + itself not be null, and must point to either null or a valid string. If no + exception is signalled, it is left unchanged. + + @return + True if no exception is signalled, otherwise false. + */ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_uriConvertRelToAbs( + rtl_uString * pBaseUriRef, + rtl_uString * pRelUriRef, + rtl_uString ** pResult, + rtl_uString ** pException) + SAL_THROW_EXTERN_C(); + +#if defined __cplusplus +} +#endif /* __cplusplus */ + +#endif // INCLUDED_RTL_URI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/uri.hxx b/include/rtl/uri.hxx new file mode 100644 index 000000000..1b2601e7d --- /dev/null +++ b/include/rtl/uri.hxx @@ -0,0 +1,179 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_URI_HXX +#define INCLUDED_RTL_URI_HXX + +#include "rtl/malformeduriexception.hxx" +#include "rtl/uri.h" +#include "rtl/textenc.h" +#include "rtl/ustring.hxx" +#include "sal/types.h" + +#if defined LIBO_INTERNAL_ONLY +#include +#include +#include +#include +#include "config_global.h" +#endif + +namespace rtl { + +/** A wrapper around the C functions from . + */ +class Uri +{ +public: + /** A wrapper around rtl_uriEncode() from (see there), using + an array of 128 booleans as char class. + */ + static inline rtl::OUString encode(rtl::OUString const & rText, + sal_Bool const * pCharClass, + rtl_UriEncodeMechanism eMechanism, + rtl_TextEncoding eCharset); + + /** A wrapper around rtl_uriEncode() from (see there), using + a predefined rtl_UriCharClass enumeration member. + */ + static inline rtl::OUString encode(rtl::OUString const & rText, + rtl_UriCharClass eCharClass, + rtl_UriEncodeMechanism eMechanism, + rtl_TextEncoding eCharset); + + /** A wrapper around rtl_uriDecode() from (see there). + */ + static inline rtl::OUString decode(rtl::OUString const & rText, + rtl_UriDecodeMechanism eMechanism, + rtl_TextEncoding eCharset); + + /** A wrapper around rtl_uriConvertRelToAbs() from (see there). + + @exception MalformedUriException + Thrown in case rtl_uriConvertRelToAbs() signals an exception due to a + malformed base URI. + */ + static inline rtl::OUString convertRelToAbs( + rtl::OUString const & rBaseUriRef, rtl::OUString const & rRelUriRef); + +private: + Uri() SAL_DELETED_FUNCTION; + + Uri(Uri &) SAL_DELETED_FUNCTION; + + ~Uri() SAL_DELETED_FUNCTION; + + void operator =(Uri) SAL_DELETED_FUNCTION; +}; + +inline rtl::OUString Uri::encode(rtl::OUString const & rText, + sal_Bool const * pCharClass, + rtl_UriEncodeMechanism eMechanism, + rtl_TextEncoding eCharset) +{ + rtl::OUString aResult; + rtl_uriEncode(const_cast< rtl::OUString & >(rText).pData, + pCharClass, + eMechanism, + eCharset, + &aResult.pData); + return aResult; +} + +inline rtl::OUString Uri::encode(rtl::OUString const & rText, + rtl_UriCharClass eCharClass, + rtl_UriEncodeMechanism eMechanism, + rtl_TextEncoding eCharset) +{ + rtl::OUString aResult; + rtl_uriEncode(const_cast< rtl::OUString & >(rText).pData, + rtl_getUriCharClass(eCharClass), + eMechanism, + eCharset, + &aResult.pData); + return aResult; +} + +inline rtl::OUString Uri::decode(rtl::OUString const & rText, + rtl_UriDecodeMechanism eMechanism, + rtl_TextEncoding eCharset) +{ + rtl::OUString aResult; + rtl_uriDecode(const_cast< rtl::OUString & >(rText).pData, + eMechanism, + eCharset, + &aResult.pData); + return aResult; +} + +inline rtl::OUString Uri::convertRelToAbs(rtl::OUString const & rBaseUriRef, + rtl::OUString const & rRelUriRef) +{ + rtl::OUString aResult; + rtl::OUString aException; + if (!rtl_uriConvertRelToAbs( + const_cast< rtl::OUString & >(rBaseUriRef).pData, + const_cast< rtl::OUString & >(rRelUriRef).pData, &aResult.pData, + &aException.pData)) + throw MalformedUriException(aException); + return aResult; +} + +#if defined LIBO_INTERNAL_ONLY + +constexpr std::size_t UriCharClassSize = 128; + +// Create a char class (for use with rtl_uriEncode and rtl::Uri::encode), represented as a +// compile-time std::array, from an UTF-8 string literal. +// +// The given `unencoded` lists each ASCII character once that shall not be encoded. (It uses an +// UTF-8 string type to emphasize that its characters' values are always interpreted as ASCII +// values.) +#if HAVE_CPP_CONSTEVAL +consteval +#else +constexpr +#endif +auto createUriCharClass( +#if defined __cpp_lib_char8_t + std::u8string_view +#else + std::string_view +#endif + unencoded) +{ + std::array a = {}; + for (auto c: unencoded) { + assert(!a[c]); // would presumably indicate a typo in the `unencoded` argument + a[c] = true; + } + return a; +} + +#endif + +} + +#endif // INCLUDED_RTL_URI_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/ustrbuf.h b/include/rtl/ustrbuf.h new file mode 100644 index 000000000..9ea590c00 --- /dev/null +++ b/include/rtl/ustrbuf.h @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_USTRBUF_H +#define INCLUDED_RTL_USTRBUF_H + +#include "sal/config.h" + +#include "rtl/ustring.h" +#include "sal/saldllapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Allocates a new String that contains characters from + the character array argument. + + The count argument specifies + the length of the array. The initial capacity of the string buffer is + 16 plus the length of the string argument. + + @param newStr out parameter, contains the new string. The reference count is 1. + @param value the initial value of the string. + @param count the length of value. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uStringbuffer_newFromStr_WithLength( + rtl_uString ** newStr, + const sal_Unicode * value, + sal_Int32 count ); + +/** + Allocates a new String that contains the same sequence of + characters as the string argument. + + The initial capacity is the larger of: +
      +
    • The bufferLen argument. +
    • The length of the string argument. +
    + + @param newStr out parameter, contains the new string. The reference count is 1. + @param capacity the initial len of the string buffer. + @param oldStr the initial value of the string. + @return the new capacity of the string buffer + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_uStringbuffer_newFromStringBuffer( + rtl_uString ** newStr, + sal_Int32 capacity, + rtl_uString * oldStr ); + +/** + Ensures that the capacity of the buffer is at least equal to the + specified minimum. + + If the current capacity of this string buffer is less than the + argument, then a new internal buffer is allocated with greater + capacity. The new capacity is the larger of: +
      +
    • The minimumCapacity argument. +
    • Twice the old capacity, plus 2. +
    + If the minimumCapacity argument is nonpositive, this + method takes no action and simply returns. + + @param[in,out] This the String to operate on. + @param[in,out] capacity in: old capacity, out: new capacity. + @param[in] minimumCapacity the minimum desired capacity. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uStringbuffer_ensureCapacity( + rtl_uString ** This, + sal_Int32* capacity, + sal_Int32 minimumCapacity); + +/** + Inserts the string representation of the str array + argument into this string buffer. + + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. + + @param This The string, on that the operation should take place + @param capacity the capacity of the string buffer + @param offset the offset. + @param str a character array. Since LibreOffice 4.4, as a special + case, if str is null then the len added characters are + left uninitialized. + @param len the number of characters to append. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uStringbuffer_insert( + /*inout*/rtl_uString ** This, + /*inout*/sal_Int32 * capacity, + sal_Int32 offset, + const sal_Unicode * str, + sal_Int32 len); + +/** + Inserts a single UTF-32 character into this string buffer. + +

    The single UTF-32 character will be represented within the string buffer + as either one or two UTF-16 code units.

    + + @param pThis the string buffer on which the operation is performed + + @param capacity the capacity of the string buffer + + @param offset the offset into this string buffer (from zero to the length + of this string buffer, inclusive) + + @param c a well-formed UTF-32 code unit (that is, a value in the range + 00x10FFFF, but excluding + 0xD8000xDFFF) + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uStringbuffer_insertUtf32( + rtl_uString ** pThis, sal_Int32 * capacity, sal_Int32 offset, sal_uInt32 c) + SAL_THROW_EXTERN_C(); + +/** + Inserts the 8-Bit ASCII string representation of the str + array argument into this string buffer. + + Since this function is optimized + for performance, the ASCII character values are not converted in any way. + The caller has to make sure that all ASCII characters are in the allowed + range between 0 and 127. +

    + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. + + @param This The string, on that the operation should take place + @param capacity the capacity of the string buffer + @param offset the offset. + @param str a character array. + @param len the number of characters to append. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uStringbuffer_insert_ascii( + /*inout*/rtl_uString ** This, + /*inout*/sal_Int32 * capacity, + sal_Int32 offset, + const char * str, + sal_Int32 len); + +/** + Removes the characters in a substring of this sequence. + + The substring begins at the specified start and + is len characters long. + + start must be >= 0 && <= This->length + + @param[in,out] This The String to operate on. + @param[in] start The beginning index, inclusive + @param[in] len The substring length + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uStringbuffer_remove( + rtl_uString ** This, + sal_Int32 start, + sal_Int32 len ); + +/** + Returns an immutable rtl_uString object, while clearing the string buffer. + + This method is primarily used to allow these completed + string allocation events to be traced. + + @param ppThis The string, on that the operation should take place + @param nCapacity pointer to the capacity of the string buffer + + @since LibreOffice 3.6 + */ +SAL_DLLPUBLIC rtl_uString * SAL_CALL rtl_uStringBuffer_makeStringAndClear( + /*inout*/ rtl_uString ** ppThis, + sal_Int32 *nCapacity ) SAL_RETURNS_NONNULL; + +/** + References and returns an immutable rtl_uString object, from a mutable + string-buffer object. + + This method is primarily used to allow legacy 'String' class + conversions to OUString to be accurately traced. + + @param pThis The string, on that the operation should take place + + @since LibreOffice 3.6 + */ +SAL_DLLPUBLIC rtl_uString * SAL_CALL rtl_uStringBuffer_refReturn( rtl_uString *pThis ); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_USTRBUF_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/ustrbuf.hxx b/include/rtl/ustrbuf.hxx new file mode 100644 index 000000000..8c8cc54f8 --- /dev/null +++ b/include/rtl/ustrbuf.hxx @@ -0,0 +1,1796 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_USTRBUF_HXX +#define INCLUDED_RTL_USTRBUF_HXX + +#include "sal/config.h" + +#include +#include +#include +#include + +#if defined LIBO_INTERNAL_ONLY +#include +#include +#endif + +#include "rtl/ustrbuf.h" +#include "rtl/ustring.hxx" +#include "rtl/stringutils.hxx" +#include "sal/types.h" + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +#include "rtl/stringconcat.hxx" +#endif + +#ifdef RTL_STRING_UNITTEST +extern bool rtl_string_unittest_invalid_conversion; +#endif + +// The unittest uses slightly different code to help check that the proper +// calls are made. The class is put into a different namespace to make +// sure the compiler generates a different (if generating also non-inline) +// copy of the function and does not merge them together. The class +// is "brought" into the proper rtl namespace by a typedef below. +#ifdef RTL_STRING_UNITTEST +#define rtl rtlunittest +#endif + +namespace rtl +{ + +#ifdef RTL_STRING_UNITTEST +#undef rtl +#endif + +/** A string buffer implements a mutable sequence of characters. + */ +class SAL_WARN_UNUSED OUStringBuffer +{ +friend class OUString; +public: + /** + Constructs a string buffer with no characters in it and an + initial capacity of 16 characters. + */ + OUStringBuffer() + : pData(NULL) + , nCapacity( 16 ) + { + rtl_uString_new_WithLength( &pData, nCapacity ); + } + + /** + Allocates a new string buffer that contains the same sequence of + characters as the string buffer argument. + + @param value a OUStringBuffer. + */ + OUStringBuffer( const OUStringBuffer & value ) + : pData(NULL) + , nCapacity( value.nCapacity ) + { + rtl_uStringbuffer_newFromStringBuffer( &pData, value.nCapacity, value.pData ); + } + + /** + Constructs a string buffer with no characters in it and an + initial capacity specified by the length argument. + + @param length the initial capacity. + */ + explicit OUStringBuffer(sal_Int32 length) + : pData(NULL) + , nCapacity( length ) + { + rtl_uString_new_WithLength( &pData, length ); + } +#if defined LIBO_INTERNAL_ONLY + template + explicit OUStringBuffer(T length, std::enable_if_t, int> = 0) + : OUStringBuffer(static_cast(length)) + { + assert( + length >= 0 + && static_cast>(length) + <= static_cast>( + std::numeric_limits::max())); + } + // avoid (obvious) bugs + explicit OUStringBuffer(bool) = delete; + explicit OUStringBuffer(char) = delete; + explicit OUStringBuffer(wchar_t) = delete; +#if defined __cpp_char8_t + explicit OUStringBuffer(char8_t) = delete; +#endif + explicit OUStringBuffer(char16_t) = delete; + explicit OUStringBuffer(char32_t) = delete; +#endif + + /** + Constructs a string buffer so that it represents the same + sequence of characters as the string argument. + + The initial + capacity of the string buffer is 16 plus the length + of the string argument. + + @param value the initial contents of the buffer. + */ +#if defined LIBO_INTERNAL_ONLY + OUStringBuffer(std::u16string_view sv) + : pData(nullptr) + , nCapacity( sv.length() + 16 ) + { + if (sv.size() > sal_uInt32(std::numeric_limits::max())) { + throw std::bad_alloc(); + } + rtl_uStringbuffer_newFromStr_WithLength( &pData, sv.data(), sv.length() ); + } +#else + OUStringBuffer(const OUString& value) + : pData(NULL) + , nCapacity( value.getLength() + 16 ) + { + rtl_uStringbuffer_newFromStr_WithLength( &pData, value.getStr(), value.getLength() ); + } +#endif + + template< typename T > + OUStringBuffer( T& literal, typename libreoffice_internal::ConstCharArrayDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy() ) + : pData(NULL) + , nCapacity( libreoffice_internal::ConstCharArrayDetector::length + 16 ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + rtl_uString_newFromLiteral( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length, 16); +#ifdef RTL_STRING_UNITTEST + rtl_string_unittest_const_literal = true; +#endif + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + OUStringBuffer( + T & literal, + typename libreoffice_internal::ConstCharArrayDetector< + T, libreoffice_internal::Dummy>::TypeUtf16 + = libreoffice_internal::Dummy()): + pData(nullptr), + nCapacity(libreoffice_internal::ConstCharArrayDetector::length + 16) + { + rtl_uStringbuffer_newFromStr_WithLength( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } +#endif + +#if defined LIBO_INTERNAL_ONLY && defined RTL_STRING_UNITTEST + /// @cond INTERNAL + /** + * Only used by unittests to detect incorrect conversions. + * @internal + */ + template< typename T > + OUStringBuffer( T&, typename libreoffice_internal::ExceptConstCharArrayDetector< T >::Type = libreoffice_internal::Dummy() ) + { + pData = NULL; + nCapacity = 10; + rtl_uString_newFromLiteral( &pData, "!!br0ken!!", 10, 0 ); // set to garbage + rtl_string_unittest_invalid_conversion = true; + } + /** + * Only used by unittests to detect incorrect conversions. + * @internal + */ + template< typename T > + OUStringBuffer( const T&, typename libreoffice_internal::ExceptCharArrayDetector< T >::Type = libreoffice_internal::Dummy() ) + { + pData = NULL; + nCapacity = 10; + rtl_uString_newFromLiteral( &pData, "!!br0ken!!", 10, 0 ); // set to garbage + rtl_string_unittest_invalid_conversion = true; + } + /// @endcond +#endif + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OUStringBuffer( OUStringConcat< T1, T2 >&& c ) + { + const sal_Int32 l = c.length(); + nCapacity = l + 16; + pData = rtl_uString_alloc( nCapacity ); + sal_Unicode* end = c.addData( pData->buffer ); + *end = '\0'; + pData->length = l; + } + + /** + @overload + @internal + */ + template< typename T > + OUStringBuffer( OUStringNumber< T >&& n ) + : pData(NULL) + , nCapacity( n.length + 16 ) + { + rtl_uStringbuffer_newFromStr_WithLength( &pData, n.buf, n.length ); + } +#endif + +#if defined LIBO_INTERNAL_ONLY + operator std::u16string_view() const { return {getStr(), sal_uInt32(getLength())}; } +#endif + + /** Assign to this a copy of value. + */ + OUStringBuffer& operator = ( const OUStringBuffer& value ) + { + if (this != &value) + { + rtl_uStringbuffer_newFromStringBuffer(&pData, + value.nCapacity, + value.pData); + nCapacity = value.nCapacity; + } + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** Move assignment + * @since LibreOffice 7.3 + */ + OUStringBuffer& operator = ( OUStringBuffer&& value ) noexcept + { + rtl_uString_release( pData ); + pData = value.pData; + nCapacity = value.nCapacity; + value.pData = nullptr; + value.nCapacity = 0; + rtl_uString_new( &value.pData ); + return *this; + } +#endif + + /** Assign from a string. + + @since LibreOffice 5.3 + */ +#if defined LIBO_INTERNAL_ONLY + OUStringBuffer & operator =(std::u16string_view string) { + sal_Int32 n = string.length(); + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + std::memcpy( + pData->buffer, string.data(), + n * sizeof (sal_Unicode)); + pData->buffer[n] = '\0'; + pData->length = n; + return *this; + } +#else + OUStringBuffer & operator =(OUString const & string) { + sal_Int32 n = string.getLength(); + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + std::memcpy( + pData->buffer, string.pData->buffer, + (n + 1) * sizeof (sal_Unicode)); + pData->length = n; + return *this; + } +#endif + + /** Assign from a string literal. + + @since LibreOffice 5.3 + */ + template + typename + libreoffice_internal::ConstCharArrayDetector::Type + operator =(T & literal) { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + sal_Int32 const n + = libreoffice_internal::ConstCharArrayDetector::length; + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + char const * from + = libreoffice_internal::ConstCharArrayDetector::toPointer( + literal); + sal_Unicode * to = pData->buffer; + for (sal_Int32 i = 0; i <= n; ++i) { + to[i] = from[i]; + } + pData->length = n; + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + typename libreoffice_internal::ConstCharArrayDetector< + T, OUStringBuffer &>::TypeUtf16 + operator =(T & literal) { + sal_Int32 const n + = libreoffice_internal::ConstCharArrayDetector::length; + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + // For OUStringChar, which is covered by this template's ConstCharArrayDetector TypeUtf16 + // check, toPointer does not return a NUL-terminated string, so we can't just memcpy n+1 + // elements but rather need to add the terminating NUL manually: + std::memcpy( + pData->buffer, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + n * sizeof (sal_Unicode)); + pData->buffer[n] = '\0'; + pData->length = n; + return *this; + } +#endif + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + OUStringBuffer & operator =(OUStringConcat && concat) { + sal_Int32 const n = concat.length(); + if (n >= nCapacity) { + ensureCapacity(n + 16); //TODO: check for overflow + } + *concat.addData(pData->buffer) = 0; + pData->length = n; + return *this; + } + + /** @overload @internal */ + template + OUStringBuffer & operator =(OUStringNumber && n) + { + *this = OUStringBuffer( std::move( n ) ); + return *this; + } +#endif + + /** + Release the string data. + */ + ~OUStringBuffer() + { + rtl_uString_release( pData ); + } + + /** + Fill the string data in the new string and clear the buffer. + + This method is more efficient than the constructor of the string. It does + not copy the buffer. + + @return the string previously contained in the buffer. + */ + SAL_WARN_UNUSED_RESULT OUString makeStringAndClear() + { + return OUString( + rtl_uStringBuffer_makeStringAndClear( &pData, &nCapacity ), + SAL_NO_ACQUIRE ); + } + + /** + Returns the length (character count) of this string buffer. + + @return the number of characters in this string buffer. + */ + sal_Int32 getLength() const + { + return pData->length; + } + + /** + Checks if a string buffer is empty. + + @return true if the string buffer is empty; + false, otherwise. + + @since LibreOffice 4.1 + */ + bool isEmpty() const + { + return pData->length == 0; + } + + /** + Returns the current capacity of the String buffer. + + The capacity + is the amount of storage available for newly inserted + characters. The real buffer size is 2 bytes longer, because + all strings are 0 terminated. + + @return the current capacity of this string buffer. + */ + sal_Int32 getCapacity() const + { + return nCapacity; + } + + /** + Ensures that the capacity of the buffer is at least equal to the + specified minimum. + + The new capacity will be at least as large as the maximum of the current + length (so that no contents of the buffer is destroyed) and the given + minimumCapacity. If the given minimumCapacity is negative, nothing is + changed. + + @param minimumCapacity the minimum desired capacity. + */ + void ensureCapacity(sal_Int32 minimumCapacity) + { + rtl_uStringbuffer_ensureCapacity( &pData, &nCapacity, minimumCapacity ); + } + + /** + Sets the length of this String buffer. + + If the newLength argument is less than the current + length of the string buffer, the string buffer is truncated to + contain exactly the number of characters given by the + newLength argument. +

    + If the newLength argument is greater than or equal + to the current length, sufficient null characters + ('\u0000') are appended to the string buffer so that + length becomes the newLength argument. +

    + The newLength argument must be greater than or equal + to 0. + + @param newLength the new length of the buffer. + */ + void setLength(sal_Int32 newLength) + { + assert(newLength >= 0); + // Avoid modifications if pData points to const empty string: + if( newLength != pData->length ) + { + if( newLength > nCapacity ) + rtl_uStringbuffer_ensureCapacity(&pData, &nCapacity, newLength); + else + pData->buffer[newLength] = 0; + pData->length = newLength; + } + } + + /** + Returns the character at a specific index in this string buffer. + + The first character of a string buffer is at index + 0, the next at index 1, and so on, for + array indexing. +

    + The index argument must be greater than or equal to + 0, and less than the length of this string buffer. + + @param index the index of the desired character. + @return the character at the specified index of this string buffer. + */ + SAL_DEPRECATED("use rtl::OUStringBuffer::operator [] instead") + sal_Unicode charAt( sal_Int32 index ) const + { + assert(index >= 0 && index < pData->length); + return pData->buffer[ index ]; + } + + /** + The character at the specified index of this string buffer is set + to ch. + + The index argument must be greater than or equal to + 0, and less than the length of this string buffer. + + @param index the index of the character to modify. + @param ch the new character. + */ + SAL_DEPRECATED("use rtl::OUStringBuffer::operator [] instead") + OUStringBuffer & setCharAt(sal_Int32 index, sal_Unicode ch) + { + assert(index >= 0 && index < pData->length); + pData->buffer[ index ] = ch; + return *this; + } + + /** + Return a null terminated unicode character array. + */ + const sal_Unicode* getStr() const SAL_RETURNS_NONNULL { return pData->buffer; } + + /** + Access to individual characters. + + @param index must be non-negative and less than length. + + @return a reference to the character at the given index. + + @since LibreOffice 3.5 + */ + sal_Unicode & operator [](sal_Int32 index) + { + assert(index >= 0 && index < pData->length); + return pData->buffer[index]; + } + + /** + Access to individual characters. + + @param index must be non-negative and less than length. + + @return a reference to the character at the given index. + + @since LibreOffice 4.2 + */ + const sal_Unicode & operator [](sal_Int32 index) const + { + assert(index >= 0 && index < pData->length); + return pData->buffer[index]; + } + + /** + Return an OUString instance reflecting the current content + of this OUStringBuffer. + */ + OUString toString() const + { + return OUString(pData->buffer, pData->length); + } + + /** + Appends the string to this string buffer. + + The characters of the OUString argument are appended, in + order, to the contents of this string buffer, increasing the + length of this string buffer by the length of the argument. + + @param str a string. + @return this string buffer. + */ +#if !defined LIBO_INTERNAL_ONLY + OUStringBuffer & append(const OUString &str) + { + return append( str.getStr(), str.getLength() ); + } +#else + OUStringBuffer & append(std::u16string_view sv) { + if (sv.size() > sal_uInt32(std::numeric_limits::max())) { + throw std::bad_alloc(); + } + return append(sv.data(), sv.size()); + } +#endif + +#if !defined LIBO_INTERNAL_ONLY + /** + Appends the content of a stringbuffer to this string buffer. + + The characters of the OUStringBuffer argument are appended, in + order, to the contents of this string buffer, increasing the + length of this string buffer by the length of the argument. + + @param str a string. + @return this string buffer. + + @since LibreOffice 4.0 + */ + OUStringBuffer & append(const OUStringBuffer &str) + { + if(!str.isEmpty()) + { + append( str.getStr(), str.getLength() ); + } + return *this; + } +#endif + + /** + Appends the string representation of the char array + argument to this string buffer. + + The characters of the array argument are appended, in order, to + the contents of this string buffer. The length of this string + buffer increases by the length of the argument. + + @param str the characters to be appended. + @return this string buffer. + */ +#if defined LIBO_INTERNAL_ONLY + template + typename libreoffice_internal::CharPtrDetector::TypeUtf16 + append(T const & str) +#else + OUStringBuffer & append( const sal_Unicode * str ) +#endif + { + return append( str, rtl_ustr_getLength( str ) ); + } + + /** + Appends the string representation of the char array + argument to this string buffer. + + Characters of the character array str are appended, + in order, to the contents of this string buffer. The length of this + string buffer increases by the value of len. + + @param str the characters to be appended; must be non-null, and must + point to at least len characters + @param len the number of characters to append; must be non-negative + @return this string buffer. + */ + OUStringBuffer & append( const sal_Unicode * str, sal_Int32 len) + { + assert( len == 0 || str != NULL ); // cannot assert that in rtl_uStringbuffer_insert + rtl_uStringbuffer_insert( &pData, &nCapacity, getLength(), str, len ); + return *this; + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, OUStringBuffer& >::Type append( T& literal ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return appendAscii( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + +#if defined LIBO_INTERNAL_ONLY + template + typename libreoffice_internal::NonConstCharArrayDetector::TypeUtf16 + append(T & value) { return append(static_cast(value)); } + + /** @overload @since LibreOffice 5.3 */ + template + typename libreoffice_internal::ConstCharArrayDetector< + T, OUStringBuffer &>::TypeUtf16 + append(T & literal) { + return append( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } +#endif + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OUStringBuffer& append( OUStringConcat< T1, T2 >&& c ) + { + sal_Int32 l = c.length(); + if( l == 0 ) + return *this; + l += pData->length; + rtl_uStringbuffer_ensureCapacity( &pData, &nCapacity, l ); + sal_Unicode* end = c.addData( pData->buffer + pData->length ); + *end = '\0'; + pData->length = l; + return *this; + } + + /** + @overload + @internal + */ + template< typename T > + OUStringBuffer& append( OUStringNumber< T >&& c ) + { + return append( c.buf, c.length ); + } +#endif + + /** + Appends a 8-Bit ASCII character string to this string buffer. + + Since this method is optimized for performance. the ASCII + character values are not converted in any way. The caller + has to make sure that all ASCII characters are in the + allowed range between 0 and 127. The ASCII string must be + NULL-terminated. +

    + The characters of the array argument are appended, in order, to + the contents of this string buffer. The length of this string + buffer increases by the length of the argument. + + @param str the 8-Bit ASCII characters to be appended. + @return this string buffer. + */ + OUStringBuffer & appendAscii( const char * str ) + { + return appendAscii( str, rtl_str_getLength( str ) ); + } + + /** + Appends a 8-Bit ASCII character string to this string buffer. + + Since this method is optimized for performance. the ASCII + character values are not converted in any way. The caller + has to make sure that all ASCII characters are in the + allowed range between 0 and 127. The ASCII string must be + NULL-terminated. +

    + Characters of the character array str are appended, + in order, to the contents of this string buffer. The length of this + string buffer increases by the value of len. + + @param str the 8-Bit ASCII characters to be appended; must be non-null, + and must point to at least len characters + @param len the number of characters to append; must be non-negative + @return this string buffer. + */ + OUStringBuffer & appendAscii( const char * str, sal_Int32 len) + { + rtl_uStringbuffer_insert_ascii( &pData, &nCapacity, getLength(), str, len ); + return *this; + } + + /** + Appends the string representation of the bool + argument to the string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param b a bool. + @return this string buffer. + + @since LibreOffice 4.1 + */ + OUStringBuffer & append(bool b) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFBOOLEAN]; + return append( sz, rtl_ustr_valueOfBoolean( sz, b ) ); + } + + /// @cond INTERNAL + // Pointer can be automatically converted to bool, which is unwanted here. + // Explicitly delete all pointer append() overloads to prevent this + // (except for char* and sal_Unicode* overloads, which are handled elsewhere). + template< typename T > + typename libreoffice_internal::Enable< void, + !libreoffice_internal::CharPtrDetector< T* >::ok && !libreoffice_internal::SalUnicodePtrDetector< T* >::ok >::Type + append( T* ) SAL_DELETED_FUNCTION; + /// @endcond + + // This overload is needed because OUString has a ctor from rtl_uString*, but + // the bool overload above would be preferred to the conversion. + /** + @internal + */ + OUStringBuffer & append(rtl_uString* str) + { + return append( OUString( str )); + } + + /** + Appends the string representation of the sal_Bool + argument to the string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param b a sal_Bool. + @return this string buffer. + */ + OUStringBuffer & append(sal_Bool b) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFBOOLEAN]; + return append( sz, rtl_ustr_valueOfBoolean( sz, b ) ); + } + + /** + Appends the string representation of the ASCII char + argument to this string buffer. + + The argument is appended to the contents of this string buffer. + The length of this string buffer increases by 1. + + @param c an ASCII char. + @return this string buffer. + + @since LibreOffice 3.5 + */ + OUStringBuffer & append(char c) + { + assert(static_cast< unsigned char >(c) <= 0x7F); + return append(sal_Unicode(c)); + } + + /** + Appends the string representation of the char + argument to this string buffer. + + The argument is appended to the contents of this string buffer. + The length of this string buffer increases by 1. + + @param c a char. + @return this string buffer. + */ + OUStringBuffer & append(sal_Unicode c) + { + return append( &c, 1 ); + } + +#if defined LIBO_INTERNAL_ONLY + void append(sal_uInt16) = delete; +#endif + + /** + Appends the string representation of the sal_Int32 + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param i an sal_Int32. + @param radix the radix + @return this string buffer. + */ + OUStringBuffer & append(sal_Int32 i, sal_Int16 radix = 10 ) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFINT32]; + return append( sz, rtl_ustr_valueOfInt32( sz, i, radix ) ); + } + + /** + Appends the string representation of the long + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param l a long. + @param radix the radix + @return this string buffer. + */ + OUStringBuffer & append(sal_Int64 l, sal_Int16 radix = 10 ) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFINT64]; + return append( sz, rtl_ustr_valueOfInt64( sz, l, radix ) ); + } + + /** + Appends the string representation of the float + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param f a float. + @return this string buffer. + */ + OUStringBuffer & append(float f) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFFLOAT]; + return append( sz, rtl_ustr_valueOfFloat( sz, f ) ); + } + + /** + Appends the string representation of the double + argument to this string buffer. + + The argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then appended to this string buffer. + + @param d a double. + @return this string buffer. + */ + OUStringBuffer & append(double d) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFDOUBLE]; + return append( sz, rtl_ustr_valueOfDouble( sz, d ) ); + } + + /** + Appends a single UTF-32 character to this string buffer. + +

    The single UTF-32 character will be represented within the string + buffer as either one or two UTF-16 code units.

    + + @param c a well-formed UTF-32 code unit (that is, a value in the range + 00x10FFFF, but excluding + 0xD8000xDFFF) + + @return + this string buffer + */ + OUStringBuffer & appendUtf32(sal_uInt32 c) { + return insertUtf32(getLength(), c); + } + + /** + Unsafe way to make space for a fixed amount of characters to be appended + into this OUStringBuffer. + + A call to this function must immediately be followed by code that + completely fills the uninitialized block pointed to by the return value. + + @param length the length of the uninitialized block of sal_Unicode + entities; must be non-negative + + @return a pointer to the start of the uninitialized block; only valid + until this OUStringBuffer's capacity changes + + @since LibreOffice 4.4 + */ + sal_Unicode * appendUninitialized(sal_Int32 length) SAL_RETURNS_NONNULL { + sal_Int32 n = getLength(); + rtl_uStringbuffer_insert(&pData, &nCapacity, n, NULL, length); + return pData->buffer + n; + } + + /** + Inserts the string into this string buffer. + + The characters of the String argument are inserted, in + order, into this string buffer at the indicated offset. The length + of this string buffer is increased by the length of the argument. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param str a string. + @return this string buffer. + */ +#if defined LIBO_INTERNAL_ONLY + OUStringBuffer & insert(sal_Int32 offset, std::u16string_view str) + { + return insert( offset, str.data(), str.length() ); + } +#else + OUStringBuffer & insert(sal_Int32 offset, const OUString & str) + { + return insert( offset, str.getStr(), str.getLength() ); + } +#endif + + /** + Inserts the string representation of the char array + argument into this string buffer. + + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param str a character array. + @return this string buffer. + */ + OUStringBuffer & insert( sal_Int32 offset, const sal_Unicode * str ) + { + return insert( offset, str, rtl_ustr_getLength( str ) ); + } + + /** + Inserts the string representation of the char array + argument into this string buffer. + + The characters of the array argument are inserted into the + contents of this string buffer at the position indicated by + offset. The length of this string buffer increases by + the length of the argument. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param str a character array. + @param len the number of characters to append. + @return this string buffer. + */ + OUStringBuffer & insert( sal_Int32 offset, const sal_Unicode * str, sal_Int32 len) + { + assert( len == 0 || str != NULL ); // cannot assert that in rtl_uStringbuffer_insert + rtl_uStringbuffer_insert( &pData, &nCapacity, offset, str, len ); + return *this; + } + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, OUStringBuffer& >::Type insert( sal_Int32 offset, T& literal ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + rtl_uStringbuffer_insert_ascii( + &pData, &nCapacity, offset, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + typename libreoffice_internal::ConstCharArrayDetector< + T, OUStringBuffer &>::TypeUtf16 + insert(sal_Int32 offset, T & literal) { + return insert( + offset, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } +#endif + + /** + Inserts the string representation of the sal_Bool + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param b a sal_Bool. + @return this string buffer. + */ + OUStringBuffer & insert(sal_Int32 offset, sal_Bool b) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFBOOLEAN]; + return insert( offset, sz, rtl_ustr_valueOfBoolean( sz, b ) ); + } + + /** + Inserts the string representation of the bool + argument into this string buffer. + + The second argument is converted to a string as if by the method + OUString::boolean, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param b a bool. + @return this string buffer. + + @since LibreOffice 4.3 + */ + OUStringBuffer & insert(sal_Int32 offset, bool b) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFBOOLEAN]; + return insert( offset, sz, rtl_ustr_valueOfBoolean( sz, b ) ); + } + + /** + Inserts the string representation of the char + argument into this string buffer. + + The second argument is inserted into the contents of this string + buffer at the position indicated by offset. The length + of this string buffer increases by one. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param c a char. + @return this string buffer. + + @since LibreOffice 3.6 + */ + OUStringBuffer & insert(sal_Int32 offset, char c) + { + sal_Unicode u = c; + return insert( offset, &u, 1 ); + } + + /** + Inserts the string representation of the char + argument into this string buffer. + + The second argument is inserted into the contents of this string + buffer at the position indicated by offset. The length + of this string buffer increases by one. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param c a char. + @return this string buffer. + */ + OUStringBuffer & insert(sal_Int32 offset, sal_Unicode c) + { + return insert( offset, &c, 1 ); + } + + /** + Inserts the string representation of the second sal_Int32 + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param i an sal_Int32. + @param radix the radix. + @return this string buffer. + @exception StringIndexOutOfBoundsException if the offset is invalid. + */ + OUStringBuffer & insert(sal_Int32 offset, sal_Int32 i, sal_Int16 radix = 10 ) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFINT32]; + return insert( offset, sz, rtl_ustr_valueOfInt32( sz, i, radix ) ); + } + + /** + Inserts the string representation of the long + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param l a long. + @param radix the radix. + @return this string buffer. + @exception StringIndexOutOfBoundsException if the offset is invalid. + */ + OUStringBuffer & insert(sal_Int32 offset, sal_Int64 l, sal_Int16 radix = 10 ) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFINT64]; + return insert( offset, sz, rtl_ustr_valueOfInt64( sz, l, radix ) ); + } + + /** + Inserts the string representation of the float + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param f a float. + @return this string buffer. + @exception StringIndexOutOfBoundsException if the offset is invalid. + */ + OUStringBuffer insert(sal_Int32 offset, float f) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFFLOAT]; + return insert( offset, sz, rtl_ustr_valueOfFloat( sz, f ) ); + } + + /** + Inserts the string representation of the double + argument into this string buffer. + + The second argument is converted to a string as if by the method + String.valueOf, and the characters of that + string are then inserted into this string buffer at the indicated + offset. +

    + The offset argument must be greater than or equal to + 0, and less than or equal to the length of this + string buffer. + + @param offset the offset. + @param d a double. + @return this string buffer. + @exception StringIndexOutOfBoundsException if the offset is invalid. + */ + OUStringBuffer & insert(sal_Int32 offset, double d) + { + sal_Unicode sz[RTL_USTR_MAX_VALUEOFDOUBLE]; + return insert( offset, sz, rtl_ustr_valueOfDouble( sz, d ) ); + } + + /** + Inserts a single UTF-32 character into this string buffer. + +

    The single UTF-32 character will be represented within the string + buffer as either one or two UTF-16 code units.

    + + @param offset the offset into this string buffer (from zero to the length + of this string buffer, inclusive) + + @param c a well-formed UTF-32 code unit (that is, a value in the range + 00x10FFFF, but excluding + 0xD8000xDFFF) + + @return this string buffer + */ + OUStringBuffer & insertUtf32(sal_Int32 offset, sal_uInt32 c) { + rtl_uStringbuffer_insertUtf32(&pData, &nCapacity, offset, c); + return *this; + } + + /** + Removes the characters in a substring of this sequence. + + The substring begins at the specified start and + is len characters long. + + start must be >= 0 && <= This->length + + @param start The beginning index, inclusive + @param len The substring length + @return this string buffer. + */ + OUStringBuffer & remove( sal_Int32 start, sal_Int32 len ) + { + rtl_uStringbuffer_remove( &pData, start, len ); + return *this; + } + + /** + Removes the tail of a string buffer start at the indicate position + + start must be >= 0 && <= This->length + + @param start The beginning index, inclusive. default to 0 + @return this string buffer. + + @since LibreOffice 4.0 + */ + OUStringBuffer & truncate( sal_Int32 start = 0 ) + { + rtl_uStringbuffer_remove( &pData, start, getLength() - start ); + return *this; + } + + /** + Replace all occurrences of + oldChar in this string buffer with newChar. + + @since LibreOffice 4.0 + + @param oldChar the old character. + @param newChar the new character. + @return this string buffer + */ + OUStringBuffer& replace( sal_Unicode oldChar, sal_Unicode newChar ) + { + sal_Int32 index = 0; + while((index = indexOf(oldChar, index)) >= 0) + { + pData->buffer[ index ] = newChar; + } + return *this; + } + + /** Allows access to the internal data of this OUStringBuffer, for effective + manipulation. + + This method should be used with care. After you have called this + method, you may use the returned pInternalData or pInternalCapacity only + as long as you make no other method call on this OUStringBuffer. + + @param pInternalData + This output parameter receives a pointer to the internal data + (rtl_uString pointer). pInternalData itself must not be null. + + @param pInternalCapacity + This output parameter receives a pointer to the internal capacity. + pInternalCapacity itself must not be null. + */ + void accessInternals(rtl_uString *** pInternalData, + sal_Int32 ** pInternalCapacity) + { + *pInternalData = &pData; + *pInternalCapacity = &nCapacity; + } + + + /** + Returns the index within this string of the first occurrence of the + specified character, starting the search at the specified index. + + @since LibreOffice 4.0 + + @param ch character to be located. + @param fromIndex the index to start the search from. + The index must be greater or equal than 0 + and less or equal as the string length. + @return the index of the first occurrence of the character in the + character sequence represented by this string that is + greater than or equal to fromIndex, or + -1 if the character does not occur. + */ + sal_Int32 indexOf( sal_Unicode ch, sal_Int32 fromIndex = 0 ) const + { + assert( fromIndex >= 0 && fromIndex <= pData->length ); + sal_Int32 ret = rtl_ustr_indexOfChar_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, ch ); + return (ret < 0 ? ret : ret+fromIndex); + } + + /** + Returns the index within this string of the last occurrence of the + specified character, searching backward starting at the end. + + @since LibreOffice 4.0 + + @param ch character to be located. + @return the index of the last occurrence of the character in the + character sequence represented by this string, or + -1 if the character does not occur. + */ + sal_Int32 lastIndexOf( sal_Unicode ch ) const + { + return rtl_ustr_lastIndexOfChar_WithLength( pData->buffer, pData->length, ch ); + } + + /** + Returns the index within this string of the last occurrence of the + specified character, searching backward starting before the specified + index. + + @since LibreOffice 4.0 + + @param ch character to be located. + @param fromIndex the index before which to start the search. + @return the index of the last occurrence of the character in the + character sequence represented by this string that + is less than fromIndex, or -1 + if the character does not occur before that point. + */ + sal_Int32 lastIndexOf( sal_Unicode ch, sal_Int32 fromIndex ) const + { + assert( fromIndex >= 0 && fromIndex <= pData->length ); + return rtl_ustr_lastIndexOfChar_WithLength( pData->buffer, fromIndex, ch ); + } + + /** + Returns the index within this string of the first occurrence of the + specified substring, starting at the specified index. + + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @since LibreOffice 4.0 + + @param str the substring to search for. + @param fromIndex the index to start the search from. + @return If the string argument occurs one or more times as a substring + within this string at the starting index, then the index + of the first character of the first such substring is + returned. If it does not occur as a substring starting + at fromIndex or beyond, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 indexOf( std::u16string_view str, sal_Int32 fromIndex = 0 ) const + { + assert( fromIndex >= 0 && fromIndex <= pData->length ); + sal_Int32 ret = rtl_ustr_indexOfStr_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.data(), str.length() ); + return (ret < 0 ? ret : ret+fromIndex); + } +#else + sal_Int32 indexOf( const OUString & str, sal_Int32 fromIndex = 0 ) const + { + assert( fromIndex >= 0 && fromIndex <= pData->length ); + sal_Int32 ret = rtl_ustr_indexOfStr_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length ); + return (ret < 0 ? ret : ret+fromIndex); + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + + @since LibreOffice 4.0 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, sal_Int32 >::Type indexOf( T& literal, sal_Int32 fromIndex = 0 ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + sal_Int32 n = rtl_ustr_indexOfAscii_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return n < 0 ? n : n + fromIndex; + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + typename + libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + indexOf(T & literal, sal_Int32 fromIndex = 0) const { + assert(fromIndex >= 0); + auto n = rtl_ustr_indexOfStr_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return n < 0 ? n : n + fromIndex; + } +#endif + + /** + Returns the index within this string of the last occurrence of + the specified substring, searching backward starting at the end. + + The returned index indicates the starting index of the substring + in this string. + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @since LibreOffice 4.0 + + @param str the substring to search for. + @return If the string argument occurs one or more times as a substring + within this string, then the index of the first character of + the last such substring is returned. If it does not occur as + a substring, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 lastIndexOf( std::u16string_view str ) const + { + return rtl_ustr_lastIndexOfStr_WithLength( pData->buffer, pData->length, + str.data(), str.length() ); + } +#else + sal_Int32 lastIndexOf( const OUString & str ) const + { + return rtl_ustr_lastIndexOfStr_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + Returns the index within this string of the last occurrence of + the specified substring, searching backward starting before the specified + index. + + The returned index indicates the starting index of the substring + in this string. + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @since LibreOffice 4.0 + + @param str the substring to search for. + @param fromIndex the index before which to start the search. + @return If the string argument occurs one or more times as a substring + within this string before the starting index, then the index + of the first character of the last such substring is + returned. Otherwise, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 lastIndexOf( std::u16string_view str, sal_Int32 fromIndex ) const + { + assert( fromIndex >= 0 && fromIndex <= pData->length ); + return rtl_ustr_lastIndexOfStr_WithLength( pData->buffer, fromIndex, + str.data(), str.length() ); + } +#else + sal_Int32 lastIndexOf( const OUString & str, sal_Int32 fromIndex ) const + { + assert( fromIndex >= 0 && fromIndex <= pData->length ); + return rtl_ustr_lastIndexOfStr_WithLength( pData->buffer, fromIndex, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 4.0 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, sal_Int32 >::Type lastIndexOf( T& literal ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return rtl_ustr_lastIndexOfAscii_WithLength( + pData->buffer, pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + typename + libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + lastIndexOf(T & literal) const { + return rtl_ustr_lastIndexOfStr_WithLength( + pData->buffer, pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } +#endif + + /** + Strip the given character from the start of the buffer. + + @since LibreOffice 4.0 + + @param c the character to strip + @return The number of characters stripped + + */ + sal_Int32 stripStart(sal_Unicode c = ' ') + { + sal_Int32 index; + for(index = 0; index < getLength() ; index++) + { + if(pData->buffer[ index ] != c) + { + break; + } + } + if(index) + { + remove(0, index); + } + return index; + } + + /** + Strip the given character from the end of the buffer. + + @since LibreOffice 4.0 + + @param c the character to strip + @return The number of characters stripped + + */ + sal_Int32 stripEnd(sal_Unicode c = ' ') + { + sal_Int32 result = getLength(); + sal_Int32 index; + for(index = getLength(); index > 0 ; index--) + { + if(pData->buffer[ index - 1 ] != c) + { + break; + } + } + if(index < getLength()) + { + truncate(index); + } + return result - getLength(); + } + /** + Strip the given character from the both end of the buffer. + + @since LibreOffice 4.0 + + @param c the character to strip + @return The number of characters stripped + + */ + sal_Int32 strip(sal_Unicode c = ' ') + { + return stripStart(c) + stripEnd(c); + } + +#if defined LIBO_INTERNAL_ONLY + /** + Returns a std::u16string_view that is a view of a substring of this string. + + The substring begins at the specified beginIndex. If + beginIndex is negative or be greater than the length of + this string, behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT std::u16string_view subView( sal_Int32 beginIndex ) const + { + assert(beginIndex >= 0); + assert(beginIndex <= getLength()); + return subView(beginIndex, getLength() - beginIndex); + } + + /** + Returns a std::u16string_view that is a view of a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. If either beginIndex or count are negative, + or beginIndex + count are greater than the length of this string + then behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @param count the number of characters. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT std::u16string_view subView( sal_Int32 beginIndex, sal_Int32 count ) const + { + assert(beginIndex >= 0); + assert(count >= 0); + assert(beginIndex <= getLength()); + assert(count <= getLength() - beginIndex); + return std::u16string_view(pData->buffer, sal_uInt32(pData->length)).substr(beginIndex, count); + } +#endif + + /** + Returns a new string buffer that is a substring of this string. + + The substring begins at the specified beginIndex. If + beginIndex is negative or be greater than the length of + this string, behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @return the specified substring. + @since LibreOffice 4.1 + */ + OUStringBuffer copy( sal_Int32 beginIndex ) const + { + return copy( beginIndex, getLength() - beginIndex ); + } + + /** + Returns a new string buffer that is a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. If either beginIndex or count are negative, + or beginIndex + count are greater than the length of this string + then behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @param count the number of characters. + @return the specified substring. + @since LibreOffice 4.1 + */ + OUStringBuffer copy( sal_Int32 beginIndex, sal_Int32 count ) const + { + assert(beginIndex >= 0 && beginIndex <= getLength()); + assert(count >= 0 && count <= getLength() - beginIndex); + rtl_uString *pNew = NULL; + rtl_uStringbuffer_newFromStr_WithLength( &pNew, getStr() + beginIndex, count ); + return OUStringBuffer( pNew, count + 16 ); + } + +private: + OUStringBuffer( rtl_uString * value, const sal_Int32 capacity ) + { + pData = value; + nCapacity = capacity; + } + + /** + A pointer to the data structure which contains the data. + */ + rtl_uString * pData; + + /** + The len of the pData->buffer. + */ + sal_Int32 nCapacity; +}; + +#if defined LIBO_INTERNAL_ONLY +template<> struct ToStringHelper { + static std::size_t length(OUStringBuffer const & s) { return s.getLength(); } + + static sal_Unicode * addData(sal_Unicode * buffer, OUStringBuffer const & s) SAL_RETURNS_NONNULL + { return addDataHelper(buffer, s.getStr(), s.getLength()); } + + static constexpr bool allowOStringConcat = false; + static constexpr bool allowOUStringConcat = true; +}; +#endif + +#if defined LIBO_INTERNAL_ONLY + // Define this here to avoid circular includes + inline OUString & OUString::operator+=( const OUStringBuffer & str ) & + { + // Call operator= if this is empty, otherwise rtl_uString_newConcat will attempt to + // acquire() the str.pData buffer, which is part of the OUStringBuffer mutable state. + if (isEmpty()) + return operator=(str.toString()); + else + return internalAppend(str.pData); + } + + inline OUString const& OUString::unacquired(const OUStringBuffer& str) + { + return unacquired(&str.pData); + } +#endif +} + +#ifdef RTL_STRING_UNITTEST +namespace rtl +{ +typedef rtlunittest::OUStringBuffer OUStringBuffer; +} +#endif + +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST +using ::rtl::OUStringBuffer; +#endif + +#endif // INCLUDED_RTL_USTRBUF_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/ustring.h b/include/rtl/ustring.h new file mode 100644 index 000000000..2371d9a5e --- /dev/null +++ b/include/rtl/ustring.h @@ -0,0 +1,2414 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_USTRING_H +#define INCLUDED_RTL_USTRING_H + +#include "sal/config.h" + +#include "osl/interlck.h" +#include "rtl/string.h" +#include "rtl/textenc.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* ======================================================================= */ + +/** Return the length of a string. + + The length is equal to the number of 16-bit Unicode characters in the + string, without the terminating NUL character. + + @param str + a null-terminated string. + + @return + the length of the sequence of characters represented by this string, + excluding the terminating NUL character. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_getLength( + const sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Compare two strings. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. Both strings must be + null-terminated. + + @param first + the first null-terminated string to be compared. + + @param second + the second null-terminated string which is compared with the first one. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_compare( + const sal_Unicode * first, const sal_Unicode * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_compare_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const sal_Unicode * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings with a maximum count of characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @param shortenedLen + the maximum number of characters to compare. This length can be greater + or smaller than the lengths of the two strings. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_shortenedCompare_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const sal_Unicode * second, sal_Int32 secondLen, sal_Int32 shortenedLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings from back to front. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string + compares less than the second string, and a value greater than 0 if the + first string compares greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_reverseCompare_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const sal_Unicode * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings from back to front for equality. + + The comparison is based on the numeric value of each character in the + strings and returns 'true' if, and only if, both strings are equal. + This function cannot be used for language-specific sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified len. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified len. + + @param len + the length of both strings. + + @return + true if both strings are equal, false if they are not equal. + */ + +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_ustr_asciil_reverseEquals_WithLength( + const sal_Unicode * first, const char * second, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. Both strings must be null-terminated. + + @param first + the first null-terminated string to be compared. + + @param second + the second null-terminated string which is compared with the first one. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_compareIgnoreAsciiCase( + const sal_Unicode * first, const sal_Unicode * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_compareIgnoreAsciiCase_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const sal_Unicode * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings with a maximum count of characters, ignoring the case + of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @param shortenedLen + the maximum number of characters to compare. This length can be greater + or smaller than the lengths of the two strings. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_shortenedCompareIgnoreAsciiCase_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const sal_Unicode * second, sal_Int32 secondLen, sal_Int32 shortenedLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. Both strings must be + null-terminated. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first null-terminated string to be compared. + + @param second + the second null-terminated ASCII string which is compared with the first + one. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_compare( + const sal_Unicode * first, const char * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second null-terminated ASCII string which is compared with the first + one. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_compare_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const char * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings with a maximum count of characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second null-terminated ASCII string which is compared with the first + one. + + @param shortenedLen + the maximum number of characters to compare. This length can be greater + or smaller than the lengths of the two strings. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_shortenedCompare_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const char * second, sal_Int32 shortenedLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings from back to front. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. This function + cannot be used for language-specific sorting. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second ASCII string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string + compares less than the second string, and a value greater than 0 if the + first string compares greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_asciil_reverseCompare_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const char * second, sal_Int32 secondLen ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. Both strings must be null-terminated. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first null-terminated string to be compared. + + @param second + the second null-terminated ASCII string which is compared with the first + one. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_compareIgnoreAsciiCase( + const sal_Unicode * first, const char * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second null-terminated ASCII string which is compared with the first + one. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_compareIgnoreAsciiCase_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const char * second ) SAL_THROW_EXTERN_C(); + +/** Compare two strings, ignoring the case of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second string which is compared with the first one. Need not be + null-terminated, but must be at least as long as the specified secondLen. + + @param secondLen + the length of the second string. + + @return + 0 if both strings are equal, a value less than 0 if the first string is + less than the second string, and a value greater than 0 if the first + string is greater than the second string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_compareIgnoreAsciiCase_WithLengths( + sal_Unicode const * first, sal_Int32 firstLen, + char const * second, sal_Int32 secondLen) SAL_THROW_EXTERN_C(); + +/** Compare two strings with a maximum count of characters, ignoring the case + of ASCII characters. + + The comparison is based on the numeric value of each character in the + strings and returns a value indicating their relationship. Character + values between 65 and 90 (ASCII A--Z) are interpreted as values between 97 + and 122 (ASCII a--z). This function cannot be used for language-specific + sorting. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param first + the first string to be compared. Need not be null-terminated, but must be + at least as long as the specified firstLen. + + @param firstLen + the length of the first string. + + @param second + the second null-terminated ASCII string which is compared with the first + one. + + @param shortenedLen + the maximum number of characters to compare. This length can be greater + or smaller than the lengths of the two strings. + + @return + 0 if both substrings are equal, a value less than 0 if the first substring + is less than the second substring, and a value greater than 0 if the first + substring is greater than the second substring. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_ascii_shortenedCompareIgnoreAsciiCase_WithLength( + const sal_Unicode * first, sal_Int32 firstLen, const char * second, sal_Int32 shortenedLen ) SAL_THROW_EXTERN_C(); + +/** Return a hash code for a string. + + It is not allowed to store the hash code persistently, because later + versions could return other hash codes. The string must be + null-terminated. + + @param str + a null-terminated string. + + @return + a hash code for the given string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_hashCode( + const sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Return a hash code for a string. + + It is not allowed to store the hash code persistently, because later + versions could return other hash codes. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @return + a hash code for the given string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_hashCode_WithLength( + const sal_Unicode * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a character within a string. + + The string must be null-terminated. + + @param str + a null-terminated string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the first occurrence of the character in the + string, or -1 if the character does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_indexOfChar( + const sal_Unicode * str, sal_Unicode ch ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a character within a string. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the first occurrence of the character in the + string, or -1 if the character does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_indexOfChar_WithLength( + const sal_Unicode * str, sal_Int32 len, sal_Unicode ch ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a character within a string. + + The string must be null-terminated. + + @param str + a null-terminated string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the last occurrence of the character in the + string, or -1 if the character does not occur. The returned value is + always smaller than the string length. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_lastIndexOfChar( + const sal_Unicode * str, sal_Unicode ch ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a character within a string. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param ch + the character to be searched for. + + @return + the index (starting at 0) of the last occurrence of the character in the + string, or -1 if the character does not occur. The returned value is + always smaller than the string length. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_lastIndexOfChar_WithLength( + const sal_Unicode * str, sal_Int32 len, sal_Unicode ch ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + Both strings must be null-terminated. + + @param str + a null-terminated string. + + @param subStr + the null-terminated substring to be searched for. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_indexOfStr( + const sal_Unicode * str, const sal_Unicode * subStr ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param subStr + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified subLen. + + @param subLen + the length of the substring. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_indexOfStr_WithLength( + const sal_Unicode * str, sal_Int32 len, const sal_Unicode * subStr, sal_Int32 subLen ) SAL_THROW_EXTERN_C(); + +/** Search for the first occurrence of an ASCII substring within a string. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string; must be non-negative. + + @param subStr + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified subLen. Must only contain characters + in the ASCII range 0x00--7F. + + @param subLen + the length of the substring; must be non-negative. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + If subLen is zero, -1 is returned. + + @since UDK 3.2.7 +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_indexOfAscii_WithLength( + sal_Unicode const * str, sal_Int32 len, + char const * subStr, sal_Int32 subLen) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + Both strings must be null-terminated. + + @param str + a null-terminated string. + + @param subStr + the null-terminated substring to be searched for. + + @return + the index (starting at 0) of the first character of the last occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_lastIndexOfStr( + const sal_Unicode * str, const sal_Unicode * subStr ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of a substring within a string. + + If subStr is empty, or both str and subStr are empty, -1 is returned. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param subStr + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified subLen. + + @param subLen + the length of the substring. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within the string, or -1 if the substring does not occur. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_lastIndexOfStr_WithLength( + const sal_Unicode * str, sal_Int32 len, const sal_Unicode * subStr, sal_Int32 subLen ) SAL_THROW_EXTERN_C(); + +/** Search for the last occurrence of an ASCII substring within a string. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string; must be non-negative. + + @param subStr + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified subLen. Must only contain characters + in the ASCII range 0x00--7F. + + @param subLen + the length of the substring; must be non-negative. + + @return + the index (starting at 0) of the first character of the last occurrence + of the substring within the string, or -1 if the substring does not occur. + If subLen is zero, -1 is returned. + + @since UDK 3.2.7 +*/ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_lastIndexOfAscii_WithLength( + sal_Unicode const * str, sal_Int32 len, + char const * subStr, sal_Int32 subLen) SAL_THROW_EXTERN_C(); + +/** Replace all occurrences of a single character within a string. + + If oldChar does not occur within str, then the string is not modified. + The string must be null-terminated. + + @param str + a null-terminated string. + + @param oldChar + the old character. + + @param newChar + the new character. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_ustr_replaceChar( + sal_Unicode * str, sal_Unicode oldChar, sal_Unicode newChar ) SAL_THROW_EXTERN_C(); + +/** Replace all occurrences of a single character within a string. + + If oldChar does not occur within str, then the string is not modified. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + + @param oldChar + the old character. + + @param newChar + the new character. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_ustr_replaceChar_WithLength( + sal_Unicode * str, sal_Int32 len, sal_Unicode oldChar, sal_Unicode newChar ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII uppercase letters to lowercase within a string. + + The characters with values between 65 and 90 (ASCII A--Z) are replaced + with values between 97 and 122 (ASCII a--z). The string must be + null-terminated. + + @param str + a null-terminated string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_ustr_toAsciiLowerCase( + sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII uppercase letters to lowercase within a string. + + The characters with values between 65 and 90 (ASCII A--Z) are replaced + with values between 97 and 122 (ASCII a--z). + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_ustr_toAsciiLowerCase_WithLength( + sal_Unicode * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII lowercase letters to uppercase within a string. + + The characters with values between 97 and 122 (ASCII a--z) are replaced + with values between 65 and 90 (ASCII A--Z). The string must be + null-terminated. + + @param str + a null-terminated string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_ustr_toAsciiUpperCase( + sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Convert all ASCII lowercase letters to uppercase within a string. + + The characters with values between 97 and 122 (ASCII a--z) are replaced + with values between 65 and 90 (ASCII A--Z). + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the length of the string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_ustr_toAsciiUpperCase_WithLength( + sal_Unicode * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Remove white space from both ends of a string. + + All characters with values less than or equal to 32 (the space character) + are considered to be white space. This function cannot be used for + language-specific operations. The string must be null-terminated. + + @param str + a null-terminated string. + + @return + the new length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_trim( + sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Remove white space from both ends of the string. + + All characters with values less than or equal to 32 (the space character) + are considered to be white space. This function cannot be used for + language-specific operations. The string must be null-terminated. + + @param str + a string. Need not be null-terminated, but must be at least as long as + the specified len. + + @param len + the original length of the string. + + @return + the new length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_trim_WithLength( + sal_Unicode * str, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Create the string representation of a boolean. + + If b is true, the buffer is filled with the string "true" and 5 is + returned. If b is false, the buffer is filled with the string "false" and + 6 is returned. This function cannot be used for language-specific + operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFBOOLEAN define to + create a buffer that is big enough. + + @param b + a boolean value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfBoolean( + sal_Unicode * str, sal_Bool b ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MAX_VALUEOFBOOLEAN RTL_STR_MAX_VALUEOFBOOLEAN + +/** Create the string representation of a character. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFCHAR define to create a + buffer that is big enough. + + @param ch + a character value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfChar( + sal_Unicode * str, sal_Unicode ch ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MAX_VALUEOFCHAR RTL_STR_MAX_VALUEOFCHAR + +/** Create the string representation of an integer. + + This function cannot be used for language-specific operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFINT32 define to create + a buffer that is big enough. + + @param i + an integer value. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfInt32( + sal_Unicode * str, sal_Int32 i, sal_Int16 radix ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MIN_RADIX RTL_STR_MIN_RADIX +#define RTL_USTR_MAX_RADIX RTL_STR_MAX_RADIX +#define RTL_USTR_MAX_VALUEOFINT32 RTL_STR_MAX_VALUEOFINT32 + +/** Create the string representation of a long integer. + + This function cannot be used for language-specific operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFINT64 define to create + a buffer that is big enough. + + @param l + a long integer value. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfInt64( + sal_Unicode * str, sal_Int64 l, sal_Int16 radix ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MAX_VALUEOFINT64 RTL_STR_MAX_VALUEOFINT64 + +/** Create the string representation of an unsigned long integer. + + This function cannot be used for language-specific operations. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFUINT64 define to create + a buffer that is big enough. + + @param l + a long integer value. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfUInt64( + sal_Unicode * str, sal_uInt64 l, sal_Int16 radix ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MAX_VALUEOFUINT64 RTL_STR_MAX_VALUEOFUINT64 + +/** Create the string representation of a float. + + This function cannot be used for language-specific conversion. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFFLOAT define to create + a buffer that is big enough. + + @param f + a float value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfFloat( + sal_Unicode * str, float f ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MAX_VALUEOFFLOAT RTL_STR_MAX_VALUEOFFLOAT + +/** Create the string representation of a double. + + This function cannot be used for language-specific conversion. + + @param str + a buffer that is big enough to hold the result and the terminating NUL + character. You should use the RTL_USTR_MAX_VALUEOFDOUBLE define to create + a buffer that is big enough. + + @param d + a double value. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_valueOfDouble( + sal_Unicode * str, double d ) SAL_THROW_EXTERN_C(); +#define RTL_USTR_MAX_VALUEOFDOUBLE RTL_STR_MAX_VALUEOFDOUBLE + +/** Interpret a string as a boolean. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @return + true if the string is "1" or "true" in any ASCII case, false otherwise. + */ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_ustr_toBoolean( + const sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as an integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the integer value represented by the string, or 0 if the string does not + represent an integer. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_ustr_toInt32( + const sal_Unicode * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as an unsigned integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the unsigned integer value represented by the string, or 0 if the string + does not represent an unsigned integer. + + @since LibreOffice 4.2 + */ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL rtl_ustr_toUInt32( + const sal_Unicode * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a long integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the long integer value represented by the string, or 0 if the string does + not represent a long integer. + */ +SAL_DLLPUBLIC sal_Int64 SAL_CALL rtl_ustr_toInt64( + const sal_Unicode * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a long integer. + + This function cannot be used for language-specific conversion. + + @param str + a string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @param nStrLength + number of chars to process + + @return + the long integer value represented by the string, or 0 if the string does + not represent a long integer. + + @internal + @since LibreOffice 6.4 +*/ +SAL_DLLPUBLIC sal_Int64 SAL_CALL rtl_ustr_toInt64_WithLength( + const sal_Unicode * str, sal_Int16 radix, sal_Int32 nStrLength ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as an unsigned long integer. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @param radix + the radix. Must be between RTL_USTR_MIN_RADIX (2) and RTL_USTR_MAX_RADIX + (36), inclusive. + + @return + the unsigned long integer value represented by the string, or 0 if the + string does not represent an unsigned long integer. + + @since LibreOffice 4.1 + */ +SAL_DLLPUBLIC sal_uInt64 SAL_CALL rtl_ustr_toUInt64( + const sal_Unicode * str, sal_Int16 radix ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a float. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @return + the float value represented by the string, or 0.0 if the string does not + represent a float. + */ +SAL_DLLPUBLIC float SAL_CALL rtl_ustr_toFloat( + const sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/** Interpret a string as a double. + + This function cannot be used for language-specific conversion. The string + must be null-terminated. + + @param str + a null-terminated string. + + @return + the float value represented by the string, or 0.0 if the string does not + represent a double. + */ +SAL_DLLPUBLIC double SAL_CALL rtl_ustr_toDouble( + const sal_Unicode * str ) SAL_THROW_EXTERN_C(); + +/* ======================================================================= */ + +#if defined(_WIN32) +#pragma pack(push, 4) +#endif + +/** @cond INTERNAL */ +/** The implementation of a Unicode string. +*/ +typedef struct SAL_DLLPUBLIC_RTTI _rtl_uString +{ + oslInterlockedCount refCount; /* opaque */ + sal_Int32 length; + sal_Unicode buffer[1]; +} rtl_uString; +/** @endcond */ + +#if defined(_WIN32) +#pragma pack(pop) +#endif + +/* ----------------------------------------------------------------------- */ + +/** Increment the reference count of a string. + + @param str + a string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_acquire( + rtl_uString * str ) SAL_THROW_EXTERN_C() SAL_HOT; + +/** Decrement the reference count of a string. + + If the count goes to zero than the string data is deleted. + + @param str + a string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_release( + rtl_uString * str ) SAL_THROW_EXTERN_C() SAL_HOT; + +/** Allocate a new string containing no characters. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_new( + rtl_uString ** newStr ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string containing space for a given number of characters. + + The reference count of the new string will be 1. The length of the string + will be nLen. This function does not handle out-of-memory conditions. + + For failed allocation this method returns NULL. + + The characters of the capacity are not cleared, and the length is set to + nLen, unlike the similar method of rtl_uString_new_WithLength which + zeros out the buffer, and sets the length to 0. So should be somewhat + more efficient for allocating a new string. + + call rtl_uString_release to release the string + alternatively pass ownership to an OUString with + rtl::OUString(newStr, SAL_NO_ACQUIRE); + + @param[in] nLen the number of characters. Must be >= 0. + + @return pointer to the new string. + + @since LibreOffice 4.1 + */ +SAL_DLLPUBLIC rtl_uString * SAL_CALL rtl_uString_alloc(sal_Int32 nLen) SAL_THROW_EXTERN_C(); + +/** Allocate a new string containing space for a given number of characters. + + If len is greater than zero, the reference count of the new string will be + 1. The values of all characters are set to 0 and the length of the string + is 0. This function does not handle out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param nLen + the number of characters. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_new_WithLength( + rtl_uString ** newStr, sal_Int32 nLen ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of another string. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromString( + rtl_uString ** newStr, const rtl_uString * value ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of a character array. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a null-terminated character array. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromStr( + rtl_uString ** newStr, const sal_Unicode * value ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of a character array. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a character array. Need not be null-terminated, but must be at least as + long as the specified len. + + @param len + the length of the character array. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromStr_WithLength( + rtl_uString ** newStr, const sal_Unicode * value, sal_Int32 len ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that is a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. Meaningless combinations such as negative beginIndex, + or beginIndex + count greater than the length of the string have + undefined behaviour. + + @param[out] newStr the specified substring. + @param[in] from the String to take the substring from. + @param[in] beginIndex the beginning index, inclusive. + @param[in] count the number of characters. + @return the specified substring. + + @since LibreOffice 4.0 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromSubString( + rtl_uString ** newStr, const rtl_uString * from, + sal_Int32 beginIndex, sal_Int32 count ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string that contains a copy of a character array. + + If the length of value is greater than zero, the reference count of the + new string will be 1. This function does not handle out-of-memory + conditions. + + Since this function is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range of 0 and 127, inclusive. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param value + a null-terminated ASCII character array. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromAscii( + rtl_uString ** newStr, const char * value ) SAL_THROW_EXTERN_C(); + +/** + @internal + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromLiteral( + rtl_uString ** newStr, const char * value, sal_Int32 len, + sal_Int32 allocExtra ) SAL_THROW_EXTERN_C(); + +/** Allocate a new string from an array of Unicode code points. + + @param newString + a non-null pointer to a (possibly null) rtl_uString pointer, which (if + non-null) will have been passed to rtl_uString_release before the function + returns. Upon return, points to the newly allocated string or to null if + there was either an out-of-memory condition or the resulting number of + UTF-16 code units would have been larger than SAL_MAX_INT32. The newly + allocated string (if any) must ultimately be passed to rtl_uString_release. + + @param codePoints + an array of at least codePointCount code points, which each must be in the + range from 0 to 0x10FFFF, inclusive. May be null if codePointCount is zero. + + @param codePointCount + the non-negative number of code points. + + @since UDK 3.2.7 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newFromCodePoints( + rtl_uString ** newString, sal_uInt32 const * codePoints, + sal_Int32 codePointCount) SAL_THROW_EXTERN_C(); + +/** Assign a new value to a string. + + First releases any value str might currently hold, then acquires + rightValue. + + @param str + pointer to the string. The pointed-to data must be null or a valid + string. + + @param rightValue + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_assign( + rtl_uString ** str, rtl_uString * rightValue ) SAL_THROW_EXTERN_C(); + +/** Return the length of a string. + + The length is equal to the number of characters in the string. + + @param str + a valid string. + + @return + the length of the string. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_uString_getLength( + const rtl_uString * str ) SAL_THROW_EXTERN_C(); + +/** Return a pointer to the underlying character array of a string. + + @param str + a valid string. + + @return + a pointer to the null-terminated character array. + */ +SAL_DLLPUBLIC sal_Unicode * SAL_CALL rtl_uString_getStr( + rtl_uString * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string that is the concatenation of two other strings. + + The new string does not necessarily have a reference count of 1 (in cases + where one of the two other strings is empty), so it must not be modified + without checking the reference count. This function does not handle + out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param left + a valid string. + + @param right + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newConcat( + rtl_uString ** newStr, rtl_uString * left, rtl_uString * right ) SAL_THROW_EXTERN_C(); + +/** Create a new string that is the concatenation of two other strings. + + The new string does not necessarily have a reference count of 1 (in cases + where the ASCII string is empty), so it must not be modified without + checking the reference count. + + @param newString + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param left + a valid string. + + @param right must not be null and must point to memory of at least + \p rightLength ASCII bytes + + @param rightLength the length of the \p right string; must be non-negative + + @since LibreOffice 5.1 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newConcatAsciiL( + rtl_uString ** newString, rtl_uString * left, char const * right, + sal_Int32 rightLength); + +/** Create a new string that is the concatenation of two other strings. + + The new string does not necessarily have a reference count of 1 (in cases + where the UTF-16 string is empty), so it must not be modified without + checking the reference count. + + @param newString pointer to the new string. The pointed-to data must be null + or a valid string. + + @param left a valid string. + + @param right must point to memory of at least \p rightLength UTF-16 code units; may be null if + \p rigthLength is zero + + @param rightLength the length of the \p right string; must be non-negative + + @since LibreOffice 5.3 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newConcatUtf16L( + rtl_uString ** newString, rtl_uString * left, sal_Unicode const * right, + sal_Int32 rightLength); + +/** Create a new string by replacing a substring of another string. + + The new string results from replacing a number of characters (count), + starting at the specified position (index) in the original string (str), + with some new substring (subStr). If subStr is null, then only a number + of characters is deleted. + + The new string does not necessarily have a reference count of 1, so it + must not be modified without checking the reference count. This function + does not handle out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + + @param idx + the index into str at which to start replacement. Must be between 0 and + the length of str, inclusive. + + @param count + the number of characters to remove. Must not be negative, and the sum of + index and count must not exceed the length of str. + + @param subStr + either null or a valid string to be inserted. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceStrAt( + rtl_uString ** newStr, rtl_uString * str, sal_Int32 idx, sal_Int32 count, rtl_uString * subStr ) SAL_THROW_EXTERN_C(); + +#ifdef LIBO_INTERNAL_ONLY +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceStrAtUtf16L( + rtl_uString ** newStr, rtl_uString * str, sal_Int32 idx, sal_Int32 count, sal_Unicode const * subStr, sal_Int32 substrLen ) SAL_THROW_EXTERN_C(); +#endif + +/** Create a new string by replacing all occurrences of a single character + within another string. + + The new string results from replacing all occurrences of oldChar in str + with newChar. + + The new string does not necessarily have a reference count of 1 (in cases + where oldChar does not occur in str), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + + @param oldChar + the old character. + + @param newChar + the new character. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplace( + rtl_uString ** newStr, rtl_uString * str, sal_Unicode oldChar, sal_Unicode newChar ) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null + + @param to pointer to the replacing substring; must not be null + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place or -1 if no replacement took place + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirst( + rtl_uString ** newStr, rtl_uString * str, rtl_uString const * from, + rtl_uString const * to, sal_Int32 * index) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength ASCII bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the replacing substring; must not be null + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place or -1 if no replacement took place + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirstAsciiL( + rtl_uString ** newStr, rtl_uString * str, char const * from, + sal_Int32 fromLength, rtl_uString const * to, sal_Int32 * index) + SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null + + @param to pointer to the replacing substring; must not be null and must + point to memory of at least \p toLength ASCII bytes + + @param toLength the length of the \p to substring; must be non-negative + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place or -1 if no replacement took place + + @since LibreOffice 5.1 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirstToAsciiL( + rtl_uString ** newStr, rtl_uString * str, rtl_uString const * from, + char const * to, sal_Int32 toLength, sal_Int32 * index) + SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength ASCII bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength ASCII bytes + + @param toLength the length of the \p to substring; must be non-negative + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place or -1 if no replacement took place + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirstAsciiLAsciiL( + rtl_uString ** newStr, rtl_uString * str, char const * from, + sal_Int32 fromLength, char const * to, sal_Int32 toLength, + sal_Int32 * index) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength ASCII bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength UTF-16 code units + + @param toLength the length of the \p to substring; must be non-negative + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place (or would have taken place if \p newStr points to + null upon return) or -1 if no replacement took place + + @since LibreOffice 5.3 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirstAsciiLUtf16L( + rtl_uString ** newStr, rtl_uString * str, char const * from, + sal_Int32 fromLength, sal_Unicode const * to, sal_Int32 toLength, + sal_Int32 * index) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength UTF-16 code units + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength ASCII bytes + + @param toLength the length of the \p to substring; must be non-negative + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place (or would have taken place if \p newStr points to + null upon return) or -1 if no replacement took place + + @since LibreOffice 5.3 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirstUtf16LAsciiL( + rtl_uString ** newStr, rtl_uString * str, sal_Unicode const * from, + sal_Int32 fromLength, char const * to, sal_Int32 toLength, + sal_Int32 * index) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing the first occurrence of a given substring + with another substring. + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must point to memory of at least + \p fromLength UTF-16 code units; may be null if \p toLength is zero + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must point to memory of at least \p toLength + UTF-16 code units; may be null if \p toLength is zero + + @param toLength the length of the \p to substring; must be non-negative + + @param[in,out] index pointer to a start index, must not be null; upon entry + to the function its value is the index into the original string at which to + start searching for the \p from substring, the value must be non-negative + and not greater than the original string's length; upon exit from the + function its value is the index into the original string at which the + replacement took place (or would have taken place if \p newStr points to + null upon return) or -1 if no replacement took place + + @since LibreOffice 5.3 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceFirstUtf16LUtf16L( + rtl_uString ** newStr, rtl_uString * str, sal_Unicode const * from, + sal_Int32 fromLength, sal_Unicode const * to, sal_Int32 toLength, + sal_Int32 * index) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null + + @param to pointer to the replacing substring; must not be null + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAll( + rtl_uString ** newStr, rtl_uString * str, rtl_uString const * from, + rtl_uString const * to) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null + + @param to pointer to the replacing substring; must not be null + + @param fromIndex the position in the string where we will begin searching + + @since LibreOffice 4.0 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllFromIndex( + rtl_uString ** newStr, rtl_uString * str, rtl_uString const * from, + rtl_uString const * to, sal_Int32 fromIndex) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength ASCII bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the replacing substring; must not be null + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllAsciiL( + rtl_uString ** newStr, rtl_uString * str, char const * from, + sal_Int32 fromLength, rtl_uString const * to) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null + + @param to pointer to the replacing substring; must not be null and must + point to memory of at least \p toLength ASCII bytes + + @param toLength the length of the \p to substring; must be non-negative + + @since LibreOffice 5.1 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllToAsciiL( + rtl_uString ** newStr, rtl_uString * str, rtl_uString const * from, + char const * to, sal_Int32 toLength) SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength ASCII bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength ASCII bytes + + @param toLength the length of the \p to substring; must be non-negative + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllAsciiLAsciiL( + rtl_uString ** newStr, rtl_uString * str, char const * from, + sal_Int32 fromLength, char const * to, sal_Int32 toLength) + SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength ASCII bytes + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must point to memory of at least \p toLength + UTF-16 code units; may be null if \p toLength is zero + + @param toLength the length of the \p to substring; must be non-negative + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllAsciiLUtf16L( + rtl_uString ** newStr, rtl_uString * str, char const * from, + sal_Int32 fromLength, sal_Unicode const * to, sal_Int32 toLength) + SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength UTF-16 code units + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength ASCII bytes + + @param toLength the length of the \p to substring; must be non-negative + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllUtf16LAsciiL( + rtl_uString ** newStr, rtl_uString * str, sal_Unicode const * from, + sal_Int32 fromLength, char const * to, sal_Int32 toLength) + SAL_THROW_EXTERN_C(); + +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength UTF-16 code units + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength UTF-16 code units + + @param toLength the length of the \p to substring; must be non-negative + + @since LibreOffice 3.6 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllUtf16LUtf16L( + rtl_uString ** newStr, rtl_uString * str, sal_Unicode const * from, + sal_Int32 fromLength, sal_Unicode const * to, sal_Int32 toLength) + SAL_THROW_EXTERN_C(); + +#if defined LIBO_INTERNAL_ONLY +/** Create a new string by replacing all occurrences of a given substring with + another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param[in, out] newStr pointer to the new string; must not be null; must + point to null or a valid rtl_uString; upon return, points to the newly + allocated string or to null if there was either an out-of-memory condition + or the resulting number of UTF-16 code units would have been larger than + SAL_MAX_INT32 + + @param str pointer to the original string; must not be null + + @param from pointer to the substring to be replaced; must not be null and + must point to memory of at least \p fromLength UTF-16 code units + + @param fromLength the length of the \p from substring; must be non-negative + + @param to pointer to the substring to be replaced; must not be null and + must point to memory of at least \p toLength UTF-16 code units + + @param toLength the length of the \p to substring; must be non-negative + + @param fromIndex the position in the string where we will begin searching + + @since LibreOffice 7.1 +*/ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newReplaceAllFromIndexUtf16LUtf16L( + rtl_uString ** newStr, rtl_uString * str, sal_Unicode const * from, + sal_Int32 fromLength, sal_Unicode const * to, sal_Int32 toLength, sal_Int32 fromIndex) + SAL_THROW_EXTERN_C(); +#endif + +/** Create a new string by converting all ASCII uppercase letters to lowercase + within another string. + + The new string results from replacing all characters with values between + 65 and 90 (ASCII A--Z) by values between 97 and 122 (ASCII a--z). + + This function cannot be used for language-specific conversion. The new + string does not necessarily have a reference count of 1 (in cases where + no characters need to be converted), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newToAsciiLowerCase( + rtl_uString ** newStr, rtl_uString * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string by converting all ASCII lowercase letters to uppercase + within another string. + + The new string results from replacing all characters with values between + 97 and 122 (ASCII a--z) by values between 65 and 90 (ASCII A--Z). + + This function cannot be used for language-specific conversion. The new + string does not necessarily have a reference count of 1 (in cases where + no characters need to be converted), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newToAsciiUpperCase( + rtl_uString ** newStr, rtl_uString * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string by removing white space from both ends of another + string. + + The new string results from removing all characters with values less than + or equal to 32 (the space character), and also Unicode General Punctuation + area Space and some Control characters, form both ends of str (see + implIsWhitespace). + + This function cannot be used for language-specific conversion. The new + string does not necessarily have a reference count of 1 (in cases where + no characters need to be removed), so it must not be modified without + checking the reference count. This function does not handle out-of-memory + conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a valid string. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_newTrim( + rtl_uString ** newStr, rtl_uString * str ) SAL_THROW_EXTERN_C(); + +/** Create a new string by extracting a single token from another string. + + Starting at index, the token's next token is searched for. If there is no + such token, the result is an empty string. Otherwise, all characters from + the start of that token and up to, but not including the next occurrence + of cTok make up the resulting token. The return value is the position of + the next token, or -1 if no more tokens follow. + + Example code could look like + rtl_uString * pToken = NULL; + sal_Int32 nIndex = 0; + do + { + ... + nIndex = rtl_uString_getToken(&pToken, pStr, 0, ';', nIndex); + ... + } + while (nIndex >= 0); + + The new string does not necessarily have a reference count of 1, so it + must not be modified without checking the reference count. This function + does not handle out-of-memory conditions. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. If either token or index is negative, an empty token is stored in + newStr (and -1 is returned). + + @param str + a valid string. + + @param token + the number of the token to return, starting at index. + + @param cTok + the character that separates the tokens. + + @param idx + the position at which searching for the token starts. Must not be greater + than the length of str. + + @return + the index of the next token, or -1 if no more tokens follow. + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_uString_getToken( + rtl_uString ** newStr , rtl_uString * str, sal_Int32 token, sal_Unicode cTok, sal_Int32 idx ) SAL_THROW_EXTERN_C(); + +/* ======================================================================= */ + +/** Supply an ASCII string literal together with its length and text encoding. + + This macro can be used to compute (some of) the arguments in function calls + like rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("foo")). + + @param constAsciiStr + must be an expression of type "(possibly cv-qualified reference to) array of + (possibly cv-qualified) char." Each element of the referenced array must + represent an ASCII value in the range 0x00--0x7F. The last element of the + referenced array is not considered part of the represented ASCII string, and + its value should be 0x00. Depending on where this macro is used, the nature + of the supplied expression might be further restricted. +*/ +// The &foo[0] trick is intentional, it makes sure the type is char* or const char* +// (plain cast to const char* would not work with non-const char foo[]="a", which seems to be allowed). +// This is to avoid mistaken use with functions that accept string literals +// (i.e. const char (&)[N]) where usage of this macro otherwise could match +// the argument and a following int argument with a default value (e.g. OUString::match()). +#define RTL_CONSTASCII_USTRINGPARAM( constAsciiStr ) (&(constAsciiStr)[0]), \ + ((sal_Int32)(SAL_N_ELEMENTS(constAsciiStr)-1)), RTL_TEXTENCODING_ASCII_US + +/* ======================================================================= */ + +/* predefined constants for String-Conversion */ +#define OSTRING_TO_OUSTRING_CVTFLAGS (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_MAPTOPRIVATE |\ + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT |\ + RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT) + +/* ----------------------------------------------------------------------- */ + +/** Create a new Unicode string by converting a byte string, using a specific + text encoding. + + The lengths of the byte string and the Unicode string may differ (e.g., + for double-byte encodings, UTF-7, UTF-8). + + If the length of the byte string is greater than zero, the reference count + of the new string will be 1. + + If an out-of-memory condition occurs, newStr will point to a null pointer + upon return. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + @param str + a byte character array. Need not be null-terminated, but must be at + least as long as the specified len. + + @param len + the length of the byte character array. + + @param encoding + the text encoding to use for conversion. + + @param convertFlags + flags which control the conversion. Either use + OSTRING_TO_OUSTRING_CVTFLAGS, or see + for more + details. + */ +SAL_DLLPUBLIC void SAL_CALL rtl_string2UString( + rtl_uString ** newStr, const char * str, sal_Int32 len, rtl_TextEncoding encoding, sal_uInt32 convertFlags ) SAL_THROW_EXTERN_C(); + +/* ======================================================================= */ +/* Interning methods */ + +/** Return a canonical representation for a string. + + A pool of strings, initially empty is maintained privately + by the string class. On invocation, if present in the pool + the original string will be returned. Otherwise this string, + or a copy thereof will be added to the pool and returned. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + If an out-of-memory condition occurs, newStr will point to a null pointer + upon return. + + @param str + pointer to the string to be interned. + + @since UDK 3.2.7 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_intern( + rtl_uString ** newStr, rtl_uString * str) SAL_THROW_EXTERN_C(); + +/** Return a canonical representation for a string. + + A pool of strings, initially empty is maintained privately + by the string class. On invocation, if present in the pool + the original string will be returned. Otherwise this string, + or a copy thereof will be added to the pool and returned. + + @param newStr + pointer to the new string. The pointed-to data must be null or a valid + string. + + If an out-of-memory condition occurs, newStr will point to a null pointer + upon return. + + @param str + a byte character array. Need not be null-terminated, but must be at + least as long as the specified len. + + @param len + the length of the byte character array. + + @param encoding + the text encoding to use for conversion. + + @param convertFlags + flags which control the conversion. Either use + OSTRING_TO_OUSTRING_CVTFLAGS, or see + for more + details. + + @param pInfo + pointer to return conversion status in, or NULL. + + @since UDK 3.2.7 + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_internConvert( + rtl_uString ** newStr, + const char * str, + sal_Int32 len, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags, + sal_uInt32 *pInfo) SAL_THROW_EXTERN_C(); + +/** Iterate through a string based on code points instead of UTF-16 code units. + + See Chapter 3 of The Unicode Standard 5.0 (Addison--Wesley, 2006) for + definitions of the various terms used in this description. + + The given string is interpreted as a sequence of zero or more UTF-16 code + units. For each index into this sequence (from zero to one less than the + length of the sequence, inclusive), a code point represented starting at the + given index is computed as follows: + + - If the UTF-16 code unit addressed by the index constitutes a well-formed + UTF-16 code unit sequence, the computed code point is the scalar value + encoded by that UTF-16 code unit sequence. + + - Otherwise, if the index is at least two UTF-16 code units away from the + end of the sequence, and the sequence of two UTF-16 code units addressed by + the index constitutes a well-formed UTF-16 code unit sequence, the computed + code point is the scalar value encoded by that UTF-16 code unit sequence. + + - Otherwise, the computed code point is the UTF-16 code unit addressed by + the index. (This last case catches unmatched surrogates as well as indices + pointing into the middle of surrogate pairs.) + + @param string + pointer to a valid string; must not be null. + + @param indexUtf16 + pointer to a UTF-16 based index into the given string; must not be null. On + entry, the index must be in the range from zero to the length of the string + (in UTF-16 code units), inclusive. Upon successful return, the index will + be updated to address the UTF-16 code unit that is the given + incrementCodePoints away from the initial index. + + @param incrementCodePoints + the number of code points to move the given *indexUtf16. If non-negative, + moving is done after determining the code point at the index. If negative, + moving is done before determining the code point at the (then updated) + index. The value must be such that the resulting UTF-16 based index is in + the range from zero to the length of the string (in UTF-16 code units), + inclusive. + + @return + the code point (an integer in the range from 0 to 0x10FFFF, inclusive) that + is represented within the string starting at the index computed as follows: + If incrementCodePoints is non-negative, the index is the initial value of + *indexUtf16; if incrementCodePoints is negative, the index is the updated + value of *indexUtf16. In either case, the computed index must be in the + range from zero to one less than the length of the string (in UTF-16 code + units), inclusive. + + @since UDK 3.2.7 +*/ +SAL_DLLPUBLIC sal_uInt32 SAL_CALL rtl_uString_iterateCodePoints( + rtl_uString const * string, sal_Int32 * indexUtf16, + sal_Int32 incrementCodePoints); + +/** Converts a byte string to a Unicode string, signalling failure. + + @param target + An out parameter receiving the converted string. Must not be null itself, + and must contain either null or a pointer to a valid rtl_uString; the + contents are unspecified if conversion fails (rtl_convertStringToUString + returns false). + + @param source + The byte string. May only be null if length is zero. + + @param length + The length of the byte string. Must be non-negative. + + @param encoding + The text encoding to convert from. Must be an octet encoding (i.e., + rtl_isOctetTextEncoding(encoding) must return true). + + @param flags + A combination of RTL_TEXTTOUNICODE_FLAGS that detail how to do the + conversion (see rtl_convertTextToUnicode). RTL_TEXTTOUNICODE_FLAGS_FLUSH + need not be included, it is implicitly assumed. Typical uses are either + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR | + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR | + RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR (fail if a byte or multi-byte sequence + cannot be converted from the source encoding) or + OSTRING_TO_OUSTRING_CVTFLAGS (make a best efforts conversion). + + @return + True if the conversion succeeded, false otherwise. + + @since UDK 3.2.9 +*/ +SAL_DLLPUBLIC sal_Bool SAL_CALL rtl_convertStringToUString( + rtl_uString ** target, char const * source, sal_Int32 length, + rtl_TextEncoding encoding, sal_uInt32 flags) SAL_THROW_EXTERN_C(); + +/** Ensure a string has enough space for a given number of characters. + + If the given string is large enough and has refcount of 1, it is not altered in any way. + Otherwise it is replaced by a copy that has enough space for the given number of characters, + data from the source string is copied to the beginning of it, the content of the remaining + capacity undefined, the string has refcount of 1, and refcount of the original string is decreased. + + @param str + pointer to the string. The pointed-to data must be a valid string. + + @param size + the number of characters + + @since LibreOffice 4.1 + @internal + */ +SAL_DLLPUBLIC void SAL_CALL rtl_uString_ensureCapacity( rtl_uString ** str, sal_Int32 size ) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +#endif // INCLUDED_RTL_USTRING_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/ustring.hxx b/include/rtl/ustring.hxx new file mode 100644 index 000000000..e6d3ed682 --- /dev/null +++ b/include/rtl/ustring.hxx @@ -0,0 +1,3560 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_RTL_USTRING_HXX +#define INCLUDED_RTL_USTRING_HXX + +#include "sal/config.h" + +#include +#include +#include +#include +#include +#include +#include + +#if defined LIBO_INTERNAL_ONLY +#include +#include +#endif + +#include "rtl/ustring.h" +#include "rtl/string.hxx" +#include "rtl/stringutils.hxx" +#include "rtl/textenc.h" + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +#include "config_global.h" +#include "rtl/stringconcat.hxx" +#endif + +#ifdef RTL_STRING_UNITTEST +extern bool rtl_string_unittest_invalid_conversion; +#endif + +// The unittest uses slightly different code to help check that the proper +// calls are made. The class is put into a different namespace to make +// sure the compiler generates a different (if generating also non-inline) +// copy of the function and does not merge them together. The class +// is "brought" into the proper rtl namespace by a typedef below. +#ifdef RTL_STRING_UNITTEST +#define rtl rtlunittest +#endif + +namespace rtl +{ + +class OUStringBuffer; + +#ifdef RTL_STRING_UNITTEST +#undef rtl +#endif + +#if defined LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +/// @cond INTERNAL + +/** +A wrapper dressing a string literal as a static-refcount rtl_uString. + +This class is not part of public API and is meant to be used only in LibreOffice code. +@since LibreOffice 4.0 +*/ +template class SAL_WARN_UNUSED OUStringLiteral { + static_assert(N != 0); + static_assert(N - 1 <= std::numeric_limits::max(), "literal too long"); + friend class OUString; + friend class OUStringConstExpr; + +public: +#if HAVE_CPP_CONSTEVAL + consteval +#else + constexpr +#endif + OUStringLiteral(char16_t const (&literal)[N]) { + assertLayout(); + assert(literal[N - 1] == '\0'); + //TODO: Use C++20 constexpr std::copy_n (P0202R3): + for (std::size_t i = 0; i != N; ++i) { + more.buffer[i] = literal[i]; + } + } + + constexpr sal_Int32 getLength() const { return more.length; } + + constexpr sal_Unicode const * getStr() const SAL_RETURNS_NONNULL { return more.buffer; } + + constexpr operator std::u16string_view() const { return {more.buffer, sal_uInt32(more.length)}; } + +private: + static constexpr void assertLayout() { + // These static_asserts verifying the layout compatibility with rtl_uString cannot be class + // member declarations, as offsetof requires a complete type, so defer them to here: + static_assert(std::is_standard_layout_v); + static_assert(offsetof(OUStringLiteral, str.refCount) == offsetof(OUStringLiteral, more.refCount)); + static_assert(offsetof(OUStringLiteral, str.length) == offsetof(OUStringLiteral, more.length)); + static_assert(offsetof(OUStringLiteral, str.buffer) == offsetof(OUStringLiteral, more.buffer)); + } + + struct Data { + Data() = default; + + oslInterlockedCount refCount = 0x40000000; // SAL_STRING_STATIC_FLAG (sal/rtl/strimp.hxx) + sal_Int32 length = N - 1; + sal_Unicode buffer[N] = {}; //TODO: drop initialization for C++20 (P1331R2) + }; + + union { + rtl_uString str; + Data more = {}; + }; +}; + +#if defined RTL_STRING_UNITTEST +namespace libreoffice_internal { +template struct ExceptConstCharArrayDetector> {}; +template struct ExceptCharArrayDetector> {}; +} +#endif + +/** + This is intended to be used when declaring compile-time-constant structs or arrays + that can be initialised from named OUStringLiteral e.g. + + constexpr OUStringLiteral AAA = u"aaa"; + constexpr OUStringLiteral BBB = u"bbb"; + constexpr OUStringConstExpr FOO[] { AAA, BBB }; +*/ +class OUString; +class OUStringConstExpr +{ +public: + template constexpr OUStringConstExpr(OUStringLiteral const & literal): + pData(const_cast(&literal.str)) {} + + // prevent mis-use + template constexpr OUStringConstExpr(OUStringLiteral && literal) + = delete; + + // no destructor necessary because we know we are pointing at a compile-time + // constant OUStringLiteral, which bypasses ref-counting. + + /** + make it easier to pass to OUStringBuffer and similar without casting/converting + */ + constexpr std::u16string_view asView() const { return {pData->buffer, static_cast(pData->length)}; } + + inline operator const OUString&() const; + +private: + rtl_uString* pData; +}; + +/// @endcond +#endif + +/* ======================================================================= */ + +/** + This String class provides base functionality for C++ like Unicode + character array handling. The advantage of this class is that it + handles all the memory management for you - and it does it + more efficiently. If you assign a string to another string, the + data of both strings are shared (without any copy operation or + memory allocation) as long as you do not change the string. This class + also stores the length of the string, so that many operations are + faster than the C-str-functions. + + This class provides only readonly string handling. So you could create + a string and you could only query the content from this string. + It provides also functionality to change the string, but this results + in every case in a new string instance (in the most cases with a + memory allocation). You don't have functionality to change the + content of the string. If you want to change the string content, then + you should use the OStringBuffer class, which provides these + functionalities and avoids too much memory allocation. + + The design of this class is similar to the string classes in Java so + less people should have understanding problems when they use this class. +*/ + +class SAL_WARN_UNUSED SAL_DLLPUBLIC_RTTI OUString +{ +public: + /// @cond INTERNAL + rtl_uString * pData; + /// @endcond + + /** + New string containing no characters. + */ + OUString() + { + pData = NULL; + rtl_uString_new( &pData ); + } + + /** + New string from OUString. + + @param str an OUString. + */ + OUString( const OUString & str ) + { + pData = str.pData; + rtl_uString_acquire( pData ); + } + +#if defined LIBO_INTERNAL_ONLY + /** + Move constructor. + + @param str an OUString. + @since LibreOffice 5.2 + */ + OUString( OUString && str ) noexcept + { + pData = str.pData; + str.pData = nullptr; + rtl_uString_new( &str.pData ); + } +#endif + + /** + New string from OUString data. + + @param str an OUString data. + */ + OUString( rtl_uString * str ) + { + pData = str; + rtl_uString_acquire( pData ); + } + + /** New OUString from OUString data without acquiring it. Takeover of ownership. + + The SAL_NO_ACQUIRE dummy parameter is only there to distinguish this + from other constructors. + + @param str + OUString data + */ + OUString( rtl_uString * str, __sal_NoAcquire ) + { pData = str; } + + /** + New string from a single Unicode character. + + @param value a Unicode character. + */ + explicit OUString( sal_Unicode value ) + : pData (NULL) + { + rtl_uString_newFromStr_WithLength( &pData, &value, 1 ); + } + +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST_CONCAT + /// @cond INTERNAL + // Catch inadvertent conversions to the above ctor (but still allow + // construction from char literals): + OUString(int) = delete; + explicit OUString(char c): + OUString(sal_Unicode(static_cast(c))) + {} + /// @endcond +#endif + +#if defined LIBO_INTERNAL_ONLY + + template explicit OUString( + T const & value, + typename libreoffice_internal::CharPtrDetector::TypeUtf16 + = libreoffice_internal::Dummy()): + pData(nullptr) + { rtl_uString_newFromStr(&pData, value); } + + template explicit OUString( + T & value, + typename + libreoffice_internal::NonConstCharArrayDetector::TypeUtf16 + = libreoffice_internal::Dummy()): + pData(nullptr) + { rtl_uString_newFromStr(&pData, value); } + +#else + + /** + New string from a Unicode character buffer array. + + @param value a NULL-terminated Unicode character array. + */ + OUString( const sal_Unicode * value ) + { + pData = NULL; + rtl_uString_newFromStr( &pData, value ); + } + +#endif + + /** + New string from a Unicode character buffer array. + + @param value a Unicode character array. + @param length the number of character which should be copied. + The character array length must be greater than + or equal to this value. + */ + OUString( const sal_Unicode * value, sal_Int32 length ) + { + pData = NULL; + rtl_uString_newFromStr_WithLength( &pData, value, length ); + } + + /** + New string from an 8-Bit string literal that is expected to contain only + characters in the ASCII set (i.e. first 128 characters). This constructor + allows an efficient and convenient way to create OUString + instances from ASCII literals. When creating strings from data that + is not pure ASCII, it needs to be converted to OUString by explicitly + providing the encoding to use for the conversion. + + If there are any embedded \0's in the string literal, the result is undefined. + Use the overload that explicitly accepts length. + + @param literal the 8-bit ASCII string literal + + @since LibreOffice 3.6 + */ + template< typename T > + OUString( T& literal, typename libreoffice_internal::ConstCharArrayDetector< T, libreoffice_internal::Dummy >::Type = libreoffice_internal::Dummy() ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + pData = NULL; + if (libreoffice_internal::ConstCharArrayDetector::length == 0) { + rtl_uString_new(&pData); + } else { + rtl_uString_newFromLiteral( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, 0); + } +#ifdef RTL_STRING_UNITTEST + rtl_string_unittest_const_literal = true; +#endif + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template OUString( + T & literal, + typename libreoffice_internal::ConstCharArrayDetector< + T, libreoffice_internal::Dummy>::TypeUtf16 + = libreoffice_internal::Dummy()): + pData(nullptr) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + if (libreoffice_internal::ConstCharArrayDetector::length == 0) { + rtl_uString_new(&pData); + } else { + rtl_uString_newFromStr_WithLength( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + } +#endif + +#if defined LIBO_INTERNAL_ONLY && defined RTL_STRING_UNITTEST + /// @cond INTERNAL + /** + * Only used by unittests to detect incorrect conversions. + * @internal + */ + template< typename T > + OUString( T&, typename libreoffice_internal::ExceptConstCharArrayDetector< T >::Type = libreoffice_internal::Dummy() ) + { + pData = NULL; + rtl_uString_newFromLiteral( &pData, "!!br0ken!!", 10, 0 ); // set to garbage + rtl_string_unittest_invalid_conversion = true; + } + /** + * Only used by unittests to detect incorrect conversions. + * @internal + */ + template< typename T > + OUString( const T&, typename libreoffice_internal::ExceptCharArrayDetector< T >::Type = libreoffice_internal::Dummy() ) + { + pData = NULL; + rtl_uString_newFromLiteral( &pData, "!!br0ken!!", 10, 0 ); // set to garbage + rtl_string_unittest_invalid_conversion = true; + } + /// @endcond +#endif + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /// @cond INTERNAL + /** + New string from a string literal. + + @since LibreOffice 5.0 + */ + template constexpr OUString(OUStringLiteral const & literal): + pData(const_cast(&literal.str)) {} + template OUString(OUStringLiteral &&) = delete; + /// @endcond +#endif + + /** + New string from an 8-Bit character buffer array. + + @param value An 8-Bit character array. + @param length The number of character which should be converted. + The 8-Bit character array length must be + greater than or equal to this value. + @param encoding The text encoding from which the 8-Bit character + sequence should be converted. + @param convertFlags Flags which control the conversion. + see RTL_TEXTTOUNICODE_FLAGS_... + + @exception std::bad_alloc is thrown if an out-of-memory condition occurs + */ + OUString( const char * value, sal_Int32 length, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OSTRING_TO_OUSTRING_CVTFLAGS ) + { + pData = NULL; + rtl_string2UString( &pData, value, length, encoding, convertFlags ); + if (pData == NULL) { + throw std::bad_alloc(); + } + } + + /** Create a new string from an array of Unicode code points. + + @param codePoints + an array of at least codePointCount code points, which each must be in + the range from 0 to 0x10FFFF, inclusive. May be null if codePointCount + is zero. + + @param codePointCount + the non-negative number of code points. + + @exception std::bad_alloc + is thrown if either an out-of-memory condition occurs or the resulting + number of UTF-16 code units would have been larger than SAL_MAX_INT32. + + @since UDK 3.2.7 + */ + explicit OUString( + sal_uInt32 const * codePoints, sal_Int32 codePointCount): + pData(NULL) + { + rtl_uString_newFromCodePoints(&pData, codePoints, codePointCount); + if (pData == NULL) { + throw std::bad_alloc(); + } + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OUString( OUStringConcat< T1, T2 >&& c ) + { + const sal_Int32 l = c.length(); + pData = rtl_uString_alloc( l ); + if (l != 0) + { + sal_Unicode* end = c.addData( pData->buffer ); + pData->length = l; + *end = '\0'; + } + } + + /** + @overload + @internal + */ + template< typename T > + OUString( OUStringNumber< T >&& n ) + : OUString( n.buf, n.length ) + {} +#endif + +#if defined LIBO_INTERNAL_ONLY + explicit OUString(std::u16string_view sv) { + if (sv.size() > sal_uInt32(std::numeric_limits::max())) { + throw std::bad_alloc(); + } + pData = nullptr; + rtl_uString_newFromStr_WithLength(&pData, sv.data(), sv.size()); + } +#endif + + /** + Release the string data. + */ + ~OUString() + { + rtl_uString_release( pData ); + } + + /** Provides an OUString const & passing a storage pointer of an + rtl_uString * handle. + It is more convenient to use C++ OUString member functions when dealing + with rtl_uString * handles. Using this function avoids unnecessary + acquire()/release() calls for a temporary OUString object. + + @param ppHandle + pointer to storage + @return + OUString const & based on given storage + */ + static OUString const & unacquired( rtl_uString * const * ppHandle ) + { return * reinterpret_cast< OUString const * >( ppHandle ); } + +#if defined LIBO_INTERNAL_ONLY + /** Provides an OUString const & passing an OUStringBuffer const reference. + It is more convenient to use C++ OUString member functions when checking + current buffer content. Use this function instead of toString (that + allocates a new OUString from buffer data) when the result is used in + comparisons. + + @param str + an OUStringBuffer + @return + OUString const & based on given storage + @since LibreOffice 7.4 + */ + static OUString const& unacquired(const OUStringBuffer& str); +#endif + + /** + Assign a new string. + + @param str an OUString. + */ + OUString & operator=( const OUString & str ) + { + rtl_uString_assign( &pData, str.pData ); + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** + Move assign a new string. + + @param str an OUString. + @since LibreOffice 5.2 + */ + OUString & operator=( OUString && str ) noexcept + { + rtl_uString_release( pData ); + pData = str.pData; + str.pData = nullptr; + rtl_uString_new( &str.pData ); + return *this; + } +#endif + + /** + Assign a new string from an 8-Bit string literal that is expected to contain only + characters in the ASCII set (i.e. first 128 characters). This operator + allows an efficient and convenient way to assign OUString + instances from ASCII literals. When assigning strings from data that + is not pure ASCII, it needs to be converted to OUString by explicitly + providing the encoding to use for the conversion. + + @param literal the 8-bit ASCII string literal + + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, OUString& >::Type operator=( T& literal ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + if (libreoffice_internal::ConstCharArrayDetector::length == 0) { + rtl_uString_new(&pData); + } else { + rtl_uString_newFromLiteral( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, 0); + } + return *this; + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + typename + libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator =(T & literal) { + if (libreoffice_internal::ConstCharArrayDetector::length == 0) { + rtl_uString_new(&pData); + } else { + rtl_uString_newFromStr_WithLength( + &pData, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + return *this; + } + + /** @overload @since LibreOffice 5.4 */ + template OUString & operator =(OUStringLiteral const & literal) { + rtl_uString_release(pData); + pData = const_cast(&literal.str); + return *this; + } + template OUString & operator =(OUStringLiteral &&) = delete; + + template + OUString & operator =(OUStringNumber && n) { + // n.length should never be zero, so no need to add an optimization for that case + rtl_uString_newFromStr_WithLength(&pData, n.buf, n.length); + return *this; + } + + OUString & operator =(std::u16string_view sv) { + if (sv.empty()) { + rtl_uString_new(&pData); + } else { + rtl_uString_newFromStr_WithLength(&pData, sv.data(), sv.size()); + } + return *this; + } +#endif + +#if defined LIBO_INTERNAL_ONLY + /** + Append the contents of an OUStringBuffer to this string. + + @param str an OUStringBuffer. + + @exception std::bad_alloc is thrown if an out-of-memory condition occurs + @since LibreOffice 6.2 + */ + inline OUString & operator+=( const OUStringBuffer & str ) &; +#endif + + /** + Append a string to this string. + + @param str an OUString. + + @exception std::bad_alloc is thrown if an out-of-memory condition occurs + */ + OUString & operator+=( const OUString & str ) +#if defined LIBO_INTERNAL_ONLY + & +#endif + { + return internalAppend(str.pData); + } +#if defined LIBO_INTERNAL_ONLY + void operator+=(OUString const &) && = delete; +#endif + + /** Append an ASCII string literal to this string. + + @param literal an 8-bit ASCII-only string literal + + @since LibreOffice 5.1 + */ + template + typename libreoffice_internal::ConstCharArrayDetector::Type + operator +=(T & literal) +#if defined LIBO_INTERNAL_ONLY + & +#endif + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + rtl_uString_newConcatAsciiL( + &pData, pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return *this; + } +#if defined LIBO_INTERNAL_ONLY + template + typename libreoffice_internal::ConstCharArrayDetector::Type + operator +=(T &) && = delete; +#endif + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template + typename + libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator +=(T & literal) & { + rtl_uString_newConcatUtf16L( + &pData, pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return *this; + } + template + typename + libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator +=(T &) && = delete; + + /** @overload @since LibreOffice 5.4 */ + template OUString & operator +=(OUStringLiteral const & literal) & { + rtl_uString_newConcatUtf16L(&pData, pData, literal.getStr(), literal.getLength()); + return *this; + } + template void operator +=(OUStringLiteral const &) && = delete; + + OUString & operator +=(std::u16string_view sv) & { + if (sv.size() > sal_uInt32(std::numeric_limits::max())) { + throw std::bad_alloc(); + } + rtl_uString_newConcatUtf16L(&pData, pData, sv.data(), sv.size()); + return *this; + } + void operator +=(std::u16string_view) && = delete; +#endif + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + @overload + @internal + */ + template< typename T1, typename T2 > + OUString& operator+=( OUStringConcat< T1, T2 >&& c ) & { + sal_Int32 l = c.length(); + if( l == 0 ) + return *this; + l += pData->length; + rtl_uString_ensureCapacity( &pData, l ); + sal_Unicode* end = c.addData( pData->buffer + pData->length ); + *end = '\0'; + pData->length = l; + return *this; + } + template void operator +=( + OUStringConcat &&) && = delete; + + /** + @overload + @internal + */ + template< typename T > + OUString& operator+=( OUStringNumber< T >&& n ) & { + sal_Int32 l = n.length; + if( l == 0 ) + return *this; + l += pData->length; + rtl_uString_ensureCapacity( &pData, l ); + sal_Unicode* end = addDataHelper( pData->buffer + pData->length, n.buf, n.length ); + *end = '\0'; + pData->length = l; + return *this; + } + template void operator +=( + OUStringNumber &&) && = delete; +#endif + + /** + Clears the string, i.e, makes a zero-character string + @since LibreOffice 4.4 + */ + void clear() + { + rtl_uString_new( &pData ); + } + + /** + Returns the length of this string. + + The length is equal to the number of Unicode characters in this string. + + @return the length of the sequence of characters represented by this + object. + */ + sal_Int32 getLength() const { return pData->length; } + + /** + Checks if a string is empty. + + @return true if the string is empty; + false, otherwise. + + @since LibreOffice 3.4 + */ + bool isEmpty() const + { + return pData->length == 0; + } + + /** + Returns a pointer to the Unicode character buffer for this string. + + It isn't necessarily NULL terminated. + + @return a pointer to the Unicode characters buffer for this object. + */ + const sal_Unicode * getStr() const SAL_RETURNS_NONNULL { return pData->buffer; } + + /** + Access to individual characters. + + @param index must be non-negative and less than length. + + @return the character at the given index. + + @since LibreOffice 3.5 + */ + sal_Unicode operator [](sal_Int32 index) const { + // silence spurious -Werror=strict-overflow warnings from GCC 4.8.2 + assert(index >= 0 && static_cast(index) < static_cast(getLength())); + return getStr()[index]; + } + + /** + Compares two strings. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + This function can't be used for language specific sorting. + + @param str the object to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 compareTo( std::u16string_view str ) const + { + return rtl_ustr_compare_WithLength( pData->buffer, pData->length, + str.data(), str.length() ); + } +#else + sal_Int32 compareTo( const OUString & str ) const + { + return rtl_ustr_compare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + Compares two strings with a maximum count of characters. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + This function can't be used for language specific sorting. + + @param str the object to be compared. + @param maxLength the maximum count of characters to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + + @since UDK 3.2.7 + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 compareTo( std::u16string_view str, sal_Int32 maxLength ) const + { + return rtl_ustr_shortenedCompare_WithLength( pData->buffer, pData->length, + str.data(), str.length(), maxLength ); + } +#else + sal_Int32 compareTo( const OUString & str, sal_Int32 maxLength ) const + { + return rtl_ustr_shortenedCompare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length, maxLength ); + } +#endif + + /** + Compares two strings in reverse order. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + This function can't be used for language specific sorting. + + @param str the object to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 reverseCompareTo(std::u16string_view sv) const { + return rtl_ustr_reverseCompare_WithLength( + pData->buffer, pData->length, sv.data(), sv.size()); + } +#else + sal_Int32 reverseCompareTo( const OUString & str ) const + { + return rtl_ustr_reverseCompare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 4.1 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, sal_Int32 >::Type reverseCompareTo( T& literal ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return rtl_ustr_asciil_reverseCompare_WithLength( + pData->buffer, pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + + /** + Perform a comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string. + This function can't be used for language specific comparison. + + @param str the object to be compared. + @return true if the strings are equal; + false, otherwise. + */ + bool equals( const OUString & str ) const + { + if ( pData->length != str.pData->length ) + return false; + if ( pData == str.pData ) + return true; + return rtl_ustr_reverseCompare_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ) == 0; + } + + /** + Perform an ASCII lowercase comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string, + ignoring the case. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the object to be compared. + @return true if the strings are equal; + false, otherwise. + */ +#if defined LIBO_INTERNAL_ONLY + bool equalsIgnoreAsciiCase(std::u16string_view sv) const { + if ( sal_uInt32(pData->length) != sv.size() ) + return false; + if ( pData->buffer == sv.data() ) + return true; + return + rtl_ustr_compareIgnoreAsciiCase_WithLength( + pData->buffer, pData->length, sv.data(), sv.size()) + == 0; + } +#else + bool equalsIgnoreAsciiCase( const OUString & str ) const + { + if ( pData->length != str.pData->length ) + return false; + if ( pData == str.pData ) + return true; + return rtl_ustr_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ) == 0; + } +#endif + + /** + Perform an ASCII lowercase comparison of two strings. + + Compare the two strings with uppercase ASCII + character values between 65 and 90 (ASCII A-Z) interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the object to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + + @since LibreOffice 4.0 + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 compareToIgnoreAsciiCase(std::u16string_view sv) const { + return rtl_ustr_compareIgnoreAsciiCase_WithLength( + pData->buffer, pData->length, sv.data(), sv.size()); + } +#else + sal_Int32 compareToIgnoreAsciiCase( const OUString & str ) const + { + return rtl_ustr_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type equalsIgnoreAsciiCase( T& literal ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + (pData->length + == libreoffice_internal::ConstCharArrayDetector::length) + && (rtl_ustr_ascii_compareIgnoreAsciiCase_WithLength( + pData->buffer, pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal)) + == 0); + } + + /** + Match against a substring appearing in this string. + + The result is true if and only if the second string appears as a substring + of this string, at the given position. + This function can't be used for language specific comparison. + + @param str the object (substring) to be compared. + @param fromIndex the index to start the comparison from. + The index must be greater than or equal to 0 + and less or equal as the string length. + @return true if str match with the characters in the string + at the given position; + false, otherwise. + */ +#if defined LIBO_INTERNAL_ONLY + bool match(std::u16string_view sv, sal_Int32 fromIndex = 0) const { + return + rtl_ustr_shortenedCompare_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, sv.data(), sv.size(), + sv.size()) + == 0; + } +#else + bool match( const OUString & str, sal_Int32 fromIndex = 0 ) const + { + return rtl_ustr_shortenedCompare_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length, str.pData->length ) == 0; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type match( T& literal, sal_Int32 fromIndex = 0 ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return + rtl_ustr_ascii_shortenedCompare_WithLength( + pData->buffer+fromIndex, pData->length-fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0; + } + + /** + Match against a substring appearing in this string, ignoring the case of + ASCII letters. + + The result is true if and only if the second string appears as a substring + of this string, at the given position. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the object (substring) to be compared. + @param fromIndex the index to start the comparison from. + The index must be greater than or equal to 0 + and less than or equal to the string length. + @return true if str match with the characters in the string + at the given position; + false, otherwise. + */ +#if defined LIBO_INTERNAL_ONLY + bool matchIgnoreAsciiCase(std::u16string_view sv, sal_Int32 fromIndex = 0) const { + return + rtl_ustr_shortenedCompareIgnoreAsciiCase_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, sv.data(), sv.size(), + sv.size()) + == 0; + } +#else + bool matchIgnoreAsciiCase( const OUString & str, sal_Int32 fromIndex = 0 ) const + { + return rtl_ustr_shortenedCompareIgnoreAsciiCase_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length, + str.pData->length ) == 0; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type matchIgnoreAsciiCase( T& literal, sal_Int32 fromIndex = 0 ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return matchIgnoreAsciiCaseAsciiL( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length, fromIndex); + } + + /** + Compares two strings. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated. + This function can't be used for language specific sorting. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ + sal_Int32 compareToAscii( const char* asciiStr ) const + { + return rtl_ustr_ascii_compare_WithLength( pData->buffer, pData->length, asciiStr ); + } + + /** + Compares two strings with a maximum count of characters. + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated. + This function can't be used for language specific sorting. + + @deprecated This is a confusing overload with unexpectedly different + semantics from the one-parameter form, so it is marked as deprecated. + Practically all uses compare the return value against zero and can thus + be replaced with uses of startsWith. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @param maxLength the maximum count of characters to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ + SAL_DEPRECATED( + "replace s1.compareToAscii(s2, strlen(s2)) == 0 with s1.startsWith(s2)") + sal_Int32 compareToAscii( const char * asciiStr, sal_Int32 maxLength ) const + { + return rtl_ustr_ascii_shortenedCompare_WithLength( pData->buffer, pData->length, + asciiStr, maxLength ); + } + + /** + Compares two strings in reverse order. + + This could be useful, if normally both strings start with the same + content. The comparison is based on the numeric value of each character + in the strings and return a value indicating their relationship. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated and must be greater than + or equal to asciiStrLength. + This function can't be used for language specific sorting. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @param asciiStrLength the length of the ascii string + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + */ + sal_Int32 reverseCompareToAsciiL( const char * asciiStr, sal_Int32 asciiStrLength ) const + { + return rtl_ustr_asciil_reverseCompare_WithLength( pData->buffer, pData->length, + asciiStr, asciiStrLength ); + } + + /** + Perform a comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated. + This function can't be used for language specific comparison. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @return true if the strings are equal; + false, otherwise. + */ + bool equalsAscii( const char* asciiStr ) const + { + return rtl_ustr_ascii_compare_WithLength( pData->buffer, pData->length, + asciiStr ) == 0; + } + + /** + Perform a comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated and must be greater than + or equal to asciiStrLength. + This function can't be used for language specific comparison. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @param asciiStrLength the length of the ascii string + @return true if the strings are equal; + false, otherwise. + */ + bool equalsAsciiL( const char* asciiStr, sal_Int32 asciiStrLength ) const + { + if ( pData->length != asciiStrLength ) + return false; + + return rtl_ustr_asciil_reverseEquals_WithLength( + pData->buffer, asciiStr, asciiStrLength ); + } + + /** + Perform an ASCII lowercase comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string, + ignoring the case. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated. + This function can't be used for language specific comparison. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @return true if the strings are equal; + false, otherwise. + */ + bool equalsIgnoreAsciiCaseAscii( const char * asciiStr ) const + { + return rtl_ustr_ascii_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, asciiStr ) == 0; + } + + /** + Compares two ASCII strings ignoring case + + The comparison is based on the numeric value of each character in + the strings and return a value indicating their relationship. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated. + This function can't be used for language specific sorting. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @return 0 - if both strings are equal + < 0 - if this string is less than the string argument + > 0 - if this string is greater than the string argument + + @since LibreOffice 3.5 + */ + sal_Int32 compareToIgnoreAsciiCaseAscii( const char * asciiStr ) const + { + return rtl_ustr_ascii_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, asciiStr ); + } + + /** + Perform an ASCII lowercase comparison of two strings. + + The result is true if and only if second string + represents the same sequence of characters as the first string, + ignoring the case. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated and must be greater than + or equal to asciiStrLength. + This function can't be used for language specific comparison. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @param asciiStrLength the length of the ascii string + @return true if the strings are equal; + false, otherwise. + */ + bool equalsIgnoreAsciiCaseAsciiL( const char * asciiStr, sal_Int32 asciiStrLength ) const + { + if ( pData->length != asciiStrLength ) + return false; + + return rtl_ustr_ascii_compareIgnoreAsciiCase_WithLength( pData->buffer, pData->length, asciiStr ) == 0; + } + + /** + Match against a substring appearing in this string. + + The result is true if and only if the second string appears as a substring + of this string, at the given position. + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated and must be greater than or + equal to asciiStrLength. + This function can't be used for language specific comparison. + + @param asciiStr the object (substring) to be compared. + @param asciiStrLength the length of asciiStr. + @param fromIndex the index to start the comparison from. + The index must be greater than or equal to 0 + and less than or equal to the string length. + @return true if str match with the characters in the string + at the given position; + false, otherwise. + */ + bool matchAsciiL( const char* asciiStr, sal_Int32 asciiStrLength, sal_Int32 fromIndex = 0 ) const + { + return rtl_ustr_ascii_shortenedCompare_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + asciiStr, asciiStrLength ) == 0; + } + + // This overload is left undefined, to detect calls of matchAsciiL that + // erroneously use RTL_CONSTASCII_USTRINGPARAM instead of + // RTL_CONSTASCII_STRINGPARAM (but would lead to ambiguities on 32 bit + // platforms): +#if SAL_TYPES_SIZEOFLONG == 8 + void matchAsciiL(char const *, sal_Int32, rtl_TextEncoding) const; +#endif + + /** + Match against a substring appearing in this string, ignoring the case of + ASCII letters. + + The result is true if and only if the second string appears as a substring + of this string, at the given position. + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated and must be greater than or + equal to asciiStrLength. + This function can't be used for language specific comparison. + + @param asciiStr the 8-Bit ASCII character string to be compared. + @param asciiStrLength the length of the ascii string + @param fromIndex the index to start the comparison from. + The index must be greater than or equal to 0 + and less than or equal to the string length. + @return true if str match with the characters in the string + at the given position; + false, otherwise. + */ + bool matchIgnoreAsciiCaseAsciiL( const char* asciiStr, sal_Int32 asciiStrLength, sal_Int32 fromIndex = 0 ) const + { + return rtl_ustr_ascii_shortenedCompareIgnoreAsciiCase_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + asciiStr, asciiStrLength ) == 0; + } + + // This overload is left undefined, to detect calls of + // matchIgnoreAsciiCaseAsciiL that erroneously use + // RTL_CONSTASCII_USTRINGPARAM instead of RTL_CONSTASCII_STRINGPARAM (but + // would lead to ambiguities on 32 bit platforms): +#if SAL_TYPES_SIZEOFLONG == 8 + void matchIgnoreAsciiCaseAsciiL(char const *, sal_Int32, rtl_TextEncoding) + const; +#endif + + /** + Check whether this string starts with a given substring. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. Available since + LibreOffice 4.2 + + @return true if and only if the given str appears as a substring at the + start of this string + + @since LibreOffice 4.0 + */ +#if defined LIBO_INTERNAL_ONLY + bool startsWith(std::u16string_view sv, OUString * rest = nullptr) const { + auto const b = match(sv); + if (b && rest != nullptr) { + *rest = copy(sv.size()); + } + return b; + } +#else + bool startsWith(OUString const & str, OUString * rest = NULL) const { + bool b = match(str); + if (b && rest != NULL) { + *rest = copy(str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 4.0 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type startsWith( + T & literal, OUString * rest = NULL) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + bool b + = (libreoffice_internal::ConstCharArrayDetector::length + <= sal_uInt32(pData->length)) + && rtl_ustr_asciil_reverseEquals_WithLength( + pData->buffer, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length); + if (b && rest != NULL) { + *rest = copy( + libreoffice_internal::ConstCharArrayDetector::length); + } + return b; + } + + /** + Check whether this string starts with a given string, ignoring the case of + ASCII letters. + + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. Available since + LibreOffice 4.2 + + @return true if and only if the given str appears as a substring at the + start of this string, ignoring the case of ASCII letters ("A"--"Z" and + "a"--"z") + + @since LibreOffice 4.0 + */ +#if defined LIBO_INTERNAL_ONLY + bool startsWithIgnoreAsciiCase(std::u16string_view sv, OUString * rest = nullptr) const { + auto const b = matchIgnoreAsciiCase(sv); + if (b && rest != nullptr) { + *rest = copy(sv.size()); + } + return b; + } +#else + bool startsWithIgnoreAsciiCase(OUString const & str, OUString * rest = NULL) + const + { + bool b = matchIgnoreAsciiCase(str); + if (b && rest != NULL) { + *rest = copy(str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 4.0 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type + startsWithIgnoreAsciiCase(T & literal, OUString * rest = NULL) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + bool b + = (libreoffice_internal::ConstCharArrayDetector::length + <= sal_uInt32(pData->length)) + && (rtl_ustr_ascii_compareIgnoreAsciiCase_WithLengths( + pData->buffer, + libreoffice_internal::ConstCharArrayDetector::length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0); + if (b && rest != NULL) { + *rest = copy( + libreoffice_internal::ConstCharArrayDetector::length); + } + return b; + } + + /** + Check whether this string ends with a given substring. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. Available since + LibreOffice 4.2 + + @return true if and only if the given str appears as a substring at the + end of this string + + @since LibreOffice 3.6 + */ +#if defined LIBO_INTERNAL_ONLY + bool endsWith(std::u16string_view sv, OUString * rest = nullptr) const { + auto const b = sv.size() <= sal_uInt32(pData->length) + && match(sv, pData->length - sv.size()); + if (b && rest != nullptr) { + *rest = copy(0, (pData->length - sv.size())); + } + return b; + } +#else + bool endsWith(OUString const & str, OUString * rest = NULL) const { + bool b = str.getLength() <= getLength() + && match(str, getLength() - str.getLength()); + if (b && rest != NULL) { + *rest = copy(0, getLength() - str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type + endsWith(T & literal, OUString * rest = NULL) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + bool b + = (libreoffice_internal::ConstCharArrayDetector::length + <= sal_uInt32(pData->length)) + && rtl_ustr_asciil_reverseEquals_WithLength( + (pData->buffer + pData->length + - libreoffice_internal::ConstCharArrayDetector::length), + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length); + if (b && rest != NULL) { + *rest = copy( + 0, + (getLength() + - libreoffice_internal::ConstCharArrayDetector::length)); + } + return b; + } + + /** + Check whether this string ends with a given ASCII string. + + @param asciiStr a sequence of at least asciiStrLength ASCII characters + (bytes in the range 0x00--0x7F) + @param asciiStrLength the length of asciiStr; must be non-negative + @return true if this string ends with asciiStr; otherwise, false is + returned + + @since UDK 3.2.7 + */ + bool endsWithAsciiL(char const * asciiStr, sal_Int32 asciiStrLength) + const + { + return asciiStrLength <= pData->length + && rtl_ustr_asciil_reverseEquals_WithLength( + pData->buffer + pData->length - asciiStrLength, asciiStr, + asciiStrLength); + } + + /** + Check whether this string ends with a given string, ignoring the case of + ASCII letters. + + Character values between 65 and 90 (ASCII A-Z) are interpreted as + values between 97 and 122 (ASCII a-z). + This function can't be used for language specific comparison. + + @param str the substring to be compared + + @param rest if non-null, and this function returns true, then assign a + copy of the remainder of this string to *rest. Available since + LibreOffice 4.2 + + @return true if and only if the given str appears as a substring at the + end of this string, ignoring the case of ASCII letters ("A"--"Z" and + "a"--"z") + + @since LibreOffice 3.6 + */ +#if defined LIBO_INTERNAL_ONLY + bool endsWithIgnoreAsciiCase(std::u16string_view sv, OUString * rest = nullptr) const { + auto const b = sv.size() <= sal_uInt32(pData->length) + && matchIgnoreAsciiCase(sv, pData->length - sv.size()); + if (b && rest != nullptr) { + *rest = copy(0, pData->length - sv.size()); + } + return b; + } +#else + bool endsWithIgnoreAsciiCase(OUString const & str, OUString * rest = NULL) const + { + bool b = str.getLength() <= getLength() + && matchIgnoreAsciiCase(str, getLength() - str.getLength()); + if (b && rest != NULL) { + *rest = copy(0, getLength() - str.getLength()); + } + return b; + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type + endsWithIgnoreAsciiCase(T & literal, OUString * rest = NULL) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + bool b + = (libreoffice_internal::ConstCharArrayDetector::length + <= sal_uInt32(pData->length)) + && (rtl_ustr_ascii_compareIgnoreAsciiCase_WithLengths( + (pData->buffer + pData->length + - libreoffice_internal::ConstCharArrayDetector::length), + libreoffice_internal::ConstCharArrayDetector::length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0); + if (b && rest != NULL) { + *rest = copy( + 0, + (getLength() + - libreoffice_internal::ConstCharArrayDetector::length)); + } + return b; + } + + /** + Check whether this string ends with a given ASCII string, ignoring the + case of ASCII letters. + + @param asciiStr a sequence of at least asciiStrLength ASCII characters + (bytes in the range 0x00--0x7F) + @param asciiStrLength the length of asciiStr; must be non-negative + @return true if this string ends with asciiStr, ignoring the case of ASCII + letters ("A"--"Z" and "a"--"z"); otherwise, false is returned + */ + bool endsWithIgnoreAsciiCaseAsciiL( + char const * asciiStr, sal_Int32 asciiStrLength) const + { + return asciiStrLength <= pData->length + && (rtl_ustr_ascii_compareIgnoreAsciiCase_WithLengths( + pData->buffer + pData->length - asciiStrLength, + asciiStrLength, asciiStr, asciiStrLength) + == 0); + } + + friend bool operator == ( const OUString& rStr1, const OUString& rStr2 ) + { return rStr1.equals(rStr2); } + + friend bool operator != ( const OUString& rStr1, const OUString& rStr2 ) + { return !(operator == ( rStr1, rStr2 )); } + + friend bool operator < ( const OUString& rStr1, const OUString& rStr2 ) + { return rStr1.compareTo( rStr2 ) < 0; } + friend bool operator > ( const OUString& rStr1, const OUString& rStr2 ) + { return rStr1.compareTo( rStr2 ) > 0; } + friend bool operator <= ( const OUString& rStr1, const OUString& rStr2 ) + { return rStr1.compareTo( rStr2 ) <= 0; } + friend bool operator >= ( const OUString& rStr1, const OUString& rStr2 ) + { return rStr1.compareTo( rStr2 ) >= 0; } + +#if defined LIBO_INTERNAL_ONLY + + template friend typename libreoffice_internal::CharPtrDetector::TypeUtf16 + operator ==(OUString const & s1, T const & s2) { + return rtl_ustr_compare_WithLength(s1.getStr(), s1.getLength(), s2, rtl_ustr_getLength(s2)) + == 0; + } + + template + friend typename libreoffice_internal::NonConstCharArrayDetector::TypeUtf16 + operator ==(OUString const & s1, T & s2) { + return rtl_ustr_compare_WithLength(s1.getStr(), s1.getLength(), s2, rtl_ustr_getLength(s2)) + == 0; + } + + template friend typename libreoffice_internal::CharPtrDetector::TypeUtf16 + operator ==(T const & s1, OUString const & s2) { + return rtl_ustr_compare_WithLength(s1, rtl_ustr_getLength(s1), s2.getStr(), s2.getLength()) + == 0; + } + + template + friend typename libreoffice_internal::NonConstCharArrayDetector::TypeUtf16 + operator ==(T & s1, OUString const & s2) { + return rtl_ustr_compare_WithLength(s1, rtl_ustr_getLength(s1), s2.getStr(), s2.getLength()) + == 0; + } + + template friend typename libreoffice_internal::CharPtrDetector::TypeUtf16 + operator !=(OUString const & s1, T const & s2) { return !(s1 == s2); } + + template + friend typename libreoffice_internal::NonConstCharArrayDetector::TypeUtf16 + operator !=(OUString const & s1, T & s2) { return !(s1 == s2); } + + template friend typename libreoffice_internal::CharPtrDetector::TypeUtf16 + operator !=(T const & s1, OUString const & s2) { return !(s1 == s2); } + + template + friend typename libreoffice_internal::NonConstCharArrayDetector::TypeUtf16 + operator !=(T & s1, OUString const & s2) { return !(s1 == s2); } + +#else + + friend bool operator == ( const OUString& rStr1, const sal_Unicode * pStr2 ) + { return rStr1.compareTo( pStr2 ) == 0; } + friend bool operator == ( const sal_Unicode * pStr1, const OUString& rStr2 ) + { return OUString( pStr1 ).compareTo( rStr2 ) == 0; } + + friend bool operator != ( const OUString& rStr1, const sal_Unicode * pStr2 ) + { return !(operator == ( rStr1, pStr2 )); } + friend bool operator != ( const sal_Unicode * pStr1, const OUString& rStr2 ) + { return !(operator == ( pStr1, rStr2 )); } + +#endif + + /** + * Compare string to an ASCII string literal. + * + * This operator is equal to calling equalsAsciiL(). + * + * @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator==( const OUString& rString, T& literal ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return rString.equalsAsciiL( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + /** + * Compare string to an ASCII string literal. + * + * This operator is equal to calling equalsAsciiL(). + * + * @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator==( T& literal, const OUString& rString ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return rString.equalsAsciiL( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + /** + * Compare string to an ASCII string literal. + * + * This operator is equal to calling !equalsAsciiL(). + * + * @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator!=( const OUString& rString, T& literal ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return !rString.equalsAsciiL( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + /** + * Compare string to an ASCII string literal. + * + * This operator is equal to calling !equalsAsciiL(). + * + * @since LibreOffice 3.6 + */ + template< typename T > + friend typename libreoffice_internal::ConstCharArrayDetector< T, bool >::Type operator!=( T& literal, const OUString& rString ) + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return !rString.equalsAsciiL( + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + +#if defined LIBO_INTERNAL_ONLY + /** @overload @since LibreOffice 5.3 */ + template friend typename libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator ==(OUString const & string, T & literal) { + return + rtl_ustr_reverseCompare_WithLength( + string.pData->buffer, string.pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + == 0; + } + /** @overload @since LibreOffice 5.3 */ + template friend typename libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator ==(T & literal, OUString const & string) { + return + rtl_ustr_reverseCompare_WithLength( + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, + string.pData->buffer, string.pData->length) + == 0; + } + /** @overload @since LibreOffice 5.3 */ + template friend typename libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator !=(OUString const & string, T & literal) { + return + rtl_ustr_reverseCompare_WithLength( + string.pData->buffer, string.pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length) + != 0; + } + /** @overload @since LibreOffice 5.3 */ + template friend typename libreoffice_internal::ConstCharArrayDetector::TypeUtf16 + operator !=(T & literal, OUString const & string) { + return + rtl_ustr_reverseCompare_WithLength( + libreoffice_internal::ConstCharArrayDetector::toPointer( + literal), + libreoffice_internal::ConstCharArrayDetector::length, + string.pData->buffer, string.pData->length) + != 0; + } +#endif + + /** + Returns a hashcode for this string. + + @return a hash code value for this object. + + @see rtl::OUStringHash for convenient use of std::unordered_map + */ + sal_Int32 hashCode() const + { + return rtl_ustr_hashCode_WithLength( pData->buffer, pData->length ); + } + + /** + Returns the index within this string of the first occurrence of the + specified character, starting the search at the specified index. + + @param ch character to be located. + @param fromIndex the index to start the search from. + The index must be greater than or equal to 0 + and less than or equal to the string length. + @return the index of the first occurrence of the character in the + character sequence represented by this string that is + greater than or equal to fromIndex, or + -1 if the character does not occur. + */ + sal_Int32 indexOf( sal_Unicode ch, sal_Int32 fromIndex = 0 ) const + { + sal_Int32 ret = rtl_ustr_indexOfChar_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, ch ); + return (ret < 0 ? ret : ret+fromIndex); + } + + /** + Returns the index within this string of the last occurrence of the + specified character, searching backward starting at the end. + + @param ch character to be located. + @return the index of the last occurrence of the character in the + character sequence represented by this string, or + -1 if the character does not occur. + */ + sal_Int32 lastIndexOf( sal_Unicode ch ) const + { + return rtl_ustr_lastIndexOfChar_WithLength( pData->buffer, pData->length, ch ); + } + + /** + Returns the index within this string of the last occurrence of the + specified character, searching backward starting before the specified + index. + + @param ch character to be located. + @param fromIndex the index before which to start the search. + @return the index of the last occurrence of the character in the + character sequence represented by this string that + is less than fromIndex, or -1 + if the character does not occur before that point. + */ + sal_Int32 lastIndexOf( sal_Unicode ch, sal_Int32 fromIndex ) const + { + return rtl_ustr_lastIndexOfChar_WithLength( pData->buffer, fromIndex, ch ); + } + + /** + Returns the index within this string of the first occurrence of the + specified substring, starting at the specified index. + + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @param fromIndex the index to start the search from. + @return If the string argument occurs one or more times as a substring + within this string at the starting index, then the index + of the first character of the first such substring is + returned. If it does not occur as a substring starting + at fromIndex or beyond, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 indexOf(std::u16string_view sv, sal_Int32 fromIndex = 0) const { + auto const n = rtl_ustr_indexOfStr_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, sv.data(), sv.size()); + return n < 0 ? n : n + fromIndex; + } +#else + sal_Int32 indexOf( const OUString & str, sal_Int32 fromIndex = 0 ) const + { + sal_Int32 ret = rtl_ustr_indexOfStr_WithLength( pData->buffer+fromIndex, pData->length-fromIndex, + str.pData->buffer, str.pData->length ); + return (ret < 0 ? ret : ret+fromIndex); + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, sal_Int32 >::Type indexOf( T& literal, sal_Int32 fromIndex = 0 ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + sal_Int32 n = rtl_ustr_indexOfAscii_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + return n < 0 ? n : n + fromIndex; + } + + /** + Returns the index within this string of the first occurrence of the + specified ASCII substring, starting at the specified index. + + @param str + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified len. Must only contain characters + in the ASCII range 0x00--7F. + + @param len + the length of the substring; must be non-negative. + + @param fromIndex + the index to start the search from. Must be in the range from zero to + the length of this string, inclusive. + + @return + the index (starting at 0) of the first character of the first occurrence + of the substring within this string starting at the given fromIndex, or + -1 if the substring does not occur. If len is zero, -1 is returned. + + @since UDK 3.2.7 + */ + sal_Int32 indexOfAsciiL( + char const * str, sal_Int32 len, sal_Int32 fromIndex = 0) const + { + sal_Int32 ret = rtl_ustr_indexOfAscii_WithLength( + pData->buffer + fromIndex, pData->length - fromIndex, str, len); + return ret < 0 ? ret : ret + fromIndex; + } + + // This overload is left undefined, to detect calls of indexOfAsciiL that + // erroneously use RTL_CONSTASCII_USTRINGPARAM instead of + // RTL_CONSTASCII_STRINGPARAM (but would lead to ambiguities on 32 bit + // platforms): +#if SAL_TYPES_SIZEOFLONG == 8 + void indexOfAsciiL(char const *, sal_Int32 len, rtl_TextEncoding) const; +#endif + + /** + Returns the index within this string of the last occurrence of + the specified substring, searching backward starting at the end. + + The returned index indicates the starting index of the substring + in this string. + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @return If the string argument occurs one or more times as a substring + within this string, then the index of the first character of + the last such substring is returned. If it does not occur as + a substring, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 lastIndexOf(std::u16string_view sv) const { + return rtl_ustr_lastIndexOfStr_WithLength( + pData->buffer, pData->length, sv.data(), sv.size()); + } +#else + sal_Int32 lastIndexOf( const OUString & str ) const + { + return rtl_ustr_lastIndexOfStr_WithLength( pData->buffer, pData->length, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + Returns the index within this string of the last occurrence of + the specified substring, searching backward starting before the specified + index. + + The returned index indicates the starting index of the substring + in this string. + If str doesn't include any character, always -1 is + returned. This is also the case, if both strings are empty. + + @param str the substring to search for. + @param fromIndex the index before which to start the search. + @return If the string argument occurs one or more times as a substring + within this string before the starting index, then the index + of the first character of the last such substring is + returned. Otherwise, -1 is returned. + */ +#if defined LIBO_INTERNAL_ONLY + sal_Int32 lastIndexOf(std::u16string_view sv, sal_Int32 fromIndex) const { + return rtl_ustr_lastIndexOfStr_WithLength(pData->buffer, fromIndex, sv.data(), sv.size()); + } +#else + sal_Int32 lastIndexOf( const OUString & str, sal_Int32 fromIndex ) const + { + return rtl_ustr_lastIndexOfStr_WithLength( pData->buffer, fromIndex, + str.pData->buffer, str.pData->length ); + } +#endif + + /** + @overload + This function accepts an ASCII string literal as its argument. + @since LibreOffice 3.6 + */ + template< typename T > + typename libreoffice_internal::ConstCharArrayDetector< T, sal_Int32 >::Type lastIndexOf( T& literal ) const + { + assert( + libreoffice_internal::ConstCharArrayDetector::isValid(literal)); + return rtl_ustr_lastIndexOfAscii_WithLength( + pData->buffer, pData->length, + libreoffice_internal::ConstCharArrayDetector::toPointer(literal), + libreoffice_internal::ConstCharArrayDetector::length); + } + + /** + Returns the index within this string of the last occurrence of the + specified ASCII substring. + + @param str + the substring to be searched for. Need not be null-terminated, but must + be at least as long as the specified len. Must only contain characters + in the ASCII range 0x00--7F. + + @param len + the length of the substring; must be non-negative. + + @return + the index (starting at 0) of the first character of the last occurrence + of the substring within this string, or -1 if the substring does not + occur. If len is zero, -1 is returned. + + @since UDK 3.2.7 + */ + sal_Int32 lastIndexOfAsciiL(char const * str, sal_Int32 len) const + { + return rtl_ustr_lastIndexOfAscii_WithLength( + pData->buffer, pData->length, str, len); + } + + /** + Returns a new string that is a substring of this string. + + The substring begins at the specified beginIndex. If + beginIndex is negative or be greater than the length of + this string, behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT OUString copy( sal_Int32 beginIndex ) const + { + return copy(beginIndex, getLength() - beginIndex); + } + + /** + Returns a new string that is a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. If either beginIndex or count are negative, + or beginIndex + count are greater than the length of this string + then behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @param count the number of characters. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT OUString copy( sal_Int32 beginIndex, sal_Int32 count ) const + { + rtl_uString *pNew = NULL; + rtl_uString_newFromSubString( &pNew, pData, beginIndex, count ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + +#if defined LIBO_INTERNAL_ONLY + /** + Returns a std::u16string_view that is a view of a substring of this string. + + The substring begins at the specified beginIndex. If + beginIndex is negative or be greater than the length of + this string, behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT std::u16string_view subView( sal_Int32 beginIndex ) const + { + assert(beginIndex >= 0); + assert(beginIndex <= getLength()); + return subView(beginIndex, getLength() - beginIndex); + } + + /** + Returns a std::u16string_view that is a view of a substring of this string. + + The substring begins at the specified beginIndex and contains count + characters. If either beginIndex or count are negative, + or beginIndex + count are greater than the length of this string + then behaviour is undefined. + + @param beginIndex the beginning index, inclusive. + @param count the number of characters. + @return the specified substring. + */ + SAL_WARN_UNUSED_RESULT std::u16string_view subView( sal_Int32 beginIndex, sal_Int32 count ) const + { + assert(beginIndex >= 0); + assert(count >= 0); + assert(beginIndex <= getLength()); + assert(count <= getLength() - beginIndex); + return std::u16string_view(*this).substr(beginIndex, count); + } +#endif + +#ifndef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + /** + Concatenates the specified string to the end of this string. + + @param str the string that is concatenated to the end + of this string. + @return a string that represents the concatenation of this string + followed by the string argument. + */ + SAL_WARN_UNUSED_RESULT OUString concat( const OUString & str ) const + { + rtl_uString* pNew = NULL; + rtl_uString_newConcat( &pNew, pData, str.pData ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } +#endif + +#ifndef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + friend OUString operator+( const OUString& rStr1, const OUString& rStr2 ) + { + return rStr1.concat( rStr2 ); + } +#endif + +// hide this from internal code to avoid ambiguous lookup error +#ifndef LIBO_INTERNAL_ONLY + /** + Returns a new string resulting from replacing n = count characters + from position index in this string with newStr. + + @param index the replacing index in str. + The index must be greater than or equal to 0 and + less than or equal to the length of the string. + @param count the count of characters that will be replaced + The count must be greater than or equal to 0 and + less than or equal to the length of the string minus index. + @param newStr the new substring. + @return the new string. + */ + SAL_WARN_UNUSED_RESULT OUString replaceAt( sal_Int32 index, sal_Int32 count, const OUString& newStr ) const + { + rtl_uString* pNew = NULL; + rtl_uString_newReplaceStrAt( &pNew, pData, index, count, newStr.pData ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } +#endif + +#ifdef LIBO_INTERNAL_ONLY + SAL_WARN_UNUSED_RESULT OUString replaceAt( sal_Int32 index, sal_Int32 count, std::u16string_view newStr ) const + { + rtl_uString* pNew = NULL; + rtl_uString_newReplaceStrAtUtf16L( &pNew, pData, index, count, newStr.data(), newStr.size() ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } +#endif + + /** + Returns a new string resulting from replacing all occurrences of + oldChar in this string with newChar. + + If the character oldChar does not occur in the character sequence + represented by this object, then the string is assigned with + str. + + @param oldChar the old character. + @param newChar the new character. + @return a string derived from this string by replacing every + occurrence of oldChar with newChar. + */ + SAL_WARN_UNUSED_RESULT OUString replace( sal_Unicode oldChar, sal_Unicode newChar ) const + { + rtl_uString* pNew = NULL; + rtl_uString_newReplace( &pNew, pData, oldChar, newChar ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a new string resulting from replacing the first occurrence of a + given substring with another substring. + + @param from the substring to be replaced + + @param to the replacing substring + + @param[in,out] index pointer to a start index; if the pointer is + non-null: upon entry to the function, its value is the index into this + string at which to start searching for the \p from substring, the value + must be non-negative and not greater than this string's length; upon exiting + the function its value is the index into this string at which the + replacement took place or -1 if no replacement took place; if the pointer + is null, searching always starts at index 0 + + @since LibreOffice 3.6 + */ +#if defined LIBO_INTERNAL_ONLY + [[nodiscard]] OUString replaceFirst( + std::u16string_view from, std::u16string_view to, sal_Int32 * index = nullptr) const + { + rtl_uString * s = nullptr; + sal_Int32 i = 0; + rtl_uString_newReplaceFirstUtf16LUtf16L( + &s, pData, from.data(), from.size(), to.data(), to.size(), + index == nullptr ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } +#else + SAL_WARN_UNUSED_RESULT OUString replaceFirst( + OUString const & from, OUString const & to, sal_Int32 * index = NULL) const + { + rtl_uString * s = NULL; + sal_Int32 i = 0; + rtl_uString_newReplaceFirst( + &s, pData, from.pData, to.pData, index == NULL ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } +#endif + + /** + Returns a new string resulting from replacing the first occurrence of a + given substring with another substring. + + @param from ASCII string literal, the substring to be replaced + + @param to the replacing substring + + @param[in,out] index pointer to a start index; if the pointer is + non-null: upon entry to the function, its value is the index into the this + string at which to start searching for the \p from substring, the value + must be non-negative and not greater than this string's length; upon exiting + the function its value is the index into this string at which the + replacement took place or -1 if no replacement took place; if the pointer + is null, searching always starts at index 0 + + @since LibreOffice 3.6 + */ +#if defined LIBO_INTERNAL_ONLY + template [[nodiscard]] + typename libreoffice_internal::ConstCharArrayDetector::Type replaceFirst( + T & from, std::u16string_view to, sal_Int32 * index = nullptr) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(from)); + rtl_uString * s = nullptr; + sal_Int32 i = 0; + rtl_uString_newReplaceFirstAsciiLUtf16L( + &s, pData, libreoffice_internal::ConstCharArrayDetector::toPointer(from), + libreoffice_internal::ConstCharArrayDetector::length, to.data(), to.size(), + index == nullptr ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } +#else + template< typename T > + SAL_WARN_UNUSED_RESULT typename libreoffice_internal::ConstCharArrayDetector< T, OUString >::Type replaceFirst( T& from, OUString const & to, + sal_Int32 * index = NULL) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(from)); + rtl_uString * s = NULL; + sal_Int32 i = 0; + rtl_uString_newReplaceFirstAsciiL( + &s, pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(from), + libreoffice_internal::ConstCharArrayDetector::length, to.pData, + index == NULL ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } +#endif + + /** + Returns a new string resulting from replacing the first occurrence of a + given substring with another substring. + + @param from the substring to be replaced + + @param to ASCII string literal, the replacing substring + + @param[in,out] index pointer to a start index; if the pointer is + non-null: upon entry to the function, its value is the index into the this + string at which to start searching for the \p from substring, the value + must be non-negative and not greater than this string's length; upon exiting + the function its value is the index into this string at which the + replacement took place or -1 if no replacement took place; if the pointer + is null, searching always starts at index 0 + + @since LibreOffice 5.1 + */ +#if defined LIBO_INTERNAL_ONLY + template [[nodiscard]] + typename libreoffice_internal::ConstCharArrayDetector::Type replaceFirst( + std::u16string_view from, T & to, sal_Int32 * index = nullptr) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(to)); + rtl_uString * s = nullptr; + sal_Int32 i = 0; + rtl_uString_newReplaceFirstUtf16LAsciiL( + &s, pData, from.data(), from.size(), + libreoffice_internal::ConstCharArrayDetector::toPointer(to), + libreoffice_internal::ConstCharArrayDetector::length, index == nullptr ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } +#else + template< typename T > + SAL_WARN_UNUSED_RESULT typename libreoffice_internal::ConstCharArrayDetector< T, OUString >::Type replaceFirst( OUString const & from, T& to, + sal_Int32 * index = NULL) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(to)); + rtl_uString * s = NULL; + sal_Int32 i = 0; + rtl_uString_newReplaceFirstToAsciiL( + &s, pData, from.pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(to), + libreoffice_internal::ConstCharArrayDetector::length, + index == NULL ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } +#endif + + /** + Returns a new string resulting from replacing the first occurrence of a + given substring with another substring. + + @param from ASCII string literal, the substring to be replaced + + @param to ASCII string literal, the substring to be replaced + + @param[in,out] index pointer to a start index; if the pointer is + non-null: upon entry to the function, its value is the index into the this + string at which to start searching for the \p from substring, the value + must be non-negative and not greater than this string's length; upon exiting + the function its value is the index into this string at which the + replacement took place or -1 if no replacement took place; if the pointer + is null, searching always starts at index 0 + + @since LibreOffice 3.6 + */ + template< typename T1, typename T2 > + SAL_WARN_UNUSED_RESULT typename libreoffice_internal::ConstCharArrayDetector< T1, typename libreoffice_internal::ConstCharArrayDetector< T2, OUString >::Type >::Type + replaceFirst( T1& from, T2& to, sal_Int32 * index = NULL) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(from)); + assert(libreoffice_internal::ConstCharArrayDetector::isValid(to)); + rtl_uString * s = NULL; + sal_Int32 i = 0; + rtl_uString_newReplaceFirstAsciiLAsciiL( + &s, pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(from), + libreoffice_internal::ConstCharArrayDetector::length, + libreoffice_internal::ConstCharArrayDetector::toPointer(to), + libreoffice_internal::ConstCharArrayDetector::length, + index == NULL ? &i : index); + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Returns a new string resulting from replacing all occurrences of a given + substring with another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param from the substring to be replaced + + @param to the replacing substring + + @param fromIndex the position in the string where we will begin searching + + @since LibreOffice 4.0 + */ +#if defined LIBO_INTERNAL_ONLY + [[nodiscard]] OUString replaceAll( + std::u16string_view from, std::u16string_view to, sal_Int32 fromIndex = 0) const + { + rtl_uString * s = nullptr; + rtl_uString_newReplaceAllFromIndexUtf16LUtf16L( + &s, pData, from.data(), from.size(), to.data(), to.size(), fromIndex); + return OUString(s, SAL_NO_ACQUIRE); + } +#else + SAL_WARN_UNUSED_RESULT OUString replaceAll( + OUString const & from, OUString const & to, sal_Int32 fromIndex = 0) const + { + rtl_uString * s = NULL; + rtl_uString_newReplaceAllFromIndex(&s, pData, from.pData, to.pData, fromIndex); + return OUString(s, SAL_NO_ACQUIRE); + } +#endif + + /** + Returns a new string resulting from replacing all occurrences of a given + substring with another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param from ASCII string literal, the substring to be replaced + + @param to the replacing substring + + @since LibreOffice 3.6 + */ +#if defined LIBO_INTERNAL_ONLY + template [[nodiscard]] + typename libreoffice_internal::ConstCharArrayDetector::Type replaceAll( + T & from, std::u16string_view to) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(from)); + rtl_uString * s = nullptr; + rtl_uString_newReplaceAllAsciiLUtf16L( + &s, pData, libreoffice_internal::ConstCharArrayDetector::toPointer(from), + libreoffice_internal::ConstCharArrayDetector::length, to.data(), to.size()); + return OUString(s, SAL_NO_ACQUIRE); + } +#else + template< typename T > + SAL_WARN_UNUSED_RESULT typename libreoffice_internal::ConstCharArrayDetector< T, OUString >::Type replaceAll( T& from, OUString const & to) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(from)); + rtl_uString * s = NULL; + rtl_uString_newReplaceAllAsciiL( + &s, pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(from), + libreoffice_internal::ConstCharArrayDetector::length, to.pData); + return OUString(s, SAL_NO_ACQUIRE); + } +#endif + + /** + Returns a new string resulting from replacing all occurrences of a given + substring with another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param from the substring to be replaced + + @param to ASCII string literal, the replacing substring + + @since LibreOffice 5.1 + */ +#if defined LIBO_INTERNAL_ONLY + template [[nodiscard]] + typename libreoffice_internal::ConstCharArrayDetector::Type replaceAll( + std::u16string_view from, T & to) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(to)); + rtl_uString * s = nullptr; + rtl_uString_newReplaceAllUtf16LAsciiL( + &s, pData, from.data(), from.size(), + libreoffice_internal::ConstCharArrayDetector::toPointer(to), + libreoffice_internal::ConstCharArrayDetector::length); + return OUString(s, SAL_NO_ACQUIRE); + } +#else + template< typename T > + SAL_WARN_UNUSED_RESULT typename libreoffice_internal::ConstCharArrayDetector< T, OUString >::Type replaceAll( OUString const & from, T& to) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(to)); + rtl_uString * s = NULL; + rtl_uString_newReplaceAllToAsciiL( + &s, pData, from.pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(to), + libreoffice_internal::ConstCharArrayDetector::length); + return OUString(s, SAL_NO_ACQUIRE); + } +#endif + + /** + Returns a new string resulting from replacing all occurrences of a given + substring with another substring. + + Replacing subsequent occurrences picks up only after a given replacement. + That is, replacing from "xa" to "xx" in "xaa" results in "xxa", not "xxx". + + @param from ASCII string literal, the substring to be replaced + + @param to ASCII string literal, the substring to be replaced + + @since LibreOffice 3.6 + */ + template< typename T1, typename T2 > + SAL_WARN_UNUSED_RESULT typename libreoffice_internal::ConstCharArrayDetector< T1, typename libreoffice_internal::ConstCharArrayDetector< T2, OUString >::Type >::Type + replaceAll( T1& from, T2& to ) const + { + assert(libreoffice_internal::ConstCharArrayDetector::isValid(from)); + assert(libreoffice_internal::ConstCharArrayDetector::isValid(to)); + rtl_uString * s = NULL; + rtl_uString_newReplaceAllAsciiLAsciiL( + &s, pData, + libreoffice_internal::ConstCharArrayDetector::toPointer(from), + libreoffice_internal::ConstCharArrayDetector::length, + libreoffice_internal::ConstCharArrayDetector::toPointer(to), + libreoffice_internal::ConstCharArrayDetector::length); + return OUString(s, SAL_NO_ACQUIRE); + } + + /** + Converts from this string all ASCII uppercase characters (65-90) + to ASCII lowercase characters (97-122). + + This function can't be used for language specific conversion. + If the string doesn't contain characters which must be converted, + then the new string is assigned with str. + + @return the string, converted to ASCII lowercase. + */ + SAL_WARN_UNUSED_RESULT OUString toAsciiLowerCase() const + { + rtl_uString* pNew = NULL; + rtl_uString_newToAsciiLowerCase( &pNew, pData ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Converts from this string all ASCII lowercase characters (97-122) + to ASCII uppercase characters (65-90). + + This function can't be used for language specific conversion. + If the string doesn't contain characters which must be converted, + then the new string is assigned with str. + + @return the string, converted to ASCII uppercase. + */ + SAL_WARN_UNUSED_RESULT OUString toAsciiUpperCase() const + { + rtl_uString* pNew = NULL; + rtl_uString_newToAsciiUpperCase( &pNew, pData ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a new string resulting from removing white space from both ends + of the string. + + All characters that have codes less than or equal to + 32 (the space character), and Unicode General Punctuation area Space + and some Control characters are considered to be white space (see + implIsWhitespace). + If the string doesn't contain white spaces at both ends, + then the new string is assigned with str. + + @return the string, with white space removed from the front and end. + */ + SAL_WARN_UNUSED_RESULT OUString trim() const + { + rtl_uString* pNew = NULL; + rtl_uString_newTrim( &pNew, pData ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a token in the string. + + Example: + sal_Int32 nIndex = 0; + do + { + ... + OUString aToken = aStr.getToken( 0, ';', nIndex ); + ... + } + while ( nIndex >= 0 ); + + @param token the number of the token to return + @param cTok the character which separate the tokens. + @param index the position at which the token is searched in the + string. + The index must not be greater than the length of the + string. + This param is set to the position of the + next token or to -1, if it is the last token. + @return the token; if either token or index is negative, an empty token + is returned (and index is set to -1) + */ + OUString getToken( sal_Int32 token, sal_Unicode cTok, sal_Int32& index ) const + { + rtl_uString * pNew = NULL; + index = rtl_uString_getToken( &pNew, pData, token, cTok, index ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Returns a token from the string. + + The same as getToken(sal_Int32, sal_Unicode, sal_Int32 &), but always + passing in 0 as the start index in the third argument. + + @param count the number of the token to return, starting with 0 + @param separator the character which separates the tokens + + @return the given token, or an empty string + + @since LibreOffice 3.6 + */ + OUString getToken(sal_Int32 count, sal_Unicode separator) const { + sal_Int32 n = 0; + return getToken(count, separator, n); + } + + /** + Returns the Boolean value from this string. + + This function can't be used for language specific conversion. + + @return true, if the string is 1 or "True" in any ASCII case. + false in any other case. + */ + bool toBoolean() const + { + return rtl_ustr_toBoolean( pData->buffer ); + } + + /** + Returns the first character from this string. + + @return the first character from this string or 0, if this string + is empty. + */ + sal_Unicode toChar() const + { + return pData->buffer[0]; + } + + /** + Returns the int32 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the int32 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + */ + sal_Int32 toInt32( sal_Int16 radix = 10 ) const + { + return rtl_ustr_toInt32( pData->buffer, radix ); + } + + /** + Returns the uint32 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the uint32 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + + @since LibreOffice 4.2 + */ + sal_uInt32 toUInt32( sal_Int16 radix = 10 ) const + { + return rtl_ustr_toUInt32( pData->buffer, radix ); + } + + /** + Returns the int64 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the int64 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + */ + sal_Int64 toInt64( sal_Int16 radix = 10 ) const + { + return rtl_ustr_toInt64( pData->buffer, radix ); + } + + /** + Returns the uint64 value from this string. + + This function can't be used for language specific conversion. + + @param radix the radix (between 2 and 36) + @return the uint64 represented from this string. + 0 if this string represents no number or one of too large + magnitude. + + @since LibreOffice 4.1 + */ + sal_uInt64 toUInt64( sal_Int16 radix = 10 ) const + { + return rtl_ustr_toUInt64( pData->buffer, radix ); + } + + /** + Returns the float value from this string. + + This function can't be used for language specific conversion. + + @return the float represented from this string. + 0.0 if this string represents no number. + */ + float toFloat() const + { + return rtl_ustr_toFloat( pData->buffer ); + } + + /** + Returns the double value from this string. + + This function can't be used for language specific conversion. + + @return the double represented from this string. + 0.0 if this string represents no number. + */ + double toDouble() const + { + return rtl_ustr_toDouble( pData->buffer ); + } + + + /** + Return a canonical representation for a string. + + A pool of strings, initially empty is maintained privately + by the string class. On invocation, if present in the pool + the original string will be returned. Otherwise this string, + or a copy thereof will be added to the pool and returned. + + @return + a version of the string from the pool. + + @exception std::bad_alloc is thrown if an out-of-memory condition occurs + + @since UDK 3.2.7 + */ + OUString intern() const + { + rtl_uString * pNew = NULL; + rtl_uString_intern( &pNew, pData ); + if (pNew == NULL) { + throw std::bad_alloc(); + } + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Return a canonical representation for a converted string. + + A pool of strings, initially empty is maintained privately + by the string class. On invocation, if present in the pool + the original string will be returned. Otherwise this string, + or a copy thereof will be added to the pool and returned. + + @param value a 8-Bit character array. + @param length the number of character which should be converted. + The 8-Bit character array length must be + greater than or equal to this value. + @param encoding the text encoding from which the 8-Bit character + sequence should be converted. + @param convertFlags flags which controls the conversion. + see RTL_TEXTTOUNICODE_FLAGS_... + @param pInfo pointer to return conversion status or NULL. + + @return + a version of the converted string from the pool. + + @exception std::bad_alloc is thrown if an out-of-memory condition occurs + + @since UDK 3.2.7 + */ + static OUString intern( const char * value, sal_Int32 length, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OSTRING_TO_OUSTRING_CVTFLAGS, + sal_uInt32 *pInfo = NULL ) + { + rtl_uString * pNew = NULL; + rtl_uString_internConvert( &pNew, value, length, encoding, + convertFlags, pInfo ); + if (pNew == NULL) { + throw std::bad_alloc(); + } + return OUString( pNew, SAL_NO_ACQUIRE ); + } + + /** + Converts to an OString, signalling failure. + + @param pTarget + An out parameter receiving the converted OString. Must not be null; the + contents are not modified if conversion fails (convertToOString returns + false). + + @param nEncoding + The text encoding to convert into. Must be an octet encoding (i.e., + rtl_isOctetTextEncoding(nEncoding) must return true). + + @param nFlags + A combination of RTL_UNICODETOTEXT_FLAGS that detail how to do the + conversion (see rtl_convertUnicodeToText). RTL_UNICODETOTEXT_FLAGS_FLUSH + need not be included, it is implicitly assumed. Typical uses are either + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR | + RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR (fail if a Unicode character cannot + be converted to the target nEncoding) or OUSTRING_TO_OSTRING_CVTFLAGS + (make a best efforts conversion). + + @return + True if the conversion succeeded, false otherwise. + */ + bool convertToString(OString * pTarget, rtl_TextEncoding nEncoding, + sal_uInt32 nFlags) const + { + return rtl_convertUStringToString(&pTarget->pData, pData->buffer, + pData->length, nEncoding, nFlags); + } + + /** Iterate through this string based on code points instead of UTF-16 code + units. + + See Chapter 3 of The Unicode Standard 5.0 (Addison--Wesley, 2006) for + definitions of the various terms used in this description. + + This string is interpreted as a sequence of zero or more UTF-16 code + units. For each index into this sequence (from zero to one less than + the length of the sequence, inclusive), a code point represented + starting at the given index is computed as follows: + + - If the UTF-16 code unit addressed by the index constitutes a + well-formed UTF-16 code unit sequence, the computed code point is the + scalar value encoded by that UTF-16 code unit sequence. + + - Otherwise, if the index is at least two UTF-16 code units away from + the end of the sequence, and the sequence of two UTF-16 code units + addressed by the index constitutes a well-formed UTF-16 code unit + sequence, the computed code point is the scalar value encoded by that + UTF-16 code unit sequence. + + - Otherwise, the computed code point is the UTF-16 code unit addressed + by the index. (This last case catches unmatched surrogates as well as + indices pointing into the middle of surrogate pairs.) + + @param indexUtf16 + pointer to a UTF-16 based index into this string; must not be null. On + entry, the index must be in the range from zero to the length of this + string (in UTF-16 code units), inclusive. Upon successful return, the + index will be updated to address the UTF-16 code unit that is the given + incrementCodePoints away from the initial index. + + @param incrementCodePoints + the number of code points to move the given *indexUtf16. If + non-negative, moving is done after determining the code point at the + index. If negative, moving is done before determining the code point + at the (then updated) index. The value must be such that the resulting + UTF-16 based index is in the range from zero to the length of this + string (in UTF-16 code units), inclusive. + + @return + the code point (an integer in the range from 0 to 0x10FFFF, inclusive) + that is represented within this string starting at the index computed as + follows: If incrementCodePoints is non-negative, the index is the + initial value of *indexUtf16; if incrementCodePoints is negative, the + index is the updated value of *indexUtf16. In either case, the computed + index must be in the range from zero to one less than the length of this + string (in UTF-16 code units), inclusive. + + @since UDK 3.2.7 + */ + sal_uInt32 iterateCodePoints( + sal_Int32 * indexUtf16, sal_Int32 incrementCodePoints = 1) const + { + return rtl_uString_iterateCodePoints( + pData, indexUtf16, incrementCodePoints); + } + + /** + * Convert an OString to an OUString, assuming that the OString is + * UTF-8-encoded. + * + * @param rSource + * an OString to convert + * + * @since LibreOffice 4.4 + */ +#if defined LIBO_INTERNAL_ONLY + static OUString fromUtf8(std::string_view rSource) + { + OUString aTarget; + bool bSuccess = rtl_convertStringToUString(&aTarget.pData, + rSource.data(), + rSource.length(), + RTL_TEXTENCODING_UTF8, + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR|RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR|RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR); + (void) bSuccess; + assert(bSuccess); + return aTarget; + } +#else + static OUString fromUtf8(const OString& rSource) + { + OUString aTarget; + bool bSuccess = rtl_convertStringToUString(&aTarget.pData, + rSource.getStr(), + rSource.getLength(), + RTL_TEXTENCODING_UTF8, + RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR|RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR|RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR); + (void) bSuccess; + assert(bSuccess); + return aTarget; + } +#endif + + /** + * Convert this string to an OString, assuming that the string can be + * UTF-8-encoded successfully. + * + * In other words, you must not use this method on a random sequence of + * UTF-16 code units, but only at places where it is assumed that the + * content is a proper string. + * + * @since LibreOffice 4.4 + */ + OString toUtf8() const + { + OString aTarget; + bool bSuccess = rtl_convertUStringToString(&aTarget.pData, + getStr(), + getLength(), + RTL_TEXTENCODING_UTF8, + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR|RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR); + (void) bSuccess; + assert(bSuccess); + return aTarget; + } + +#ifdef LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" + + static OUStringNumber< int > number( int i, sal_Int16 radix = 10 ) + { + return OUStringNumber< int >( i, radix ); + } + static OUStringNumber< long long > number( long long ll, sal_Int16 radix = 10 ) + { + return OUStringNumber< long long >( ll, radix ); + } + static OUStringNumber< unsigned long long > number( unsigned long long ll, sal_Int16 radix = 10 ) + { + return OUStringNumber< unsigned long long >( ll, radix ); + } + static OUStringNumber< unsigned long long > number( unsigned int i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + static OUStringNumber< long long > number( long i, sal_Int16 radix = 10) + { + return number( static_cast< long long >( i ), radix ); + } + static OUStringNumber< unsigned long long > number( unsigned long i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + static OUStringNumber< float > number( float f ) + { + return OUStringNumber< float >( f ); + } + static OUStringNumber< double > number( double d ) + { + return OUStringNumber< double >( d ); + } +#else + /** + Returns the string representation of the integer argument. + + This function can't be used for language specific conversion. + + @param i an integer value + @param radix the radix (between 2 and 36) + @return a string with the string representation of the argument. + @since LibreOffice 4.1 + */ + static OUString number( int i, sal_Int16 radix = 10 ) + { + sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFINT32]; + return OUString(aBuf, rtl_ustr_valueOfInt32(aBuf, i, radix)); + } + /// @overload + /// @since LibreOffice 4.1 + static OUString number( unsigned int i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + /// @overload + /// @since LibreOffice 4.1 + static OUString number( long i, sal_Int16 radix = 10) + { + return number( static_cast< long long >( i ), radix ); + } + /// @overload + /// @since LibreOffice 4.1 + static OUString number( unsigned long i, sal_Int16 radix = 10 ) + { + return number( static_cast< unsigned long long >( i ), radix ); + } + /// @overload + /// @since LibreOffice 4.1 + static OUString number( long long ll, sal_Int16 radix = 10 ) + { + sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFINT64]; + return OUString(aBuf, rtl_ustr_valueOfInt64(aBuf, ll, radix)); + } + /// @overload + /// @since LibreOffice 4.1 + static OUString number( unsigned long long ll, sal_Int16 radix = 10 ) + { + sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFUINT64]; + return OUString(aBuf, rtl_ustr_valueOfUInt64(aBuf, ll, radix)); + } + + /** + Returns the string representation of the float argument. + + This function can't be used for language specific conversion. + + @param f a float. + @return a string with the decimal representation of the argument. + @since LibreOffice 4.1 + */ + static OUString number( float f ) + { + sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFFLOAT]; + return OUString(aBuf, rtl_ustr_valueOfFloat(aBuf, f)); + } + + /** + Returns the string representation of the double argument. + + This function can't be used for language specific conversion. + + @param d a double. + @return a string with the decimal representation of the argument. + @since LibreOffice 4.1 + */ + static OUString number( double d ) + { + sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFDOUBLE]; + return OUString(aBuf, rtl_ustr_valueOfDouble(aBuf, d)); + } +#endif + + /** + Returns the string representation of the sal_Bool argument. + + If the sal_Bool is true, the string "true" is returned. + If the sal_Bool is false, the string "false" is returned. + This function can't be used for language specific conversion. + + @param b a sal_Bool. + @return a string with the string representation of the argument. + @deprecated use boolean() + */ + SAL_DEPRECATED("use boolean()") static OUString valueOf( sal_Bool b ) + { + return boolean(b); + } + + /** + Returns the string representation of the boolean argument. + + If the argument is true, the string "true" is returned. + If the argument is false, the string "false" is returned. + This function can't be used for language specific conversion. + + @param b a bool. + @return a string with the string representation of the argument. + @since LibreOffice 4.1 + */ + static OUString boolean( bool b ) + { + sal_Unicode aBuf[RTL_USTR_MAX_VALUEOFBOOLEAN]; + return OUString(aBuf, rtl_ustr_valueOfBoolean(aBuf, b)); + } + + /** + Returns the string representation of the char argument. + + @param c a character. + @return a string with the string representation of the argument. + @deprecated use operator, function or constructor taking char or sal_Unicode argument + */ + SAL_DEPRECATED("convert to OUString or use directly") static OUString valueOf( sal_Unicode c ) + { + return OUString( &c, 1 ); + } + + /** + Returns the string representation of the int argument. + + This function can't be used for language specific conversion. + + @param i a int32. + @param radix the radix (between 2 and 36) + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OUString valueOf( sal_Int32 i, sal_Int16 radix = 10 ) + { + return number( i, radix ); + } + + /** + Returns the string representation of the long argument. + + This function can't be used for language specific conversion. + + @param ll a int64. + @param radix the radix (between 2 and 36) + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OUString valueOf( sal_Int64 ll, sal_Int16 radix = 10 ) + { + return number( ll, radix ); + } + + /** + Returns the string representation of the float argument. + + This function can't be used for language specific conversion. + + @param f a float. + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OUString valueOf( float f ) + { + return number(f); + } + + /** + Returns the string representation of the double argument. + + This function can't be used for language specific conversion. + + @param d a double. + @return a string with the string representation of the argument. + @deprecated use number() + */ + SAL_DEPRECATED("use number()") static OUString valueOf( double d ) + { + return number(d); + } + + /** + Returns an OUString copied without conversion from an ASCII + character string. + + Since this method is optimized for performance, the ASCII character + values are not converted in any way. The caller has to make sure that + all ASCII characters are in the allowed range between 0 and 127. + The ASCII string must be NULL-terminated. + + Note that for string literals it is simpler and more efficient + to directly use the OUString constructor. + + @param value the 8-Bit ASCII character string + @return a string with the string representation of the argument. + */ + static OUString createFromAscii( const char * value ) + { + rtl_uString* pNew = NULL; + rtl_uString_newFromAscii( &pNew, value ); + return OUString( pNew, SAL_NO_ACQUIRE ); + } + +#if defined LIBO_INTERNAL_ONLY + static OUString createFromAscii(std::string_view value) { + rtl_uString * p = nullptr; + rtl_uString_newFromLiteral(&p, value.data(), value.size(), 0); //TODO: check for overflow + return OUString(p, SAL_NO_ACQUIRE); + } + #endif + +#if defined LIBO_INTERNAL_ONLY + operator std::u16string_view() const { return {getStr(), sal_uInt32(getLength())}; } +#endif + +#if defined LIBO_INTERNAL_ONLY + // A wrapper for the first expression in an + // + // OUString::Concat(e1) + e2 + ... + // + // concatenation chain, when neither of the first two e1, e2 is one of our rtl string-related + // classes (so something like + // + // OUString s = "a" + (b ? std::u16string_view(u"c") : std::u16string_view(u"dd")); + // + // would not compile): + template [[nodiscard]] static + typename std::enable_if_t< + ToStringHelper::allowOUStringConcat, OUStringConcat> + Concat(T const & value) { return OUStringConcat({}, value); } + + // This overload is needed so that an argument of type 'char const[N]' ends up as + // 'OUStringConcat' rather than as + // 'OUStringConcat': + template [[nodiscard]] static + typename std::enable_if_t< + ToStringHelper::allowOUStringConcat, OUStringConcat> + Concat(T (& value)[N]) { return OUStringConcat({}, value); } +#endif + +private: + OUString & internalAppend( rtl_uString* pOtherData ) + { + rtl_uString* pNewData = NULL; + rtl_uString_newConcat( &pNewData, pData, pOtherData ); + if (pNewData == NULL) { + throw std::bad_alloc(); + } + rtl_uString_assign(&pData, pNewData); + rtl_uString_release(pNewData); + return *this; + } + +}; + +#if defined LIBO_INTERNAL_ONLY +// Can only define this after we define OUString +inline OUStringConstExpr::operator const OUString &() const { return OUString::unacquired(&pData); } +#endif + +#if defined LIBO_INTERNAL_ONLY +// Prevent the operator ==/!= overloads with 'sal_Unicode const *' parameter from +// being selected for nonsensical code like +// +// if (ouIdAttr == nullptr) +// +void operator ==(OUString const &, std::nullptr_t) = delete; +void operator ==(std::nullptr_t, OUString const &) = delete; +void operator !=(OUString const &, std::nullptr_t) = delete; +void operator !=(std::nullptr_t, OUString const &) = delete; +#endif + +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST +inline bool operator ==(OUString const & lhs, OUStringConcatenation const & rhs) +{ return lhs == std::u16string_view(rhs); } +inline bool operator !=(OUString const & lhs, OUStringConcatenation const & rhs) +{ return lhs != std::u16string_view(rhs); } +inline bool operator ==(OUStringConcatenation const & lhs, OUString const & rhs) +{ return std::u16string_view(lhs) == rhs; } +inline bool operator !=(OUStringConcatenation const & lhs, OUString const & rhs) +{ return std::u16string_view(lhs) != rhs; } +#endif + +#if defined LIBO_INTERNAL_ONLY // "RTL_FAST_STRING" +/// @cond INTERNAL + +/** + @internal +*/ +template<> +struct ToStringHelper< OUString > + { + static std::size_t length( const OUString& s ) { return s.getLength(); } + static sal_Unicode* addData( sal_Unicode* buffer, const OUString& s ) { return addDataHelper( buffer, s.getStr(), s.getLength()); } + static const bool allowOStringConcat = false; + static const bool allowOUStringConcat = true; + }; + +/** + @internal +*/ +template +struct ToStringHelper< OUStringLiteral > + { + static std::size_t length( const OUStringLiteral& str ) { return str.getLength(); } + static sal_Unicode* addData( sal_Unicode* buffer, const OUStringLiteral& str ) { return addDataHelper( buffer, str.getStr(), str.getLength() ); } + static const bool allowOStringConcat = false; + static const bool allowOUStringConcat = true; + }; + +/** + @internal +*/ +template< typename charT, typename traits, typename T1, typename T2 > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, OUStringConcat< T1, T2 >&& concat) +{ + return stream << OUString( std::move(concat) ); +} + + +/// @endcond +#endif + +/** A helper to use OUStrings with hash maps. + + Instances of this class are unary function objects that can be used as + hash function arguments to std::unordered_map and similar constructs. + */ +struct OUStringHash +{ + /** Compute a hash code for a string. + + @param rString + a string. + + @return + a hash code for the string. This hash code should not be stored + persistently, as its computation may change in later revisions. + */ + size_t operator()(const OUString& rString) const + { return static_cast(rString.hashCode()); } +}; + +/* ======================================================================= */ + +/** Convert an OString to an OUString, using a specific text encoding. + + The lengths of the two strings may differ (e.g., for double-byte + encodings, UTF-7, UTF-8). + + @param rStr + an OString to convert. + + @param encoding + the text encoding to use for conversion. + + @param convertFlags + flags which control the conversion. Either use + OSTRING_TO_OUSTRING_CVTFLAGS, or see + for more + details. + */ +#if defined LIBO_INTERNAL_ONLY +inline OUString OStringToOUString( std::string_view rStr, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OSTRING_TO_OUSTRING_CVTFLAGS ) +{ + return OUString( rStr.data(), rStr.length(), encoding, convertFlags ); +} +#else +inline OUString OStringToOUString( const OString & rStr, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OSTRING_TO_OUSTRING_CVTFLAGS ) +{ + return OUString( rStr.getStr(), rStr.getLength(), encoding, convertFlags ); +} +#endif + +/** Convert an OUString to an OString, using a specific text encoding. + + The lengths of the two strings may differ (e.g., for double-byte + encodings, UTF-7, UTF-8). + + @param rUnicode + an OUString to convert. + + @param encoding + the text encoding to use for conversion. + + @param convertFlags + flags which control the conversion. Either use + OUSTRING_TO_OSTRING_CVTFLAGS, or see + for more + details. + */ +#if defined LIBO_INTERNAL_ONLY +inline OString OUStringToOString( std::u16string_view rUnicode, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OUSTRING_TO_OSTRING_CVTFLAGS ) +{ + return OString( rUnicode.data(), rUnicode.length(), encoding, convertFlags ); +} +#else +inline OString OUStringToOString( const OUString & rUnicode, + rtl_TextEncoding encoding, + sal_uInt32 convertFlags = OUSTRING_TO_OSTRING_CVTFLAGS ) +{ + return OString( rUnicode.getStr(), rUnicode.getLength(), encoding, convertFlags ); +} +#endif + +/* ======================================================================= */ + +/** + Support for rtl::OUString in std::ostream (and thus in + CPPUNIT_ASSERT or SAL_INFO macros, for example). + + The rtl::OUString is converted to UTF-8. + + @since LibreOffice 3.5. +*/ +template< typename charT, typename traits > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, OUString const & rString) +{ + return stream << + OUStringToOString(rString, RTL_TEXTENCODING_UTF8); + // best effort; potentially loses data due to conversion failures + // (stray surrogate halves) and embedded null characters +} + +} // namespace + +#ifdef RTL_STRING_UNITTEST +namespace rtl +{ +typedef rtlunittest::OUString OUString; +} +#endif + +// In internal code, allow to use classes like OUString without having to +// explicitly refer to the rtl namespace, which is kind of superfluous given +// that OUString itself is namespaced by its OU prefix: +#if defined LIBO_INTERNAL_ONLY && !defined RTL_STRING_UNITTEST +using ::rtl::OUString; +using ::rtl::OUStringHash; +using ::rtl::OStringToOUString; +using ::rtl::OUStringToOString; +using ::rtl::OUStringLiteral; +using ::rtl::OUStringChar; +using ::rtl::OUStringConcatenation; +#endif + +/// @cond INTERNAL +/** + Make OUString hashable by default for use in STL containers. + + @since LibreOffice 6.0 +*/ +#if defined LIBO_INTERNAL_ONLY +namespace std { + +template<> +struct hash<::rtl::OUString> +{ + std::size_t operator()(::rtl::OUString const & s) const + { return std::size_t(s.hashCode()); } +}; + +} + +#endif +/// @endcond + +#endif /* _RTL_USTRING_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/rtl/uuid.h b/include/rtl/uuid.h new file mode 100644 index 000000000..e65c5e12b --- /dev/null +++ b/include/rtl/uuid.h @@ -0,0 +1,186 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ +#ifndef INCLUDED_RTL_UUID_H +#define INCLUDED_RTL_UUID_H + +#include "sal/config.h" + +#include "rtl/string.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +/** + @file + Specification (from draft-leach-uuids-guids-01.txt ) + +

    + A UUID is an identifier that is unique across both space and time, + with respect to the space of all UUIDs. To be precise, the UUID + consists of a finite bit space. Thus, collision cannot be avoided in + principle. A UUID can be used for multiple purposes, from tagging objects + with an extremely short lifetime, to reliably identifying very persistent + objects across a network. + +

    + The generation of UUIDs does not require that a registration + authority be contacted for each identifier. Instead, Version 4 UUIDs are + generated from (pseudo unique) sequences of (pseudo) random bits. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** Generates a new Version 4 (random number based) UUID (Universally Unique + IDentifier). + + @param pTargetUUID pointer to at least 16 bytes of memory. After the call it contains + the newly generated uuid in network byte order. + @param pPredecessorUUID ignored (was used when this function returned + Version 1 instead of Version 4 UUIDs). + @param bUseEthernetAddress ignored (was used when this function returned + Version 1 instead of Version 4 UUIDs). + */ +SAL_DLLPUBLIC void SAL_CALL rtl_createUuid( + sal_uInt8 *pTargetUUID, + const sal_uInt8 *pPredecessorUUID, + sal_Bool bUseEthernetAddress ); + +/** Compare two UUID's lexically + +

    + Note: lexical ordering is not temporal ordering! +

    + Note: For equalnesschecking, a memcmp(pUUID1,pUUID2,16) is more efficient + + @return +

      +
    • -1 u1 is lexically before u2 +
    • 0 u1 is equal to u2 +
    • 1 u1 is lexically after u2 +
    + + */ +SAL_DLLPUBLIC sal_Int32 SAL_CALL rtl_compareUuid( + const sal_uInt8 *pUUID1 , const sal_uInt8 *pUUID2 ); + +/** Creates named UUIDs. + +

    + The version 3 UUID is meant for generating UUIDs from names that + are drawn from, and unique within, some name space. Some examples + of names (and, implicitly, name spaces) might be DNS names, URLs, ISO + Object IDs (OIDs), reserved words in a programming language, or X.500 + Distinguished Names (DNs); thus, the concept of name and name space + should be broadly construed, and not limited to textual names. + +

    + The requirements for such UUIDs are as follows: + +

      +
    • The UUIDs generated at different times from the same name in the + same namespace MUST be equal + +
    • The UUIDs generated from two different names in the same namespace + should be different (with very high probability) + +
    • The UUIDs generated from the same name in two different namespaces + should be different with (very high probability) + +
    • If two UUIDs that were generated from names are equal, then they + were generated from the same name in the same namespace (with very + high probability). +
    + + @param pTargetUUID pointer to at least 16 bytes of memory. After the call + it contains the newly generated uuid in network byte order. + @param pNameSpaceUUID The namespace uuid. Below are some predefined ones, + but any arbitrary uuid can be used as namespace. + + @param pName the name + */ +SAL_DLLPUBLIC void SAL_CALL rtl_createNamedUuid( + sal_uInt8 *pTargetUUID, + const sal_uInt8 *pNameSpaceUUID, + const rtl_String *pName + ); + + + +/* + Predefined Namespaces + (Use them the following way : sal_uInt8 aNsDNS[16]) = RTL_UUID_NAMESPACE_DNS; + */ +/** namespace DNS + +

    + (Use them the following way : sal_uInt8 aNsDNS[16]) = RTL_UUID_NAMESPACE_DNS; +

    + 6ba7b810-9dad-11d1-80b4-00c04fd430c8 */ +#define RTL_UUID_NAMESPACE_DNS {\ + 0x6b,0xa7,0xb8,0x10,\ + 0x9d,0xad,\ + 0x11,0xd1,\ + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8\ + } + +/** namespace URL + +

    + 6ba7b811-9dad-11d1-80b4-00c04fd430c8 */ +#define RTL_UUID_NAMESPACE_URL { \ + 0x6b, 0xa7, 0xb8, 0x11,\ + 0x9d, 0xad,\ + 0x11, 0xd1,\ + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8\ + } + +/** namespace oid + +

    + 6ba7b812-9dad-11d1-80b4-00c04fd430c8 */ +#define RTL_UUID_NAMESPACE_OID {\ + 0x6b, 0xa7, 0xb8, 0x12,\ + 0x9d, 0xad,\ + 0x11, 0xd1,\ + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8\ + } + +/** namespace X500 + +

    + 6ba7b814-9dad-11d1-80b4-00c04fd430c8 */ +#define RTL_UUID_NAMESPACE_X500 {\ + 0x6b, 0xa7, 0xb8, 0x14,\ + 0x9d, 0xad,\ + 0x11, 0xd1,\ + 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8\ + } + +#ifdef __cplusplus +} +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/alloca.h b/include/sal/alloca.h new file mode 100644 index 000000000..ce6b60cc9 --- /dev/null +++ b/include/sal/alloca.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_ALLOCA_H +#define INCLUDED_SAL_ALLOCA_H + +#if defined(__sun) || defined(LINUX) || defined(AIX) || defined(ANDROID) || defined(HAIKU) \ + || defined(MACOSX) || defined(IOS) || defined(EMSCRIPTEN) + +#ifndef INCLUDED_ALLOCA_H +#include +#define INCLUDED_ALLOCA_H +#endif + +#elif defined(FREEBSD) || defined(NETBSD) || defined(OPENBSD) || defined(DRAGONFLY) + +#ifndef INCLUDED_STDLIB_H +#include +#define INCLUDED_STDLIB_H +#endif + +#elif defined(_WIN32) + +#ifndef INCLUDED_MALLOC_H +#include +#define INCLUDED_MALLOC_H +#endif + +#else + +#error "unknown platform: please check for alloca" + +#endif + +#endif /* INCLUDED_SAL_ALLOCA_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/backtrace.hxx b/include/sal/backtrace.hxx new file mode 100644 index 000000000..5f44e5e01 --- /dev/null +++ b/include/sal/backtrace.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SAL_BACKTRACE_HXX +#define INCLUDED_SAL_BACKTRACE_HXX + +#include "sal/config.h" +#include "sal/saldllapi.h" +#include "sal/types.h" +#include "rtl/ustring.hxx" +#include + +/// @cond INTERNAL +/** + Two stage API for recording and then later decoding stack backtraces. + Useful for debugging facilities where we are only interested in decoding + a small handful of recorded stack traces. + + @param backtraceDepth value indicating the maximum backtrace depth; must be > 0 + + @since LibreOffice 6.0 +*/ +#if defined LIBO_INTERNAL_ONLY + +namespace sal +{ +struct BacktraceState +{ + void** buffer; + int nDepth; + ~BacktraceState() { delete[] buffer; } +}; + +SAL_DLLPUBLIC std::unique_ptr backtrace_get(sal_uInt32 backtraceDepth); + +SAL_DLLPUBLIC OUString backtrace_to_string(BacktraceState* backtraceState); +} + +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/config.h b/include/sal/config.h new file mode 100644 index 000000000..bf5958519 --- /dev/null +++ b/include/sal/config.h @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_CONFIG_H +#define INCLUDED_SAL_CONFIG_H + +#if defined LIBO_INTERNAL_ONLY && defined ANDROID && defined __cplusplus +#include +#endif + +#ifdef _WIN32 +#define SAL_W32 +#define SAL_DLLEXTENSION ".dll" +#define SAL_EXEEXTENSION ".exe" +#define SAL_PATHSEPARATOR ';' +#define SAL_PATHDELIMITER '\\' +#define SAL_NEWLINE_STRING "\r\n" +#define SAL_CONFIGFILE(name) name ".ini" + +#ifdef _MSC_VER + +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES // needed by Visual C++ for math constants +#endif + +#endif /* defined _MSC_VER */ + +#endif /* defined _WIN32 */ + +#if defined(__sun) || defined(LINUX) || defined(NETBSD) || defined(FREEBSD) || defined(AIX) \ + || defined(OPENBSD) || defined(DRAGONFLY) || defined(ANDROID) || defined(HAIKU) +#define SAL_UNX +#define SAL_DLLEXTENSION ".so" +#define SAL_EXEEXTENSION "" +#define SAL_DLLPREFIX "lib" +#define SAL_PATHSEPARATOR ':' +#define SAL_PATHDELIMITER '/' +#define SAL_NEWLINE_STRING "\n" +#define SAL_CONFIGFILE(name) name "rc" +#endif + +#ifdef MACOSX +#define SAL_UNX +#define SAL_DLLEXTENSION ".dylib" +#define SAL_EXEEXTENSION "" +#define SAL_DLLPREFIX "lib" +#define SAL_PATHSEPARATOR ':' +#define SAL_PATHDELIMITER '/' +#define SAL_NEWLINE_STRING "\n" +#define SAL_CONFIGFILE(name) name "rc" +#endif + +#ifdef IOS +#define SAL_UNX +/* SAL_DLLEXTENSION should not really be used on iOS, as iOS apps are + * not allowed to load own dynamic libraries. + */ +#define SAL_DLLEXTENSION ".dylib" +#define SAL_DLLPREFIX "lib" +#define SAL_PATHSEPARATOR ':' +#define SAL_PATHDELIMITER '/' +#define SAL_NEWLINE_STRING "\n" +#define SAL_CONFIGFILE(name) name "rc" +#endif + +#ifdef EMSCRIPTEN +#define SAL_UNX +#define SAL_DLLEXTENSION ".bc" +#define SAL_EXEEXTENSION "" +#define SAL_DLLPREFIX "lib" +#define SAL_PATHSEPARATOR ':' +#define SAL_PATHDELIMITER '/' +#define SAL_NEWLINE_STRING "\n" +#define SAL_CONFIGFILE(name) name "rc" +#endif + +/* The following spell is for Solaris and its descendants. + * See the "Solaris" section of + * , and + * . + */ +#ifdef sun +#undef sun +#define sun sun +#endif + +#if defined __clang__ +#if __has_warning("-Wpotentially-evaluated-expression") +#pragma GCC diagnostic ignored "-Wpotentially-evaluated-expression" +#endif +// Before fixing occurrences of this warning, lets see whether C++20 will still change to obsolete +// the warning (see +// "[c++20] +// Add rewriting from comparison operators to <=> / =="): +#if __has_warning("-Wambiguous-reversed-operator") +#pragma GCC diagnostic ignored "-Wambiguous-reversed-operator" +#endif +#endif + +#endif // INCLUDED_SAL_CONFIG_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/detail/log.h b/include/sal/detail/log.h new file mode 100644 index 000000000..f68512d16 --- /dev/null +++ b/include/sal/detail/log.h @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_DETAIL_LOG_H +#define INCLUDED_SAL_DETAIL_LOG_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +/** @cond INTERNAL */ + +/* This header makes available replacements working in both C and C++ for the + obsolete osl/diagnose.h functionality that in turn is used from both C and + C++ code and the obsolete tools/debug.hxx functionality that uses printf-style + formatting. Once that obsolete functionality is removed, this header can be + removed, too. + + This header uses variadic macros in both C (where they are officially only + supported since C99) and C++ (where they are officially only supported since + C++11). It appears that all relevant compilers (esp. GCC 4.0 and MS VS 2008 + Express) already support them in their C and C++ dialects. See also + . + + Avoid the use of other sal code in this header as much as possible, so that + this code can be called from other sal code without causing endless + recursion. +*/ + +#if defined __cplusplus +extern "C" { +#endif + +/* + Clang warns about 'sal_True && sal_True' (those being integers and not booleans) + when it sees preprocessed source (-save-temps or using icecream) +*/ +#if defined __cplusplus +#define SAL_LOG_TRUE true +#define SAL_LOG_FALSE false +#else +#define SAL_LOG_TRUE sal_True +#define SAL_LOG_FALSE sal_False +#endif + +enum sal_detail_LogLevel { + SAL_DETAIL_LOG_LEVEL_INFO, SAL_DETAIL_LOG_LEVEL_WARN, + SAL_DETAIL_LOG_LEVEL_DEBUG = SAL_MAX_ENUM +}; + +SAL_DLLPUBLIC void SAL_CALL sal_detail_logFormat( + enum sal_detail_LogLevel level, char const * area, char const * where, + char const * format, ...) +#if defined __GNUC__ + __attribute__((format(printf, 4, 5))) +#endif + ; + +#if defined __cplusplus +} +#endif + +#define SAL_DETAIL_LOG_FORMAT(condition, level, area, where, ...) \ + do { \ + if (condition) { \ + sal_detail_logFormat((level), (area), (where), __VA_ARGS__); \ + } \ + } while (SAL_LOG_FALSE) + +#if defined SAL_LOG_INFO +#define SAL_DETAIL_ENABLE_LOG_INFO SAL_LOG_TRUE +#else +#define SAL_DETAIL_ENABLE_LOG_INFO SAL_LOG_FALSE +#endif +#if defined SAL_LOG_WARN +#define SAL_DETAIL_ENABLE_LOG_WARN SAL_LOG_TRUE +#else +#define SAL_DETAIL_ENABLE_LOG_WARN SAL_LOG_FALSE +#endif + +#define SAL_DETAIL_WHERE __FILE__ ":" SAL_STRINGIFY(__LINE__) ": " + +#define SAL_DETAIL_INFO_IF_FORMAT(condition, area, ...) \ + SAL_DETAIL_LOG_FORMAT( \ + SAL_DETAIL_ENABLE_LOG_INFO && (condition), SAL_DETAIL_LOG_LEVEL_INFO, \ + area, SAL_DETAIL_WHERE, __VA_ARGS__) + +#define SAL_DETAIL_WARN_IF_FORMAT(condition, area, ...) \ + SAL_DETAIL_LOG_FORMAT( \ + SAL_DETAIL_ENABLE_LOG_WARN && (condition), SAL_DETAIL_LOG_LEVEL_WARN, \ + area, SAL_DETAIL_WHERE, __VA_ARGS__) + +/** @endcond */ + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/log-areas.dox b/include/sal/log-areas.dox new file mode 100644 index 000000000..b365b20e1 --- /dev/null +++ b/include/sal/log-areas.dox @@ -0,0 +1,654 @@ +// NOTE: This file is also parsed by a compiler plugin. Make sure all +// areas are marked with '@li @c'. + +/** +@page sal_log_areas SAL debug areas + +@short List and description of areas for the SAL debug macros + +This is a list of areas that are used by the SAL_INFO family of macros. See +@ref sal_log "basic log functionality" for details about this functionality. + +If you need a debug area in some code, first check this list and use the +appropriate area if it exists. This list is not definite, if you need a new +area, use it and add it to an appropriate section with an explanation. +Generally, use the name of the relevant code module as the first area segment. +Please keep all entries sorted. + +This list should give you an overview of which areas to enable when debugging +certain functionality. + +@section SAL + +@li @c sal.bootstrap - SAL bootstrap +@li @c sal.cppunittester +@li @c sal.debug - SAL debugging functionality +@li @c sal.file - file system operations +@li @c sal.fileio - file I/O +@li @c sal.osl - SAL OSL library +@li @c sal.osl.condition +@li @c sal.osl.mutex +@li @c sal.osl.pipe +@li @c sal.rtl - SAL RTL library +@li @c sal.textenc - the textencoding SAL library + +@section basctl + +@li @c basctl +@li @c basctl.basicide + +@section basic + +@li @c basic +@li @c basic.sbx + +@section bridges + +@li @c bridges +@li @c bridges.ios +@li @c bridges.osx + +@section canvas + +@li @c canvas +@li @c canvas.cairo +@li @c canvas.directx +@li @c canvas.null +@li @c canvas.ogl +@li @c canvas.vcl + +@section chart2 + +@li @c chart2 +@li @c chart2.accessibility +@li @c chart2.areachart +@li @c chart2.main +@li @c chart2.pie.label.bestfit +@li @c chart2.pie.label.bestfit.inside +@li @c chart2.template +@li @c chart2.tools + +@section connectivity + +@li @c connectivity.ado +@li @c connectivity.commontools +@li @c connectivity.cpool +@li @c connectivity.dbase +@li @c connectivity.drivers - a bit overly general, maybe it should be removed? +@li @c connectivity.evoab2 +@li @c connectivity.firebird +@li @c connectivity.flat +@li @c connectivity.hsqldb +@li @c connectivity.jdbc +@li @c connectivity.kab +@li @c connectivity.macab +@li @c connectivity.manager +@li @c connectivity.mozab +@li @c connectivity.mysqlc +@li @c connectivity.odbc +@li @c connectivity.parse +@li @c connectivity.postgresql +@li @c connectivity.resource +@li @c connectivity.writer + +@section comphelper + +@li @c comphelper +@li @c comphelper.backupfilehelper +@li @c comphelper.container - EmbeddedObjectContainer +@li @c comphelper.crypto +@li @c comphelper.lok +@li @c comphelper.traceevent + +@section cppu + +@li @c cppu +@li @c cppu.affinebridge +@li @c cppu.log +@li @c cppu.purpenv +@li @c cppu.threadpool +@li @c cppu.typelib +@li @c cppu.unsafebridge + +@section cppuhelper + +@li @c cppuhelper +@li @c cppuhelper.shlib + +@section cpputools + +@li @c cpputools +@li @c cpputools.unoexe + +@section cui + +@li @c cui.customize +@li @c cui.customnotebookbar +@li @c cui.dialogs +@li @c cui.factory +@li @c cui.options +@li @c cui.tabpages + +@section drawinglayer + +@li @c drawinglayer +@li @c drawinglayer.emf + +@section emfio + +@li @c emfio - EMF and VMF image file formats import module + +@section Calc + +@li @c sc +@li @c sc.core +@li @c sc.core.formulacell - ScFormulaCell and group +@li @c sc.core.formulagroup +@li @c sc.core.grouparealistener - sc::FormulaGroupAreaListener +@li @c sc.filter - Calc filter +@li @c sc.lok.docsize +@li @c sc.lok.header +@li @c sc.lok.poshelper +@li @c sc.opencl - OpenCL-related stuff in general +@li @c sc.opencl.source - Generated OpenCL source code +@li @c sc.orcus +@li @c sc.orcus.autofilter +@li @c sc.orcus.condformat +@li @c sc.orcus.style +@li @c sc.orcus.table +@li @c sc.qa +@li @c sc.threaded +@li @c sc.timing +@li @c sc.ui - Calc UI +@li @c sc.uitest - Calc UI Test part +@li @c sc.viewdata + +@section desktop + +@li @c desktop +@li @c desktop.app +@li @c desktop.deployment +@li @c desktop.lib +@li @c desktop.migration +@li @c desktop.offacc +@li @c desktop.splash +@li @c desktop.test +@li @c desktop.updater + +@section Draw + +@li @c sd +@li @c sd.core +@li @c sd.eppt +@li @c sd.filter +@li @c sd.fwk +@li @c sd.slideshow +@li @c sd.sls - slidesorter +@li @c sd.tools +@li @c sd.transitions +@li @c sd.ui +@li @c sd.view +@li @c sdremote +@li @c sdremote.bluetooth +@li @c sdremote.wifi + +@section editeng + +@li @c editeng +@li @c editeng.chaining +@li @c editeng.items + +@section embeddedobj + +@li @c embeddedobj - embedded objects +@li @c embeddedobj.common +@li @c embeddedobj.general +@li @c embeddedobj.ole - OLE embedded objects + +@section embedserv +@li @c embedserv - embedding server +@li @c embedserv.ole - OLE server + +@section extensions + +@li @c extensions.abpilot +@li @c extensions.biblio +@li @c extensions.config +@li @c extensions.dbpilots +@li @c extensions.evoab +@li @c extensions.logging +@li @c extensions.olebridge - OLE automation bridge +@li @c extensions.plugin +@li @c extensions.propctrlr +@li @c extensions.scanner +@li @c extensions.update + +@section Filter + +@li @c filter.config +@li @c filter.eps +@li @c filter.hwp - Hangul word processor import +@li @c filter.icgm +@li @c filter.ms - escher import/export +@li @c filter.odfflatxml +@li @c filter.os2met +@li @c filter.pdf +@li @c filter.pict +@li @c filter.psd +@li @c filter.ras +@li @c filter.svg +@li @c filter.tga +@li @c filter.tiff +@li @c filter.xmlfa +@li @c filter.xmlfd +@li @c filter.xslt - xslt import/export + +@section oox + +@li @c oox +@li @c oox.chart +@li @c oox.cscode - see oox/source/drawingml/customshapes/README +@li @c oox.csdata - see oox/source/drawingml/customshapes/README +@li @c oox.drawingml - DrawingML +@li @c oox.drawingml.gradient +@li @c oox.ppt - pptx filter +@li @c oox.shape +@li @c oox.storage - ZipStorage class +@li @c oox.vml - VML +@li @c oox.xmlstream - XmlStream class + +@section forms + +@li @c forms.component +@li @c forms.helper +@li @c forms.misc +@li @c forms.richtext +@li @c forms.runtime +@li @c forms.xforms + +@section formula + +@li @c formula.core +@li @c formula.ui + +@section fpicker + +@li @c fpicker +@li @c fpicker.aqua +@li @c fpicker.office + +@section framework + +@li @c fwk - framework (abbreviation) +@li @c fwk.accelerators +@li @c fwk.autorecovery +@li @c fwk.desktop +@li @c fwk.dispatch +@li @c fwk.frame +@li @c fwk.joburl +@li @c fwk.loadenv +@li @c fwk.session +@li @c fwk.session.debug +@li @c fwk.uiconfiguration +@li @c fwk.uielement + +@section i18nlangtag + +@li @c i18nlangtag - language tags + +@section i18npool + +@li @c i18npool - general i18npool + +@section i18n + +@li @c i18n - module independent i18n related, e.g. language tag usage + +@section io + +@li @c io.connector +@li @c io.streams + +@section jvmfwk + +@li @c jfw +@li @c jfw.level1 +@li @c jfw.level2 + +@section LibreOfficeKit + +@li @c lok +@li @c lok.tiledrendering +@li @c lok.dialog + +@section l10ntools + +@li @c l10ntools + +@section Math + +@li @c starmath +@li @c starmath.ooxml - OOXML import/export +@li @c starmath.rtf +@li @c starmath.wordbase + +@section package + +@li @c package +@li @c package.xstor +@li @c package.threadeddeflate + +@section sdext + +@li @c sdext +@li @c sdext.minimizer +@li @c sdext.pdfimport +@li @c sdext.pdfimport.pdfparse +@li @c sdext.presenter + +@section sfx + +@li @c sfx +@li @c sfx.appl +@li @c sfx.bastyp +@li @c sfx.config +@li @c sfx.control +@li @c sfx.dialog +@li @c sfx.doc +@li @c sfx.notify +@li @c sfx.sidebar +@li @c sfx.view + +@section slideshow + +@li @c slideshow +@li @c slideshow.eventqueue +@li @c slideshow.opengl +@li @c slideshow.verbose + +@section sot + +@li @c sot - COM structured storage + +@section svl + +@li @c svl +@li @c svl.crypto +@li @c svl.items +@li @c svl.numbers + +@section svtools + +@li @c svtools +@li @c svtools.config +@li @c svtools.contnr +@li @c svtools.control +@li @c svtools.dialogs +@li @c svtools.misc +@li @c svtools.table +@li @c svtools.uno + +@section svx + +@li @c svx +@li @c svx.chaining +@li @c svx.diagram - Diagram ModelData +@li @c svx.dialog +@li @c svx.fmcomp +@li @c svx.form +@li @c svx.sdr +@li @c svx.sidebar +@li @c svx.stbcrtls - StatusBarControl +@li @c svx.svdraw +@li @c svx.table +@li @c svx.tbxcrtls - ToolboxControl +@li @c svx.uno + +@section toolkit + +@li @c toolkit +@li @c toolkit.controls +@li @c toolkit.helper + +@section tools + +@li @c tools +@li @c tools.datetime +@li @c tools.debug +@li @c tools.fraction +@li @c tools.generic +@li @c tools.memtools +@li @c tools.rc - resource manager +@li @c tools.stream - SvStream class +@li @c tools.urlobj - INetURLObject class + +@section ucb + +@li @c ucb +@li @c ucb.core +@li @c ucb.ucp +@li @c ucb.ucp.cmis +@li @c ucb.ucp.ext +@li @c ucb.ucp.file +@li @c ucb.ucp.ftp +@li @c ucb.ucp.gio +@li @c ucb.ucp.webdav +@li @c ucb.ucp.webdav.curl + +@section unotools + +@li @c unotools +@li @c unotools.config +@li @c unotools.i18n +@li @c unotools.misc +@li @c unotools.ucbhelper + +@section URE + +@li @c rtl.string - ::rtl::OString, ::rtl::OUString, and related functionality +@li @c salhelper.thread - ::salhelper::Thread class + +@section sax + +@li @c sax.cppunit +@li @c sax.fastparser + +@section stoc + +@li @c stoc.corerefl - CoreReflection +@li @c stoc.java - javaloader and javavm + +@section VCL + +@li @c vcl +@li @c vcl.a11y +@li @c vcl.app +@li @c vcl.builder +@li @c vcl.control +@li @c vcl.ct - CoreText-using code for macOS and iOS +@li @c vcl.debugevent +@li @c vcl.driver Graphics driver handling +@li @c vcl.emf - EMF/EMF+ processing +@li @c vcl.eventtesting +@li @c vcl.filter +@li @c vcl.filter.webp +@li @c vcl.fonts - font-specific code +@li @c vcl.fonts.detail +@li @c vcl.gdi - the GDI part of VCL, devices, bitmaps, etc. +@li @c vcl.gdi.wndproc - Windows Procedure part of VCL +@li @c vcl.gdi.fontmetric +@li @c vcl.gtk - Gtk+ 2/3 plugin +@li @c vcl.gtk3 +@li @c vcl.gtkkde5 +@li @c vcl.harfbuzz - HarfBuzz text layout +@li @c vcl.headless - bitmap-based backend +@li @c vcl.helper +@li @c vcl.icontest +@li @c vcl.ios.clipboard +@li @c vcl.kf5 - KF5 +@li @c vcl.layout - Widget layout +@li @c vcl.lazydelete +@li @c vcl.opengl +@li @c vcl.opengl.qt - Qt OpenGL +@li @c vcl.osx +@li @c vcl.osx.clipboard +@li @c vcl.osx.print +@li @c vcl.pdfwriter +@li @c vcl.print +@li @c vcl.plugadapt - the Unix/X11 backend plugin mechanism +@li @c vcl.qt - Qt +@li @c vcl.quartz +@li @c vcl.schedule - scheduler / main-loop information +@li @c vcl.schedule.deinit +@li @c vcl.screensaverinhibitor +@li @c vcl.scrollbar - Scroll Bars +@li @c vcl.se - VCL Session Manager +@li @c vcl.se.debug +@li @c vcl.skia - VCL Skia-based code +@li @c vcl.skia.trace - tracing drawing in VCL Skia-based code +@li @c vcl.sm - Session Manager Client +@li @c vcl.sm.debug +@li @c vcl.uitest - The UI testing framework code +@li @c vcl.unity +@li @c vcl.unx.dtrans +@li @c vcl.unx.freetype +@li @c vcl.unx.print +@li @c vcl.virdev +@li @c vcl.watchdog +@li @c vcl.window +@li @c vcl.win.dtrans + +@section winaccessibility + +@li @c iacc2 - IAccessible2 bridge debug + +@section Writer + +@li @c sw +@li @c sw.a11y - accessibility +@li @c sw.calc - formula calculation +@li @c sw.core - Writer core +@li @c sw.createcopy +@li @c sw.doc +@li @c sw.docappend +@li @c sw.docx +@li @c sw.envelp +@li @c sw.filter +@li @c sw.html - Writer HTML import/export +@li @c sw.idle +@li @c sw.layout - Writer core view: document layout +@li @c sw.layout.debug - Writer layout dbg_lay output +@li @c sw.mailmerge - Writer mail merge +@li @c sw.pageframe - debug lifecycle of SwPageFrame +@li @c sw.rtf - .rtf export filter +@li @c sw.tiled +@li @c sw.ui +@li @c sw.uno - Writer UNO interfaces +@li @c sw.vba - Writer VBA +@li @c sw.ww8 - .doc/.docx export filter, .doc import filter (not writerfilter) +@li @c sw.ww8.level2 - further info for sw.ww8 +@li @c sw.xml - Writer .odt import/export + +@section writerfilter + +@li @c writerfilter +@li @c writerfilter.dmapper +@li @c writerfilter.ooxml +@li @c writerfilter.profile - load times of filters +@li @c writerfilter.rtf + +@section writerperfect + +@li @c writerperfect + +@section xmloff + +@li @c xmloff +@li @c xmloff.chart +@li @c xmloff.core +@li @c xmloff.draw +@li @c xmloff.forms +@li @c xmloff.style +@li @c xmloff.table +@li @c xmloff.text +@li @c xmloff.transform + +@section xmlsecurity + +@li @c xmlsecurity.comp - xml security component +@li @c xmlsecurity.dialogs - xml security dialogs +@li @c xmlsecurity.helper +@li @c xmlsecurity.ooxml - OOXML signature support +@li @c xmlsecurity.qa +@li @c xmlsecurity.workben +@li @c xmlsecurity.xmlsec - xmlsec wrapper +@li @c xmlsecurity.xmlsec.gpg - gpg xmlsec component + +@section xmlscript + +@li @c xmlscript.xmldlg +@li @c xmlscript.xmlflat +@li @c xmlscript.xmlhelper +@li @c xmlscript.xmllib +@li @c xmlscript.xmlmod + +@section dbaccess + +@li @c dbaccess +@li @c dbaccess.core +@li @c dbaccess.ui +@li @c dbaccess.ui.generalpage + +@section avmedia + +@li @c avmedia +@li @c avmedia.gstreamer +@li @c avmedia.gtk +@li @c avmedia.quicktime + +@section other + +@li @c accessibility +@li @c animations +@li @c basegfx +@li @c binaryurp +@li @c cli +@li @c configmgr +@li @c configmgr.dconf +@li @c cppcanvas +@li @c cppcanvas.emf +@li @c helpcompiler +@li @c idl +@li @c javaunohelper +@li @c jvmaccess +@li @c lingucomponent +@li @c linguistic +@li @c lwp - lotuswordpro +@li @c opencl +@li @c opencl.device +@li @c opencl.file +@li @c registry +@li @c reportdesign +@li @c rsc +@li @c sax +@li @c scripting +@li @c scripting.provider +@li @c shell +@li @c shell.jumplist +@li @c stoc +@li @c store +@li @c svg +@li @c svgio +@li @c test +@li @c ucbhelper +@li @c unodevtools +@li @c unoidl +@li @c unoxml +@li @c uui +@li @c vbahelper +@li @c wasm +@li @c xmlhelp +@li @c xmlreader + +*/ +/* vim:set ft=cpp shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/log.hxx b/include/sal/log.hxx new file mode 100644 index 000000000..5faeec311 --- /dev/null +++ b/include/sal/log.hxx @@ -0,0 +1,436 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_LOG_HXX +#define INCLUDED_SAL_LOG_HXX + +#include "sal/config.h" + +#include +#include +#include + +#include "sal/detail/log.h" +#include "sal/saldllapi.h" +#include "sal/types.h" + +// Avoid the use of other sal code in this header as much as possible, so that +// this code can be called from other sal code without causing endless +// recursion. + +/// @cond INTERNAL + +enum sal_detail_LogAction +{ + SAL_DETAIL_LOG_ACTION_IGNORE, + SAL_DETAIL_LOG_ACTION_LOG, + SAL_DETAIL_LOG_ACTION_FATAL +}; + +extern "C" SAL_DLLPUBLIC void SAL_CALL sal_detail_log( + sal_detail_LogLevel level, char const * area, char const * where, + char const * message, sal_uInt32 backtraceDepth); + +extern "C" SAL_DLLPUBLIC void SAL_CALL sal_detail_set_log_selector(char const *logSelector); + +// the return value is actually "enum sal_detail_LogAction", but due to ABI +// compatibility, it's left as the original "sal_Bool" / "unsigned char". +extern "C" SAL_DLLPUBLIC unsigned char SAL_CALL sal_detail_log_report( + sal_detail_LogLevel level, char const * area); + +namespace sal { namespace detail { + +inline void log( + sal_detail_LogLevel level, char const * area, char const * where, + std::ostringstream const & stream, sal_uInt32 backtraceDepth) +{ + // An alternative would be to have sal_detail_log take a std::ostringstream + // pointer (via a C void pointer); the advantage would be smaller client + // code (the ".str().c_str()" part would move into the implementation of + // sal_detail_log) and potential for proper support of embedded null + // characters within the message, but the disadvantage would be dependence + // on the C++ ABI; as a compromise, the ".str().c_str()" part has been moved + // to this inline function so that it is potentially only emitted once per + // dynamic library: + sal_detail_log(level, area, where, stream.str().c_str(), backtraceDepth); +} + +// Special handling of the common case where the message consists of just a +// string literal, to produce smaller call-site code: + +struct StreamStart {}; + +struct StreamString { + StreamString(char const * s): string(s) {} + + char const * string; + + typedef char Result; +}; + +struct StreamIgnore { + typedef struct { char a[2]; } Result; +}; + +inline StreamString operator <<( + SAL_UNUSED_PARAMETER StreamStart const &, char const * s) +{ + return StreamString(s); +} + +template< typename T > inline StreamIgnore operator <<( + SAL_UNUSED_PARAMETER StreamStart const &, SAL_UNUSED_PARAMETER T const &) +{ + std::abort(); +#if defined _MSC_VER && _MSC_VER < 1700 + return StreamIgnore(); +#endif +} + +template< typename T > inline StreamIgnore operator <<( + SAL_UNUSED_PARAMETER StreamString const &, SAL_UNUSED_PARAMETER T const &) +{ + std::abort(); +#if defined _MSC_VER && _MSC_VER < 1700 + return StreamIgnore(); +#endif +} + +template< typename T > inline StreamIgnore operator <<( + SAL_UNUSED_PARAMETER StreamIgnore const &, SAL_UNUSED_PARAMETER T const &) +{ + std::abort(); +#if defined _MSC_VER && _MSC_VER < 1700 + return StreamIgnore(); +#endif +} + +template< typename T > typename T::Result getResult(T const &); + +inline char const * unwrapStream(StreamString const & s) { return s.string; } + +inline char const * unwrapStream(SAL_UNUSED_PARAMETER StreamIgnore const &) { + std::abort(); +#if defined _MSC_VER && _MSC_VER < 1700 + return 0; +#endif +} + +} } + +// to prevent using a local variable, which can eventually shadow, +// resulting in compiler warnings (or even errors with -Werror) +#define SAL_DETAIL_LOG_STREAM_PRIVATE_(level, area, where, stream) \ + if (sizeof ::sal::detail::getResult( \ + ::sal::detail::StreamStart() << stream) == 1) \ + { \ + ::sal_detail_log( \ + (level), (area), (where), \ + ::sal::detail::unwrapStream( \ + ::sal::detail::StreamStart() << stream), \ + 0); \ + } else { \ + ::std::ostringstream sal_detail_stream; \ + sal_detail_stream << stream; \ + ::sal::detail::log( \ + (level), (area), (where), sal_detail_stream, 0); \ + } + +#define SAL_DETAIL_LOG_STREAM(condition, level, area, where, stream) \ + do { \ + if (condition) \ + { \ + switch (sal_detail_log_report(level, area)) \ + { \ + case SAL_DETAIL_LOG_ACTION_IGNORE: break; \ + case SAL_DETAIL_LOG_ACTION_LOG: \ + SAL_DETAIL_LOG_STREAM_PRIVATE_(level, area, where, stream); \ + break; \ + case SAL_DETAIL_LOG_ACTION_FATAL: \ + SAL_DETAIL_LOG_STREAM_PRIVATE_(level, area, where, stream); \ + std::abort(); \ + break; \ + } \ + } \ + } while (false) + +/// @endcond + +/** A simple macro to create a "file and line number" string. + + Potentially not only useful within the log framework (where it is used + automatically), but also when creating exception messages. + + @attention For now, this functionality should only be used internally within + LibreOffice. It may change again in a future version. + + @since LibreOffice 3.5 +*/ +#define SAL_WHERE SAL_DETAIL_WHERE + +/** A facility for generating temporary string messages by piping items into a + C++ std::ostringstream. + + This can be useful for example in a call to SAL_INFO when depending on some + boolean condition data of incompatible types shall be streamed into the + message, as in: + + SAL_INFO("foo", "object: " << (hasName ? obj->name : SAL_STREAM(obj))); + + @attention For now, this functionality should only be used internally within + LibreOffice. It may change again in a future version. + + @since LibreOffice 3.5 +*/ +#if defined _LIBCPP_VERSION \ + || (defined _GLIBCXX_RELEASE \ + && (_GLIBCXX_RELEASE >= 12 || (_GLIBCXX_RELEASE == 11 && __GLIBCXX__ > 20210428))) \ + || (defined _MSC_VER && _MSC_VER >= 1915) +#define SAL_STREAM(stream) \ + (::std::ostringstream() << stream).str() +#else +#define SAL_STREAM(stream) \ + (dynamic_cast< ::std::ostringstream & >(::std::ostringstream() << stream).str()) +#endif + +/** + @page sal_log Basic logging functionality. + + @short Macros for logging. + + SAL_INFO(char const * area, expr), + SAL_INFO_IF(bool condition, char const * area, expr), + SAL_WARN(char const * area, expr), + SAL_WARN_IF(bool condition, char const * area, expr), and SAL_DEBUG(expr) + produce an info, warning, or debug log entry with a message produced by + piping items into a C++ std::ostringstream. The given expr must be so that + the full expression "stream << expr" is valid, where stream is a variable of + type std::ostringstream. + + SAL_INFO("foo", "string " << s << " of length " << n) + + would be an example of such a call. + + The composed message should be in UTF-8 and it should contain no vertical + formatting characters and no null characters + + For the _IF variants, log output is only generated if the given condition is + true (in addition to the other conditions that have to be met). + + The SAL_DEBUG macro is for temporary debug statements that are used while + working on code. It is never meant to remain in the code. It will always + simply output the given expression in debug builds. + + For all the other macros, the given area argument must be non-null and must + match the regular expression + + @verbatim + ::= (".")* + @endverbatim + + with + + @verbatim + ::= [0-9a-z]+ + @endverbatim + + For a list of areas used see @ref sal_log_areas "SAL debug areas". Whenever + you use a new log area, add it to the file include/sal/log-areas.dox . + + Whether these macros generate any log output is controlled in a two-stage + process. + + First, at compile time the macros SAL_LOG_INFO and SAL_LOG_WARN, + respectively, control whether the INFO and WARN macros, respectively, + expand to actual code (in case the macro is defined, to any value) or to + no-ops (in case the macro is not defined). + + Second, at runtime the environment variable SAL_LOG further limits which + macro calls actually generate log output. The environment variable SAL_LOG + must either be unset or must match the regular expression + + @verbatim + ::= * + @endverbatim + + with + + @verbatim + ::= + ::= "+"|"-" + ::= |(".")? + ::= "TIMESTAMP"|"RELATIVETIMER"|"FATAL" + ::= "INFO"|"WARN" + @endverbatim + + If the environment variable is unset, the setting "+WARN" is + assumed instead (which results in all warnings being output but no + infos). If the given value does not match the regular expression, + "+INFO+WARN" is used instead (which in turn results in everything + being output). + + The "+TIMESTAMP" flag causes each output line (as selected by the level + switch(es)) to be prefixed by a timestamp like 2016-08-18:14:04:43. + + The "+RELATIVETIMER" flag causes each output line (as selected by + the level switch(es)) to be prefixed by a relative timestamp in + seconds since the first output line like 1.312. + + The "+FATAL" flag will cause later matching rules to log and call + std::abort. This can be disabled at some later point by using the + "-FATAL" flag before specifying additional rules. The flag will just + abort on positive rules, as it doesn't seem to make sense to abort + on ignored output. + + If both +TIMESTAMP and +RELATIVETIMER are specified, they are + output in that order. + + Specifying a flag with a negative sense has no effect. Specifying + the same flag multiple times has no extra effect. + + A given macro call's level (INFO or WARN) and area is matched against the + given switches as follows: Only those switches for which the level matches + the given level and for which the area is a prefix (including both empty and + full prefixes) of the given area are considered. Log output is generated if + and only if among the longest such switches (if any), there is at least one + that has a sense of "+". (That is, if both +INFO.foo and -INFO.foo are + present, +INFO.foo wins.) + + If no WARN selection is specified, but an INFO selection is, the + INFO selection is used for WARN messages, too. + + For example, if SAL_LOG is "+INFO-INFO.foo+INFO.foo.bar", then calls like + SAL_INFO("foo.bar", ...), SAL_INFO("foo.bar.baz", ...), or + SAL_INFO("other", ...) generate output, while calls like + SAL_INFO("foo", ...) or SAL_INFO("foo.barzzz", ...) do not. + + The generated log output consists of the optional timestamp, the given level + ("info" or "warn"), the given area, the process ID, the thread ID, the + source file, and the source line number, each followed by a colon, followed + by a space, the given message, and a newline. The precise format of the log + output is subject to change. The log output is printed to stderr without + further text encoding conversion. + + On some systems, log output can be redirected to other log sinks, + notably a file provided as a system path and filename via + environment variable SAL_LOG_FILE; or to a syslog facility if + LibreOffice is suitably built, by setting environment variable + SAL_LOG_SYSLOG. + + @see @ref sal_log_areas + + @attention For now, this functionality should only be used internally within + LibreOffice. It may change again in a future version. + + @since LibreOffice 3.5 +*/ + +/** + Produce log entry from stream in the given log area. + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_INFO(area, stream) \ + SAL_DETAIL_LOG_STREAM( \ + SAL_DETAIL_ENABLE_LOG_INFO, ::SAL_DETAIL_LOG_LEVEL_INFO, area, \ + SAL_WHERE, stream) + +/** + Produce log entry from stream in the given log area if condition is true. + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_INFO_IF(condition, area, stream) \ + SAL_DETAIL_LOG_STREAM( \ + SAL_DETAIL_ENABLE_LOG_INFO && (condition), \ + ::SAL_DETAIL_LOG_LEVEL_INFO, area, SAL_WHERE, stream) + +/** + Produce warning entry from stream in the given log area. + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_WARN(area, stream) \ + SAL_DETAIL_LOG_STREAM( \ + SAL_DETAIL_ENABLE_LOG_WARN, ::SAL_DETAIL_LOG_LEVEL_WARN, area, \ + SAL_WHERE, stream) + +/** + Produce warning entry from stream in the given log area if condition is true. + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_WARN_IF(condition, area, stream) \ + SAL_DETAIL_LOG_STREAM( \ + SAL_DETAIL_ENABLE_LOG_WARN && (condition), \ + ::SAL_DETAIL_LOG_LEVEL_WARN, area, SAL_WHERE, stream) + +/** + Produce temporary debugging output from stream. This macro is meant to be + used only while working on code and should never exist in production code. + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_DEBUG(stream) \ + SAL_DETAIL_LOG_STREAM( \ + SAL_LOG_TRUE, ::SAL_DETAIL_LOG_LEVEL_DEBUG, NULL, NULL, stream) + +/** + Produce temporary debugging output from stream, if condition is true. This + macro is meant to be used only while working on code and should never exist + in production code. + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_DEBUG_IF(condition, stream) \ + SAL_DETAIL_LOG_STREAM( \ + (condition), ::SAL_DETAIL_LOG_LEVEL_DEBUG, NULL, NULL, stream) + +/** + Produce temporary debugging output from stream along with a backtrace of the + calling location. + + This macro is meant to be used only while working on code and should never + exist in production code. + + @param stream input stream + + @param backtraceDepth a sal_uInt32 value indicating the maximum backtrace + depth; zero means no backtrace + + See @ref sal_log "basic logging functionality" for details. +*/ +#define SAL_DEBUG_BACKTRACE(stream, backtraceDepth) \ + do { \ + if (sizeof ::sal::detail::getResult( \ + ::sal::detail::StreamStart() << stream) == 1) \ + { \ + ::sal_detail_log( \ + ::SAL_DETAIL_LOG_LEVEL_DEBUG, NULL, NULL, \ + ::sal::detail::unwrapStream( \ + ::sal::detail::StreamStart() << stream), \ + backtraceDepth); \ + } else { \ + ::std::ostringstream sal_detail_stream; \ + sal_detail_stream << stream; \ + ::sal::detail::log( \ + ::SAL_DETAIL_LOG_LEVEL_DEBUG, NULL, NULL, sal_detail_stream, \ + backtraceDepth); \ + } \ + } while (false) + + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/macros.h b/include/sal/macros.h new file mode 100644 index 000000000..2705fa63f --- /dev/null +++ b/include/sal/macros.h @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_MACROS_H +#define INCLUDED_SAL_MACROS_H + +#include + +#ifndef SAL_N_ELEMENTS +# if defined(__cplusplus) && ( defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L ) + /* + * Magic template to calculate at compile time the number of elements + * in an array. Enforcing that the argument must be an array and not + * a pointer, e.g. + * char *pFoo="foo"; + * SAL_N_ELEMENTS(pFoo); + * fails while + * SAL_N_ELEMENTS("foo"); + * or + * char aFoo[]="foo"; + * SAL_N_ELEMENTS(aFoo); + * pass + * + * Unfortunately if arr is an array of an anonymous class then we need + * C++0x, i.e. see + * http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#757 + */ + template char (&sal_n_array_size( T(&)[S] ))[S]; +# define SAL_N_ELEMENTS(arr) (sizeof(sal_n_array_size(arr))) +# else +# define SAL_N_ELEMENTS(arr) (sizeof (arr) / sizeof ((arr)[0])) +# endif +#endif + +#ifndef SAL_STRINGIFY +# define SAL_STRINGIFY_ARG(x) #x +# define SAL_STRINGIFY(x) SAL_STRINGIFY_ARG(x) +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/main.h b/include/sal/main.h new file mode 100644 index 000000000..7d10988c6 --- /dev/null +++ b/include/sal/main.h @@ -0,0 +1,157 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_MAIN_H +#define INCLUDED_SAL_MAIN_H + +#include "sal/config.h" + +#include "sal/saldllapi.h" +#include "sal/types.h" + +#if defined AIX +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined LIBO_INTERNAL_ONLY && defined __cplusplus +// Special token for sal_detail_initialize argc parameter, used by the soffice.bin process to tell +// SAL that it is running as part of that process (see sal/osl/unx/soffice.hxx); argv should be null +// in such a sal_detail_initialize call: +namespace sal::detail { constexpr int InitializeSoffice = -1; } +#endif + +SAL_DLLPUBLIC void SAL_CALL sal_detail_initialize(int argc, char ** argv); +SAL_DLLPUBLIC void SAL_CALL sal_detail_deinitialize(void); + +#if !(defined IOS || defined ANDROID) + /* No code that uses this should be built for iOS or Android */ + +#define SAL_MAIN_WITH_ARGS_IMPL \ +int SAL_DLLPUBLIC_EXPORT SAL_CALL main(int argc, char ** argv) \ +{ \ + int ret; \ + sal_detail_initialize(argc, argv); \ + ret = sal_main_with_args(argc, argv); \ + sal_detail_deinitialize(); \ + return ret; \ +} + +#define SAL_MAIN_IMPL \ +int SAL_DLLPUBLIC_EXPORT SAL_CALL main(int argc, char ** argv) \ +{ \ + int ret; \ + sal_detail_initialize(argc, argv); \ + ret = sal_main(); \ + sal_detail_deinitialize(); \ + return ret; \ +} + +#endif + + +/* Definition macros for CRT entries */ + +#ifdef _WIN32 + +#include + +/* Sorry but this is necessary cause HINSTANCE is a typedef that differs (C++ causes an error) */ + +#ifndef WINAPI +# define WINAPI __stdcall +#endif + +#if !defined(DECLARE_HANDLE) +# ifdef STRICT + typedef void *HANDLE; +# define DECLARE_HANDLE(name) struct name##__ { int unused; }; typedef struct name##__ *name +# else + typedef void *PVOID; + typedef PVOID HANDLE; +# define DECLARE_HANDLE(name) typedef HANDLE name +# endif +DECLARE_HANDLE(HINSTANCE); +#endif + + + +#define SAL_WIN_WinMain \ +int WINAPI WinMain( HINSTANCE _hinst, HINSTANCE _dummy, char* _cmdline, int _nshow ) \ +{ \ + int argc = __argc; char ** argv = __argv; \ + (void) _hinst; (void) _dummy; (void) _cmdline; (void) _nshow; /* unused */ \ + return main(argc, argv); \ +} + +#else /* ! _WIN32 */ + +# define SAL_WIN_WinMain + +#endif /* ! _WIN32 */ + +/* Implementation macro */ + +#define SAL_IMPLEMENT_MAIN_WITH_ARGS(_argc_, _argv_) \ + static int SAL_CALL sal_main_with_args (int _argc_, char ** _argv_); \ + SAL_MAIN_WITH_ARGS_IMPL \ + SAL_WIN_WinMain \ + static int SAL_CALL sal_main_with_args(int _argc_, char ** _argv_) + +#define SAL_IMPLEMENT_MAIN() \ + static int SAL_CALL sal_main(void); \ + SAL_MAIN_IMPL \ + SAL_WIN_WinMain \ + static int SAL_CALL sal_main(void) + +/* + "How to use" Examples: + + #include + + SAL_IMPLEMENT_MAIN() + { + DoSomething(); + + return 0; + } + + SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) + { + DoSomethingWithArgs(argc, argv); + + return 0; + } + +*/ + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif // INCLUDED_SAL_MAIN_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/mathconf.h b/include/sal/mathconf.h new file mode 100644 index 000000000..3f8e98937 --- /dev/null +++ b/include/sal/mathconf.h @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_MATHCONF_H +#define INCLUDED_SAL_MATHCONF_H + +#include "osl/endian.h" + +#if defined __sun +#include +#endif /* __sun */ + +#if defined(__cplusplus) && ( defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L ) +#include +#endif + +#if defined(IOS) +#if defined(__cplusplus) +#include +#else +#include +#endif +#endif + +#if defined __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* Generally, the C standard guarantees that at program startup, "trapping or + stopping (if supported) is disabled on all [floating-point] exceptions" + (F.7.3/1 of the August 3, 1998 draft of C99), and that during program + execution, "a programmer can safely assume default modes (or be unaware of + them)" (7.6/2, footnote 161 of the August 3, 1998 draft of C99). Reportedly, + on Windows there are printer drivers that switch on exceptions. To avoid + problems, the SAL_MATH_FPEXCEPTIONS_OFF macro can be used to explicitly + switch off exceptions (on Windows). + */ +#if defined(_WIN32) +#define SAL_MATH_FPEXCEPTIONS_OFF() _control87( _MCW_EM, _MCW_EM ) +#else /* WNT */ +#define SAL_MATH_FPEXCEPTIONS_OFF() +#endif /* WNT */ + + +/* SAL_MATH_FINITE(d): test double d on INFINITY, NaN et al. */ +#if !defined __sun && !defined ANDROID \ + && defined(__cplusplus) \ + && ( defined(__GXX_EXPERIMENTAL_CXX0X__) \ + || __cplusplus >= 201103L \ + || defined(IOS) ) +#define SAL_MATH_FINITE(d) std::isfinite(d) +#elif defined __APPLE__ && !(defined __i386__ || defined __x86_64__) +#define SAL_MATH_FINITE(d) isfinite(d) +#elif defined( WNT) +#define SAL_MATH_FINITE(d) _finite(d) +#elif defined(ANDROID) || defined LINUX || defined UNX +#define SAL_MATH_FINITE(d) finite(d) +#else /* WNT, LINUX, UNX */ +#error "SAL_MATH_FINITE not defined" +#endif /* WNT, LINUX, UNX */ + + +/* This needs to be fixed for non--IEEE-754 platforms: */ +#if 1 /* IEEE 754 supported */ +#if defined OSL_BIGENDIAN + +/* IEEE 754 double structures for BigEndian */ +union sal_math_Double +{ + struct + { + unsigned sign : 1; + unsigned exponent :11; + unsigned fraction_hi :20; + unsigned fraction_lo :32; + } inf_parts; + struct + { + unsigned sign : 1; + unsigned exponent :11; + unsigned qnan_bit : 1; + unsigned bits :19; + unsigned fraction_lo :32; + } nan_parts; + struct + { + unsigned msw :32; + unsigned lsw :32; + } w32_parts; + struct + { + sal_uInt64 sign : 1; + sal_uInt64 exponent :11; + sal_uInt64 fraction :52; + } parts; + sal_uInt64 intrep; + double value; +}; + +#elif defined OSL_LITENDIAN + +/* IEEE 754 double structures for LittleEndian */ +union sal_math_Double +{ + struct { + unsigned fraction_lo :32; + unsigned fraction_hi :20; + unsigned exponent :11; + unsigned sign : 1; + } inf_parts; + struct { + unsigned fraction_lo :32; + unsigned bits :19; + unsigned qnan_bit : 1; + unsigned exponent :11; + unsigned sign : 1; + } nan_parts; + struct + { + unsigned lsw :32; + unsigned msw :32; + } w32_parts; + struct + { + sal_uInt64 fraction :52; + sal_uInt64 exponent :11; + sal_uInt64 sign : 1; + } parts; + sal_uInt64 intrep; + double value; +}; + +#else /* OSL_BIGENDIAN, OSL_LITENDIAN */ + +#error "neither OSL_BIGENDIAN nor OSL_LITENDIAN" + +#endif /* OSL_BIGENDIAN, OSL_LITENDIAN */ +#else /* IEEE 754 supported */ + +#error "don't know how to handle IEEE 754" + +#endif /* IEEE 754 supported */ + + +#if defined __cplusplus +} +#endif /* __cplusplus */ + +#endif /* INCLUDED_SAL_MATHCONF_H */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/saldllapi.h b/include/sal/saldllapi.h new file mode 100644 index 000000000..d5ec89e67 --- /dev/null +++ b/include/sal/saldllapi.h @@ -0,0 +1,39 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_SALDLLAPI_H +#define INCLUDED_SAL_SALDLLAPI_H + +#include "sal/config.h" + +#include "sal/types.h" + +#if defined(SAL_DLLIMPLEMENTATION) +#define SAL_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define SAL_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif // INCLUDED_SAL_SALDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/types.h b/include/sal/types.h new file mode 100644 index 000000000..7bfb256e3 --- /dev/null +++ b/include/sal/types.h @@ -0,0 +1,687 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SAL_TYPES_H +#define INCLUDED_SAL_TYPES_H + +#include "sal/config.h" + +#include + +#include "sal/macros.h" +#include "sal/typesizes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned char sal_Bool; +# define sal_False ((sal_Bool)0) +# define sal_True ((sal_Bool)1) + +/* char is assumed to always be 1 byte long */ +typedef signed char sal_Int8; +typedef unsigned char sal_uInt8; + +#if SAL_TYPES_SIZEOFSHORT == 2 + typedef signed short sal_Int16; + typedef unsigned short sal_uInt16; +#else + #error "Could not find 16-bit type, add support for your architecture" +#endif + +#if SAL_TYPES_SIZEOFLONG == 4 + typedef signed long sal_Int32; + typedef unsigned long sal_uInt32; + #define SAL_PRIdINT32 "ld" + #define SAL_PRIuUINT32 "lu" + #define SAL_PRIxUINT32 "lx" + #define SAL_PRIXUINT32 "lX" +#elif SAL_TYPES_SIZEOFINT == 4 + typedef signed int sal_Int32; + typedef unsigned int sal_uInt32; + #define SAL_PRIdINT32 "d" + #define SAL_PRIuUINT32 "u" + #define SAL_PRIxUINT32 "x" + #define SAL_PRIXUINT32 "X" +#else + #error "Could not find 32-bit type, add support for your architecture" +#endif + +#ifdef _MSC_VER + typedef __int64 sal_Int64; + typedef unsigned __int64 sal_uInt64; + + /* The following are macros that will add the 64 bit constant suffix. */ + #define SAL_CONST_INT64(x) x##i64 + #define SAL_CONST_UINT64(x) x##ui64 + + #define SAL_PRIdINT64 "I64d" + #define SAL_PRIuUINT64 "I64u" + #define SAL_PRIxUINT64 "I64x" + #define SAL_PRIXUINT64 "I64X" +#elif defined (__GNUC__) + #if SAL_TYPES_SIZEOFLONG == 8 + typedef signed long int sal_Int64; + typedef unsigned long int sal_uInt64; + + + /* The following are macros that will add the 64 bit constant suffix. */ + #define SAL_CONST_INT64(x) x##l + #define SAL_CONST_UINT64(x) x##ul + + #define SAL_PRIdINT64 "ld" + #define SAL_PRIuUINT64 "lu" + #define SAL_PRIxUINT64 "lx" + #define SAL_PRIXUINT64 "lX" + #elif SAL_TYPES_SIZEOFLONGLONG == 8 + typedef signed long long sal_Int64; + typedef unsigned long long sal_uInt64; + + /* The following are macros that will add the 64 bit constant suffix. */ + #define SAL_CONST_INT64(x) x##ll + #define SAL_CONST_UINT64(x) x##ull + + #define SAL_PRIdINT64 "lld" + #define SAL_PRIuUINT64 "llu" + #define SAL_PRIxUINT64 "llx" + #define SAL_PRIXUINT64 "llX" + #else + #error "Could not find 64-bit type, add support for your architecture" + #endif +#else + #error "Please define the 64-bit types for your architecture/compiler in include/sal/types.h" +#endif + +#if defined LIBO_INTERNAL_ONLY && defined __cplusplus + #define SAL_UNICODE_NOTEQUAL_WCHAR_T + typedef char16_t sal_Unicode; +#elif defined(_WIN32) + typedef wchar_t sal_Unicode; +#else + #define SAL_UNICODE_NOTEQUAL_WCHAR_T + typedef sal_uInt16 sal_Unicode; +#endif + +typedef void * sal_Handle; + +/* sal_Size should currently be the native width of the platform */ +#if SAL_TYPES_SIZEOFPOINTER == 4 + typedef sal_uInt32 sal_Size; + typedef sal_Int32 sal_sSize; +#elif SAL_TYPES_SIZEOFPOINTER == 8 + typedef sal_uInt64 sal_Size; + typedef sal_Int64 sal_sSize; +#else + #error "Please make sure SAL_TYPES_SIZEOFPOINTER is defined for your architecture/compiler" +#endif + +/* sal_PtrDiff holds the result of a pointer subtraction */ +#if SAL_TYPES_SIZEOFPOINTER == 4 + typedef sal_Int32 sal_PtrDiff; +#elif SAL_TYPES_SIZEOFPOINTER == 8 + typedef sal_Int64 sal_PtrDiff; +#else + #error "Please make sure SAL_TYPES_SIZEOFPOINTER is defined for your architecture/compiler" +#endif + +/* printf-style conversion specification length modifiers for size_t and + ptrdiff_t (most platforms support C99, MSC has its own extension) */ +#if defined(_MSC_VER) + #define SAL_PRI_SIZET "I" + #define SAL_PRI_PTRDIFFT "I" +#else + #define SAL_PRI_SIZET "z" + #define SAL_PRI_PTRDIFFT "t" +#endif + +/* sal_IntPtr, sal_uIntPtr are integer types designed to hold pointers so that any valid + * pointer to void can be converted to this type and back to a pointer to void and the + * result will compare to the original pointer */ +#if SAL_TYPES_SIZEOFPOINTER == 4 + typedef sal_Int32 sal_IntPtr; + typedef sal_uInt32 sal_uIntPtr; + #define SAL_PRIdINTPTR SAL_PRIdINT32 + #define SAL_PRIuUINTPTR SAL_PRIuUINT32 + #define SAL_PRIxUINTPTR SAL_PRIxUINT32 + #define SAL_PRIXUINTPTR SAL_PRIXUINT32 +#elif SAL_TYPES_SIZEOFPOINTER == 8 + typedef sal_Int64 sal_IntPtr; + typedef sal_uInt64 sal_uIntPtr; + #define SAL_PRIdINTPTR SAL_PRIdINT64 + #define SAL_PRIuUINTPTR SAL_PRIuUINT64 + #define SAL_PRIxUINTPTR SAL_PRIxUINT64 + #define SAL_PRIXUINTPTR SAL_PRIXUINT64 +#else + #error "Please make sure SAL_TYPES_SIZEOFPOINTER is defined for your architecture/compiler" +#endif + +/* The following SAL_MIN_INTn defines codify the assumption that the signed + * sal_Int types use two's complement representation. Defining them as + * "-0x7F... - 1" instead of as "-0x80..." prevents warnings about applying the + * unary minus operator to unsigned quantities. + */ +#define SAL_MIN_INT8 ((sal_Int8) (-0x7F - 1)) +#define SAL_MAX_INT8 ((sal_Int8) 0x7F) +#define SAL_MAX_UINT8 ((sal_uInt8) 0xFF) +#define SAL_MIN_INT16 ((sal_Int16) (-0x7FFF - 1)) +#define SAL_MAX_INT16 ((sal_Int16) 0x7FFF) +#define SAL_MAX_UINT16 ((sal_uInt16) 0xFFFF) +#define SAL_MIN_INT32 ((sal_Int32) (-0x7FFFFFFF - 1)) +#define SAL_MAX_INT32 ((sal_Int32) 0x7FFFFFFF) +#define SAL_MAX_UINT32 ((sal_uInt32) 0xFFFFFFFF) +#define SAL_MIN_INT64 ((sal_Int64) (SAL_CONST_INT64(-0x7FFFFFFFFFFFFFFF) - 1)) +#define SAL_MAX_INT64 ((sal_Int64) SAL_CONST_INT64(0x7FFFFFFFFFFFFFFF)) +#define SAL_MAX_UINT64 ((sal_uInt64) SAL_CONST_UINT64(0xFFFFFFFFFFFFFFFF)) + +#if SAL_TYPES_SIZEOFPOINTER == 4 +#define SAL_MAX_SSIZE SAL_MAX_INT32 +#define SAL_MAX_SIZE SAL_MAX_UINT32 +#elif SAL_TYPES_SIZEOFPOINTER == 8 +#define SAL_MAX_SSIZE SAL_MAX_INT64 +#define SAL_MAX_SIZE SAL_MAX_UINT64 +#endif + +#define SAL_MAX_ENUM 0x7fffffff + +#if defined(_MSC_VER) +# define SAL_DLLPUBLIC_EXPORT __declspec(dllexport) +# define SAL_JNI_EXPORT __declspec(dllexport) +# define SAL_DLLPUBLIC_IMPORT __declspec(dllimport) +# define SAL_DLLPRIVATE +# define SAL_DLLPUBLIC_TEMPLATE +# define SAL_DLLPUBLIC_RTTI +# define SAL_CALL __cdecl +#elif defined SAL_UNX +# if defined(__GNUC__) +# if defined(DISABLE_DYNLOADING) +# define SAL_DLLPUBLIC_EXPORT __attribute__ ((visibility("hidden"))) +# define SAL_JNI_EXPORT __attribute__ ((visibility("default"))) +# define SAL_DLLPUBLIC_IMPORT __attribute__ ((visibility("hidden"))) +# define SAL_DLLPRIVATE __attribute__ ((visibility("hidden"))) +# define SAL_DLLPUBLIC_TEMPLATE __attribute__ ((visibility("hidden"))) +# define SAL_DLLPUBLIC_RTTI +# else +# define SAL_DLLPUBLIC_EXPORT __attribute__ ((visibility("default"))) +# define SAL_JNI_EXPORT __attribute__ ((visibility("default"))) +# define SAL_DLLPUBLIC_IMPORT __attribute__ ((visibility("default"))) +# define SAL_DLLPRIVATE __attribute__ ((visibility("hidden"))) +# define SAL_DLLPUBLIC_TEMPLATE __attribute__ ((visibility("default"))) +# if defined __clang__ +# if __has_attribute(type_visibility) +# define SAL_DLLPUBLIC_RTTI __attribute__ ((type_visibility("default"))) +# else +# define SAL_DLLPUBLIC_RTTI __attribute__ ((visibility("default"))) +# endif +# else +# define SAL_DLLPUBLIC_RTTI +# endif +# endif +# else +# define SAL_DLLPUBLIC_EXPORT +# define SAL_JNI_EXPORT +# define SAL_DLLPUBLIC_IMPORT +# define SAL_DLLPRIVATE +# define SAL_DLLPUBLIC_TEMPLATE +# define SAL_DLLPUBLIC_RTTI +# endif +# define SAL_CALL +#else +# error("unknown platform") +#endif + +/** + Exporting the symbols necessary for exception handling on GCC. + + These macros are used for inline declarations of exception classes, as in + rtl/malformeduriexception.hxx. +*/ +#if defined(__GNUC__) +# if defined(DISABLE_DYNLOADING) +# define SAL_EXCEPTION_DLLPUBLIC_EXPORT __attribute__((visibility("default"))) +# else +# define SAL_EXCEPTION_DLLPUBLIC_EXPORT SAL_DLLPUBLIC_EXPORT +# endif +# define SAL_EXCEPTION_DLLPRIVATE SAL_DLLPRIVATE +#else +# define SAL_EXCEPTION_DLLPUBLIC_EXPORT +# define SAL_EXCEPTION_DLLPRIVATE +#endif + +/** Use this as markup for functions and methods whose return value must be + checked. + + Compilers that support a construct of this nature will emit a compile + time warning on unchecked return value. +*/ +#if defined LIBO_INTERNAL_ONLY && defined __cplusplus +#define SAL_WARN_UNUSED_RESULT [[nodiscard]] +#elif (defined __GNUC__ \ + && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))) \ + || defined __clang__ +# define SAL_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#else +# define SAL_WARN_UNUSED_RESULT +#endif + +/** Use this for pure virtual classes, e.g. class SAL_NO_VTABLE Foo { ... + This hinders the compiler from setting a generic vtable stating that + a pure virtual function was called and thus slightly reduces code size. +*/ +#ifdef _MSC_VER +# define SAL_NO_VTABLE __declspec(novtable) +#else +# define SAL_NO_VTABLE +#endif + +#ifdef _WIN32 +# pragma pack(push, 8) +#endif + +/** This is the binary specification of a SAL sequence. +*/ +typedef struct _sal_Sequence +{ + /** reference count of sequence
    + */ + sal_Int32 nRefCount; + /** element count
    + */ + sal_Int32 nElements; + /** elements array
    + */ + char elements[1]; +} sal_Sequence; + +#define SAL_SEQUENCE_HEADER_SIZE ((sal_Size) offsetof(sal_Sequence,elements)) + +#if defined( _WIN32) +#pragma pack(pop) +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +/** Nothrow specification for C functions. + + This is a macro so it can expand to nothing in C code. +*/ +#if defined __cplusplus +#if __cplusplus >= 201103L +#define SAL_THROW_EXTERN_C() noexcept +#else +#define SAL_THROW_EXTERN_C() throw () +#endif +#else +#define SAL_THROW_EXTERN_C() +#endif + +#ifdef __cplusplus + +/** To markup destructors that coverity warns might throw exceptions + which won't throw in practice, or where std::terminate is + an acceptable response if they do +*/ +#if defined(LIBO_INTERNAL_ONLY) && defined(__COVERITY__) +# define COVERITY_NOEXCEPT_FALSE noexcept(false) +#else +# define COVERITY_NOEXCEPT_FALSE +#endif + +enum __sal_NoAcquire +{ + /** definition of a no acquire enum for ctors + */ + SAL_NO_ACQUIRE +}; + +namespace com { namespace sun { namespace star { } } } + +/** short-circuit extra-verbose API namespaces + + @since LibreOffice 4.0 +*/ +namespace css = ::com::sun::star; + +/** C++11 "= delete" feature. + + For LIBO_INTERNAL_ONLY, calling a deleted function will cause a compile-time + error, while otherwise it will only cause a link-time error as the declared + function is not defined. + + @since LibreOffice 4.1 +*/ +#if defined LIBO_INTERNAL_ONLY +#define SAL_DELETED_FUNCTION = delete +#else +#define SAL_DELETED_FUNCTION +#endif + +/** C++11 "override" feature. + + For LIBO_INTERNAL_ONLY, force the method to override an existing method in + parent, error out if the method with the correct signature does not exist. + + @since LibreOffice 4.1 +*/ +#if defined LIBO_INTERNAL_ONLY +#define SAL_OVERRIDE override +#else +#define SAL_OVERRIDE +#endif + +/** C++11 "constexpr" feature. + + For LIBO_INTERNAL_ONLY, declare that it's possible to evaluate the value + at compile time. + + @since LibreOffice 7.2 +*/ +#if defined LIBO_INTERNAL_ONLY +#define SAL_CONSTEXPR constexpr +#else +#define SAL_CONSTEXPR +#endif + +/** Macro for C++11 "noexcept" vs. "throw ()" exception specification. + + The latter has been removed completely from C++20. + + @since LibreOffice 7.2 + */ +#if __cplusplus >= 201103L +#define SAL_NOEXCEPT noexcept +#else +#define SAL_NOEXCEPT throw () +#endif + +#endif /* __cplusplus */ + +#ifdef __cplusplus + +namespace sal { + +/** + A static_cast between integral types, to avoid C++ compiler warnings. + + In C++ source code, use sal::static_int_cast(n) instead of + static_cast(n) whenever a compiler warning about integral type problems + shall be silenced. That way, source code that needs to be modified when the + type of any of the expressions involved in the compiler warning is changed + can be found more easily. + + Both template arguments T1 and T2 must be integral types. +*/ +template< typename T1, typename T2 > inline T1 static_int_cast(T2 n) { + return static_cast< T1 >(n); +} + +} + +#else /* __cplusplus */ + +/** + A cast between integer types, to avoid C compiler warnings. + + In C source code, use SAL_INT_CAST(type, expr) instead of ((type) (expr)) + whenever a compiler warning about integer type problems shall be silenced. + That way, source code that needs to be modified when the type of any of the + expressions involved in the compiler warning is changed can be found more + easily. + + The argument 'type' must be an integer type and the argument 'expr' must be + an integer expression. Both arguments are evaluated exactly once. +*/ +#define SAL_INT_CAST(type, expr) ((type) (expr)) + +#endif /* __cplusplus */ + +/** + Use as follows: + SAL_DEPRECATED("Don't use, it's evil.") void doit(int nPara); +*/ + +#if defined __GNUC__ || defined __clang__ +#if defined LIBO_INTERNAL_ONLY +# define SAL_DEPRECATED(message) __attribute__((deprecated(message))) +#else +# define SAL_DEPRECATED(message) __attribute__((deprecated)) +#endif +#elif defined(_MSC_VER) +# define SAL_DEPRECATED(message) __declspec(deprecated(message)) +#else +# define SAL_DEPRECATED(message) +#endif + +/** + This macro is used in cppumaker-generated include files, to tag entities that + are marked as @deprecated in UNOIDL. + + It causes deprecation warnings to be generated in external code, but for now + is silenced in internal code. It would need some substantial clean-up of + internal code to fix all warnings/errors generated by it. (Once that is + done, it can become a synonym for SAL_DEPRECATED under LIBO_INTERNAL_ONLY, + too. Completely removing the macro then would be incompatible, in case there + are include files still around generated with a cppumaker that emitted it.) + */ +#ifdef LIBO_INTERNAL_ONLY +# define SAL_DEPRECATED_INTERNAL(message) +#else +# define SAL_DEPRECATED_INTERNAL(message) SAL_DEPRECATED(message) +#endif + +/** + Use as follows: + SAL_WNODEPRECATED_DECLARATIONS_PUSH + \::std::auto_ptr ... + SAL_WNODEPRECATED_DECLARATIONS_POP +*/ + +#if defined LIBO_INTERNAL_ONLY && defined __GNUC__ +#define SAL_WNODEPRECATED_DECLARATIONS_PUSH \ + _Pragma(SAL_STRINGIFY_ARG(GCC diagnostic push)) \ + _Pragma(SAL_STRINGIFY_ARG(GCC diagnostic ignored "-Wdeprecated-declarations")) +#define SAL_WNODEPRECATED_DECLARATIONS_POP \ + _Pragma(SAL_STRINGIFY_ARG(GCC diagnostic pop)) +#else +# define SAL_WNODEPRECATED_DECLARATIONS_PUSH +# define SAL_WNODEPRECATED_DECLARATIONS_POP +#endif + +/** + Use as follows: + + SAL_WNOUNREACHABLE_CODE_PUSH + + function definition + + SAL_WNOUNREACHABLE_CODE_POP + + Useful in cases where the compiler is "too clever" like when doing + link-time code generation, and noticing that a called function + always throws, and fixing the problem cleanly so that it produces + no warnings in normal non-LTO compilations either is not easy. + +*/ + +#ifdef _MSC_VER +#define SAL_WNOUNREACHABLE_CODE_PUSH \ + __pragma(warning(push)) \ + __pragma(warning(disable:4702)) \ + __pragma(warning(disable:4722)) +#define SAL_WNOUNREACHABLE_CODE_POP \ + __pragma(warning(pop)) +#else +/* Add definitions for GCC and Clang if needed */ +#define SAL_WNOUNREACHABLE_CODE_PUSH +#define SAL_WNOUNREACHABLE_CODE_POP +#endif + +/** Annotate unused but required C++ function parameters. + + An unused parameter is required if the function needs to adhere to a given + type (e.g., if its address is assigned to a function pointer of a specific + type, or if it is called from template code). This annotation helps static + analysis tools suppress false warnings. In the case of virtual functions + (where unused required parameters are common, too), the annotation is not + required (as static analysis tools can themselves derive the information + whether a function is virtual). + + Use the annotation in function definitions like + + void f(SAL_UNUSED_PARAMETER int) {} + + C does not allow unnamed parameters, anyway, so a function definition like + the above needs to be written there as + + void f(int dummy) { (void) dummy; / * avoid warnings * / } + + without a SAL_UNUSED_PARAMETER annotation. + + @since LibreOffice 3.6 + */ +#if defined __cplusplus +#if defined __GNUC__ || defined __clang__ +#define SAL_UNUSED_PARAMETER __attribute__ ((unused)) +#else +#define SAL_UNUSED_PARAMETER +#endif +#endif + +/** + + Annotate classes where a compiler should warn if an instance is unused. + + The compiler cannot warn about unused instances if they have non-trivial + or external constructors or destructors. Classes marked with SAL_WARN_UNUSED + will be warned about. + + @since LibreOffice 4.0 + +*/ + +#if defined LIBO_INTERNAL_ONLY && (defined __GNUC__ || defined __clang__) +#define SAL_WARN_UNUSED __attribute__((warn_unused)) +#else +#define SAL_WARN_UNUSED +#endif + +/// @cond INTERNAL + +#if defined __GNUC__ || defined __clang__ +// Macro to try to catch and warn on assignments inside expr. +# define SAL_DETAIL_BOOLEAN_EXPR(expr) \ + __extension__ ({ \ + int sal_boolean_var_; \ + if (expr) \ + sal_boolean_var_ = 1; \ + else \ + sal_boolean_var_ = 0; \ + sal_boolean_var_; \ + }) + +/** An optimization annotation: denotes that expression is likely to be true. + + Use it to annotate paths that we think are likely eg. + if (SAL_LIKELY(ptr != nullptr)) + // this path is the one that is ~always taken. + + @since LibreOffice 5.2 + + Returns: the boolean value of expr (expressed as either int 1 or 0) + */ +# define SAL_LIKELY(expr) __builtin_expect(SAL_DETAIL_BOOLEAN_EXPR((expr)), 1) + +/** An optimization annotation: denotes that expression is unlikely to be true. + + Use it to annotate paths that we think are likely eg. + if (SAL_UNLIKELY(ptr != nullptr)) + // this path is the one that is ~never taken. + + @since LibreOffice 5.2 + + Returns: the boolean value of expr (expressed as either int 1 or 0) + */ +# define SAL_UNLIKELY(expr) __builtin_expect(SAL_DETAIL_BOOLEAN_EXPR((expr)), 0) + +/** An optimization annotation: tells the compiler to work harder at this code + + If the SAL_HOT annotation is present on a function or a label then + subsequent code statements may have more aggressive compiler + optimization and in-lining work performed on them. + + In addition this code can end up in a special section, to be + grouped with other frequently used code. + + @since LibreOffice 5.2 + */ +# define SAL_HOT __attribute__((hot)) + +/** An optimization annotation: tells the compiler to work less on this code + + If the SAL_COLD annotation is present on a function or a label then + subsequent code statements are unlikely to be performed except in + exceptional circumstances, and optimizing for code-size rather + than performance is preferable. + + In addition this code can end up in a special section, to be grouped + with (and away from) other more frequently used code, to improve + locality of reference. + + @since LibreOffice 5.2 + */ +# define SAL_COLD __attribute__((cold)) +#else +# define SAL_LIKELY(expr) (expr) +# define SAL_UNLIKELY(expr) (expr) +# define SAL_HOT +# define SAL_COLD +#endif + +/// @endcond + +/// @cond INTERNAL +/** Annotate pointer-returning functions to indicate that such a pointer + is never nullptr. + + Note that MSVC supports this feature via it's SAL _Ret_notnull_ + annotation, but since it's in a completely different place on + the function declaration, it's a little hard to support both. + + @since LibreOffice 5.5 +*/ +#ifndef __has_attribute +#define __has_attribute(x) 0 +#endif + +#if defined LIBO_INTERNAL_ONLY && ((defined __GNUC__ && !defined __clang__) || (defined __clang__ && __has_attribute(returns_nonnull))) +#define SAL_RETURNS_NONNULL __attribute__((returns_nonnull)) +#else +#define SAL_RETURNS_NONNULL +#endif +/// @endcond + +#endif // INCLUDED_SAL_TYPES_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sal/typesizes.h b/include/sal/typesizes.h new file mode 100644 index 000000000..e981818b9 --- /dev/null +++ b/include/sal/typesizes.h @@ -0,0 +1,20 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* DO NOT INCLUDE THIS HEADER DIRECTLY! + * + * It is only needed to make the build work. config_typesizes.h is + * copied to SDK as sal/typesizes.h and this is how sal/types.h includes + * it. This means we need to have sal/typesizes.h available for build + * too. + */ + +#include "config_typesizes.h" + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/condition.hxx b/include/salhelper/condition.hxx new file mode 100644 index 000000000..cb9d8206d --- /dev/null +++ b/include/salhelper/condition.hxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_CONDITION_HXX +#define INCLUDED_SALHELPER_CONDITION_HXX + + +#include "osl/conditn.hxx" +#include "salhelper/salhelperdllapi.h" + +namespace osl { class Mutex; } + +namespace salhelper +{ + + class SALHELPER_DLLPUBLIC Condition + { + friend class ConditionModifier; + friend class ConditionWaiter; + + public: + + Condition(osl::Mutex& aMutex); + + virtual ~Condition(); + + + protected: + + virtual bool applies() const = 0; + + + private: + Condition(Condition &) SAL_DELETED_FUNCTION; + void operator =(Condition &) SAL_DELETED_FUNCTION; + + osl::Mutex& m_aMutex; + osl::Condition m_aCondition; + }; + + + class SALHELPER_DLLPUBLIC ConditionModifier + { + public: + + ConditionModifier(Condition& aCond); + + ~ConditionModifier(); + + + private: + ConditionModifier(ConditionModifier &) SAL_DELETED_FUNCTION; + void operator =(ConditionModifier &) SAL_DELETED_FUNCTION; + + Condition& m_aCond; + }; + + + class SALHELPER_DLLPUBLIC ConditionWaiter + { + public: + + ConditionWaiter(Condition& aCond); + + struct SALHELPER_DLLPUBLIC timedout { + timedout(); + + timedout(timedout const &); + + virtual ~timedout(); + + timedout & operator =(timedout const &); + }; + + /// @throws timedout + ConditionWaiter(Condition& aCond,sal_uInt32 milliSec); + + + ~ConditionWaiter(); + + + private: + ConditionWaiter(ConditionWaiter &) SAL_DELETED_FUNCTION; + void operator =(ConditionWaiter &) SAL_DELETED_FUNCTION; + + Condition& m_aCond; + }; + + +} // namespace salhelper + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/dynload.hxx b/include/salhelper/dynload.hxx new file mode 100644 index 000000000..b4ae693ea --- /dev/null +++ b/include/salhelper/dynload.hxx @@ -0,0 +1,209 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_DYNLOAD_HXX +#define INCLUDED_SALHELPER_DYNLOAD_HXX + +#include "sal/types.h" +#include "rtl/ustring.hxx" +#include "osl/module.h" +#include "salhelper/salhelperdllapi.h" + +namespace salhelper +{ + +/** The ORealDynamicLoader is an implementation helper class for the template loader ODynamicLoader. + */ +class SALHELPER_DLLPUBLIC ORealDynamicLoader +{ +public: + /** initializes the loader, loads the library and call the initialization function. + + @param ppSetToZeroInDestructor points to the loader instance which must be set to NULL + if the loader will be destroyed. + @param strModuleName specifies the library name. + @param strInitFunction specifies the name of the initialization function. + */ + static ORealDynamicLoader* SAL_CALL newInstance( + ORealDynamicLoader ** ppSetToZeroInDestructor, + const ::rtl::OUString& strModuleName, + const ::rtl::OUString& strInitFunction ); + + /// increase the reference count. + sal_uInt32 SAL_CALL acquire(); + /// decrease the reference count and delete the last instance. + sal_uInt32 SAL_CALL release(); + + /// returns a pointer to the initialized API function structure. + void* SAL_CALL getApi() const; + +protected: + /** Constructor. + + @param ppSetToZeroInDestructor points to the loader instance which must be set to NULL + if the loader will be destroyed. + @param strModuleName specifies the library name. + @param strInitFunction specifies the name of the initialization function. + @param pApi points to a structure with the initialized API function pointers. + @param pModule points to the loaded library handle. + */ + ORealDynamicLoader( ORealDynamicLoader ** ppSetToZeroInDestructor, + const ::rtl::OUString& strModuleName, + const ::rtl::OUString& strInitFunction, + void* pApi, + oslModule pModule ); + + /// Destructor, try to unload the library. + virtual ~ORealDynamicLoader(); + + /// points to the structure with the initialized API function pointers. + void* m_pApi; + /// stores the reference count. + sal_uInt32 m_refCount; + /// stores the library handle. + oslModule m_pModule; + /// stores the library name. + ::rtl::OUString m_strModuleName; + /// stores the name of the initialization function. + ::rtl::OUString m_strInitFunction; + /** stores a pointer to itself, which must be reset in the destructor to signal + that the loader is invalid. + */ + ORealDynamicLoader ** ppSetToZeroInDestructor; +}; + + +/** The ODynamicLoader provides a special load on call mechanism for dynamic libraries + which support a C-API. + + The libraries must provide a struct with function pointers for all supported C functions. + The loader loads the specified library and call the specified initialization function + to initialize the function pointers with the real functions. Furthermore provides the + loader a reference counter for the library. When the last instance of the laoder will + be destroyed the loader will unload the library. + + @deprecated + Do not use. + */ +template +class ODynamicLoader +{ +public: + /// Default constructor + ODynamicLoader() + { + m_pLoader = NULL; + } + + /** Constructor, loads the library if necessary otherwise the reference count will + be increased. + + @param strModuleName specifies the library name. + @param strInitFunction specifies the name of the initialization function. + */ + ODynamicLoader( const ::rtl::OUString& strModuleName, + const ::rtl::OUString& strInitFunction ) + { + if (!m_pStaticLoader) + { + m_pStaticLoader = ORealDynamicLoader::newInstance( + &m_pStaticLoader, + strModuleName, + strInitFunction); + } + else + { + m_pStaticLoader->acquire(); + } + + m_pLoader = m_pStaticLoader; + } + + /// Copy constructor + ODynamicLoader(const ODynamicLoader& toCopy) + { + m_pLoader = toCopy.m_pLoader; + if( m_pLoader ) + m_pLoader->acquire(); + } + + /// Destructor, decrease the reference count and unload the library if it is the last instance. + ~ODynamicLoader() + { + if( m_pLoader ) + if (m_pLoader->release()==0) + m_pStaticLoader = NULL; + } + + /// Assign operator + ODynamicLoader& SAL_CALL operator = (const ODynamicLoader& toAssign) + { + if( m_pLoader != toAssign.m_pLoader ) + { + if( toAssign.m_pLoader ) + { + toAssign.m_pLoader->acquire(); + } + if( m_pLoader ) + { + m_pLoader->release(); + } + m_pLoader = toAssign.m_pLoader; + } + + return (*this); + } + + /// returns a pointer to the initialized API function structure. + API* SAL_CALL getApi() const + { + return static_cast(m_pLoader->getApi()); + } + + /// cast operator, which cast to a pointer with the initialized API function structure. + API* SAL_CALL operator->() const + { + return static_cast(m_pLoader->getApi()); + } + + /// checks if the loader works on a loaded and initialized library. + bool SAL_CALL isLoaded() const + { + return (m_pLoader != NULL); + } + +protected: + /// stores the real loader helper instance + static ORealDynamicLoader* m_pStaticLoader; + ORealDynamicLoader* m_pLoader; +}; + + +template +ORealDynamicLoader* ODynamicLoader::m_pStaticLoader = NULL; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/linkhelper.hxx b/include/salhelper/linkhelper.hxx new file mode 100644 index 000000000..aa8da261a --- /dev/null +++ b/include/salhelper/linkhelper.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_LINKHELPER_HXX +#define INCLUDED_SALHELPER_LINKHELPER_HXX + +#include "rtl/ustring.hxx" +#include "osl/file.hxx" + +namespace salhelper +{ + class SAL_WARN_UNUSED LinkResolver + { + public: + osl::FileStatus m_aStatus; + + LinkResolver(sal_uInt32 nMask) + : m_aStatus(nMask | + osl_FileStatus_Mask_FileURL | + osl_FileStatus_Mask_Type | + osl_FileStatus_Mask_LinkTargetURL) + { + } + + /** Resolve a file url if it's a symbolic link, to a maximum depth of + * nDepth and fill in m_aStatus with the requested ctor flags + * + * @return osl::FileBase::E_None on success + * + * @see DirectoryItem::getFileStatus + */ + osl::FileBase::RC fetchFileStatus(const rtl::OUString &rURL, + int nDepth = 128) + { + //In an ideal world this wouldn't be inline, but I want to use this + //in jvmfwk hence salhelper, but salhelper is .map controlled and + //getting all the mangled names right is a misery, moving it over + //to visibility markup would drop per-symbol versioning + osl::FileBase::RC eReturn; + + osl::DirectoryItem item; + rtl::OUString sURL(rURL); + while ((eReturn = osl::DirectoryItem::get(sURL, item)) + == osl::File::E_None) + { + if (--nDepth == 0) + { + eReturn = osl::FileBase::E_MULTIHOP; + break; + } + eReturn = item.getFileStatus(m_aStatus); + if (eReturn != osl::File::E_None) + break; + if (m_aStatus.getFileType() != osl::FileStatus::Link) + { + eReturn = osl::FileBase::E_None; + break; + } + sURL = m_aStatus.getLinkTargetURL(); + } + + return eReturn; + } + }; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/refobj.hxx b/include/salhelper/refobj.hxx new file mode 100644 index 000000000..b1b308958 --- /dev/null +++ b/include/salhelper/refobj.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_REFOBJ_HXX +#define INCLUDED_SALHELPER_REFOBJ_HXX + +#include + +#include "sal/types.h" +#include "rtl/alloc.h" +#include "osl/interlck.h" + +namespace salhelper +{ + +/** A base implementation for reference-counted objects. + + @deprecated use salhelper::SimpleReferenceObject instead +*/ +class ReferenceObject +{ + /** Representation. + */ + oslInterlockedCount m_nReferenceCount; + + ReferenceObject (const ReferenceObject&) SAL_DELETED_FUNCTION; + ReferenceObject& operator= (const ReferenceObject&) SAL_DELETED_FUNCTION; + +public: + /** Allocation. + */ + static void* operator new (size_t n) + { + return ::rtl_allocateMemory (n); + } + static void operator delete (void* p) + { + ::rtl_freeMemory (p); + } + static void* operator new (size_t, void* p) + { + return p; + } + static void operator delete (void*, void*) + {} + +public: + /** Construction. + */ + ReferenceObject() : m_nReferenceCount(0) + {} + + + void SAL_CALL acquire() + { + osl_atomic_increment(&m_nReferenceCount); + } + + void SAL_CALL release() + { + if (osl_atomic_decrement(&m_nReferenceCount) == 0) + { + // Last reference released. + delete this; + } + } + +protected: + /** Destruction. + */ + virtual ~ReferenceObject() + { + assert(m_nReferenceCount == 0); + } +}; + + +} // namespace salhelper + +#endif /* ! INCLUDED_SALHELPER_REFOBJ_HXX */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/salhelperdllapi.h b/include/salhelper/salhelperdllapi.h new file mode 100644 index 000000000..4de2430f6 --- /dev/null +++ b/include/salhelper/salhelperdllapi.h @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_SALHELPERDLLAPI_H +#define INCLUDED_SALHELPER_SALHELPERDLLAPI_H + +#include "sal/types.h" + +#if defined(SALHELPER_DLLIMPLEMENTATION) +#define SALHELPER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define SALHELPER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define SALHELPER_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_SALHELPER_SALHELPERDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/simplereferenceobject.hxx b/include/salhelper/simplereferenceobject.hxx new file mode 100644 index 000000000..ac721ad3d --- /dev/null +++ b/include/salhelper/simplereferenceobject.hxx @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_SIMPLEREFERENCEOBJECT_HXX +#define INCLUDED_SALHELPER_SIMPLEREFERENCEOBJECT_HXX + +#include "osl/interlck.h" +#include "salhelper/salhelperdllapi.h" + +#include +#include + +namespace salhelper { + +/** A simple base implementation for reference-counted objects. + + Classes that want to implement a reference-counting mechanism based on the + acquire()/release() interface should derive from this class. + + The reason to have class local operators new and delete here is technical. + Imagine a class D derived from SimpleReferenceObject, but implemented in + another shared library that happens to use different global operators new + and delete from those used in this shared library (which, sadly, seems to + be possible with shared libraries). Now, without the class local + operators new and delete here, a code sequence like "new D" would use the + global operator new as found in the other shared library, while the code + sequence "delete this" in release() would use the global operator delete + as found in this shared library---and these two operators would not be + guaranteed to match. + + There are no overloaded operators new and delete for placement new here, + because it is felt that the concept of placement new does not work well + with the concept of reference-counted objects; so it seems best to simply + leave those operators out. + + The same problem as with operators new and delete would also be there with + operators new[] and delete[]. But since arrays of reference-counted + objects are of no use, anyway, it seems best to simply + define operators new[] and delete[] as deleted. + */ +class SALHELPER_DLLPUBLIC SimpleReferenceObject +{ +public: + SimpleReferenceObject(): m_nCount(0) {} + + /** @attention + The results are undefined if, for any individual instance of + SimpleReferenceObject, the total number of calls to acquire() exceeds + the total number of calls to release() by a platform dependent amount + (which, hopefully, is quite large). + */ + void acquire() + { osl_atomic_increment(&m_nCount); } + + void release() + { if (osl_atomic_decrement(&m_nCount) == 0) delete this; } + + /** see general class documentation + */ + static void * operator new(std::size_t nSize); + + /** see general class documentation + */ + static void * operator new(std::size_t nSize, + std::nothrow_t const & rNothrow); + + /** see general class documentation + */ + static void operator delete(void * pPtr); + + /** see general class documentation + */ + static void operator delete(void * pPtr, std::nothrow_t const & rNothrow); + +protected: + virtual ~SimpleReferenceObject() COVERITY_NOEXCEPT_FALSE; + + oslInterlockedCount m_nCount; + +private: + /** not implemented + */ + SimpleReferenceObject(SimpleReferenceObject &) SAL_DELETED_FUNCTION; + + /** not implemented + */ + void operator =(SimpleReferenceObject) SAL_DELETED_FUNCTION; + + /** see general class documentation + */ + static void * operator new[](std::size_t) SAL_DELETED_FUNCTION; + + /** see general class documentation + */ + static void operator delete[](void * pPtr) SAL_DELETED_FUNCTION; +}; + +} + +#endif // INCLUDED_SALHELPER_SIMPLEREFERENCEOBJECT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/singletonref.hxx b/include/salhelper/singletonref.hxx new file mode 100644 index 000000000..191e585c1 --- /dev/null +++ b/include/salhelper/singletonref.hxx @@ -0,0 +1,203 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_SINGLETONREF_HXX +#define INCLUDED_SALHELPER_SINGLETONREF_HXX + +#include "sal/config.h" + +#include + +#include "osl/mutex.hxx" +#include "rtl/instance.hxx" +#include "osl/diagnose.h" +#include "osl/getglobalmutex.hxx" + + +namespace salhelper{ + + +/** @short template for implementing singleton classes. + + Such classes can be instantiated every time they + are needed. But the internal wrapped object will + be created one times only. Of course it's used + resources are referenced one times only too. + This template hold it alive till the last + reference is gone. Further all operations + on this reference are threadsafe. Only + calls directly to the internal object (which modify + its state) must be made threadsafe by the object itself + or from outside. + + @attention To prevent the code against race conditions, it's not + allowed to start operations inside the ctor + of the internal wrapped object - especially operations + which needs a reference to the same singleton too. + + The only chance to suppress such strange constellations + is a lazy-init mechanism. + +

      +
    • a) The singleton class can provide a special init() + method, which must be called as first after creation.
    • +
    • b) The singleton class can call a special impl_init() + method implicit for every called interface method.
    • +
    + + Note further that this singleton pattern can work only, if + all user of such singleton are located inside the same library! + Because static values can't be exported - e.g. from windows libraries. + */ +template< class SingletonClass > +class SingletonRef +{ + + // member + + private: + + /** @short pointer to the internal wrapped singleton. */ + static SingletonClass* m_pInstance; + + /** @short ref count, which regulate creation and removing of m_pInstance. */ + static sal_Int32 m_nRef; + + + // interface + + public: + + + /** @short standard ctor. + + The internal wrapped object is created only, + if its ref count was 0. Otherwise this method + does nothing ... except increasing of the internal + ref count! + */ + SingletonRef() + { + // GLOBAL SAFE -> + ::osl::MutexGuard aLock(SingletonRef::ownStaticLock()); + + // must be increased before(!) the check is done. + // Otherwise this check can fail inside the same thread ... + ++m_nRef; + if (m_nRef == 1) + m_pInstance = new SingletonClass(); + + OSL_ENSURE(m_nRef>0 && m_pInstance, "Race? Ref count of singleton >0, but instance is NULL!"); + // <- GLOBAL SAFE + } + + + /** @short standard dtor. + + The internal wrapped object is removed only, + if its ref count will be 0. Otherwise this method + does nothing ... except decreasing of the internal + ref count! + */ + ~SingletonRef() + { + // GLOBAL SAFE -> + ::osl::MutexGuard aLock(SingletonRef::ownStaticLock()); + + // must be decreased before(!) the check is done. + // Otherwise this check can fail inside the same thread ... + --m_nRef; + if (m_nRef == 0) + { + delete m_pInstance; + m_pInstance = NULL; + } + // <- GLOBAL SAFE + } + +#if defined LIBO_INTERNAL_ONLY + SingletonRef & operator =(SingletonRef const &) = default; +#endif + + /** @short Allows rSingle->someBodyOp(). + */ + SingletonClass* operator->() const + { + // GLOBAL SAFE -> + ::osl::MutexGuard aLock(SingletonRef::ownStaticLock()); + return m_pInstance; + // <- GLOBAL SAFE + } + + + /** @short Allows (*rSingle).someBodyOp(). + */ + SingletonClass& operator*() const + { + // GLOBAL SAFE -> + ::osl::MutexGuard aLock(SingletonRef::ownStaticLock()); + return *m_pInstance; + // <- GLOBAL SAFE + } + + + // helper + + private: + SingletonRef(SingletonRef &) SAL_DELETED_FUNCTION; + + /** @short creates an own mutex for guarding static contents. + + The global mutex the osl library is used one times + only to create an own static mutex, which can be used + next time to guard own static member operations. + */ + struct SingletonLockInit + { + ::osl::Mutex* operator()() + { + static ::osl::Mutex aInstance; + return &aInstance; + } + }; + + ::osl::Mutex& ownStaticLock() const + { + return *rtl_Instance< ::osl::Mutex, + SingletonLockInit, + ::osl::MutexGuard, + ::osl::GetGlobalMutex >::create(SingletonLockInit(), ::osl::GetGlobalMutex()); + } +}; + +template< class SingletonClass > +SingletonClass* SingletonRef< SingletonClass >::m_pInstance = NULL; + +template< class SingletonClass > +sal_Int32 SingletonRef< SingletonClass >::m_nRef = 0; + +} // namespace salhelper + +#endif // INCLUDED_SALHELPER_SINGLETONREF_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/thread.hxx b/include/salhelper/thread.hxx new file mode 100644 index 000000000..daea7f352 --- /dev/null +++ b/include/salhelper/thread.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_THREAD_HXX +#define INCLUDED_SALHELPER_THREAD_HXX + +#include "sal/config.h" + +#include + +#include "osl/thread.hxx" +#include "sal/types.h" +#include "salhelper/salhelperdllapi.h" +#include "salhelper/simplereferenceobject.hxx" + +namespace salhelper +{ +/** + A safe encapsulation of ::osl::Thread. + + @since LibreOffice 3.6 +*/ +class SALHELPER_DLLPUBLIC Thread : public salhelper::SimpleReferenceObject, private osl::Thread +{ +public: + /** + @param name the thread name, see ::osl_setThreadName; must be a non-null + null terminated string + */ + Thread(char const* name); + + /** + Launch the thread. + + This function must be called at most once. + + Each call of this function should eventually be followed by a call to + ::osl::Thread::join before exit(3), to ensure the thread is no longer + relying on any infrastructure while that infrastructure is being shut + down in atexit handlers. + */ + void launch(); + + using osl::Thread::getIdentifier; + using osl::Thread::join; + using osl::Thread::schedule; + using osl::Thread::terminate; + + // While the below static member functions should arguably always be called + // with qualified (osl::Thread) names, compilers would still complain that + // they are inaccessible from within derivations of salhelper::Thread (an + // alternative would be to force such derivations to use global names, + // prefixed with ::osl::Thread): + using osl::Thread::getCurrentIdentifier; + using osl::Thread::wait; + using osl::Thread::yield; + + static void* operator new(std::size_t size) + { + return SimpleReferenceObject::operator new(size); + } + + static void operator delete(void* pointer) { SimpleReferenceObject::operator delete(pointer); } + +protected: + virtual ~Thread() SAL_OVERRIDE; + + /** + The main function executed by the thread. + + Any uncaught exceptions lead to std::terminate. + */ + virtual void execute() = 0; + +private: + virtual void SAL_CALL run() SAL_OVERRIDE; + + virtual void SAL_CALL onTerminated() SAL_OVERRIDE; + + char const* name_; +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/salhelper/timer.hxx b/include/salhelper/timer.hxx new file mode 100644 index 000000000..8c0ce5d3a --- /dev/null +++ b/include/salhelper/timer.hxx @@ -0,0 +1,225 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/* + * This file is part of LibreOffice published API. + */ + +#ifndef INCLUDED_SALHELPER_TIMER_HXX +#define INCLUDED_SALHELPER_TIMER_HXX + +#include "salhelper/simplereferenceobject.hxx" +#include "osl/time.h" +#include "salhelper/salhelperdllapi.h" + +namespace salhelper +{ + +/** Helper class for easier manipulation with TimeValue. + * + * Times are seconds in UTC since 01.01.1970 + */ +struct SAL_WARN_UNUSED TTimeValue : public TimeValue +{ + TTimeValue() + { + Seconds = 0; + Nanosec = 0; + } + + TTimeValue( sal_uInt32 Secs, sal_uInt32 Nano ) + { + Seconds = Secs; + Nanosec = Nano; + + normalize(); + } + + TTimeValue(sal_uInt32 MilliSecs) + { + Seconds = MilliSecs / 1000; + Nanosec = (MilliSecs % 1000) * 1000000L; + + normalize(); + } + + TTimeValue( const TimeValue& rTimeValue ) + { + Seconds = rTimeValue.Seconds; + Nanosec = rTimeValue.Nanosec; + + normalize(); + } + + void SAL_CALL normalize() + { + if ( Nanosec > 1000000000 ) + { + Seconds += Nanosec / 1000000000; + Nanosec %= 1000000000; + } + } + + void SAL_CALL addTime( const TTimeValue& Delta ) + { + Seconds += Delta.Seconds; + Nanosec += Delta.Nanosec; + + normalize(); + } + + bool SAL_CALL isEmpty() const + { + return ( ( Seconds == 0 ) && ( Nanosec == 0 ) ); + } +}; + +inline bool operator<( const TTimeValue& rTimeA, const TTimeValue& rTimeB ) +{ + if ( rTimeA.Seconds < rTimeB.Seconds ) + return true; + else if ( rTimeA.Seconds > rTimeB.Seconds ) + return false; + else + return ( rTimeA.Nanosec < rTimeB.Nanosec ); +} + +inline bool operator>( const TTimeValue& rTimeA, const TTimeValue& rTimeB ) +{ + if ( rTimeA.Seconds > rTimeB.Seconds ) + return true; + else if ( rTimeA.Seconds < rTimeB.Seconds ) + return false; + else + return ( rTimeA.Nanosec > rTimeB.Nanosec ); +} + +inline bool operator==( const TTimeValue& rTimeA, const TTimeValue& rTimeB ) +{ + return ( ( rTimeA.Seconds == rTimeB.Seconds ) && + ( rTimeA.Nanosec == rTimeB.Nanosec ) ); +} + +class TimerManager; + +/** Interface for the Timer and handling the event +*/ +class SALHELPER_DLLPUBLIC Timer : public salhelper::SimpleReferenceObject +{ +public: + + /** Constructor. + */ + Timer(); + + /** Constructor. + */ + Timer( const TTimeValue& Time ); + + /** Constructor. + */ + Timer( const TTimeValue& Time, const TTimeValue& RepeatTime ); + + /** Start timer. + */ + void SAL_CALL start(); + + /** Abort timer prematurely. + */ + void SAL_CALL stop(); + + /** Returns sal_True if timer is running. + */ + sal_Bool SAL_CALL isTicking() const; + + /** Is the timer expired? + */ + sal_Bool SAL_CALL isExpired() const; + + /** Does pTimer expires before us? + */ + sal_Bool SAL_CALL expiresBefore( const Timer* pTimer ) const; + + /** Set the absolute time when the timer should fire. + */ + void SAL_CALL setAbsoluteTime( const TTimeValue& Time ); + + /** Set the time to fire to 'now' + Remaining. + */ + void SAL_CALL setRemainingTime( const TTimeValue& Remaining ); + + /** Set the time to fire to 'now' + Remaining with repeat interveal + * Repeat. + */ + void SAL_CALL setRemainingTime( const TTimeValue& Remaining, const TTimeValue& Repeat ); + + /** Adds Time to the 'fire time'. + */ + void SAL_CALL addTime( const TTimeValue& Time ); + + /** Returns the remaining time before timer expiration relative to now. + */ + TTimeValue SAL_CALL getRemainingTime() const; + +protected: + + /** Destructor. + */ + virtual ~Timer() SAL_OVERRIDE; + + /** What should be done when the 'timer fires'. + */ + virtual void SAL_CALL onShot() = 0; + +protected: + + /** holds (initial) expiration time of this timer. + */ + TTimeValue m_aTimeOut; + + /** holds the time of expiration of this timer. + */ + TTimeValue m_aExpired; + + /** holds the time interveal of successive expirations. + */ + TTimeValue m_aRepeatDelta; + + /** Pointer to the next timer (to fire). + */ + Timer* m_pNext; + +private: + + /** Copy constructor deleted. + */ + Timer( const Timer& rTimer ) SAL_DELETED_FUNCTION; + + /** Copy assignment operator deleted. + */ + void SAL_CALL operator=( const Timer& rTimer ) SAL_DELETED_FUNCTION; + + friend class TimerManager; +}; + +} + +#endif // INCLUDED_SALHELPER_TIMER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/fastattribs.hxx b/include/sax/fastattribs.hxx new file mode 100644 index 000000000..57619b922 --- /dev/null +++ b/include/sax/fastattribs.hxx @@ -0,0 +1,237 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_FASTATTRIBS_HXX +#define INCLUDED_SAX_FASTATTRIBS_HXX + +#include +#include +#include + +#include +#include + +#include +#include + +namespace com::sun::star::xml::sax { class XFastTokenHandler; } +namespace com::sun::star::xml { struct Attribute; } +namespace com::sun::star::xml { struct FastAttribute; } + +namespace sax_fastparser +{ + +struct UnknownAttribute +{ + OUString maNamespaceURL; + OString maName; + OString maValue; + + UnknownAttribute( OUString sNamespaceURL, OString aName, OString value ); + UnknownAttribute( OString sName, OString value ); + + void FillAttribute( css::xml::Attribute* pAttrib ) const; +}; + +/// A native C++ interface to tokenisation +class SAX_DLLPUBLIC FastTokenHandlerBase : + public cppu::WeakImplHelper< css::xml::sax::XFastTokenHandler > +{ + public: + virtual ~FastTokenHandlerBase(); + virtual sal_Int32 getTokenDirect( const char *pToken, sal_Int32 nLength ) const = 0; + + /** + * Client method to attempt the use of this interface if possible. + * @xTokenHandler - the token lookup interface + * @pStr - string buffer to lookup + * @nLength - optional length of chars in that buffer + * + * @return Tokenized form of pStr + */ + static sal_Int32 getTokenFromChars( + const FastTokenHandlerBase *pTokenHandler, + const char *pStr, size_t nLength ); +}; + + +class SAX_DLLPUBLIC FastAttributeList final : public cppu::WeakImplHelper< css::xml::sax::XFastAttributeList, css::util::XCloneable > +{ +public: + FastAttributeList( FastTokenHandlerBase *pTokenHandler ); + FastAttributeList( const css::uno::Reference< css::xml::sax::XFastAttributeList > & xAttrList ); + virtual ~FastAttributeList() override; + + void clear(); + void reserve( sal_Int32 nNumTokens ) + { + maAttributeValues.reserve(nNumTokens+1); + maAttributeTokens.reserve(nNumTokens); + } + void add( const FastAttributeList& ); + void add( const css::uno::Reference& ); + void add( sal_Int32 nToken, const char* pValue ); + void add( sal_Int32 nToken, const char* pValue, size_t nValueLength ); + void add( sal_Int32 nToken, const OString& rValue ); + void add( sal_Int32 nToken, std::u16string_view sValue ); // Converts to UTF-8 + void addNS( sal_Int32 nNamespaceToken, sal_Int32 nToken, const OString& rValue ); + void addNS( sal_Int32 nNamespaceToken, sal_Int32 nToken, std::u16string_view sValue ); + // note: rQName is *namespace-prefixed* + void addUnknown( const OUString& rNamespaceURL, const OString& rQName, const OString& value ); + void addUnknown( const OString& rName, const OString& value ); + const std::vector< sal_Int32 >& getFastAttributeTokens() const { return maAttributeTokens; } + const char* getFastAttributeValue(size_t nIndex) const { return mpChunk + maAttributeValues[nIndex]; } + sal_Int32 AttributeValueLength(size_t i) const { return maAttributeValues[i + 1] - maAttributeValues[i] - 1; } + size_t size() const { return maAttributeValues.size(); } + + // performance sensitive shortcuts to avoid allocation ... + bool getAsInteger( sal_Int32 nToken, sal_Int32 &rInt) const; + bool getAsDouble( sal_Int32 nToken, double &rDouble) const; + bool getAsChar( sal_Int32 nToken, const char*& rPos ) const; + sal_Int32 getAsIntegerByIndex( sal_Int32 nTokenIndex ) const; + const char* getAsCharByIndex( sal_Int32 nTokenIndex ) const; + OUString getValueByIndex( sal_Int32 nTokenIndex ) const; + + // XFastAttributeList + virtual sal_Bool SAL_CALL hasAttribute( ::sal_Int32 Token ) override; + virtual ::sal_Int32 SAL_CALL getValueToken( ::sal_Int32 Token ) override; + virtual ::sal_Int32 SAL_CALL getOptionalValueToken( ::sal_Int32 Token, ::sal_Int32 Default ) override; + virtual OUString SAL_CALL getValue( ::sal_Int32 Token ) override; + virtual OUString SAL_CALL getOptionalValue( ::sal_Int32 Token ) override; + virtual css::uno::Sequence< css::xml::Attribute > SAL_CALL getUnknownAttributes( ) override; + virtual css::uno::Sequence< css::xml::FastAttribute > SAL_CALL getFastAttributes() override; + + // XCloneable + virtual ::css::uno::Reference< ::css::util::XCloneable > SAL_CALL createClone() override; + + sal_Int32 getAttributeIndex( ::sal_Int32 Token ) + { + for (size_t i=0; i maAttributeValues; + std::vector< sal_Int32 > maAttributeTokens; + std::vector< UnknownAttribute > maUnknownAttributes; + FastTokenHandlerBase * mpTokenHandler; +}; + +inline FastAttributeList& castToFastAttributeList( + const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttrList ) +{ + assert( dynamic_cast ( xAttrList.get() ) != nullptr ); + return *static_cast ( xAttrList.get() ); +} + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/fastparser.hxx b/include/sax/fastparser.hxx new file mode 100644 index 000000000..aebaa4056 --- /dev/null +++ b/include/sax/fastparser.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_FASTPARSER_HXX +#define INCLUDED_SAX_FASTPARSER_HXX + +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::xml::sax { + class XFastDocumentHandler; + class XFastTokenHandler; +} + +namespace sax_fastparser { + + +class FastSaxParserImpl; + +// This class implements the external Parser interface +class FASTSAX_DLLPUBLIC FastSaxParser final + : public ::cppu::WeakImplHelper< + css::lang::XInitialization, + css::xml::sax::XFastParser, + css::lang::XServiceInfo > +{ + std::unique_ptr mpImpl; + +public: + FastSaxParser(); + virtual ~FastSaxParser() override; + + // css::lang::XInitialization: + virtual void SAL_CALL initialize(css::uno::Sequence const& rArguments) override; + + // XFastParser + virtual void SAL_CALL parseStream( const css::xml::sax::InputSource& aInputSource ) override; + virtual void SAL_CALL setFastDocumentHandler( const css::uno::Reference< css::xml::sax::XFastDocumentHandler >& Handler ) override; + virtual void SAL_CALL setTokenHandler( const css::uno::Reference< css::xml::sax::XFastTokenHandler >& Handler ) override; + virtual void SAL_CALL registerNamespace( const OUString& NamespaceURL, sal_Int32 NamespaceToken ) override; + virtual OUString SAL_CALL getNamespaceURL( const OUString& rPrefix ) override; + virtual void SAL_CALL setErrorHandler( const css::uno::Reference< css::xml::sax::XErrorHandler >& Handler ) override; + virtual void SAL_CALL setEntityResolver( const css::uno::Reference< css::xml::sax::XEntityResolver >& Resolver ) override; + virtual void SAL_CALL setLocale( const css::lang::Locale& rLocale ) override; + virtual void SAL_CALL setNamespaceHandler( const css::uno::Reference< css::xml::sax::XFastNamespaceHandler >& Handler) override; + virtual void SAL_CALL setCustomEntityNames( const ::css::uno::Sequence< ::css::beans::Pair<::rtl::OUString, ::rtl::OUString> >& replacements ) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName( ) override; + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override; + virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override; +}; + +} + +#endif // _SAX_FASTPARSER_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/fastsaxdllapi.h b/include/sax/fastsaxdllapi.h new file mode 100644 index 000000000..e532dd2c5 --- /dev/null +++ b/include/sax/fastsaxdllapi.h @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_FASTSAXDLLAPI_H +#define INCLUDED_SAX_FASTSAXDLLAPI_H + +#include + +#if defined FASTSAX_DLLIMPLEMENTATION +#define FASTSAX_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define FASTSAX_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/fshelper.hxx b/include/sax/fshelper.hxx new file mode 100644 index 000000000..79f0e1a0f --- /dev/null +++ b/include/sax/fshelper.hxx @@ -0,0 +1,178 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_FSHELPER_HXX +#define INCLUDED_SAX_FSHELPER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::io { class XOutputStream; } +namespace sax_fastparser { class FastAttributeList; } + +constexpr sal_Int32 FSNS(sal_Int32 namespc, sal_Int32 element) { return (namespc << 16) | element; } + +namespace sax_fastparser { + +enum class MergeMarks { APPEND = 0, PREPEND = 1, POSTPONE = 2}; + +class FastSaxSerializer; + +class SAX_DLLPUBLIC FastSerializerHelper +{ +public: + + FastSerializerHelper( const css::uno::Reference< css::io::XOutputStream >& xOutputStream, bool bWriteHeader ); + + ~FastSerializerHelper(); + + /// Start an element. After the first argument there can be a number of (attribute, value) pairs. + template + void startElement(sal_Int32 elementTokenId, sal_Int32 attribute, const char* value, Args &&... args) + { + if (value) + pushAttributeValue(attribute, value); + startElement(elementTokenId, std::forward(args)...); + } + template + void startElement(sal_Int32 elementTokenId, sal_Int32 attribute, + const std::optional& value, Args&&... args) + { + if (value) + pushAttributeValue(attribute, *value); + startElement(elementTokenId, std::forward(args)...); + } + template + void startElement(sal_Int32 elementTokenId, sal_Int32 attribute, + const std::optional& value, Args&&... args) + { + std::optional opt; + if (value) + opt = value->toUtf8(); + startElement(elementTokenId, attribute, opt, std::forward(args)...); + } + void startElement(sal_Int32 elementTokenId); + + /// Start an element. After the first two arguments there can be a number of (attribute, value) pairs. + template + void startElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, Args &&... args) + { + startElement(FSNS(namespaceTokenId, elementTokenId), std::forward(args)...); + } + + /// Create a single element. After the first argument there can be a number of (attribute, value) pairs. + template + void singleElement(sal_Int32 elementTokenId, sal_Int32 attribute, const char* value, Args &&... args) + { + if (value) + pushAttributeValue(attribute, value); + singleElement(elementTokenId, std::forward(args)...); + } + template + void singleElement(sal_Int32 elementTokenId, sal_Int32 attribute, + const std::optional& value, Args&&... args) + { + if (value) + pushAttributeValue(attribute, *value); + singleElement(elementTokenId, std::forward(args)...); + } + template + void singleElement(sal_Int32 elementTokenId, sal_Int32 attribute, + const std::optional& value, Args&&... args) + { + std::optional opt; + if (value) + opt = value->toUtf8(); + singleElement(elementTokenId, attribute, opt, std::forward(args)...); + } + void singleElement(sal_Int32 elementTokenId); + + /// Create a single element. After the first two arguments there can be a number of (attribute, value) pairs. + template + void singleElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, Args &&... args) + { + singleElement(FSNS(namespaceTokenId, elementTokenId), std::forward(args)...); + } + + void endElement(sal_Int32 elementTokenId); + void endElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId) + { endElement( FSNS( namespaceTokenId, elementTokenId ) ); } + + void singleElement(sal_Int32 elementTokenId, const rtl::Reference& xAttrList); + void singleElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, rtl::Reference const & xAttrList) + { singleElement(FSNS( namespaceTokenId, elementTokenId), xAttrList); } + + void startElement(sal_Int32 elementTokenId, const rtl::Reference& xAttrList); + void startElementNS(sal_Int32 namespaceTokenId, sal_Int32 elementTokenId, rtl::Reference const & xAttrList) + { startElement( FSNS( namespaceTokenId, elementTokenId ), xAttrList ); } + + FastSerializerHelper* write(const char* value); + FastSerializerHelper* write(const OString& value); + FastSerializerHelper* write(std::u16string_view value); + FastSerializerHelper* write(sal_Int32 value); + FastSerializerHelper* write(sal_Int64 value); + FastSerializerHelper* write(double value); + + FastSerializerHelper* writeEscaped(const char* value); + FastSerializerHelper* writeEscaped(std::u16string_view value); + + FastSerializerHelper* writeId(sal_Int32 tokenId); + + css::uno::Reference< css::io::XOutputStream > const & getOutputStream() const; + + static rtl::Reference createAttrList(); + + void mark(sal_Int32 nTag, + const css::uno::Sequence< sal_Int32 >& rOrder = + css::uno::Sequence< sal_Int32 >() ); + void mergeTopMarks(sal_Int32 nTag, + MergeMarks eMergeType = MergeMarks::APPEND ); + +private: + void pushAttributeValue( sal_Int32 attribute, const char* value ); + void pushAttributeValue( sal_Int32 attribute, const OString& value ); + + FastSaxSerializer* mpSerializer; +}; + +typedef std::shared_ptr< FastSerializerHelper > FSHelperPtr; + +// Helpers to make intention to pass optional attributes to *Element functions explicit, instead of +// using `(condition) ? value.toUtf8().getStr() : nullptr` syntax. +inline const char* UseIf(const char* s, bool bUse) { return bUse ? s : nullptr; } +// OString, OUString +template +std::optional UseIf(const TString& s, bool bUse) +{ + return bUse ? std::optional(s) : std::optional(); +} + +} + +#endif // INCLUDED_SAX_FSHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/saxdllapi.h b/include/sax/saxdllapi.h new file mode 100644 index 000000000..9b56b94ce --- /dev/null +++ b/include/sax/saxdllapi.h @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_SAXDLLAPI_H +#define INCLUDED_SAX_SAXDLLAPI_H + +#include + +#if defined SAX_DLLIMPLEMENTATION +#define SAX_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define SAX_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/tools/converter.hxx b/include/sax/tools/converter.hxx new file mode 100644 index 000000000..d797eace3 --- /dev/null +++ b/include/sax/tools/converter.hxx @@ -0,0 +1,313 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SAX_TOOLS_CONVERTER_HXX +#define INCLUDED_SAX_TOOLS_CONVERTER_HXX + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace uno { + class Any; + } + namespace util { + struct Date; + struct DateTime; + struct Duration; + } +} + +namespace sax { + +/** the Converter converts values of various types from + their internal representation to the textual form used in xml + and back. + + All unit types are expressed as css::util::MeasureUnit +*/ + + +class SAX_DLLPUBLIC Converter +{ +public: + /** convert string to measure using optional min and max values*/ + static bool convertMeasure( sal_Int32& rValue, + std::u16string_view rString, + sal_Int16 nTargetUnit = css::util::MeasureUnit::MM_100TH, + sal_Int32 nMin = SAL_MIN_INT32, + sal_Int32 nMax = SAL_MAX_INT32 ); + + /** convert string to measure using optional min and max values*/ + static bool convertMeasure( sal_Int32& rValue, + std::string_view rString, + sal_Int16 nTargetUnit = css::util::MeasureUnit::MM_100TH, + sal_Int32 nMin = SAL_MIN_INT32, + sal_Int32 nMax = SAL_MAX_INT32 ); + + /** convert measure to string */ + static void convertMeasure( OUStringBuffer& rBuffer, + sal_Int32 nMeasure, + sal_Int16 SourceUnit, + sal_Int16 nTargetUnit ); + + /** convert string to boolean */ + static bool convertBool( bool& rBool, + std::u16string_view rString ); + + /** convert string to boolean */ + static bool convertBool( bool& rBool, + std::string_view rString ); + + /** convert boolean to string */ + static void convertBool( OUStringBuffer& rBuffer, + bool bValue ); + + /** convert string to percent */ + static bool convertPercent( sal_Int32& rValue, + std::u16string_view rString ); + + /** convert string to percent */ + static bool convertPercent( sal_Int32& rValue, + std::string_view rString ); + + /** convert percent to string */ + static void convertPercent( OUStringBuffer& rBuffer, + sal_Int32 nValue ); + + /** convert string to pixel measure unit */ + static bool convertMeasurePx( sal_Int32& rValue, + std::u16string_view rString ); + + /** convert string to pixel measure unit */ + static bool convertMeasurePx( sal_Int32& rValue, + std::string_view rString ); + + /** convert pixel measure unit to string */ + static void convertMeasurePx( OUStringBuffer& rBuffer, + sal_Int32 nValue ); + + /** convert string to rgb color */ + static bool convertColor( sal_Int32& rColor, + std::u16string_view rValue ); + static bool convertColor( sal_Int32& rColor, + std::string_view rValue ); + static bool convertColor( ::Color& rColor, + std::u16string_view rValue ) + { + sal_Int32 n(rColor); + bool b = convertColor( n, rValue ); + if (b) rColor = Color(ColorTransparency, n); + return b; + } + static bool convertColor( ::Color& rColor, + std::string_view rValue ) + { + sal_Int32 n(rColor); + bool b = convertColor( n, rValue ); + if (b) rColor = Color(ColorTransparency, n); + return b; + } + + /** convert color to string */ + static void convertColor( OUStringBuffer &rBuffer, + sal_Int32 nColor ); + static void convertColor( OUStringBuffer &rBuffer, + ::Color nColor ) + { convertColor( rBuffer, sal_Int32(nColor) ); } + + /** convert string to number with optional min and max values */ + static bool convertNumber( sal_Int32& rValue, + std::u16string_view aString, + sal_Int32 nMin = SAL_MIN_INT32, + sal_Int32 nMax = SAL_MAX_INT32 ); + + /** convert string to number with optional min and max values */ + static bool convertNumber( sal_Int32& rValue, + std::string_view aString, + sal_Int32 nMin = SAL_MIN_INT32, + sal_Int32 nMax = SAL_MAX_INT32 ); + + /** convert string to number with optional min and max values */ + static bool convertNumber64(sal_Int64& rValue, + std::u16string_view aString, + sal_Int64 nMin = SAL_MIN_INT64, + sal_Int64 nMax = SAL_MAX_INT64); + + /** convert string to number with optional min and max values */ + static bool convertNumber64(sal_Int64& rValue, + std::string_view aString, + sal_Int64 nMin = SAL_MIN_INT64, + sal_Int64 nMax = SAL_MAX_INT64); + + /** convert double number to string (using ::rtl::math) and + DO convert from source unit to target unit */ + static void convertDouble( OUStringBuffer& rBuffer, + double fNumber, + bool bWriteUnits, + sal_Int16 nSourceUnit, + sal_Int16 nTargetUnit ); + + /** convert double number to string (using ::rtl::math) without unit conversion */ + static void convertDouble( OUStringBuffer& rBuffer, double fNumber); + + /** convert string to double number (using ::rtl::math) and DO convert from + source unit to target unit. */ + static bool convertDouble( double& rValue, + std::u16string_view rString, + sal_Int16 nSourceUnit, + sal_Int16 nTargetUnit ); + + /** convert string to double number (using ::rtl::math) and DO convert from + source unit to target unit. */ + static bool convertDouble( double& rValue, + std::string_view rString, + sal_Int16 nSourceUnit, + sal_Int16 nTargetUnit ); + + /** convert string to double number (using ::rtl::math) without unit conversion */ + static bool convertDouble(double& rValue, std::u16string_view rString); + + /** convert string to double number (using ::rtl::math) without unit conversion */ + static bool convertDouble(double& rValue, std::string_view rString); + + /** convert number, 10th of degrees with range [0..3600] to SVG angle */ + static void convertAngle(OUStringBuffer& rBuffer, sal_Int16 nAngle, + SvtSaveOptions::ODFSaneDefaultVersion nVersion); + + /** convert SVG angle to number, 10th of degrees with range [0..3600] */ + static bool convertAngle(sal_Int16& rAngle, std::u16string_view rString, + bool isWrongOOo10thDegAngle); + + /** convert SVG angle to number, 10th of degrees with range [0..3600] */ + static bool convertAngle(sal_Int16& rAngle, std::string_view rString, + bool isWrongOOo10thDegAngle); + + /** convert double to XMLSchema-2 "duration" string; negative durations allowed */ + static void convertDuration(OUStringBuffer& rBuffer, + const double fTime); + + /** convert util::Duration to XMLSchema-2 "duration" string */ + static void convertDuration(OUStringBuffer& rBuffer, + const css::util::Duration& rDuration); + + /** convert XMLSchema-2 "duration" string to double; negative durations allowed */ + static bool convertDuration(double & rfTime, + std::string_view rString); + + /** convert XMLSchema-2 "duration" string to util::Duration */ + static bool convertDuration(css::util::Duration& rDuration, + std::u16string_view rString); + + /** convert XMLSchema-2 "duration" string to util::Duration */ + static bool convertDuration(css::util::Duration& rDuration, + std::string_view rString); + + /** convert util::Date to XMLSchema-2 "date" string */ + static void convertDate( OUStringBuffer& rBuffer, + const css::util::Date& rDate, + sal_Int16 const* pTimeZoneOffset); + + /** convert util::DateTime to XMLSchema-2 "date" or "dateTime" string */ + static void convertDateTime( OUStringBuffer& rBuffer, + const css::util::DateTime& rDateTime, + sal_Int16 const* pTimeZoneOffset, + bool bAddTimeIf0AM = false ); + + /** convert util::DateTime to XMLSchema-2 "time" or "dateTime" string */ + static void convertTimeOrDateTime(OUStringBuffer& rBuffer, + const css::util::DateTime& rDateTime); + + /** convert XMLSchema-2 "date" or "dateTime" string to util::DateTime */ + static bool parseDateTime( css::util::DateTime& rDateTime, + std::u16string_view rString ); + + /** convert XMLSchema-2 "date" or "dateTime" string to util::DateTime */ + static bool parseDateTime( css::util::DateTime& rDateTime, + std::string_view rString ); + + /** convert XMLSchema-2 "time" or "dateTime" string to util::DateTime */ + static bool parseTimeOrDateTime(css::util::DateTime& rDateTime, + std::u16string_view rString); + + /** convert XMLSchema-2 "time" or "dateTime" string to util::DateTime */ + static bool parseTimeOrDateTime(css::util::DateTime& rDateTime, + std::string_view rString); + + /** convert XMLSchema-2 "date" or "dateTime" string to util::DateTime or + util::Date */ + static bool parseDateOrDateTime( + css::util::Date * pDate, + css::util::DateTime & rDateTime, + bool & rbDateTime, + std::optional * pTimeZoneOffset, + std::u16string_view rString ); + + /** convert XMLSchema-2 "date" or "dateTime" string to util::DateTime or + util::Date */ + static bool parseDateOrDateTime( + css::util::Date * pDate, + css::util::DateTime & rDateTime, + bool & rbDateTime, + std::optional * pTimeZoneOffset, + std::string_view rString ); + + /** gets the position of the first comma after npos in the string + rStr. Commas inside '"' pairs are not matched */ + static sal_Int32 indexOfComma( std::u16string_view rStr, + sal_Int32 nPos ); + + static double GetConversionFactor(OUStringBuffer& rUnit, sal_Int16 nSourceUnit, sal_Int16 nTargetUnit); + static double GetConversionFactor(OStringBuffer& rUnit, sal_Int16 nSourceUnit, sal_Int16 nTargetUnit); + static sal_Int16 GetUnitFromString(std::u16string_view rString, sal_Int16 nDefaultUnit); + static sal_Int16 GetUnitFromString(std::string_view rString, sal_Int16 nDefaultUnit); + + /** convert an Any to string (typesafe) */ + static bool convertAny(OUStringBuffer& rsValue, + OUStringBuffer& rsType , + const css::uno::Any& rValue); + + /** convert specified byte sequence to xsd:hexBinary string **/ + static void convertBytesToHexBinary(OUStringBuffer& rBuffer, const void* pBytes, + sal_Int32 nBytes); + + template , int> = 0> + static void convertNumberToHexBinary(OUStringBuffer& rBuffer, T n) + { + convertBytesToHexBinary(rBuffer, &n, sizeof(n)); + } + +}; + +} + +#endif // INCLUDED_SAX_TOOLS_CONVERTER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sax/tools/documenthandleradapter.hxx b/include/sax/tools/documenthandleradapter.hxx new file mode 100644 index 000000000..0296abfd6 --- /dev/null +++ b/include/sax/tools/documenthandleradapter.hxx @@ -0,0 +1,214 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SAX_TOOLS_DOCUMENTHANDLERADAPTER_HXX +#define INCLUDED_SAX_TOOLS_DOCUMENTHANDLERADAPTER_HXX + +#include +#include + +namespace sax +{ + /** + * DocumentHandlerAdapter provides a base class for simple decorators to XDocumentHandlers. + * It forwards all method calls to a delegate. An inheriting class only needs to override the + * methods it actually wants to modify. + * + * See filters/source/odfflatxml/FlatXml.cxx for an example. + */ + class DocumentHandlerAdapter : public css::xml::sax::XDocumentHandler + { + public: + // XDocumentHandler + virtual void SAL_CALL + startDocument() override + { + m_handler->startDocument(); + } + + virtual void SAL_CALL + endDocument() override + { + m_handler->endDocument(); + } + + virtual void SAL_CALL + startElement(const OUString& aName, + const css::uno::Reference< css::xml::sax::XAttributeList > & xAttribs) override + { + m_handler->startElement(aName, xAttribs); + } + + virtual void SAL_CALL + endElement(const OUString& aName) override + { + m_handler->endElement(aName); + } + + virtual void SAL_CALL + characters(const OUString& aChars) override + { + m_handler->characters(aChars); + } + + virtual void SAL_CALL + ignorableWhitespace(const OUString& aWhitespaces) override + { + m_handler->ignorableWhitespace(aWhitespaces); + } + virtual void SAL_CALL + processingInstruction(const OUString& aTarget, const OUString& aData) override + { + m_handler->processingInstruction(aTarget, aData); + } + virtual void SAL_CALL + setDocumentLocator(const css::uno::Reference< css::xml::sax::XLocator > & xLocator) override + { + m_handler->setDocumentLocator(xLocator); + } + DocumentHandlerAdapter() : + m_handler(css::uno::Reference< css::xml::sax::XDocumentHandler > (nullptr, css::uno::UNO_QUERY)) + { + } + ; + + protected: + void + setDelegate(const css::uno::Reference< css::xml::sax::XDocumentHandler >& delegate) + { + m_handler = delegate; + } + const css::uno::Reference< css::xml::sax::XDocumentHandler >& + getDelegate() const + { + return m_handler; + } + virtual + ~DocumentHandlerAdapter() + { + + } + + private: + css::uno::Reference< css::xml::sax::XDocumentHandler > m_handler; + + }; + + /** + * ExtendedDocumentHandlerAdapter provides a base class for simple decorators to XExtendedDocumentHandlers. + * It forwards all method calls to a delegate. An inheriting class only needs to override the + * methods it actually wants to modify. + */ + class ExtendedDocumentHandlerAdapter : public css::xml::sax::XExtendedDocumentHandler + + { + + public: + // XDocumentHandler + virtual void SAL_CALL + startDocument() override + { + m_handler->startDocument(); + } + + virtual void SAL_CALL + endDocument() override + { + m_handler->endDocument(); + } + + virtual void SAL_CALL + startElement(const OUString& aName, + const css::uno::Reference< css::xml::sax::XAttributeList > & xAttribs) override + { + m_handler->startElement(aName, xAttribs); + } + + virtual void SAL_CALL + endElement(const OUString& aName) override + { + m_handler->endElement(aName); + } + + virtual void SAL_CALL + characters(const OUString& aChars) override + { + m_handler->characters(aChars); + } + + virtual void SAL_CALL + ignorableWhitespace(const OUString& aWhitespaces) override + { + m_handler->ignorableWhitespace(aWhitespaces); + } + virtual void SAL_CALL + processingInstruction(const OUString& aTarget, const OUString& aData) override + { + m_handler->processingInstruction(aTarget, aData); + } + virtual void SAL_CALL + setDocumentLocator(const css::uno::Reference< css::xml::sax::XLocator > & xLocator) override + { + m_handler->setDocumentLocator(xLocator); + } + // XExtendedDocumentHandler + virtual void SAL_CALL + startCDATA() override + { + m_handler->startCDATA(); + } + virtual void SAL_CALL + endCDATA() override + { + m_handler->endCDATA(); + } + virtual void SAL_CALL + comment(const OUString& sComment) override + { + m_handler->comment(sComment); + } + virtual void SAL_CALL + unknown(const OUString& sString) override + { + m_handler->unknown(sString); + } + virtual void SAL_CALL + allowLineBreak() override + { + m_handler->allowLineBreak(); + } + protected: + ExtendedDocumentHandlerAdapter() : + m_handler(css::uno::Reference< css::xml::sax::XExtendedDocumentHandler > (nullptr, css::uno::UNO_QUERY)) + { + } + + void + setDelegate(const css::uno::Reference< css::xml::sax::XExtendedDocumentHandler >& delegate) + { + m_handler = delegate; + } + const css::uno::Reference< css::xml::sax::XExtendedDocumentHandler >& + getDelegate() const + { + return m_handler; + } + virtual + ~ExtendedDocumentHandlerAdapter() + { + + } + + private: + css::uno::Reference< css::xml::sax::XExtendedDocumentHandler > m_handler; + }; +} +#endif // INCLUDED_SAX_TOOLS_DOCUMENTHANDLERADAPTER_HXX +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/AccessibilityCheck.hxx b/include/sfx2/AccessibilityCheck.hxx new file mode 100644 index 000000000..4c90ad31d --- /dev/null +++ b/include/sfx2/AccessibilityCheck.hxx @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include + +namespace sfx +{ +class SFX2_DLLPUBLIC AccessibilityCheck +{ +protected: + AccessibilityIssueCollection m_aIssueCollection; + +public: + AccessibilityCheck() = default; + virtual ~AccessibilityCheck(); + + virtual void check() = 0; + + AccessibilityIssueCollection& getIssueCollection(); +}; + +} // end sfx namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/AccessibilityIssue.hxx b/include/sfx2/AccessibilityIssue.hxx new file mode 100644 index 000000000..4cc9a72e7 --- /dev/null +++ b/include/sfx2/AccessibilityIssue.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include +#include +#include + +namespace sfx +{ +enum class AccessibilityIssueID +{ + UNSPECIFIED, // TODO: remove - temporary + DOCUMENT_TITLE, + DOCUMENT_LANGUAGE, + STYLE_LANGUAGE, + NO_ALT_OLE, + NO_ALT_GRAPHIC, + NO_ALT_SHAPE, + TABLE_MERGE_SPLIT, + TEXT_FORMATTING, +}; + +class SFX2_DLLPUBLIC AccessibilityIssue +{ +public: + AccessibilityIssue(AccessibilityIssueID eIssueID = AccessibilityIssueID::UNSPECIFIED); + virtual ~AccessibilityIssue(); + + virtual bool canGotoIssue() const = 0; + virtual void gotoIssue() const = 0; + + AccessibilityIssueID m_eIssueID; + OUString m_aIssueText; +}; + +class SFX2_DLLPUBLIC AccessibilityIssueCollection +{ +private: + std::vector> m_aIssues; + +public: + AccessibilityIssueCollection() = default; + + std::vector>& getIssues(); +}; + +} // end sfx namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/DocumentMetadataAccess.hxx b/include/sfx2/DocumentMetadataAccess.hxx new file mode 100644 index 000000000..bcbf9f1b3 --- /dev/null +++ b/include/sfx2/DocumentMetadataAccess.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_DOCUMENTMETADATAACCESS_HXX +#define INCLUDED_SFX2_DOCUMENTMETADATAACCESS_HXX + +#include + +#include + +#include + +#include + +#include + + +/** Implementation of the interface com.sun.star.rdf.XDocumentMetadataAccess + + This is not a service only because it needs some kind of XML ID registry + from the document, and i do not like defining an API for that. + Also, the implementation does _no_ locking, so make sure access is + protected externally. + */ + +namespace com::sun::star::embed { + class XStorage; +} +namespace com::sun::star::frame { + class XModel; +} + +namespace com::sun::star::uno { class XComponentContext; } + +class SfxObjectShell; + +namespace sfx2 { + + +/** create a base URI for loading metadata from an ODF (sub)document. + + @param i_xContext component context + @param i_xModel model of the document (required if no URI is provided) + @param i_rPkgURI the URI for the package + @param i_rSubDocument (optional) path of the subdocument in package + + @return a base URI suitable for XDocumentMetadataAccess::loadFromStorage + */ +css::uno::Reference< css::rdf::XURI> SFX2_DLLPUBLIC +createBaseURI( + css::uno::Reference const & i_xContext, + css::uno::Reference const & i_xModel, + OUString const & i_rPkgURI, + std::u16string_view i_rSubDocument = std::u16string_view()); + + +struct DocumentMetadataAccess_Impl; + +class DocumentMetadataAccess final : + public cppu::WeakImplHelper +{ + DocumentMetadataAccess(const DocumentMetadataAccess&) = delete; + DocumentMetadataAccess& operator=( const DocumentMetadataAccess& ) = delete; +public: + explicit DocumentMetadataAccess(css::uno::Reference< css::uno::XComponentContext > const & i_xContext, + SfxObjectShell const & i_rRegistrySupplier, + OUString const & i_rBaseURI); + // N.B.: in contrast to previous, this constructor does _not_ initialize! + // caller must immediately call loadFromStorage/Medium! + explicit DocumentMetadataAccess(css::uno::Reference< css::uno::XComponentContext > const & i_xContext, + SfxObjectShell const & i_rRegistrySupplier); + virtual ~DocumentMetadataAccess() override; + + // css::rdf::XNode: + virtual OUString SAL_CALL getStringValue() override; + + // css::rdf::XURI: + virtual OUString SAL_CALL getNamespace() override; + virtual OUString SAL_CALL getLocalName() override; + + // css::rdf::XRepositorySupplier: + virtual css::uno::Reference< + css::rdf::XRepository > SAL_CALL getRDFRepository() override; + + // css::rdf::XDocumentMetadataAccess: + virtual css::uno::Reference< + css::rdf::XMetadatable > SAL_CALL + getElementByMetadataReference( + const css::beans::StringPair & i_rReference) override; + virtual css::uno::Reference< css::rdf::XMetadatable > SAL_CALL + getElementByURI(const css::uno::Reference< css::rdf::XURI > & i_xURI) override; + virtual css::uno::Sequence< css::uno::Reference< css::rdf::XURI > > SAL_CALL getMetadataGraphsWithType( + const css::uno::Reference< css::rdf::XURI > & i_xType) override; + virtual css::uno::Reference< css::rdf::XURI> SAL_CALL + addMetadataFile(const OUString & i_rFileName, + const css::uno::Sequence< css::uno::Reference< css::rdf::XURI > > & i_rTypes) override; + virtual css::uno::Reference< css::rdf::XURI> SAL_CALL + importMetadataFile(::sal_Int16 i_Format, + const css::uno::Reference< css::io::XInputStream > & i_xInStream, + const OUString & i_rFileName, + const css::uno::Reference< css::rdf::XURI > & i_xBaseURI, + const css::uno::Sequence< css::uno::Reference< css::rdf::XURI > > & i_rTypes) override; + virtual void SAL_CALL removeMetadataFile( + const css::uno::Reference< + css::rdf::XURI > & i_xGraphName) override; + virtual void SAL_CALL addContentOrStylesFile( + const OUString & i_rFileName) override; + virtual void SAL_CALL removeContentOrStylesFile( + const OUString & i_rFileName) override; + + virtual void SAL_CALL loadMetadataFromStorage( + const css::uno::Reference< + css::embed::XStorage > & i_xStorage, + const css::uno::Reference< + css::rdf::XURI > & i_xBaseURI, + const css::uno::Reference< + css::task::XInteractionHandler> & i_xHandler) override; + virtual void SAL_CALL storeMetadataToStorage( + const css::uno::Reference< + css::embed::XStorage > & i_xStorage) override; + virtual void SAL_CALL loadMetadataFromMedium( + const css::uno::Sequence< + css::beans::PropertyValue > & i_rMedium) override; + virtual void SAL_CALL storeMetadataToMedium( + const css::uno::Sequence< + css::beans::PropertyValue > & i_rMedium) override; + +private: + std::unique_ptr m_pImpl; +}; + +} // namespace sfx2 + +#endif // INCLUDED_SFX2_DOCUMENTMETADATAACCESS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/DocumentSigner.hxx b/include/sfx2/DocumentSigner.hxx new file mode 100644 index 000000000..8059cb9cb --- /dev/null +++ b/include/sfx2/DocumentSigner.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#ifndef INCLUDED_SFX2_DOCUMENTSIGNER_HXX +#define INCLUDED_SFX2_DOCUMENTSIGNER_HXX + +#include +#include +#include + +namespace com::sun::star::security +{ +class XCertificate; +} +namespace com::sun::star::uno +{ +template class Reference; +} + +namespace sfx2 +{ +class SFX2_DLLPUBLIC DocumentSigner +{ +private: + OUString m_aUrl; + +public: + DocumentSigner(OUString const& rUrl) + : m_aUrl(rUrl) + { + } + + bool signDocument(css::uno::Reference const& rxCertificate); +}; + +} // namespace sfx2 + +#endif // INCLUDED_SFX2_DOCUMENTSIGNER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/LokControlHandler.hxx b/include/sfx2/LokControlHandler.hxx new file mode 100644 index 000000000..c422afc97 --- /dev/null +++ b/include/sfx2/LokControlHandler.hxx @@ -0,0 +1,155 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class LokControlHandler +{ +public: + static bool postMouseEvent(const SdrPage* pPage, const SdrView* pDrawView, + vcl::Window const& rMainWindow, int nType, Point aPointHmm, + int nCount, int nButtons, int nModifier) + { + SdrObjListIter aIterator(pPage, SdrIterMode::Flat); + while (aIterator.IsMore()) + { + SdrObject* pObject = aIterator.Next(); + SdrUnoObj* pUnoObect = dynamic_cast(pObject); + if (pUnoObect) + { + tools::Rectangle aControlRectHMM = pUnoObect->GetLogicRect(); + if (aControlRectHMM.Contains(aPointHmm)) + { + css::uno::Reference xControl + = pUnoObect->GetUnoControl(*pDrawView, *rMainWindow.GetOutDev()); + if (!xControl.is()) + return false; + + css::uno::Reference xControlWindow(xControl, + css::uno::UNO_QUERY); + if (!xControlWindow.is()) + return false; + + css::uno::Reference xWindowPeer(xControl->getPeer()); + + VclPtr pWindow = VCLUnoHelper::GetWindow(xWindowPeer); + if (pWindow) + { + Point aControlRelativePositionHMM = aPointHmm - aControlRectHMM.TopLeft(); + Point aControlRelativePosition = o3tl::convert( + aControlRelativePositionHMM, o3tl::Length::mm100, o3tl::Length::px); + + LokMouseEventData aMouseEventData(nType, aControlRelativePosition, nCount, + MouseEventModifiers::SIMPLECLICK, + nButtons, nModifier); + + SfxLokHelper::postMouseEventAsync(pWindow, aMouseEventData); + return true; + } + } + } + } + return false; + } + + static void drawUnoControl(const SdrView* pDrawView, const SdrUnoObj* pUnoObect, + vcl::Window const& rMainWindow, VirtualDevice& rDevice, + tools::Rectangle const& rTileRectHMM, double scaleX, double scaleY) + { + css::uno::Reference xControl + = pUnoObect->GetUnoControl(*pDrawView, *rMainWindow.GetOutDev()); + if (!xControl.is()) + return; + + css::uno::Reference xControlWindow(xControl, css::uno::UNO_QUERY); + if (!xControlWindow.is()) + return; + + css::uno::Reference xGraphics(rDevice.CreateUnoGraphics()); + if (!xGraphics.is()) + return; + + css::uno::Reference xControlView(xControl, css::uno::UNO_QUERY); + if (!xControlView.is()) + return; + + tools::Rectangle aObjectRectHMM = pUnoObect->GetLogicRect(); + Point aOffsetFromTile(aObjectRectHMM.Left() - rTileRectHMM.Left(), + aObjectRectHMM.Top() - rTileRectHMM.Top()); + tools::Rectangle aRectangleHMM(aOffsetFromTile, aObjectRectHMM.GetSize()); + tools::Rectangle aRectanglePx + = o3tl::convert(aRectangleHMM, o3tl::Length::mm100, o3tl::Length::px); + + xControlWindow->setPosSize(0, 0, aRectanglePx.GetWidth(), aRectanglePx.GetHeight(), + css::awt::PosSize::POSSIZE); + + xControlView->setGraphics(xGraphics); + + xControlView->draw(aRectanglePx.Left() * scaleX, aRectanglePx.Top() * scaleY); + } + + static void paintControlTile(const SdrPage* pPage, const SdrView* pDrawView, + vcl::Window const& rMainWindow, VirtualDevice& rDevice, + Size aOutputSize, tools::Rectangle const& rTileRect) + { + tools::Rectangle aTileRectHMM + = o3tl::convert(rTileRect, o3tl::Length::twip, o3tl::Length::mm100); + + // Resizes the virtual device so to contain the entries context + rDevice.SetOutputSizePixel(aOutputSize); + + rDevice.Push(vcl::PushFlags::MAPMODE); + MapMode aDeviceMapMode(rDevice.GetMapMode()); + + const Fraction scale = conversionFract(o3tl::Length::px, o3tl::Length::mm100); + Fraction scaleX = Fraction(aOutputSize.Width(), aTileRectHMM.GetWidth()) * scale; + Fraction scaleY = Fraction(aOutputSize.Height(), aTileRectHMM.GetHeight()) * scale; + aDeviceMapMode.SetScaleX(scaleX); + aDeviceMapMode.SetScaleY(scaleY); + rDevice.SetMapMode(aDeviceMapMode); + + SdrObjListIter aIterator(pPage, SdrIterMode::Flat); + + while (aIterator.IsMore()) + { + SdrObject* pObject = aIterator.Next(); + SdrUnoObj* pUnoObect = dynamic_cast(pObject); + if (pUnoObect) + { + tools::Rectangle aObjectRectHMM = pUnoObect->GetLogicRect(); + + // Check if we intersect with the tile rectangle and we + // need to draw the control. + if (aObjectRectHMM.Overlaps(aTileRectHMM)) + { + drawUnoControl(pDrawView, pUnoObect, rMainWindow, rDevice, aTileRectHMM, + double(scaleX), double(scaleY)); + } + } + } + + rDevice.Pop(); + } +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/Metadatable.hxx b/include/sfx2/Metadatable.hxx new file mode 100644 index 000000000..a84bddb89 --- /dev/null +++ b/include/sfx2/Metadatable.hxx @@ -0,0 +1,170 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_METADATABLE_HXX +#define INCLUDED_SFX2_METADATABLE_HXX + +#include + +#include + +#include +#include + +#include + + +namespace com::sun::star { + namespace frame { class XModel; } +} + +namespace sfx2 { + class IXmlIdRegistry; +} + +namespace sfx2 { + +class XmlIdRegistry; +class MetadatableUndo; + + +// XML ID handling --------------------------------------------------- + + +/// create a sfx2::XmlIdRegistryDocument or a sfx2::XmlIdRegistryClipboard +SFX2_DLLPUBLIC ::sfx2::IXmlIdRegistry * +createXmlIdRegistry(const bool i_DocIsClipboard); + + +/** base class for core objects that may have xml:id. + +

    The interface of this class consists of 3 parts: +

    • implementations that are used by the MetadatableMixin + below
    • +
    • hooks to be called by the sw core whenever actions that are + relevant to the uniqueness of xml:ids are taken (copying, + splitting, merging, deletion, undo, etc.)
    • +
    • abstract methods that are called by the implementation of the + previous hooks
    +

    + */ +class SFX2_DLLPUBLIC Metadatable +{ +public: + Metadatable() : m_pReg(nullptr) {} + + // destructor calls RemoveMetadataReference + virtual ~Metadatable(); + + // for MetadatableMixin ---------------------------------------------- + + css::beans::StringPair GetMetadataReference() const; + void SetMetadataReference( const css::beans::StringPair & i_rReference); + void EnsureMetadataReference(); + + // hooks ------------------------------------------------------------- + + // called from dtor! + void RemoveMetadataReference(); + + /** register this as a copy of i_rSource */ + void RegisterAsCopyOf(Metadatable const & i_rSource, + const bool i_bCopyPrecedesSource = false); + + /** create an Undo Metadatable, which remembers this' reference */ + std::shared_ptr CreateUndo() const; + std::shared_ptr CreateUndoForDelete(); + + /** restore this from Undo Metadatable */ + void RestoreMetadata(std::shared_ptr const& i_pUndo); + + /** merge this and i_rOther into this */ + void JoinMetadatable(Metadatable const & i_rOther, + const bool i_isMergedEmpty, const bool i_isOtherEmpty); + + // abstract methods -------------------------------------------------- + + /** get the registry from the SwDoc */ + virtual ::sfx2::IXmlIdRegistry& GetRegistry() = 0; + + /** is this in a clipboard document? */ + virtual bool IsInClipboard() const = 0; + + /** is this in undo array? */ + virtual bool IsInUndo() const = 0; + + /** which stream is this in? true: content.xml; false: styles.xml */ + virtual bool IsInContent() const = 0; + + /** create XMetadatable from this. + note: if IsInUndo or IsInClipboard return true, + MakeUnoObject must not be called! + */ + virtual css::uno::Reference< css::rdf::XMetadatable > MakeUnoObject() = 0; + +private: + Metadatable(const Metadatable&) = delete; + Metadatable& operator=(const Metadatable&) = delete; + + friend class MetadatableClipboard; + friend class MetadatableUndo; + + // note that Reg may be a XmlIdRegistryDocument or a XmlIdRegistryClipboard + XmlIdRegistry* m_pReg; // null => no XmlId +}; + + +/** base class for UNO objects that implement XMetadatable. + +

    An instance of this base class is associated with an instance of + Metadatable.

    + */ +class SFX2_DLLPUBLIC MetadatableMixin : + public cppu::WeakImplHelper +{ + +public: + MetadatableMixin() {}; + + // css::rdf::XNode: + virtual OUString SAL_CALL getStringValue() override; + + // css::rdf::XURI: + virtual OUString SAL_CALL getLocalName() override; + virtual OUString SAL_CALL getNamespace() override; + + // css::rdf::XMetadatable: + virtual css::beans::StringPair SAL_CALL getMetadataReference() override; + virtual void SAL_CALL setMetadataReference( + const css::beans::StringPair & i_rReference) override; + virtual void SAL_CALL ensureMetadataReference() override; + +protected: + /// get the core object corresponding to this UNO object. + virtual Metadatable * GetCoreObject() = 0; + /// get the XModel for the document + virtual css::uno::Reference< css::frame::XModel > + GetModel() = 0; + +}; + +} // namespace sfx2 + +#endif // INCLUDED_SFX2_METADATABLE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/QuerySaveDocument.hxx b/include/sfx2/QuerySaveDocument.hxx new file mode 100644 index 000000000..2d800be80 --- /dev/null +++ b/include/sfx2/QuerySaveDocument.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_QUERYSAVEDOCUMENT_HXX +#define INCLUDED_SFX2_QUERYSAVEDOCUMENT_HXX + +#include + +#include + +#include + +namespace weld +{ +class Widget; +} + +/** Opens the general query save document dialog. + @param _pParent + The parent window. + @_rTitle + The title of the document. +*/ +SFX2_DLLPUBLIC short ExecuteQuerySaveDocument(weld::Widget* _pParent, std::u16string_view _rTitle); + +#endif // INCLUDED_SFX2_QUERYSAVEDOCUMENT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/StyleManager.hxx b/include/sfx2/StyleManager.hxx new file mode 100644 index 000000000..1c19b981d --- /dev/null +++ b/include/sfx2/StyleManager.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_STYLEMANAGER_HXX +#define INCLUDED_SFX2_STYLEMANAGER_HXX + +#include + +#include +#include + +#include + +class OutputDevice; +class SfxObjectShell; +namespace sfx2 { class StylePreviewRenderer; } + +namespace sfx2 +{ + +class SFX2_DLLPUBLIC StyleManager +{ +protected: + SfxObjectShell& mrShell; + +public: + StyleManager(SfxObjectShell& rShell) + : mrShell(rShell) + {} + + virtual ~StyleManager() + {} + + SfxStyleSheetBase* Search(std::u16string_view rStyleName, SfxStyleFamily eFamily); + + virtual std::unique_ptr CreateStylePreviewRenderer( + OutputDevice& rOutputDev, SfxStyleSheetBase* pStyle, + tools::Long nMaxHeight) = 0; +}; + +} // end namespace sfx2 + +#endif //INCLUDED_SFX2_STYLEMANAGER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/StylePreviewRenderer.hxx b/include/sfx2/StylePreviewRenderer.hxx new file mode 100644 index 000000000..1692182bd --- /dev/null +++ b/include/sfx2/StylePreviewRenderer.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_STYLEPREVIEWRENDERER_HXX +#define INCLUDED_SFX2_STYLEPREVIEWRENDERER_HXX + +#include +#include + +class OutputDevice; +class SfxStyleSheetBase; + +namespace sfx2 +{ + +class SFX2_DLLPUBLIC StylePreviewRenderer +{ +protected: + const SfxObjectShell& mrShell; + OutputDevice& mrOutputDev; + SfxStyleSheetBase* mpStyle; + tools::Long mnMaxHeight; + +public: + enum class RenderAlign + { + TOP, CENTER + }; + + StylePreviewRenderer(const SfxObjectShell& rShell, + OutputDevice& rOutputDev, + SfxStyleSheetBase* pStyle, + tools::Long nMaxHeight) + : mrShell(rShell) + , mrOutputDev(rOutputDev) + , mpStyle(pStyle) + , mnMaxHeight(nMaxHeight) + {} + + virtual ~StylePreviewRenderer() + {} + + virtual bool recalculate() = 0; + virtual bool render(const tools::Rectangle& aRectangle, RenderAlign eRenderAlign = RenderAlign::CENTER) = 0; +}; + +} // end namespace sfx2 + +#endif // INCLUDED_SVX_STYLEPREVIEWRENDERER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/XmlIdRegistry.hxx b/include/sfx2/XmlIdRegistry.hxx new file mode 100644 index 000000000..494c83020 --- /dev/null +++ b/include/sfx2/XmlIdRegistry.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_XMLIDREGISTRY_HXX +#define INCLUDED_SFX2_XMLIDREGISTRY_HXX + +#include + +#include + +#include + +namespace com::sun::star::beans { struct StringPair; } +namespace com::sun::star::uno { template class Reference; } + +namespace com::sun::star::rdf { + class XMetadatable; +} + +namespace sfx2 { + +// XML ID utilities -------------------------------------------------- + +/** is i_rIdref a valid NCName ? */ +bool SFX2_DLLPUBLIC isValidNCName(std::u16string_view i_rIdref); + +bool SFX2_DLLPUBLIC isValidXmlId(std::u16string_view i_rStreamName, + std::u16string_view i_rIdref); + +// XML ID handling --------------------------------------------------- + +/** interface for getElementByMetadataReference; + for use by sfx2::DocumentMetadataAccess + */ +class SFX2_DLLPUBLIC IXmlIdRegistry +{ + +public: + virtual ~IXmlIdRegistry() { } + + virtual css::uno::Reference< css::rdf::XMetadatable > + GetElementByMetadataReference( + const css::beans::StringPair & i_rXmlId) const = 0; + +}; + +} // namespace sfx2 + +#endif // INCLUDED_SFX2_XMLIDREGISTRY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/app.hxx b/include/sfx2/app.hxx new file mode 100644 index 000000000..3be667198 --- /dev/null +++ b/include/sfx2/app.hxx @@ -0,0 +1,233 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_APP_HXX +#define INCLUDED_SFX2_APP_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::script { class XLibraryContainer; } + +namespace weld { class Window; } + +class BasicManager; +class DdeService; +class SfxAppData_Impl; +class SfxDispatcher; +class SfxEventHint; +class SfxItemSet; +class SfxObjectShell; +class SfxObjectShellLock; +class SfxProgress; +class SfxSlotPool; +class SfxViewFrame; +class StarBASIC; +class SfxWorkWindow; +class SfxFilterMatcher; +class SfxModule; +struct SfxChildWinFactory; +struct SfxStbCtrlFactory; +struct SfxTbxCtrlFactory; +class SbxArray; +class SbxValue; + +namespace sfx2 +{ + namespace sidebar { + class Theme; + } +} + +enum class SfxToolsModule +{ + Math = 0, + Calc = 1, + Draw = 2, + Writer = 3, + Basic = 4, + LAST = Basic +}; + +class SFX2_DLLPUBLIC SfxLinkItem final : public SfxPoolItem +{ + Link aLink; +public: + SfxLinkItem( sal_uInt16 nWhichId, const Link& rValue ) : SfxPoolItem( nWhichId ) + { aLink = rValue; } + + virtual SfxLinkItem* Clone( SfxItemPool* = nullptr ) const override + { return new SfxLinkItem( *this ); } + virtual bool operator==( const SfxPoolItem& rL) const override + { return static_cast(rL).aLink == aLink; } + const Link& + GetValue() const { return aLink; } +}; + +// This is a singleton class. Sad that there apparently is no other +// way than a comment like this to indicate that to the code reader. +class SFX2_DLLPUBLIC SfxApplication final : public SfxShell +{ + std::unique_ptr pImpl; + + DECL_DLLPRIVATE_STATIC_LINK( SfxApplication, GlobalBasicErrorHdl_Impl, StarBASIC*, bool ); + + void Deinitialize(); + +public: + SFX_DECL_INTERFACE(SFX_INTERFACE_SFXAPP) + +private: + /// SfxInterface initializer. + static void InitInterface_Impl(); + SfxApplication(); + +public: + virtual ~SfxApplication() override; + static SfxApplication* GetOrCreate(); + static SfxApplication* Get(); + + // DDE +#if defined(_WIN32) + static bool DdeExecute( const OUString& rCmd ); +#endif + bool InitializeDde(); + const DdeService* GetDdeService() const; + DdeService* GetDdeService(); +#if defined(_WIN32) + void AddDdeTopic( SfxObjectShell* ); +#endif + void RemoveDdeTopic( SfxObjectShell const * ); + + // "static" methods + /** + * @param pArgs Takes ownership + */ + ErrCode LoadTemplate( SfxObjectShellLock& xDoc, const OUString& rFileName, std::unique_ptr pArgs ); + weld::Window* GetTopWindow() const; + + // members + SfxFilterMatcher& GetFilterMatcher(); + SfxProgress* GetProgress() const; + sal_uInt16 GetFreeIndex(); + void ReleaseIndex(sal_uInt16 i); + + // Basic/Scripting + static bool IsXScriptURL( const OUString& rScriptURL ); + static OUString ChooseScript(weld::Window *pParent); + static void MacroOrganizer(weld::Window* pParent, sal_Int16 nTabId); + static ErrCode CallBasic( const OUString&, BasicManager*, SbxArray *pArgs, SbxValue *pRet ); + static ErrCode CallAppBasic( const OUString& i_macroName ) + { return CallBasic( i_macroName, SfxApplication::GetBasicManager(), nullptr, nullptr ); } + static BasicManager* GetBasicManager(); + css::script::XLibraryContainer * GetDialogContainer(); + css::script::XLibraryContainer * GetBasicContainer(); + static StarBASIC* GetBasic(); + void SaveBasicAndDialogContainer() const; + + // misc. + static void GetOptions(SfxItemSet &); + void SetOptions(const SfxItemSet &); + virtual void Invalidate(sal_uInt16 nId = 0) override; + void NotifyEvent(const SfxEventHint& rEvent, bool bSynchron = true ); + bool IsDowning() const; + void ResetLastDir(); + + SAL_DLLPRIVATE SfxDispatcher* GetAppDispatcher_Impl(); + SAL_DLLPRIVATE SfxDispatcher* GetDispatcher_Impl(); + + SAL_DLLPRIVATE void SetOptions_Impl(const SfxItemSet &); + SAL_DLLPRIVATE void Initialize_Impl(); + + SAL_DLLPRIVATE SfxAppData_Impl* Get_Impl() const { return pImpl.get(); } + + // Object-Factories/global arrays + SAL_DLLPRIVATE void RegisterChildWindow_Impl(SfxModule*, const SfxChildWinFactory&); + SAL_DLLPRIVATE void RegisterStatusBarControl_Impl(SfxModule*, const SfxStbCtrlFactory&); + SAL_DLLPRIVATE void RegisterToolBoxControl_Impl( SfxModule*, const SfxTbxCtrlFactory&); + SAL_DLLPRIVATE SfxTbxCtrlFactory* GetTbxCtrlFactory(const std::type_info& rSlotType, sal_uInt16 nSlotID) const; + SAL_DLLPRIVATE SfxStbCtrlFactory* GetStbCtrlFactory(const std::type_info& rSlotType, sal_uInt16 nSlotID) const; + SAL_DLLPRIVATE SfxChildWinFactory* GetChildWinFactoryById(sal_uInt16 nId) const; + SAL_DLLPRIVATE std::vector& GetViewFrames_Impl() const; + SAL_DLLPRIVATE std::vector& GetViewShells_Impl() const; + SAL_DLLPRIVATE std::vector& GetObjectShells_Impl() const; + SAL_DLLPRIVATE void SetViewFrame_Impl(SfxViewFrame *pViewFrame); + + // Slot Methods + // TODO/CLEANUP: still needed? + SAL_DLLPRIVATE void NewDocDirectExec_Impl(SfxRequest &); + SAL_DLLPRIVATE static void NewDocDirectState_Impl(SfxItemSet &); + SAL_DLLPRIVATE void NewDocExec_Impl(SfxRequest &); + SAL_DLLPRIVATE void OpenDocExec_Impl(SfxRequest &); + SAL_DLLPRIVATE void OpenRemoteExec_Impl(SfxRequest &); + SAL_DLLPRIVATE void SignPDFExec_Impl(SfxRequest&); + SAL_DLLPRIVATE void MiscExec_Impl(SfxRequest &); + SAL_DLLPRIVATE void MiscState_Impl(SfxItemSet &); + SAL_DLLPRIVATE static void PropExec_Impl(SfxRequest const &); + SAL_DLLPRIVATE static void PropState_Impl(SfxItemSet &); + SAL_DLLPRIVATE void OfaExec_Impl(SfxRequest &); + SAL_DLLPRIVATE static void OfaState_Impl(SfxItemSet &); + + SAL_DLLPRIVATE void SetProgress_Impl(SfxProgress *); + SAL_DLLPRIVATE const OUString& GetLastDir_Impl() const; + SAL_DLLPRIVATE void SetLastDir_Impl( const OUString & ); + + SAL_DLLPRIVATE static void Registrations_Impl(); + SAL_DLLPRIVATE SfxWorkWindow* GetWorkWindow_Impl(const SfxViewFrame *pFrame) const; + + // TODO/CLEANUP: still needed? -- unclear whether this comment + // refers to the GetDisabledSlotList_Impl() method which was + // already removed, or the below methods? + SAL_DLLPRIVATE SfxSlotPool& GetAppSlotPool_Impl() const; + SAL_DLLPRIVATE static SfxModule* GetModule_Impl(); + + static void SetModule(SfxToolsModule nSharedLib, std::unique_ptr pModule); + static SfxModule* GetModule(SfxToolsModule nSharedLib); + + static bool loadBrandSvg(const char *pName, BitmapEx &rBitmap, int nWidth); + + /** loads the application logo as used in the impress slideshow pause screen */ + static BitmapEx GetApplicationLogo(tools::Long nWidth); + + /** if true then dialog/infobar notifications like the tip of the day or + version change infobar should be suppressed */ + static bool IsHeadlessOrUITest(); + + static bool IsTipOfTheDayDue(); + + /** this Theme contains Images so must be deleted before DeInitVCL */ + sfx2::sidebar::Theme & GetSidebarTheme(); +}; + +inline SfxApplication* SfxGetpApp() +{ + return SfxApplication::Get(); +} + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/basedlgs.hxx b/include/sfx2/basedlgs.hxx new file mode 100644 index 000000000..b753569ef --- /dev/null +++ b/include/sfx2/basedlgs.hxx @@ -0,0 +1,136 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_BASEDLGS_HXX +#define INCLUDED_SFX2_BASEDLGS_HXX + +#include +#include +#include +#include + +class SfxTabPage; +class SfxBindings; +class SfxChildWindow; +struct SfxChildWinInfo; +class SfxItemSet; +struct WhichRangesContainer; + +class SFX2_DLLPUBLIC SfxDialogController : public weld::GenericDialogController +{ +private: + DECL_DLLPRIVATE_STATIC_LINK(SfxDialogController, InstallLOKNotifierHdl, void*, vcl::ILibreOfficeKitNotifier*); + + DECL_DLLPRIVATE_LINK(FocusChangeHdl, weld::Container&, void); + +public: + SfxDialogController(weld::Widget* pParent, const OUString& rUIFile, const OString& rDialogId); + // dialog gets focus + virtual void Activate() {} + // dialog loses focus + virtual void Deactivate() {} + + // when the dialog has an associated SfxChildWin, typically for Modeless interaction + virtual void ChildWinDispose() {} // called from the associated SfxChildWin dtor + virtual void Close(); // called by the SfxChildWin when the dialog is closed + virtual void EndDialog(int nResponse); // called by the SfxChildWin to close the dialog +}; + +class SfxModelessDialog_Impl; + +class SFX2_DLLPUBLIC SfxModelessDialogController : public SfxDialogController +{ + SfxBindings* m_pBindings; + std::unique_ptr m_xImpl; + + SfxModelessDialogController(SfxModelessDialogController&) = delete; + void operator =(SfxModelessDialogController&) = delete; + + void Init(SfxBindings *pBindinx, SfxChildWindow *pCW); + +protected: + SfxModelessDialogController(SfxBindings*, SfxChildWindow* pChildWin, + weld::Window* pParent, const OUString& rUIXMLDescription, const OString& rID); + +public: + virtual ~SfxModelessDialogController() override; + + void Initialize (SfxChildWinInfo const * pInfo); + bool IsClosing() const; + virtual void Close() override; + virtual void EndDialog(int nResponse) override; + virtual void Activate() override; + virtual void Deactivate() override; + virtual void ChildWinDispose() override; + virtual void FillInfo(SfxChildWinInfo&) const; + SfxBindings& GetBindings() const { return *m_pBindings; } +}; + +typedef WhichRangesContainer (*GetTabPageRanges)(); // provides international Which values + +class SFX2_DLLPUBLIC SfxOkDialogController : public SfxDialogController +{ +public: + SfxOkDialogController(weld::Widget* pParent, const OUString& rUIXMLDescription, + const OString& rID) + : SfxDialogController(pParent, rUIXMLDescription, rID) + { + } + + virtual weld::Button& GetOKButton() const = 0; + virtual const SfxItemSet* GetExampleSet() const = 0; +}; + +class SFX2_DLLPUBLIC SfxSingleTabDialogController : public SfxOkDialogController +{ +private: + std::unique_ptr m_xOutputSet; + const SfxItemSet* m_pInputSet; + +public: + SfxSingleTabDialogController(weld::Widget* pParent, const SfxItemSet* pOptionsSet, + const OUString& rUIXMLDescription = OUString("sfx/ui/singletabdialog.ui"), + const OString& rID = OString("SingleTabDialog")); + + weld::Container* get_content_area() { return m_xContainer.get(); } + + virtual ~SfxSingleTabDialogController() override; + + void SetTabPage(std::unique_ptr xTabPage); + SfxTabPage* GetTabPage() const { return m_xSfxPage.get(); } + + virtual weld::Button& GetOKButton() const override { return *m_xOKBtn; } + virtual const SfxItemSet* GetExampleSet() const override { return nullptr; } + + const SfxItemSet* GetOutputItemSet() const { return m_xOutputSet.get(); } + const SfxItemSet* GetInputItemSet() const { return m_pInputSet; } + +protected: + std::unique_ptr m_xSfxPage; + std::unique_ptr m_xContainer; + std::unique_ptr m_xOKBtn; + std::unique_ptr m_xHelpBtn; + + void CreateOutputItemSet(const SfxItemSet& rInput); + void SetInputSet(const SfxItemSet* pInSet) { m_pInputSet = pInSet; } + DECL_DLLPRIVATE_LINK(OKHdl_Impl, weld::Button&, void); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/bindings.hxx b/include/sfx2/bindings.hxx new file mode 100644 index 000000000..d058c939e --- /dev/null +++ b/include/sfx2/bindings.hxx @@ -0,0 +1,208 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_BINDINGS_HXX +#define INCLUDED_SFX2_BINDINGS_HXX + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::frame { class XDispatch; } +namespace com::sun::star::frame { class XDispatchProvider; } +namespace com::sun::star::frame { class XDispatchRecorder; } +namespace com::sun::star::frame { class XFrame; } +namespace com::sun::star::util { struct URL; } + +class SfxSlot; +class SfxSlotServer; +class SfxControllerItem; +class SfxStateCache; +class SfxItemSet; +class SfxDispatcher; +class SfxBindings_Impl; +class Timer; +class SfxWorkWindow; +struct SfxFoundCache_Impl; +class SfxFoundCacheArr_Impl; + +enum class SfxCallMode : sal_uInt16 +{ + SLOT = 0x00, // sync/async from Slot + SYNCHRON = 0x01, // synchronously in the same Stackframe + ASYNCHRON = 0x02, // asynchronously via AppEvent + RECORD = 0x04, // take into account while recording + API = 0x08 // API call (silent) +}; + +namespace o3tl { + +template<> struct typed_flags: is_typed_flags +{}; + +} + +class SFX2_DLLPUBLIC SfxBindings final : public SfxBroadcaster + +/* [Description] + + In each SFx application one instance of the SfxBindings-Class will + exists from until . + This instance is automatically created and destroyed by SfxApplication. + However these instances will be handled by the Macro + or the associated . + + The SfxBindings manages all of its Slot-Ids bound by the registered + controllers and keeps a cache of the respectively. + (it is what we call the combination of SfxShell instance and SfxSlot). + In the SfxBindings it is stored, if and in this case which controllers + that are dirty and which Slot-Server-Caches are dirty respectively. + It summarizes status queries (calls to the status methods specified + in the IDL) that are served by the same state methods, and handles + the simulation of . +*/ + +{ +friend class SfxApplication; +friend class SfxShell; +friend class SfxBindings_Impl; + + std::unique_ptr< SfxBindings_Impl> pImpl; // Data of the Bindings instance + SfxDispatcher* pDispatcher; // Dispatcher, to be used + sal_uInt16 nRegLevel; // Lock-Level while Reconfig + +private: + SAL_DLLPRIVATE const SfxPoolItem* Execute_Impl( sal_uInt16 nSlot, const SfxPoolItem **pArgs, sal_uInt16 nModi, + SfxCallMode nCall, const SfxPoolItem **pInternalArgs, bool bGlobalOnly=false); + SAL_DLLPRIVATE void SetSubBindings_Impl( SfxBindings* ); + SAL_DLLPRIVATE void UpdateSlotServer_Impl(); // Update SlotServer + SAL_DLLPRIVATE std::optional CreateSet_Impl(SfxStateCache& rCache, const SfxSlot* &pRealSlot, + const SfxSlotServer**, SfxFoundCacheArr_Impl&); + SAL_DLLPRIVATE std::size_t GetSlotPos( sal_uInt16 nId, std::size_t nStartSearchAt = 0 ); + SAL_DLLPRIVATE void Update_Impl(SfxStateCache& rCache); + static SAL_DLLPRIVATE void UpdateControllers_Impl( + const SfxFoundCache_Impl& rFound, + const SfxPoolItem *pItem, + SfxItemState eItemState ); + SAL_DLLPRIVATE SfxStateCache* GetStateCache( sal_uInt16 nId, std::size_t * pPos); + DECL_DLLPRIVATE_LINK( NextJob, Timer *, void ); + SAL_DLLPRIVATE bool NextJob_Impl(Timer const * pTimer); + +public: + SfxBindings(); + virtual ~SfxBindings() override; + + void HidePopups( bool bHide = true ); + + void SetDispatcher(SfxDispatcher *pDisp); + + void Update( sal_uInt16 nId ); // For example, from Menu::Activate + void Update(); + SAL_DLLPRIVATE void StartUpdate_Impl(bool bComplete=false); + void Invalidate( sal_uInt16 nId ); + void Invalidate( const sal_uInt16* pIds ); + void InvalidateShell( const SfxShell &rSh, bool bDeep = false ); + void InvalidateAll( bool bWithMsg ); + void SetState( const SfxItemSet &rSet ); + void SetState( const SfxPoolItem &rItem ); + void Invalidate( sal_uInt16 nId, bool bWithItem, bool bWithMsg=false); + bool IsInUpdate() const; + void SetVisibleState( sal_uInt16 nId, bool bShow ); + + SfxStateCache* GetStateCache( sal_uInt16 nId); + SAL_DLLPRIVATE SfxStateCache* GetAnyStateCache_Impl( sal_uInt16 nId ); + /** + * @param rpState the caller has to delete the pointer + */ + SfxItemState QueryState( sal_uInt16 nSID, std::unique_ptr &rpState ); + template + SfxItemState QueryState( TypedWhichId nSID, std::unique_ptr &rpState ) + { + std::unique_ptr tmp; + auto ret = QueryState(sal_uInt16(nSID), tmp); + rpState.reset(static_cast(tmp.release())); + return ret; + } + + void QueryControlState ( sal_uInt16 nSID, boost::property_tree::ptree& rState ); + + sal_uInt16 QuerySlotId( const css::util::URL& aURL ); + + const SfxPoolItem* ExecuteSynchron( sal_uInt16 nSlot, + const SfxPoolItem **pArgs = nullptr); + bool Execute( sal_uInt16 nSlot, + const SfxPoolItem **pArgs = nullptr, + SfxCallMode nCall = SfxCallMode::SLOT); + + SAL_DLLPRIVATE void SetDispatchProvider_Impl( const css::uno::Reference< css::frame::XDispatchProvider > & rFrame ); + void SetActiveFrame( const css::uno::Reference< css::frame::XFrame > & rFrame ); + css::uno::Reference< css::frame::XFrame > GetActiveFrame() const; + // Reconfig + sal_uInt16 EnterRegistrations(const char *pFile = nullptr, int nLine = 0); + void LeaveRegistrations( const char *pFile = nullptr, int nLine = 0 ); + void Register( SfxControllerItem& rBinding ); + void Release( SfxControllerItem& rBinding ); + SfxDispatcher* GetDispatcher() const + { return pDispatcher; } + const css::uno::Reference< css::frame::XDispatchRecorder >& GetRecorder() const; + css::uno::Reference < css::frame::XDispatch > + GetDispatch( const SfxSlot*, const css::util::URL& aURL, bool bMasterCommand ); + SAL_DLLPRIVATE void ContextChanged_Impl(); + SAL_DLLPRIVATE void Execute_Impl( SfxRequest& rReq, const SfxSlot* pSlot, SfxShell* pShell ); + SAL_DLLPRIVATE void DeleteControllers_Impl(); + SAL_DLLPRIVATE SfxDispatcher* GetDispatcher_Impl() { return pDispatcher; } + SAL_DLLPRIVATE void ClearCache_Impl( sal_uInt16 nSlotId ); + SAL_DLLPRIVATE void RegisterInternal_Impl( SfxControllerItem& rBinding ); + SAL_DLLPRIVATE void Register_Impl( SfxControllerItem& rBinding, bool ); + SAL_DLLPRIVATE SfxWorkWindow* GetWorkWindow_Impl() const; + SAL_DLLPRIVATE void SetWorkWindow_Impl( std::unique_ptr ); + SAL_DLLPRIVATE SfxBindings* GetSubBindings_Impl() const; + SAL_DLLPRIVATE void SetRecorder_Impl( css::uno::Reference< css::frame::XDispatchRecorder > const & ); + SAL_DLLPRIVATE void InvalidateSlotsInMap_Impl(); + SAL_DLLPRIVATE void AddSlotToInvalidateSlotsMap_Impl( sal_uInt16 nId ); +}; + +#ifdef DBG_UTIL +#define ENTERREGISTRATIONS() EnterRegistrations(__FILE__, __LINE__) +#define LEAVEREGISTRATIONS() LeaveRegistrations(__FILE__, __LINE__) +#define DENTERREGISTRATIONS() \ + EnterRegistrations( OStringBuffer(__FILE__).append('(').append(reinterpret_cast(this)).append(')').getStr(), __LINE__ ) +#define DLEAVEREGISTRATIONS( ) \ + LeaveRegistrations( OStringBuffer(__FILE__).append('(').append(reinterpret_cast(this)).append(')').getStr(), __LINE__ ) +#else +#define ENTERREGISTRATIONS() EnterRegistrations() +#define LEAVEREGISTRATIONS() LeaveRegistrations() +#define DENTERREGISTRATIONS() EnterRegistrations() +#define DLEAVEREGISTRATIONS() LeaveRegistrations() +#endif + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/brokenpackageint.hxx b/include/sfx2/brokenpackageint.hxx new file mode 100644 index 000000000..37c98540a --- /dev/null +++ b/include/sfx2/brokenpackageint.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_BROKENPACKAGEINT_HXX +#define INCLUDED_SFX2_BROKENPACKAGEINT_HXX + +#include +#include +#include + +#include + +namespace com::sun::star::task +{ +class XInteractionRequest; +} + +class RequestPackageReparation_Impl; +class SFX2_DLLPUBLIC RequestPackageReparation +{ + rtl::Reference mxImpl; + +public: + RequestPackageReparation(const OUString& aName); + ~RequestPackageReparation(); + RequestPackageReparation(const RequestPackageReparation&) = delete; + RequestPackageReparation& operator=(const RequestPackageReparation&) = delete; + bool isApproved() const; + css::uno::Reference GetRequest() const; +}; + +class NotifyBrokenPackage_Impl; +class SFX2_DLLPUBLIC NotifyBrokenPackage +{ + rtl::Reference mxImpl; + +public: + NotifyBrokenPackage(const OUString& aName); + ~NotifyBrokenPackage(); + NotifyBrokenPackage(const NotifyBrokenPackage&) = delete; + NotifyBrokenPackage& operator=(const NotifyBrokenPackage&) = delete; + css::uno::Reference GetRequest() const; +}; + +#endif // INCLUDED_SFX2_BROKENPACKAGEINT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/chalign.hxx b/include/sfx2/chalign.hxx new file mode 100644 index 000000000..d63646ea1 --- /dev/null +++ b/include/sfx2/chalign.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_CHALIGN_HXX +#define INCLUDED_SFX2_CHALIGN_HXX + +// New order: first, navigation bar, then vertically docked child windows +// (Explorer!), then horizontally docked child windows (Browser!), +// then the format bar, status bar, and at the end of the toolbar. + +enum class SfxChildAlignment +{ + HIGHESTTOP, // for example Navigation bar + LOWESTBOTTOM, + FIRSTLEFT, + LASTRIGHT, + LEFT, // for example SplitWindow + RIGHT, + LASTLEFT, + FIRSTRIGHT, + TOP, // for example Hyperlink-Builder, SplitWindow + BOTTOM, // for example SplitWindow + TOOLBOXTOP, // for example Object bar + TOOLBOXBOTTOM, + LOWESTTOP, // for example Calc bar + HIGHESTBOTTOM, // for example Status bar + TOOLBOXLEFT, // for example Tool bar + TOOLBOXRIGHT, + NOALIGNMENT // all FloatingWindows +}; + +// Verifies that a valid alignment is used +inline bool SfxChildAlignValid( SfxChildAlignment eAlign ) +{ + return ( eAlign >= SfxChildAlignment::HIGHESTTOP && eAlign <= SfxChildAlignment::NOALIGNMENT ); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/charwin.hxx b/include/sfx2/charwin.hxx new file mode 100644 index 000000000..f4118d44c --- /dev/null +++ b/include/sfx2/charwin.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_INC_CHARWIN_HXX +#define INCLUDED_SFX2_INC_CHARWIN_HXX + +#include +#include +#include +#include + +class SFX2_DLLPUBLIC SvxCharView final : public weld::CustomWidgetController +{ +private: + VclPtr mxVirDev; + tools::Long mnY; + Point maPosition; + vcl::Font maFont; + bool maHasInsert; + OUString m_sText; + + Link maMouseClickHdl; + Link maClearClickHdl; + Link maClearAllClickHdl; + + virtual void Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect) override; + virtual void Resize() override; + virtual bool MouseButtonDown(const MouseEvent&) override; + virtual void GetFocus() override; + virtual void LoseFocus() override; + virtual bool KeyInput(const KeyEvent&) override; + virtual void SetDrawingArea(weld::DrawingArea* pDrawingArea) override; +public: + SvxCharView(const VclPtr& rVirDev); + + void SetFont( const vcl::Font& rFont ); + vcl::Font const & GetFont() const { return maFont; } + void SetText( const OUString& rText ); + OUString const & GetText() const { return m_sText; } + void SetHasInsert( bool bInsert ); + void InsertCharToDoc(); + + void createContextMenu(); + + Size get_preferred_size() const { return GetDrawingArea()->get_preferred_size(); } + + void setMouseClickHdl(const Link &rLink); + void setClearClickHdl(const Link &rLink); + void setClearAllClickHdl(const Link &rLink); + + void ContextMenuSelect(std::string_view rIdent); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/sfx2/childwin.hxx b/include/sfx2/childwin.hxx new file mode 100644 index 000000000..68ad6ff50 --- /dev/null +++ b/include/sfx2/childwin.hxx @@ -0,0 +1,235 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_CHILDWIN_HXX +#define INCLUDED_SFX2_CHILDWIN_HXX + +#include +#include + +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::frame { class XFrame; } + +class SfxWorkWindow; +class SfxModule; +class SfxChildWindow; +class SfxBindings; +class SfxModelessDialogController; + +enum class SfxChildWindowFlags +{ + NONE = 0x000, + FORCEDOCK = 0x004, // Float forbidden + TASK = 0x010, // ChildWindow inside the Task + CANTGETFOCUS = 0x020, // ChildWindow can not get focus + ALWAYSAVAILABLE = 0x040, // ChildWindow is never disabled + NEVERHIDE = 0x080, // ChildWindow is always visible + NEVERCLONE = 0x100, // ChildWindow is not recreated in new view +}; + +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + + +#define CHILDWIN_NOPOS USHRT_MAX + +// ChildWindow Configuration +struct SAL_DLLPUBLIC_RTTI SfxChildWinInfo +{ + OUString aExtraString; + OUString aModule; + OString aWinState; + Point aPos; + Size aSize; + SfxChildWindowFlags nFlags; + bool bVisible; + + SfxChildWinInfo() + { + bVisible = false; + nFlags = SfxChildWindowFlags::NONE; + } + bool GetExtraData_Impl( SfxChildAlignment *pAlign ) const; +}; + +// ChildWindow factory methods +typedef std::unique_ptr (*SfxChildWinCtor)( vcl::Window *pParentWindow, + sal_uInt16 nId, + SfxBindings *pBindings, + SfxChildWinInfo *pInfo); + +struct SFX2_DLLPUBLIC SfxChildWinFactory +{ + SfxChildWinCtor pCtor; // Factory method + SfxChildWinInfo aInfo; // Configuration + sal_uInt16 nId; // ChildWindow-Id ( SlotId ) + sal_uInt16 nPos; // Position in UI + + SfxChildWinFactory( SfxChildWinCtor pTheCtor, sal_uInt16 nID, sal_uInt16 n ); +}; + +struct SfxChildWindow_Impl; + +extern SFX2_DLLPUBLIC bool ParentIsFloatingWindow(const vcl::Window *pParent); + +class SFX2_DLLPUBLIC SfxChildWindow +{ + VclPtr pParent; // parent window ( Topwindow ) + VclPtr pWindow; // actual contents + std::unique_ptr< SfxChildWindow_Impl> pImpl; // Implementation data + std::shared_ptr xController; // actual contents + SfxChildAlignment eChildAlignment; // Current css::drawing::Alignment + // Another window in pWindow + sal_uInt16 nType; // ChildWindow-Id + SAL_DLLPRIVATE void ClearWorkwin(); + +protected: + void SetWindow(const VclPtr& p) { pWindow = p; } + SfxChildWindow(vcl::Window *pParentWindow, sal_uInt16 nId); + +public: + virtual ~SfxChildWindow(); + void Destroy(); + vcl::Window* GetWindow() const + { return pWindow; } + void SetController(std::shared_ptr controller) { xController = controller; } + void ClearController() { xController.reset(); } + std::shared_ptr& GetController() { return xController; } + const std::shared_ptr& GetController() const { return xController; } + vcl::Window* GetParent() const + { return pParent; } + SfxChildAlignment GetAlignment() const + { return eChildAlignment; } + void SetAlignment(SfxChildAlignment eAlign); + virtual void Hide(); + virtual void Show( ShowFlags nFlags ); + sal_uInt16 GetPosition() const; + sal_uInt16 GetType() const + { return nType; } + + virtual SfxChildWinInfo GetInfo() const; + void SaveStatus(const SfxChildWinInfo& rInfo); + + static void RegisterChildWindow(SfxModule*, const SfxChildWinFactory&); + + static std::unique_ptr CreateChildWindow( sal_uInt16, vcl::Window*, SfxBindings*, SfxChildWinInfo const &); + void SetHideNotDelete( bool bOn ); + bool IsHideNotDelete() const; + bool IsVisible() const; + void SetWantsFocus( bool ); + bool WantsFocus() const; + + virtual bool QueryClose(); + const css::uno::Reference< css::frame::XFrame >& GetFrame() const; + void SetFrame( const css::uno::Reference< css::frame::XFrame > & ); + + SAL_DLLPRIVATE static void InitializeChildWinFactory_Impl(sal_uInt16, SfxChildWinInfo&); + void SetVisible_Impl( bool bVis ); + SAL_DLLPRIVATE void SetWorkWindow_Impl( SfxWorkWindow* ); + SAL_DLLPRIVATE void Activate_Impl(); + + SAL_DLLPRIVATE void SetFactory_Impl( const SfxChildWinFactory* ); +}; + +const int nCloseResponseToJustHide = -42; + +#define SFX_DECL_CHILDWINDOW(Class) \ + public : \ + static std::unique_ptr CreateImpl(vcl::Window *pParent, sal_uInt16 nId, \ + SfxBindings *pBindings, SfxChildWinInfo* pInfo ); \ + static void RegisterChildWindow (bool bVisible=false, SfxModule *pMod=nullptr, SfxChildWindowFlags nFlags=SfxChildWindowFlags::NONE); \ + virtual SfxChildWinInfo GetInfo() const override + +#define SFX_DECL_CHILDWINDOW_WITHID(Class) \ + SFX_DECL_CHILDWINDOW(Class); \ + static sal_uInt16 GetChildWindowId ()\ + +#define SFX_IMPL_CHILDWINDOW(Class, MyID) \ + SFX_IMPL_POS_CHILDWINDOW(Class, MyID, CHILDWIN_NOPOS) + +#define SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ + SFX_IMPL_POS_CHILDWINDOW_WITHID(Class, MyID, CHILDWIN_NOPOS) + +#define SFX_IMPL_POS_CHILDWINDOW(Class, MyID, Pos) \ + std::unique_ptr Class::CreateImpl( vcl::Window *pParent, \ + sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo* pInfo ) \ + { \ + return std::make_unique(pParent, nId, pBindings, pInfo);\ + } \ + void Class::RegisterChildWindow (bool bVis, SfxModule *pMod, SfxChildWindowFlags nFlags) \ + { \ + SfxChildWinFactory aFact( \ + Class::CreateImpl, MyID, Pos ); \ + aFact.aInfo.nFlags |= nFlags; \ + aFact.aInfo.bVisible = bVis; \ + SfxChildWindow::RegisterChildWindow(pMod, aFact); \ + } + +#define SFX_IMPL_POS_CHILDWINDOW_WITHID(Class, MyID, Pos) \ + SFX_IMPL_POS_CHILDWINDOW(Class, MyID, Pos) \ + sal_uInt16 Class::GetChildWindowId () \ + { return MyID; } \ + +#define SFX_IMPL_MODELESSDIALOGCONTOLLER(Class, MyID) \ + SFX_IMPL_CHILDWINDOW(Class, MyID) \ + SfxChildWinInfo Class::GetInfo() const \ + { \ + SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ + static_cast(GetController().get())->FillInfo( aInfo ); \ + return aInfo; } + +#define SFX_IMPL_MODELESSDIALOGCONTOLLER_WITHID(Class, MyID) \ + SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ + SfxChildWinInfo Class::GetInfo() const \ + { \ + SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ + static_cast(GetController().get())->FillInfo( aInfo ); \ + return aInfo; } + +#define SFX_IMPL_DOCKINGWINDOW(Class, MyID) \ + SFX_IMPL_CHILDWINDOW(Class, MyID) \ + SfxChildWinInfo Class::GetInfo() const \ + { \ + SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ + static_cast(GetWindow())->FillInfo( aInfo ); \ + return aInfo; } + +#define SFX_IMPL_DOCKINGWINDOW_WITHID(Class, MyID) \ + SFX_IMPL_CHILDWINDOW_WITHID(Class, MyID) \ + SfxChildWinInfo Class::GetInfo() const \ + { \ + SfxChildWinInfo aInfo = SfxChildWindow::GetInfo(); \ + static_cast(GetWindow())->FillInfo( aInfo ); \ + return aInfo; } + +bool GetPosSizeFromString( std::u16string_view rStr, Point& rPos, Size& rSize ); + +bool GetSplitSizeFromString( std::u16string_view rStr, Size& rSize ); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/classificationhelper.hxx b/include/sfx2/classificationhelper.hxx new file mode 100644 index 000000000..5a4fa6b1e --- /dev/null +++ b/include/sfx2/classificationhelper.hxx @@ -0,0 +1,227 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_CLASSIFICATIONHELPER_HXX +#define INCLUDED_SFX2_CLASSIFICATIONHELPER_HXX + +#include +#include +#include + +#include +#include +#include +#include + +namespace com::sun::star::beans +{ +class XPropertyContainer; +} +namespace com::sun::star::document +{ +class XDocumentProperties; +} + +class SfxViewFrame; + +/// Return code of SfxClassificationHelper::CheckPaste(). +enum class SfxClassificationCheckPasteResult +{ + None = 1, + TargetDocNotClassified = 2, + DocClassificationTooLow = 3 +}; + +/// Specifies a policy type, to be used with SetBACName(). Getters always use IntellectualProperty for now. +enum class SfxClassificationPolicyType +{ + ExportControl = 1, + NationalSecurity = 2, + IntellectualProperty = 3 +}; + +/// Shared code to handle Business Authorization Identification and Labeling Scheme (BAILS) properties. +class SFX2_DLLPUBLIC SfxClassificationHelper +{ + class SAL_DLLPRIVATE Impl; + std::unique_ptr m_pImpl; + +public: + /// Does the document have any BAILS properties? + static bool IsClassified( + const css::uno::Reference& xDocumentProperties); + /// Checks if pasting from xSource to xDestination would leak information. + static SfxClassificationCheckPasteResult + CheckPaste(const css::uno::Reference& xSource, + const css::uno::Reference& xDestination); + /// Wrapper around CheckPaste(): informs the user if necessary and finds out if the paste can be continued or not. + static bool ShowPasteInfo(SfxClassificationCheckPasteResult eResult); + + SfxClassificationHelper( + const css::uno::Reference& xDocumentProperties, + bool bUseLocalizedPolicy = true); + ~SfxClassificationHelper(); + /// Get the currently selected category for eType. + const OUString& GetBACName(SfxClassificationPolicyType eType) const; + /// Return all possible valid category names, based on the policy. + std::vector GetBACNames(); + /// Return all possible valid category identifiers, based on the policy. + std::vector GetBACIdentifiers(); + /// Get the currently selected category abbreviation for eType. Returns full name if no abbreviation defined. + const OUString& GetAbbreviatedBACName(const OUString& sFullName); + /// Get the currently selected category for the identifier. + OUString GetBACNameForIdentifier(std::u16string_view sIdentifier); + /// Return all possible valid abbreviated category names, based on the policy. + std::vector GetAbbreviatedBACNames(); + /// Setting this sets all the other properties, based on the policy. + void SetBACName(const OUString& rName, SfxClassificationPolicyType eType); + /// Returns the class with the higher priority (based on sensitivity). + OUString GetHigherClass(const OUString& first, const OUString& second); + /// If GetImpactScale() and GetImpactLevel*() will return something meaningful. + bool HasImpactLevel(); + InfobarType GetImpactLevelType(); + /// Larger value means more confidential. + sal_Int32 GetImpactLevel(); + /// Comparing the GetImpactLevel() result is only meaningful when the impact scale is the same. + OUString GetImpactScale(); + OUString GetDocumentWatermark(); + /// The selected category has some content for the document header. + bool HasDocumentHeader(); + /// The selected category has some content for the document footer. + bool HasDocumentFooter(); + void UpdateInfobar(SfxViewFrame& rViewFrame); + + std::vector const& GetMarkings() const; + std::vector const& GetIntellectualPropertyParts() const; + std::vector const& GetIntellectualPropertyPartNumbers() const; + + /// Does a best-effort conversion of rType to SfxClassificationPolicyType. + static SfxClassificationPolicyType stringToPolicyType(std::u16string_view rType); + /// Returns the string representation of a SfxClassificationPolicyType element. + static const OUString& policyTypeToString(SfxClassificationPolicyType eType); + + /// Brief text located at the top of each document's pages. + static const OUString& PROP_DOCHEADER(); + /// Brief text located at the bottom of each document's pages. + static const OUString& PROP_DOCFOOTER(); + /// Brief text formatted as a watermark on each document's page. + static const OUString& PROP_DOCWATERMARK(); + /// Get the property prefix for the IntellectualProperty policy type. + static const OUString& PROP_PREFIX_INTELLECTUALPROPERTY(); + + static SfxClassificationPolicyType getPolicyType(); +}; + +namespace sfx +{ +/// Specifies the origin: either defined by the BAF policy or manual via. the advanced classification dialog +enum class ClassificationCreationOrigin +{ + NONE, + BAF_POLICY, + MANUAL +}; + +class ClassificationKeyCreator +{ +private: + const SfxClassificationPolicyType m_ePolicyType; + const OUString m_sPolicy; + sal_Int32 m_nTextNumber; + sal_Int32 m_nIPPartNumber; + sal_Int32 m_nMarkingNumber; + + OUString const& getPolicyKey() const { return m_sPolicy; } + +public: + ClassificationKeyCreator(SfxClassificationPolicyType ePolicyType) + : m_ePolicyType(ePolicyType) + , m_sPolicy(SfxClassificationHelper::policyTypeToString(m_ePolicyType)) + , m_nTextNumber(1) + , m_nIPPartNumber(1) + , m_nMarkingNumber(1) + { + } + + OUString makeTextKey() const { return getPolicyKey() + "Custom:Text"; } + + OUString makeNumberedTextKey() + { + return makeTextKey() + ":n" + OUString::number(m_nTextNumber++); + } + + bool isMarkingTextKey(std::u16string_view aKey) const + { + return o3tl::starts_with(aKey, makeTextKey()); + } + + OUString makeCategoryNameKey() const + { + return getPolicyKey() + "BusinessAuthorizationCategory:Name"; + } + + bool isCategoryNameKey(std::u16string_view aKey) const + { + return o3tl::starts_with(aKey, makeCategoryNameKey()); + } + + OUString makeCategoryIdentifierKey() const + { + return getPolicyKey() + "BusinessAuthorizationCategory:Identifier"; + } + + bool isCategoryIdentifierKey(std::u16string_view aKey) const + { + return o3tl::starts_with(aKey, makeCategoryIdentifierKey()); + } + + OUString makeMarkingKey() const { return getPolicyKey() + "Custom:Marking"; } + + OUString makeNumberedMarkingKey() + { + return makeMarkingKey() + ":n" + OUString::number(m_nMarkingNumber++); + } + + bool isMarkingKey(std::u16string_view aKey) const + { + return o3tl::starts_with(aKey, makeMarkingKey()); + } + + OUString makeIntellectualPropertyPartKey() const + { + return getPolicyKey() + "Custom:IntellectualPropertyPart"; + } + + OUString makeNumberedIntellectualPropertyPartKey() + { + return makeIntellectualPropertyPartKey() + ":n" + OUString::number(m_nIPPartNumber++); + } + + bool isIntellectualPropertyPartKey(std::u16string_view aKey) const + { + return o3tl::starts_with(aKey, makeIntellectualPropertyPartKey()); + } + + OUString makeFullTextualRepresentationKey() const + { + return getPolicyKey() + "Custom:FullTexturalRepresentation"; + } + + /// Classification creation origin key + OUString makeCreationOriginKey() const { return getPolicyKey() + "CreationOrigin"; } +}; + +SFX2_DLLPUBLIC sfx::ClassificationCreationOrigin getCreationOriginProperty( + css::uno::Reference const& rxPropertyContainer, + sfx::ClassificationKeyCreator const& rKeyCreator); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/ctrlitem.hxx b/include/sfx2/ctrlitem.hxx new file mode 100644 index 000000000..03e530c78 --- /dev/null +++ b/include/sfx2/ctrlitem.hxx @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_CTRLITEM_HXX +#define INCLUDED_SFX2_CTRLITEM_HXX + +#include +#include +#include +#include +#include + +class SfxBindings; + +class SFX2_DLLPUBLIC SfxControllerItem +{ +private: + SfxControllerItem* pNext; // to notify next ControllerItem + SfxBindings* pBindings; + MapUnit eFallbackCoreMetric; + sal_uInt16 nId; + +public: + SfxBindings & GetBindings() { + DBG_ASSERT(pBindings, "no Bindings"); + return *pBindings; + } + const SfxBindings & GetBindings() const { + DBG_ASSERT(pBindings, "no Bindings"); + return *pBindings; + } + + SfxControllerItem(); // for arrays + SfxControllerItem( sal_uInt16 nId, SfxBindings & ); + virtual ~SfxControllerItem(); + virtual void dispose(); + + void Bind( sal_uInt16 nNewId, SfxBindings *); // Register in SfxBindings + void UnBind(); + void ReBind(); + bool IsBound() const; + void ClearCache(); + + SfxControllerItem* GetItemLink(); + SfxControllerItem* ChangeItemLink( SfxControllerItem* pNewLink ); + + void SetId( sal_uInt16 nItemId ); + sal_uInt16 GetId() const { return nId; } + + virtual void StateChangedAtToolBoxControl( sal_uInt16 nSID, SfxItemState eState, + const SfxPoolItem* pState ); + + virtual void GetControlState( sal_uInt16 nSID, boost::property_tree::ptree& ); + + MapUnit GetCoreMetric() const; + // override what GetCoreMetric will return if it cannot determine the current CoreMetric + void SetFallbackCoreMetric(MapUnit eFallback) + { + eFallbackCoreMetric = eFallback; + } + + static SfxItemState GetItemState( const SfxPoolItem* pState ); + + SAL_DLLPRIVATE void BindInternal_Impl( sal_uInt16 nNewId, SfxBindings* ); +}; + + +class SFX2_DLLPUBLIC SfxStatusForwarder final : public SfxControllerItem +{ + SfxControllerItem* pMaster; + + virtual void StateChangedAtToolBoxControl( sal_uInt16 nSID, SfxItemState eState, + const SfxPoolItem* pState ) override; + +public: + SfxStatusForwarder( sal_uInt16 nSlotId, + SfxControllerItem&rMaster ); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/devtools/DevelopmentToolChildWindow.hxx b/include/sfx2/devtools/DevelopmentToolChildWindow.hxx new file mode 100644 index 000000000..d78ac5c2e --- /dev/null +++ b/include/sfx2/devtools/DevelopmentToolChildWindow.hxx @@ -0,0 +1,27 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include + +/** + * Necessary child window for the development tools docking window + */ +class SAL_WARN_UNUSED SFX2_DLLPUBLIC DevelopmentToolChildWindow final : public SfxChildWindow +{ + SFX_DECL_CHILDWINDOW_WITHID(DevelopmentToolChildWindow); + + DevelopmentToolChildWindow(vcl::Window* pParentWindow, sal_uInt16 nId, SfxBindings* pBindings, + SfxChildWinInfo* pInfo); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/devtools/DevelopmentToolDockingWindow.hxx b/include/sfx2/devtools/DevelopmentToolDockingWindow.hxx new file mode 100644 index 000000000..4da9fccd9 --- /dev/null +++ b/include/sfx2/devtools/DevelopmentToolDockingWindow.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +/** Development tool main docking window + * + * Contains two sides. Left side contains the simplified DOM tree and + * the right side the object inspector tree. + */ +class SFX2_DLLPUBLIC DevelopmentToolDockingWindow final : public SfxDockingWindow +{ +private: + std::unique_ptr mpObjectInspectorWidgets; + std::unique_ptr mpDocumentModelTreeView; + std::unique_ptr mpDomToolbar; + + // Reference to the root object for the current document + css::uno::Reference mxRoot; + // Stores the current selected object in the document + css::uno::Reference mxCurrentSelection; + css::uno::Reference mxSelectionListener; + css::uno::Reference mxSelectionSupplier; + + // Handler for the DOM tree + DocumentModelTreeHandler maDocumentModelTreeHandler; + // Handler for the object inspector tree + ObjectInspectorTreeHandler maObjectInspectorTreeHandler; + + DECL_DLLPRIVATE_LINK(DocumentModelTreeViewSelectionHandler, weld::TreeView&, void); + DECL_DLLPRIVATE_LINK(DomToolbarButtonClicked, const OString&, void); + + void updateSelection(); + +public: + DevelopmentToolDockingWindow(SfxBindings* pBindings, SfxChildWindow* pChildWindow, + vcl::Window* pParent); + + virtual ~DevelopmentToolDockingWindow() override; + + void dispose() override; + + void ToggleFloatingMode() override; + + // Signals that the selected object in the document changes + void selectionChanged(css::uno::Reference const& xInterface); + + // Signals to change to the current selected object in the object inspector + void changeToCurrentSelection(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/devtools/DocumentModelTreeHandler.hxx b/include/sfx2/devtools/DocumentModelTreeHandler.hxx new file mode 100644 index 000000000..47294d527 --- /dev/null +++ b/include/sfx2/devtools/DocumentModelTreeHandler.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include + +#include +#include + +/** Document model tree handler + * + * Handles the DOM tree part of DevTools, which includes interaction with + * the DOM tree view UI elements and the DOM model. + */ +class DocumentModelTreeHandler +{ +private: + std::unique_ptr& mpDocumentModelTree; + css::uno::Reference mxDocument; + + // Clears all children of a tree node, where the parent is + // identified by the input tree iter. + void clearChildren(weld::TreeIter const& rParent); + + // Clear all tree view nodes. + void clearAll(); + +public: + DocumentModelTreeHandler(std::unique_ptr& pDocumentModelTree, + css::uno::Reference const& xDocument); + + DECL_LINK(ExpandingHandler, const weld::TreeIter&, bool); + + void inspectDocument(); + + static css::uno::Reference getObjectByID(OUString const& rID); + + void dispose(); + + // selects the input object if it exists in the DOM tree view + void selectObject(css::uno::Reference const& xInterface); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/devtools/ObjectInspectorTreeHandler.hxx b/include/sfx2/devtools/ObjectInspectorTreeHandler.hxx new file mode 100644 index 000000000..b6fa678de --- /dev/null +++ b/include/sfx2/devtools/ObjectInspectorTreeHandler.hxx @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + +/** Object inspector tree handler + * + * Handles the object inspector part of DevTools - mainly interaction + * between UI objects that consist of the object inspector. + * + */ +class ObjectInspectorTreeHandler +{ +private: + std::unique_ptr& mpObjectInspectorWidgets; + + // object stack to remember previously inspected objects so it is + // possible to return back to them + std::deque maInspectionStack; + + // just the current context + css::uno::Reference mxContext; + + // treeview sort and compare + comphelper::string::NaturalStringSorter mxSorter; + void setSortFunction(std::unique_ptr& pTreeView); + sal_Int32 compare(std::unique_ptr& pTreeView, const weld::TreeIter& rLeft, + const weld::TreeIter& rRight); + + // treeview manipulation + static void clearObjectInspectorChildren(std::unique_ptr& pTreeView, + weld::TreeIter const& rParent); + static void handleExpanding(std::unique_ptr& pTreeView, + weld::TreeIter const& rParent); + static void clearAll(std::unique_ptr& pTreeView); + + void appendInterfaces(css::uno::Reference const& xInterface); + void appendServices(css::uno::Reference const& xInterface); + void appendProperties(css::uno::Reference const& xInterface); + void appendMethods(css::uno::Reference const& xInterface); + + void inspectObject(css::uno::Reference const& xInterface); + + // Object stack handling + void clearStack(); + void addToStack(css::uno::Any const& rAny); + css::uno::Any popFromStack(); + + void updateBackButtonState(); + +public: + ObjectInspectorTreeHandler(std::unique_ptr& pObjectInspectorWidgets); + + // callbacks when a node in the tree view is expanded + DECL_LINK(ExpandingHandlerInterfaces, const weld::TreeIter&, bool); + DECL_LINK(ExpandingHandlerServices, const weld::TreeIter&, bool); + DECL_LINK(ExpandingHandlerProperties, const weld::TreeIter&, bool); + DECL_LINK(ExpandingHandlerMethods, const weld::TreeIter&, bool); + + // callback when the tree view selection changed to a different node + DECL_LINK(SelectionChanged, weld::TreeView&, void); + + // callback when a pop-up is triggered on a tree view node + DECL_LINK(PopupMenuHandler, const CommandEvent&, bool); + + // callback when a button is clicked on a toolbar + DECL_LINK(ToolbarButtonClicked, const OString&, void); + + // callback when a page is entered or left on the notebook bar for + // different categories + DECL_LINK(NotebookEnterPage, const OString&, void); + DECL_LINK(NotebookLeavePage, const OString&, bool); + + DECL_LINK(HeaderBarClick, int, void); + + void introspect(css::uno::Reference const& xInterface); + + void dispose(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/devtools/ObjectInspectorWidgets.hxx b/include/sfx2/devtools/ObjectInspectorWidgets.hxx new file mode 100644 index 000000000..9c719d2aa --- /dev/null +++ b/include/sfx2/devtools/ObjectInspectorWidgets.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include + +struct ObjectInspectorWidgets +{ + ObjectInspectorWidgets(const std::unique_ptr& rxBuilder) + : mpClassNameLabel(rxBuilder->weld_label("class_name_value_id")) + , mpInterfacesTreeView(rxBuilder->weld_tree_view("interfaces_treeview_id")) + , mpServicesTreeView(rxBuilder->weld_tree_view("services_treeview_id")) + , mpPropertiesTreeView(rxBuilder->weld_tree_view("properties_treeview_id")) + , mpMethodsTreeView(rxBuilder->weld_tree_view("methods_treeview_id")) + , mpToolbar(rxBuilder->weld_toolbar("object_inspector_toolbar")) + , mpNotebook(rxBuilder->weld_notebook("object_inspector_notebookbar")) + , mpTextView(rxBuilder->weld_text_view("object_inspector_text_view")) + , mpPaned(rxBuilder->weld_paned("object_inspector_paned")) + { + } + + ~ObjectInspectorWidgets() + { + // dispose welded objects + mpClassNameLabel.reset(); + mpInterfacesTreeView.reset(); + mpServicesTreeView.reset(); + mpPropertiesTreeView.reset(); + mpMethodsTreeView.reset(); + mpToolbar.reset(); + mpNotebook.reset(); + mpTextView.reset(); + mpPaned.reset(); + } + + std::unique_ptr mpClassNameLabel; + std::unique_ptr mpInterfacesTreeView; + std::unique_ptr mpServicesTreeView; + std::unique_ptr mpPropertiesTreeView; + std::unique_ptr mpMethodsTreeView; + std::unique_ptr mpToolbar; + std::unique_ptr mpNotebook; + std::unique_ptr mpTextView; + std::unique_ptr mpPaned; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/dialoghelper.hxx b/include/sfx2/dialoghelper.hxx new file mode 100644 index 000000000..a853d5d9d --- /dev/null +++ b/include/sfx2/dialoghelper.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_DIALOGHELPER_HXX +#define INCLUDED_SFX2_DIALOGHELPER_HXX + +#include +#include +#include + +class DateTime; +class LocaleDataWrapper; +class OutputDevice; + +//when two tab pages both have the same basic layout with a preview on the +//right, get both of their non-preview areas to request the same size so that +//the preview appears in the same place in each one so flipping between tabs +//isn't distracting as it jumps around + +Size SFX2_DLLPUBLIC getParagraphPreviewOptimalSize(const OutputDevice& rReference); + +Size SFX2_DLLPUBLIC getDrawPreviewOptimalSize(const OutputDevice& rReference); + +Size SFX2_DLLPUBLIC getPreviewStripSize(const OutputDevice& rReference); + +Size SFX2_DLLPUBLIC getPreviewOptionsSize(const OutputDevice& rReference); + +OUString SFX2_DLLPUBLIC getWidestDateTime(const LocaleDataWrapper& rWrapper, bool bWithSec); + +OUString SFX2_DLLPUBLIC formatDateTime(const DateTime& rDateTime, const LocaleDataWrapper& rWrapper, + bool bWithSec); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/digitalsignatures.hxx b/include/sfx2/digitalsignatures.hxx new file mode 100644 index 000000000..8f0e161b4 --- /dev/null +++ b/include/sfx2/digitalsignatures.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include +#include + +#include + +namespace sfx2 +{ +/// Extension of css::security::XDocumentDigitalSignatures for internal purposes. +class SAL_NO_VTABLE SAL_DLLPUBLIC_RTTI DigitalSignatures +{ +public: + /// Same as signDocumentWithCertificate(), but passes the xModel as well. + virtual bool + SignModelWithCertificate(const css::uno::Reference& xModel, + const css::uno::Reference& xCertificate, + const css::uno::Reference& xStorage, + const css::uno::Reference& xStream) + = 0; + +protected: + ~DigitalSignatures() noexcept = default; +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/dinfdlg.hxx b/include/sfx2/dinfdlg.hxx new file mode 100644 index 000000000..fc7ebbfd4 --- /dev/null +++ b/include/sfx2/dinfdlg.hxx @@ -0,0 +1,579 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DINFDLG_HXX +#define INCLUDED_SFX2_DINFDLG_HXX + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include + +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } + +namespace com::sun::star { + namespace document { + class XDocumentProperties; + } +} + +struct CustomProperty; +class SvtCalendarBox; + +// class SfxDocumentInfoItem --------------------------------------------- + +class UNLESS_MERGELIBS(SFX2_DLLPUBLIC) SfxDocumentInfoItem final : public SfxStringItem +{ +private: + sal_Int32 m_AutoloadDelay; + OUString m_AutoloadURL; + bool m_isAutoloadEnabled; + OUString m_DefaultTarget; + OUString m_TemplateName; + OUString m_Author; + css::util::DateTime m_CreationDate; + OUString m_ModifiedBy; + css::util::DateTime m_ModificationDate; + OUString m_PrintedBy; + css::util::DateTime m_PrintDate; + sal_Int16 m_EditingCycles; + sal_Int32 m_EditingDuration; + OUString m_Description; + OUString m_Keywords; + OUString m_Subject; + OUString m_Title; + bool m_bHasTemplate; + bool m_bDeleteUserData; + bool m_bUseUserData; + bool m_bUseThumbnailSave; + std::vector< std::unique_ptr > m_aCustomProperties; + css::uno::Sequence< css::document::CmisProperty > m_aCmisProperties; + +public: + static SfxPoolItem* CreateDefault(); + SfxDocumentInfoItem(); + SfxDocumentInfoItem( const OUString &rFileName, + const css::uno::Reference< css::document::XDocumentProperties> & i_xDocProps, + const css::uno::Sequence< css::document::CmisProperty> & i_cmisProps, + bool bUseUserData, bool bUseThumbnailSave ); + SfxDocumentInfoItem( const SfxDocumentInfoItem& ); + virtual ~SfxDocumentInfoItem() override; + + /// update i_xDocProps with the data in this object + void UpdateDocumentInfo( + const css::uno::Reference< css::document::XDocumentProperties> & i_xDocProps, + bool i_bDoNotUpdateUserDefined = false) + const; + bool isCmisDocument() const { return m_aCmisProperties.hasElements();} + + bool isAutoloadEnabled() const { return m_isAutoloadEnabled; } + sal_Int32 getAutoloadDelay() const { return m_AutoloadDelay; } + const OUString& getAutoloadURL() const { return m_AutoloadURL; } + const OUString& getDefaultTarget() const { return m_DefaultTarget; } + const OUString& getTemplateName() const { return m_TemplateName; } + const OUString& getAuthor() const { return m_Author; } + + const css::util::DateTime& + getCreationDate() const { return m_CreationDate; } + const OUString& getModifiedBy() const { return m_ModifiedBy; } + + const css::util::DateTime& + getModificationDate() const { return m_ModificationDate; } + const OUString& getPrintedBy() const { return m_PrintedBy; } + const css::util::DateTime& + getPrintDate() const { return m_PrintDate; } + sal_Int16 getEditingCycles() const { return m_EditingCycles; } + sal_Int32 getEditingDuration() const { return m_EditingDuration; } + const OUString& getDescription() const { return m_Description; } + void setDescription(const OUString& i_val) { m_Description = i_val; } + const OUString& getKeywords() const { return m_Keywords; } + void setKeywords(const OUString& i_val) { m_Keywords = i_val; } + const OUString& getSubject() const { return m_Subject; } + void setSubject(const OUString& i_val) { m_Subject = i_val; } + const OUString& getTitle() const { return m_Title; } + void setTitle(const OUString& i_val) { m_Title = i_val; } + + /// reset user-specific data (author, modified-by, ...) + void resetUserData(const OUString & i_rAuthor); + + void SetTemplate( bool b ) { m_bHasTemplate = b; } + bool HasTemplate() const { return m_bHasTemplate; } + void SetDeleteUserData( bool bSet ); + void SetUseUserData( bool bSet ); + void SetUseThumbnailSave( bool bSet ); + bool IsUseUserData() const { return m_bUseUserData;} + bool IsUseThumbnailSave() const { return m_bUseThumbnailSave;} + + + std::vector< std::unique_ptr > GetCustomProperties() const; + void ClearCustomProperties(); + void AddCustomProperty( const OUString& sName, + const css::uno::Any& rValue ); + + const css::uno::Sequence< css::document::CmisProperty >& + GetCmisProperties() const { return m_aCmisProperties;} + + void SetCmisProperties(const css::uno::Sequence< css::document::CmisProperty >& cmisProps ); + virtual SfxDocumentInfoItem* Clone( SfxItemPool* pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +// class SfxDocumentPage ------------------------------------------------- + +class SfxDocumentPage final : public SfxTabPage +{ +private: + OUString m_aUnknownSize; + OUString m_aMultiSignedStr; + + bool bEnableUseUserData : 1, + bHandleDelete : 1; + + std::unique_ptr m_xBmp; + std::unique_ptr m_xNameED; + std::unique_ptr m_xChangePassBtn; + + std::unique_ptr m_xShowTypeFT; + std::unique_ptr m_xFileValEd; + std::unique_ptr m_xShowSizeFT; + + std::unique_ptr m_xCreateValFt; + std::unique_ptr m_xChangeValFt; + std::unique_ptr m_xSignedValFt; + std::unique_ptr m_xSignatureBtn; + std::unique_ptr m_xPrintValFt; + std::unique_ptr m_xTimeLogValFt; + std::unique_ptr m_xDocNoValFt; + + std::unique_ptr m_xUseUserDataCB; + std::unique_ptr m_xDeleteBtn; + std::unique_ptr m_xUseThumbnailSaveCB; + + std::unique_ptr m_xTemplFt; + std::unique_ptr m_xTemplValFt; + std::unique_ptr m_xImagePreferredDpiCheckButton; + std::unique_ptr m_xImagePreferredDpiComboBox; + + DECL_LINK(DeleteHdl, weld::Button&, void); + DECL_LINK(SignatureHdl, weld::Button&, void); + DECL_LINK(ChangePassHdl, weld::Button&, void); + DECL_LINK(ImagePreferredDPICheckBoxClicked, weld::Toggleable&, void); + + void ImplUpdateSignatures(); + void ImplCheckPasswordState(); + + virtual bool FillItemSet( SfxItemSet* ) override; + virtual void Reset( const SfxItemSet* ) override; + +public: + SfxDocumentPage(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet&); + static std::unique_ptr Create( weld::Container* pPage, weld::DialogController* pController, const SfxItemSet* ); + virtual ~SfxDocumentPage() override; + + void EnableUseUserData(); +}; + +// class SfxDocumentDescPage --------------------------------------------- + +class SfxDocumentDescPage final : public SfxTabPage +{ +private: + SfxDocumentInfoItem* m_pInfoItem; + std::unique_ptr m_xTitleEd; + std::unique_ptr m_xThemaEd; + std::unique_ptr m_xKeywordsEd; + std::unique_ptr m_xCommentEd; + + virtual bool FillItemSet( SfxItemSet* ) override; + virtual void Reset( const SfxItemSet* ) override; + +public: + SfxDocumentDescPage(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet&); + virtual ~SfxDocumentDescPage() override; + static std::unique_ptr Create( weld::Container* pPage, weld::DialogController* pController, const SfxItemSet* ); +}; + +// class SfxDocumentInfoDialog ------------------------------------------- + +class SFX2_DLLPUBLIC SfxDocumentInfoDialog final : public SfxTabDialogController +{ + virtual void PageCreated(const OString& rId, SfxTabPage& rPage) override; + +public: + SfxDocumentInfoDialog(weld::Window* pParent, const SfxItemSet&); + void AddFontTabPage(); +}; + +// class CustomPropertiesRemoveButton ------------------------------------ +struct CustomPropertyLine; + +class CustomPropertiesDateField +{ +private: + std::unique_ptr m_xDateField; +public: + ::std::optional m_TZ; + + CustomPropertiesDateField(SvtCalendarBox* pDateField); + void set_visible(bool bVisible); + Date get_date() const; + void set_date(const Date& rDate); + ~CustomPropertiesDateField(); +}; + +namespace weld +{ + class TimeFormatter; +} + +class CustomPropertiesTimeField +{ +public: + std::unique_ptr m_xTimeField; + std::unique_ptr m_xFormatter; + bool m_isUTC; + + CustomPropertiesTimeField(std::unique_ptr xTimeField); + void set_visible(bool bVisible) { m_xTimeField->set_visible(bVisible); } + tools::Time get_value() const; + void set_value(const tools::Time& rTime); + + ~CustomPropertiesTimeField(); +}; + +class CustomPropertiesDurationField +{ + css::util::Duration m_aDuration; + std::unique_ptr m_xEntry; + std::unique_ptr m_xEditButton; + + DECL_LINK(ClickHdl, weld::Button&, void); +public: + CustomPropertiesDurationField(std::unique_ptr xEntry, + std::unique_ptr xEditButton); + + void SetDuration( const css::util::Duration& rDuration ); + const css::util::Duration& GetDuration() const { return m_aDuration; } + + void set_visible(bool bVisible); +}; + +class CustomPropertiesYesNoButton +{ +private: + std::unique_ptr m_xTopLevel; + std::unique_ptr m_xYesButton; + std::unique_ptr m_xNoButton; + +public: + CustomPropertiesYesNoButton(std::unique_ptr, + std::unique_ptr xYesButton, + std::unique_ptr xNoButton); + ~CustomPropertiesYesNoButton(); + + void CheckYes() { m_xYesButton->set_active(true); } + void CheckNo() { m_xNoButton->set_active(true); } + bool IsYesChecked() const { return m_xYesButton->get_active(); } + void set_visible(bool bVisible) { m_xTopLevel->set_visible(bVisible); } +}; + +class CustomPropertiesWindow; + +// struct CustomPropertyLine --------------------------------------------- +struct CustomPropertyLine +{ + CustomPropertiesWindow* m_pParent; + + std::unique_ptr m_xBuilder; + std::unique_ptr m_xLine; + std::unique_ptr m_xNameBox; + std::unique_ptr m_xTypeBox; + std::unique_ptr m_xValueEdit; + std::unique_ptr m_xDateTimeBox; + std::unique_ptr m_xDateField; + std::unique_ptr m_xTimeField; + std::unique_ptr m_xDurationBox; + std::unique_ptr m_xDurationField; + std::unique_ptr m_xYesNoButton; + std::unique_ptr m_xRemoveButton; + + bool m_bTypeLostFocus; + + CustomPropertyLine(CustomPropertiesWindow* pParent, weld::Widget* pContainer); + DECL_LINK(TypeHdl, weld::ComboBox&, void); + DECL_LINK(RemoveHdl, weld::Button&, void); + DECL_LINK(EditLoseFocusHdl, weld::Widget&, void); + DECL_LINK(BoxLoseFocusHdl, weld::Widget&, void); + + void DoTypeHdl(const weld::ComboBox& rBox); + + void Clear(); + void Hide(); +}; + +// class CustomPropertiesWindow ------------------------------------------ + +class CustomPropertiesWindow +{ +private: + sal_Int32 m_nHeight; + sal_Int32 m_nLineHeight; + sal_Int32 m_nScrollPos; + std::vector> m_aCustomProperties; + std::vector> m_aCustomPropertiesLines; + CustomPropertyLine* m_pCurrentLine; + SvNumberFormatter m_aNumberFormatter; + Idle m_aEditLoseFocusIdle; + Idle m_aBoxLoseFocusIdle; + Link m_aRemovedHdl; + + weld::Container& m_rBody; + weld::Label& m_rHeaderAccName; + weld::Label& m_rHeaderAccType; + weld::Label& m_rHeaderAccValue; + + DECL_LINK(EditTimeoutHdl, Timer *, void); + DECL_LINK(BoxTimeoutHdl, Timer *, void); + + bool IsLineValid( CustomPropertyLine* pLine ) const; + void ValidateLine( CustomPropertyLine* pLine, bool bIsFromTypeBox ); + void CreateNewLine(); + void StoreCustomProperties(); + sal_uInt32 GetCurrentDataModelPosition() const { return -1 * m_nScrollPos / m_nLineHeight; } + +public: + CustomPropertiesWindow(weld::Container& rParent, weld::Label& rHeaderAccName, + weld::Label& rHeaderAccType, weld::Label& rHeaderAccValue); + ~CustomPropertiesWindow(); + + sal_uInt16 GetExistingLineCount() const { return m_aCustomPropertiesLines.size(); } + sal_uInt16 GetTotalLineCount() const { return m_aCustomProperties.size(); } + void SetVisibleLineCount(sal_uInt32 nCount); + sal_Int32 GetHeight() const { return m_nHeight; } + void SetHeight(int nHeight) { m_nHeight = nHeight; } + sal_Int32 GetLineHeight() const { return m_nLineHeight; } + void SetLineHeight(sal_Int32 nLineHeight) { m_nLineHeight = nLineHeight; } + void AddLine( const OUString& sName, css::uno::Any const & rAny ); + bool AreAllLinesValid() const; + void ClearAllLines(); + void DoScroll( sal_Int32 nNewPos ); + void ReloadLinesContent(); + + css::uno::Sequence< css::beans::PropertyValue > + GetCustomProperties(); + void SetCustomProperties(std::vector< std::unique_ptr >&& rProperties); + void SetRemovedHdl( const Link& rLink ) { m_aRemovedHdl = rLink; } + + void BoxLoseFocus(CustomPropertyLine* pLine); + void EditLoseFocus(CustomPropertyLine* pLine); + void Remove(const CustomPropertyLine* pLine); +}; + +// class CustomPropertiesControl ----------------------------------------- + +class CustomPropertiesControl +{ +private: + sal_Int32 m_nThumbPos; + + std::unique_ptr m_xBox; + std::unique_ptr m_xBody; + std::unique_ptr m_xVertScroll; + std::unique_ptr m_xPropertiesWin; + std::unique_ptr m_xName; + std::unique_ptr m_xType; + std::unique_ptr m_xValue; + + DECL_LINK( ResizeHdl, const Size&, void ); + DECL_LINK( ScrollHdl, weld::ScrolledWindow&, void ); + DECL_LINK( RemovedHdl, void*, void ); + +public: + CustomPropertiesControl(); + ~CustomPropertiesControl(); + + void AddLine(css::uno::Any const & rAny); + + bool AreAllLinesValid() const { return m_xPropertiesWin->AreAllLinesValid(); } + void ClearAllLines() { m_xPropertiesWin->ClearAllLines(); } + + css::uno::Sequence + GetCustomProperties() const + { return m_xPropertiesWin->GetCustomProperties(); } + void SetCustomProperties(std::vector< std::unique_ptr >&& rProperties); + + void Init(weld::Builder& rParent); +}; + +// class SfxCustomPropertiesPage ----------------------------------------- + +class SfxCustomPropertiesPage final : public SfxTabPage +{ +private: + DECL_LINK(AddHdl, weld::Button&, void); + + std::unique_ptr m_xPropertiesCtrl; + std::unique_ptr m_xAdd; + + virtual bool FillItemSet( SfxItemSet* ) override; + virtual void Reset( const SfxItemSet* ) override; + virtual DeactivateRC DeactivatePage( SfxItemSet* pSet ) override; + +public: + SfxCustomPropertiesPage(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet&); + static std::unique_ptr Create( weld::Container* pPage, weld::DialogController* pController, const SfxItemSet* ); + virtual ~SfxCustomPropertiesPage() override; +}; + +struct CmisValue +{ + std::unique_ptr m_xBuilder; + std::unique_ptr m_xFrame; + std::unique_ptr m_xValueEdit; + + CmisValue(weld::Widget* pParent, const OUString& rStr); +}; + +struct CmisDateTime +{ + std::unique_ptr m_xBuilder; + std::unique_ptr m_xFrame; + std::unique_ptr m_xDateField; + std::unique_ptr m_xTimeField; + std::unique_ptr m_xFormatter; + + CmisDateTime(weld::Widget* pParent, const css::util::DateTime& rDateTime); +}; + +struct CmisYesNo +{ + std::unique_ptr m_xBuilder; + std::unique_ptr m_xFrame; + std::unique_ptr m_xYesButton; + std::unique_ptr m_xNoButton; + + CmisYesNo(weld::Widget* pParent, bool bValue); +}; + +// struct CmisPropertyLine --------------------------------------------- + +struct CmisPropertyLine +{ + std::unique_ptr m_xBuilder; + OUString m_sId; + OUString m_sType; + bool m_bUpdatable; + bool m_bRequired; + bool m_bMultiValued; + bool m_bOpenChoice; + std::unique_ptr m_xFrame; + std::unique_ptr m_xName; + std::unique_ptr m_xType; + std::vector< std::unique_ptr > m_aValues; + std::vector< std::unique_ptr > m_aDateTimes; + std::vector< std::unique_ptr > m_aYesNos; + CmisPropertyLine(weld::Widget* pParent); + ~CmisPropertyLine(); +}; + +// class CmisPropertiesWindow ------------------------------------------ + +class CmisPropertiesWindow +{ +private: + std::unique_ptr m_xBox; + SvNumberFormatter m_aNumberFormatter; + std::vector< std::unique_ptr > m_aCmisPropertiesLines; +public: + CmisPropertiesWindow(std::unique_ptr xParent); + ~CmisPropertiesWindow(); + + void AddLine( const OUString& sId, const OUString& sName, + const OUString& sType, const bool bUpdatable, + const bool bRequired, const bool bMultiValued, + const bool bOpenChoice, + css::uno::Any& aChoices, + css::uno::Any const & rAny ); + void ClearAllLines(); + + css::uno::Sequence< css::document::CmisProperty > + GetCmisProperties() const; +}; + +// class CmisPropertiesControl ----------------------------------------- + +class CmisPropertiesControl +{ +private: + CmisPropertiesWindow m_aPropertiesWin; + std::unique_ptr m_xScrolledWindow; + +public: + CmisPropertiesControl(weld::Builder& rBuilder); + + void AddLine( const OUString& sId, const OUString& sName, + const OUString& sType, const bool bUpdatable, + const bool bRequired, const bool bMultiValude, + const bool bOpenChoice, + css::uno::Any& aChoices, + css::uno::Any const & rAny ); + + void ClearAllLines(); + css::uno::Sequence< css::document::CmisProperty > + GetCmisProperties() const + { return m_aPropertiesWin.GetCmisProperties(); } +}; + +// class SfxCmisPropertiesPage ------------------------------------------------- + +class SfxCmisPropertiesPage final : public SfxTabPage +{ +private: + std::unique_ptr m_xPropertiesCtrl; + + virtual bool FillItemSet( SfxItemSet* ) override; + virtual void Reset( const SfxItemSet* ) override; + virtual DeactivateRC DeactivatePage( SfxItemSet* pSet ) override; + +public: + SfxCmisPropertiesPage(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet&); + virtual ~SfxCmisPropertiesPage() override; + static std::unique_ptr Create(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet*); +}; + +#endif // #ifndef _ INCLUDED_SFX2_DINFDLG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/dispatch.hxx b/include/sfx2/dispatch.hxx new file mode 100644 index 000000000..ee445710b --- /dev/null +++ b/include/sfx2/dispatch.hxx @@ -0,0 +1,184 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DISPATCH_HXX +#define INCLUDED_SFX2_DISPATCH_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +class SfxSlotServer; +class SfxRequest; +class SfxViewFrame; +class SfxItemSet; +class SfxModule; +class Point; +struct SfxDispatcher_Impl; + +namespace com::sun::star::awt { class XPopupMenu; } +namespace vcl { class Window; } + +enum class SfxDispatcherPopFlags +{ + NONE = 0, + POP_UNTIL = 4, + POP_DELETE = 2, + PUSH = 1, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +enum class SfxSlotFilterState +{ + DISABLED, + ENABLED, + // enabled even if ReadOnlyDoc + ENABLED_READONLY, +}; + + +class SFX2_DLLPUBLIC SfxDispatcher final +{ + std::unique_ptr xImp; + + // Search for temporary evaluated Todos + SAL_DLLPRIVATE bool CheckVirtualStack( const SfxShell& rShell ); + +friend class SfxApplication; +friend class SfxViewFrame; +friend class SfxBindings; +friend class SfxStateCache; +friend class SfxPopupMenuManager; +friend class SfxHelp; + + DECL_DLLPRIVATE_LINK( EventHdl_Impl, Timer *, void ); + void PostMsgHandler(std::unique_ptr); + + SAL_DLLPRIVATE void Call_Impl( SfxShell& rShell, const SfxSlot &rSlot, SfxRequest &rReq, bool bRecord ); + SAL_DLLPRIVATE void Update_Impl_( bool,bool,bool,SfxWorkWindow*); + + + bool FindServer_( sal_uInt16 nId, SfxSlotServer &rServer ); + bool FillState_( const SfxSlotServer &rServer, + SfxItemSet &rState, const SfxSlot *pRealSlot ); + void Execute_( SfxShell &rShell, const SfxSlot &rSlot, + SfxRequest &rReq, + SfxCallMode eCall); + + void FlushImpl(); + +public: + SfxDispatcher(); + SfxDispatcher( SfxViewFrame *pFrame ); + + SAL_DLLPRIVATE void Construct_Impl(); + + ~SfxDispatcher(); + + const SfxPoolItem* Execute( sal_uInt16 nSlot, + SfxCallMode nCall = SfxCallMode::SLOT, + const SfxPoolItem **pArgs = nullptr, + sal_uInt16 nModi = 0, + const SfxPoolItem **pInternalArgs = nullptr); + + const SfxPoolItem* Execute(sal_uInt16 nSlot, + SfxCallMode nCall, + SfxItemSet const * pArgs, + SfxItemSet const * pInternalArgs, + sal_uInt16 nModi); + + const SfxPoolItem* ExecuteList(sal_uInt16 nSlot, + SfxCallMode nCall, + std::initializer_list args, + std::initializer_list internalargs = std::initializer_list()); + + const SfxPoolItem* Execute( sal_uInt16 nSlot, + SfxCallMode nCall, + const SfxItemSet &rArgs ); + + const SfxSlot* GetSlot( const OUString& rCommand ); + + bool IsActive( const SfxShell& rShell ); + sal_uInt16 GetShellLevel( const SfxShell &rShell ); + SfxBindings* GetBindings() const; + + void Push( SfxShell& rShell ); + void Pop( SfxShell& rShell, SfxDispatcherPopFlags nMode = SfxDispatcherPopFlags::NONE ); + + SfxShell* GetShell(sal_uInt16 nIdx) const; + SfxViewFrame* GetFrame() const; + SfxModule* GetModule() const; + + void ExecutePopup( const OUString &rResName, vcl::Window *pWin = nullptr, const Point *pPos = nullptr ); + static void ExecutePopup( vcl::Window *pWin = nullptr, const Point *pPosPixel = nullptr ); + + bool IsAppDispatcher() const; + bool IsFlushed() const; + void Flush(); + void Lock( bool bLock ); + bool IsLocked() const; + void SetSlotFilter( SfxSlotFilterState nEnable = SfxSlotFilterState::DISABLED, + o3tl::span pSIDs = o3tl::span()); + + void HideUI( bool bHide = true ); + ToolbarId GetObjectBarId( sal_uInt16 nPos ) const; + + SfxItemState QueryState( sal_uInt16 nSID, const SfxPoolItem* &rpState ); + template + SfxItemState QueryState( TypedWhichId nSID, const T* &rpState ) + { + return QueryState(sal_uInt16(nSID), reinterpret_cast(rpState)); + } + SfxItemState QueryState( sal_uInt16 nSID, css::uno::Any& rAny ); + + void SetDisableFlags( SfxDisableFlags nFlags ); + SfxDisableFlags GetDisableFlags() const; + + SAL_DLLPRIVATE void SetMenu_Impl(); + SAL_DLLPRIVATE void Update_Impl( bool bForce = false ); // ObjectBars etc. + SAL_DLLPRIVATE bool IsUpdated_Impl() const; + SAL_DLLPRIVATE bool GetShellAndSlot_Impl( sal_uInt16 nSlot, SfxShell **ppShell, const SfxSlot **ppSlot, + bool bOwnShellsOnly, bool bRealSlot ); + SAL_DLLPRIVATE void SetReadOnly_Impl( bool bOn ); + SAL_DLLPRIVATE bool GetReadOnly_Impl() const; + SAL_DLLPRIVATE SfxSlotFilterState IsSlotEnabledByFilter_Impl( sal_uInt16 nSID ) const; + SAL_DLLPRIVATE void SetQuietMode_Impl( bool bOn ); + SAL_DLLPRIVATE bool IsReadOnlyShell_Impl( sal_uInt16 nShell ) const; + SAL_DLLPRIVATE void RemoveShell_Impl( SfxShell& rShell ); + SAL_DLLPRIVATE void DoActivate_Impl( bool bMDI ); + SAL_DLLPRIVATE void DoDeactivate_Impl( bool bMDI, SfxViewFrame const * pNew ); + SAL_DLLPRIVATE void InvalidateBindings_Impl(bool); + + static boost::property_tree::ptree fillPopupMenu(const css::uno::Reference& rMenu); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/dllapi.h b/include/sfx2/dllapi.h new file mode 100644 index 000000000..a6877f769 --- /dev/null +++ b/include/sfx2/dllapi.h @@ -0,0 +1,36 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_DLLAPI_H +#define INCLUDED_SFX2_DLLAPI_H + +#include +#include + +#if defined SFX2_DLLIMPLEMENTATION +#define SFX2_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define SFX2_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +#define SFX2_DLLPRIVATE SAL_DLLPRIVATE + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docfac.hxx b/include/sfx2/docfac.hxx new file mode 100644 index 000000000..884112530 --- /dev/null +++ b/include/sfx2/docfac.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DOCFAC_HXX +#define INCLUDED_SFX2_DOCFAC_HXX + +#include +#include +#include + +#include +#include +#include + +class SfxFilter; +class SfxViewFactory; +struct SfxObjectFactory_Impl; +class SfxFilterContainer; +class SvGlobalName; +class SfxModule; + +typedef void (*SfxVoidFunc)(); + + +class SFX2_DLLPUBLIC SfxObjectFactory +{ +private: + const OUString m_sFactoryName; + std::unique_ptr pImpl; // Additional Data + +public: + SfxObjectFactory( const SvGlobalName &rName, const OUString& sFactoryName ); + ~SfxObjectFactory(); + + const SvGlobalName& GetClassId() const; + OUString GetFactoryURL() const; // shortcut for "private:factory/GetShortName()" + const OUString& GetFactoryName() const { return m_sFactoryName; } + OUString GetModuleName() const; + SfxFilterContainer *GetFilterContainer() const; + + // Views + void RegisterViewFactory(SfxViewFactory &rFactory); + sal_uInt16 GetViewFactoryCount() const; + SfxViewFactory& GetViewFactory(sal_uInt16 i = 0) const; + + /// returns the view factory whose GetAPIViewName or GetLegacyViewName delivers the requested logical name + SfxViewFactory* GetViewFactoryByViewName( std::u16string_view i_rViewName ) const; + + // Filter + std::shared_ptr GetTemplateFilter() const; + static OUString GetStandardTemplate( std::u16string_view rServiceName ); + static void SetStandardTemplate( const OUString& rServiceName, const OUString& rTemplateName ); + static void SetSystemTemplate( const OUString& rServiceName, const OUString& rTemplateName ); + + void SetDocumentServiceName( const OUString& rServiceName ); + const OUString& GetDocumentServiceName() const; + + SfxModule* GetModule() const; + + SAL_DLLPRIVATE void SetModule_Impl( SfxModule* ); + SAL_DLLPRIVATE sal_uInt16 GetViewNo_Impl( const SfxInterfaceId i_nViewId, const sal_uInt16 i_nFallback ) const; + +private: + SfxObjectFactory(const SfxObjectFactory&) = delete; + const SfxObjectFactory& operator=(const SfxObjectFactory &) = delete; +}; + +#define SFX_DECL_OBJECTFACTORY() \ +public: \ + static SfxObjectFactory& Factory(); \ + virtual SfxObjectFactory& GetFactory() const override { return Factory(); } + +#define SFX_IMPL_OBJECTFACTORY(ClassName,GlobName,ShortName) \ + SfxObjectFactory& ClassName::Factory() \ + { \ + static SfxObjectFactory aObjectFactory(GlobName, ShortName); \ + return aObjectFactory; \ + } +#endif // INCLUDED_SFX2_DOCFAC_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docfile.hxx b/include/sfx2/docfile.hxx new file mode 100644 index 000000000..bc6e0cf1e --- /dev/null +++ b/include/sfx2/docfile.hxx @@ -0,0 +1,309 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_DOCFILE_HXX +#define INCLUDED_SFX2_DOCFILE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::graphic { class XGraphic; } +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::security { class XCertificate; } +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::ucb { class XCommandEnvironment; } +namespace com::sun::star::ucb { class XContent; } +namespace com::sun::star::util { struct DateTime; } +namespace com::sun::star::util { struct RevisionTag; } +namespace com::sun::star::frame +{ +class XModel; +} +namespace ucbhelper { class Content; } + +class SvKeyValueIterator; +class SfxFilter; +class SfxMedium_Impl; +class INetURLObject; +class SfxFrame; +class DateTime; +struct ImplSVEvent; + +namespace weld +{ + class Window; +} + +class SFX2_DLLPUBLIC SfxMedium final : public SvRefBase +{ + std::unique_ptr< SfxMedium_Impl > pImpl; + + SAL_DLLPRIVATE void SetIsRemote_Impl(); + SAL_DLLPRIVATE void CloseInStream_Impl(bool bInDestruction = false); + SAL_DLLPRIVATE void CloseOutStream_Impl(); + SAL_DLLPRIVATE void CloseStreams_Impl(bool bInDestruction = false); + + SAL_DLLPRIVATE void SetEncryptionDataToStorage_Impl(); + +public: + + SfxMedium(); + SfxMedium( const OUString &rName, + StreamMode nOpenMode, + std::shared_ptr pFilter = nullptr, + const std::shared_ptr& pSet = nullptr ); + SfxMedium( const OUString &rName, + const OUString &rReferer, + StreamMode nOpenMode, + std::shared_ptr pFilter = nullptr, + const std::shared_ptr& pSet = nullptr ); + SfxMedium( const css::uno::Reference< css::embed::XStorage >& xStorage, + const OUString& rBaseURL, + const std::shared_ptr& pSet = nullptr ); + SfxMedium( const css::uno::Reference< css::embed::XStorage >& xStorage, + const OUString& rBaseURL, + const OUString& rTypeName, + const std::shared_ptr& pSet = nullptr ); + SfxMedium( const css::uno::Sequence< css::beans::PropertyValue >& aArgs ); + + virtual ~SfxMedium() override; + + DECL_DLLPRIVATE_STATIC_LINK(SfxMedium, ShowReloadEditableDialog, void*, void); + bool CheckCanGetLockfile() const; + void SetOriginallyReadOnly(bool val); + void AddToCheckEditableWorkerList(); + void SetWorkerReloadEvent(ImplSVEvent* pEvent); + ImplSVEvent* GetWorkerReloadEvent() const; + const std::shared_ptr& GetCheckEditableMutex() const; + void CancelCheckEditableEntry(bool bRemoveEvent = true); + + void UseInteractionHandler( bool ); + css::uno::Reference< css::task::XInteractionHandler > + GetInteractionHandler( bool bGetAlways = false ); + + void setStreamToLoadFrom( + const css::uno::Reference& xInputStream, + bool bIsReadOnly); + + void SetLoadTargetFrame(SfxFrame* pFrame ); + SfxFrame* GetLoadTargetFrame() const; + + /** + * Does not take ownership of pFlt but pFlt needs to be around as long as the SfxMedium instance. + */ + void SetFilter(const std::shared_ptr& pFilter); + const std::shared_ptr& GetFilter() const; + const OUString& GetOrigURL() const; + + SfxItemSet * GetItemSet() const; + void SetArgs(const css::uno::Sequence& rArgs); + const css::uno::Sequence & GetArgs() const; + void Close(bool bInDestruction = false); + void CloseAndRelease(); + void ReOpen(); + void CompleteReOpen(); + const OUString& GetName() const; + const INetURLObject& GetURLObject() const; + + void CheckFileDate( const css::util::DateTime& aInitDate ); + [[nodiscard]] bool DocNeedsFileDateCheck() const; + css::util::DateTime const & GetInitFileDate( bool bIgnoreOldValue ); + + css::uno::Reference< css::ucb::XContent > GetContent() const; + const OUString& GetPhysicalName() const; + [[nodiscard]] bool IsRemote() const; + [[nodiscard]] bool IsOpen() const; // { return aStorage.Is() || pInStream; } + void Download( const Link& aLink = Link()); + void SetDoneLink( const Link& rLink ); + + ErrCode GetErrorCode() const; + ErrCode GetError() const + { return GetErrorCode().IgnoreWarning(); } + ErrCode const & GetLastStorageCreationState() const; + + void SetError(ErrCode nError); + + void CloseInStream(); + void CloseOutStream(); + + void CloseStorage(); + + StreamMode GetOpenMode() const; + void SetOpenMode( StreamMode nStorOpen, bool bDontClose = false ); + + SvStream* GetInStream(); + SvStream* GetOutStream(); + + bool Commit(); + bool IsStorage(); + + enum class LockFileResult + { + Failed, + FailedLockFile, // there was only lock file that prevented success - no syslock or IO error + Succeeded, + }; + LockFileResult LockOrigFileOnDemand(bool bLoading, bool bNoUI, bool bTryIgnoreLockFile = false, + LockFileEntry* pLockData = nullptr); + void DisableUnlockWebDAV( bool bDisableUnlockWebDAV = true ); + void UnlockFile( bool bReleaseLockStream ); + /// Lets Transfer_Impl() not fsync the output file. + void DisableFileSync(bool bDisableFileSync); + + css::uno::Reference< css::embed::XStorage > GetStorage( bool bCreateTempFile = true ); + css::uno::Reference< css::embed::XStorage > GetOutputStorage(); + void ResetError(); + [[nodiscard]] bool IsExpired() const; + void SetName( const OUString& rName, bool bSetOrigURL = false ); + + const css::uno::Sequence < css::util::RevisionTag >& + GetVersionList( bool _bNoReload = false ); + [[nodiscard]] bool IsReadOnly() const; + + // Whether the medium had originally been opened r/o (either because it is + // "physically" r/o, or because it was requested to be opened r/o, + // independent of later changes via SetOpenMode; used to keep track of the + // "true" state of the medium across toggles via SID_EDITDOC (which do + // change SetOpenMode): + [[nodiscard]] bool IsOriginallyReadOnly() const; + + // Whether the medium had originally been requested to be opened r/o, + // independent of later changes via SetOpenMode; used for SID_RELOAD: + [[nodiscard]] bool IsOriginallyLoadedReadOnly() const; + + css::uno::Reference< css::io::XInputStream > const & GetInputStream(); + + void CreateTempFile( bool bReplace = true ); + void CreateTempFileNoCopy(); + OUString SwitchDocumentToTempFile(); + bool SwitchDocumentToFile( const OUString& aURL ); + + OUString GetBaseURL( bool bForSaving=false ); + void SetInCheckIn( bool bInCheckIn ); + bool IsInCheckIn( ) const; + bool IsSkipImages( ) const; + + SAL_DLLPRIVATE bool HasStorage_Impl() const; + + SAL_DLLPRIVATE void StorageBackup_Impl(); + SAL_DLLPRIVATE OUString const & GetBackup_Impl(); + + SAL_DLLPRIVATE css::uno::Reference< css::embed::XStorage > const & GetZipStorageToSign_Impl( bool bReadOnly = true ); + SAL_DLLPRIVATE void CloseZipStorage_Impl(); + + // the storage that will be returned by the medium on GetStorage request + SAL_DLLPRIVATE void SetStorage_Impl( const css::uno::Reference< css::embed::XStorage >& xNewStorage ); + + SAL_DLLPRIVATE void CloseAndReleaseStreams_Impl(); + SAL_DLLPRIVATE void AddVersion_Impl( css::util::RevisionTag& rVersion ); + SAL_DLLPRIVATE bool TransferVersionList_Impl( SfxMedium const & rMedium ); + SAL_DLLPRIVATE void SaveVersionList_Impl(); + SAL_DLLPRIVATE void RemoveVersion_Impl( const OUString& rVersion ); + + SAL_DLLPRIVATE void SetExpired_Impl( const DateTime& rDateTime ); + SAL_DLLPRIVATE SvKeyValueIterator* GetHeaderAttributes_Impl(); + + SAL_DLLPRIVATE void Init_Impl(); + + SAL_DLLPRIVATE void GetLockingStream_Impl(); + SAL_DLLPRIVATE void GetMedium_Impl(); + SAL_DLLPRIVATE bool TryDirectTransfer( const OUString& aURL, SfxItemSet const & aTargetSet ); + SAL_DLLPRIVATE void Transfer_Impl(); + SAL_DLLPRIVATE void CreateFileStream(); + SAL_DLLPRIVATE void SetUpdatePickList(bool); + SAL_DLLPRIVATE bool IsUpdatePickList() const; + + SAL_DLLPRIVATE void SetLongName(const OUString &rName); + SAL_DLLPRIVATE const OUString & GetLongName() const; + SAL_DLLPRIVATE bool IsPreview_Impl() const; + SAL_DLLPRIVATE void ClearBackup_Impl(); + SAL_DLLPRIVATE void SetPhysicalName_Impl(const OUString& rName); + SAL_DLLPRIVATE void CanDisposeStorage_Impl( bool bDisposeStorage ); + SAL_DLLPRIVATE bool WillDisposeStorageOnClose_Impl(); + + SAL_DLLPRIVATE void DoBackup_Impl(); + SAL_DLLPRIVATE void DoInternalBackup_Impl( const ::ucbhelper::Content& aOriginalContent ); + SAL_DLLPRIVATE void DoInternalBackup_Impl( const ::ucbhelper::Content& aOriginalContent, + std::u16string_view aPrefix, + const OUString& aExtension, + const OUString& aDestDir ); + + SAL_DLLPRIVATE bool UseBackupToRestore_Impl( ::ucbhelper::Content& aOriginalContent, + const css::uno::Reference< css::ucb::XCommandEnvironment >& xComEnv ); + + SAL_DLLPRIVATE bool StorageCommit_Impl(); + + SAL_DLLPRIVATE void TransactedTransferForFS_Impl( const INetURLObject& aSource, + const INetURLObject& aDest, + const css::uno::Reference< css::ucb::XCommandEnvironment >& xComEnv ); + + SAL_DLLPRIVATE bool + SignContents_Impl(weld::Window* pDialogParent, + bool bSignScriptingContent, bool bHasValidDocumentSignature, + const OUString& aSignatureLineId = OUString(), + const css::uno::Reference& xCert + = css::uno::Reference(), + const css::uno::Reference& xValidGraphic + = css::uno::Reference(), + const css::uno::Reference& xInvalidGraphic + = css::uno::Reference(), + const OUString& aComment = OUString()); + + SAL_DLLPRIVATE bool SignDocumentContentUsingCertificate( + const css::uno::Reference& xModel, bool bHasValidDocumentSignature, + const css::uno::Reference& xCertificate); + + // the following two methods must be used and make sense only during saving currently + // TODO/LATER: in future the signature state should be controlled by the medium not by the document + // in this case the methods will be used generally, and might need to be renamed + SAL_DLLPRIVATE SignatureState GetCachedSignatureState_Impl() const; + SAL_DLLPRIVATE void SetCachedSignatureState_Impl( SignatureState nState ); + + void SetHasEmbeddedObjects(bool bHasEmbeddedObjects); + + static css::uno::Sequence < css::util::RevisionTag > GetVersionList( + const css::uno::Reference< css::embed::XStorage >& xStorage ); + static OUString CreateTempCopyWithExt( std::u16string_view aURL ); + static bool CallApproveHandler(const css::uno::Reference< css::task::XInteractionHandler >& xHandler, const css::uno::Any& rRequest, bool bAllowAbort); + + static bool SetWritableForUserOnly( const OUString& aURL ); + static sal_uInt32 CreatePasswordToModifyHash( std::u16string_view aPasswd, bool bWriter ); + +private: + enum class ShowLockResult { NoLock, Succeeded, Try }; + ShowLockResult ShowLockedDocumentDialog(const LockFileEntry& aData, + bool bIsLoading, bool bOwnLock, bool bHandleSysLocked); + enum class MessageDlg { LockFileIgnore, LockFileCorrupt }; + bool ShowLockFileProblemDialog(MessageDlg nWhichDlg); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docfilt.hxx b/include/sfx2/docfilt.hxx new file mode 100644 index 000000000..fb5bb5505 --- /dev/null +++ b/include/sfx2/docfilt.hxx @@ -0,0 +1,125 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DOCFILT_HXX +#define INCLUDED_SFX2_DOCFILT_HXX + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::uno { template class Reference; } + +class SotStorage; + +class SFX2_DLLPUBLIC SfxFilter +{ + friend class SfxFilterContainer; + + WildCard aWildCard; + + OUString aTypeName; + OUString aUserData; + OUString aServiceName; + OUString aMimeType; + OUString maFilterName; + OUString aUIName; + OUString aDefaultTemplate; + + /** + * Custom provider name in case the filter is provided via external + * libraries. Empty for conventional filter types. + */ + OUString maProvider; + + SfxFilterFlags nFormatType; + sal_Int32 nVersion; + SotClipboardFormatId lFormat; + bool mbEnabled; + +public: + SfxFilter( const OUString& rProvider, const OUString& rFilterName ); + + SfxFilter( const OUString &rName, + std::u16string_view rWildCard, + SfxFilterFlags nFormatType, + SotClipboardFormatId lFormat, + const OUString &rTypeName, + const OUString &rMimeType, + const OUString &rUserData, + const OUString& rServiceName, + bool bEnabled = true ); + ~SfxFilter(); + + bool IsAllowedAsTemplate() const { return bool(nFormatType & SfxFilterFlags::TEMPLATE); } + bool IsOwnFormat() const { return bool(nFormatType & SfxFilterFlags::OWN); } + /// If the filter supports digital signatures. + bool GetSupportsSigning() const { return bool(nFormatType & SfxFilterFlags::SUPPORTSSIGNING); } + bool GetGpgEncryption() const { return bool(nFormatType & SfxFilterFlags::GPGENCRYPTION); } + bool IsOwnTemplateFormat() const { return bool(nFormatType & SfxFilterFlags::TEMPLATEPATH); } + /// not our built-in format + bool IsAlienFormat() const { return bool(nFormatType & SfxFilterFlags::ALIEN); } + /// an unusual/legacy file to be loading + bool IsExoticFormat() const { return bool(nFormatType & SfxFilterFlags::EXOTIC); } + bool CanImport() const { return bool(nFormatType & SfxFilterFlags::IMPORT); } + bool CanExport() const { return bool(nFormatType & SfxFilterFlags::EXPORT); } + SfxFilterFlags GetFilterFlags() const { return nFormatType; } + const OUString& GetFilterName() const { return maFilterName; } + const OUString& GetMimeType() const { return aMimeType; } + const OUString& GetName() const { return maFilterName; } + const WildCard& GetWildcard() const { return aWildCard; } + const OUString& GetRealTypeName() const { return aTypeName; } + SotClipboardFormatId GetFormat() const { return lFormat; } + const OUString& GetTypeName() const { return aTypeName; } + const OUString& GetUIName() const { return aUIName; } + const OUString& GetUserData() const { return aUserData; } + const OUString& GetDefaultTemplate() const { return aDefaultTemplate; } + void SetDefaultTemplate( const OUString& rStr ) { aDefaultTemplate = rStr; } + bool UsesStorage() const { return GetFormat() != SotClipboardFormatId::NONE; } + void SetUIName( const OUString& rName ) { aUIName = rName; } + void SetVersion( sal_Int32 nVersionP ) { nVersion = nVersionP; } + sal_Int32 GetVersion() const { return nVersion; } + OUString GetSuffixes() const; + OUString GetDefaultExtension() const; + const OUString& GetServiceName() const { return aServiceName; } + const OUString& GetProviderName() const { return maProvider;} + + static std::shared_ptr GetDefaultFilter( std::u16string_view rName ); + static std::shared_ptr GetFilterByName( const OUString& rName ); + static std::shared_ptr GetDefaultFilterFromFactory( const OUString& rServiceName ); + + static OUString GetTypeFromStorage( const SotStorage& rStg ); + /// @throws css::beans::UnknownPropertyException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + static OUString GetTypeFromStorage( + const css::uno::Reference& xStorage ); + bool IsEnabled() const { return mbEnabled; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docinf.hxx b/include/sfx2/docinf.hxx new file mode 100644 index 000000000..09ecfff6b --- /dev/null +++ b/include/sfx2/docinf.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DOCINF_HXX +#define INCLUDED_SFX2_DOCINF_HXX + +#include +#include +#include +#include + + +class GDIMetaFile; +class SotStorage; + +namespace com::sun::star { + namespace document { + class XDocumentProperties; + } +} + +namespace com::sun::star::uno { template class Reference; } +namespace com::sun::star::uno { template class Sequence; } + + +namespace sfx2 { + +/** load document meta-data from OLE stream + + @param i_xDocProps Document meta-data + @param i_pStorage OLE Storage + */ +ErrCode SFX2_DLLPUBLIC LoadOlePropertySet( + const css::uno::Reference< css::document::XDocumentProperties>& i_xDocProps, + SotStorage* i_pStorage ); + +/** save document meta-data to OLE stream + + @param i_xDocProps Document meta-data + @param i_pStorage OLE Storage + @param i_pThumb Thumbnail: preview bitmap + @param i_pGuid Blob: Guid blob ("_PID_GUID") + @param i_pHyperlinks Blob: Hyperlink blob ("_PID_HLINKS") + */ +bool SFX2_DLLPUBLIC SaveOlePropertySet( + const css::uno::Reference< css::document::XDocumentProperties>& i_xDocProps, + SotStorage* i_pStorage, + const css::uno::Sequence * i_pThumb = nullptr, + const css::uno::Sequence * i_pGuid = nullptr, + const css::uno::Sequence * i_pHyperlinks = nullptr); + + +css::uno::Sequence SFX2_DLLPUBLIC convertMetaFile( + GDIMetaFile const * i_pThumb); + +} // namespace sfx2 + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docinsert.hxx b/include/sfx2/docinsert.hxx new file mode 100644 index 000000000..7c4107124 --- /dev/null +++ b/include/sfx2/docinsert.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_DOCINSERT_HXX +#define INCLUDED_SFX2_DOCINSERT_HXX + +#include +#include +#include +#include +#include +#include + +namespace sfx2 { class FileDialogHelper; } +namespace weld { class Window; } +class SfxItemSet; +class SfxMedium; +enum class FileDialogFlags; + +typedef ::std::vector< std::unique_ptr > SfxMediumList; + +namespace sfx2 { + +class SFX2_DLLPUBLIC DocumentInserter +{ +private: + weld::Window* m_pParent; + OUString m_sDocFactory; + OUString m_sFilter; + Link m_aDialogClosedLink; + + FileDialogFlags const m_nDlgFlags; + ErrCode m_nError; + + std::unique_ptr + m_pFileDlg; + std::shared_ptr m_xItemSet; + std::vector m_pURLList; + + DECL_DLLPRIVATE_LINK(DialogClosedHdl, sfx2::FileDialogHelper*, void); + +public: + enum class Mode { + Insert, + InsertMulti, + Compare, + Merge + }; + DocumentInserter(weld::Window* pParent, const OUString& rFactory, const Mode mode = Mode::Insert); + ~DocumentInserter(); + + void StartExecuteModal( const Link& _rDialogClosedLink ); + std::unique_ptr CreateMedium(char const* pFallbackHack = nullptr); + SfxMediumList CreateMediumList(); +}; + +} // namespace sfx2 + +#endif // INCLUDED_SFX2_DOCINSERT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/dockwin.hxx b/include/sfx2/dockwin.hxx new file mode 100644 index 000000000..886f4ae11 --- /dev/null +++ b/include/sfx2/dockwin.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DOCKWIN_HXX +#define INCLUDED_SFX2_DOCKWIN_HXX + +#include +#include +#include +#include + +#include + +#include +#include + +namespace com::sun::star::frame { class XFrame; } + +class SfxDockingWindow_Impl; +enum class SplitWindowItemFlags; + +void SfxDockingWindowFactory( const css::uno::Reference< css::frame::XFrame >& rFrame, std::u16string_view rDockingWindowName ); +bool IsDockingWindowVisible( const css::uno::Reference< css::frame::XFrame >& rFrame, std::u16string_view rDockingWindowName ); + +class SFX2_DLLPUBLIC SfxDockingWindow : public ResizableDockingWindow +{ +protected: + std::unique_ptr m_xBuilder; + std::unique_ptr m_xContainer; + +private: + tools::Rectangle aInnerRect; + tools::Rectangle aOuterRect; + SfxBindings* pBindings; + Size aFloatSize; + SfxChildWindow* pMgr; + std::unique_ptr< SfxDockingWindow_Impl > pImpl; + + SfxDockingWindow(SfxDockingWindow const &) = delete; + SfxDockingWindow& operator =(SfxDockingWindow const &) = delete; + +protected: + SfxChildAlignment CalcAlignment(const Point& rPos, tools::Rectangle& rRect ); + virtual Size CalcDockingSize(SfxChildAlignment); + virtual SfxChildAlignment + CheckAlignment(SfxChildAlignment,SfxChildAlignment); + + virtual void Resize() override; + virtual bool PrepareToggleFloatingMode() override; + virtual void ToggleFloatingMode() override; + virtual void StartDocking() override; + virtual bool Docking( const Point& rPos, tools::Rectangle& rRect ) override; + virtual void EndDocking( const tools::Rectangle& rRect, bool bFloatMode ) override; + virtual void Resizing( Size& rSize ) override; + virtual void Paint( vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect ) override; + virtual bool Close() override; + virtual void Move() override; + + SAL_DLLPRIVATE SfxChildWindow* GetChildWindow_Impl() { return pMgr; } + +public: + SfxDockingWindow( SfxBindings *pBindings, + SfxChildWindow *pCW, + vcl::Window* pParent, + WinBits nWinBits); + SfxDockingWindow( SfxBindings *pBindings, + SfxChildWindow *pCW, + vcl::Window* pParent, + const OString& rID, const OUString& rUIXMLDescription ); + virtual ~SfxDockingWindow() override; + virtual void dispose() override; + + void Initialize (SfxChildWinInfo* pInfo); + virtual void FillInfo(SfxChildWinInfo&) const; + virtual void StateChanged( StateChangedType nStateChange ) override; + + void SetDockingRects(const tools::Rectangle& rOuter, const tools::Rectangle& rInner) + { aInnerRect = rInner; aOuterRect = rOuter; } + const tools::Rectangle& GetInnerRect() const { return aInnerRect; } + const tools::Rectangle& GetOuterRect() const { return aOuterRect; } + SfxBindings& GetBindings() const { return *pBindings; } + sal_uInt16 GetType() const { return pMgr->GetType(); } + SfxChildAlignment GetAlignment() const { return pMgr->GetAlignment(); } + void SetAlignment(SfxChildAlignment eAlign) { pMgr->SetAlignment(eAlign); } + const Size& GetFloatingSize() const { return aFloatSize; } + void SetFloatingSize(const Size& rSize) { aFloatSize=rSize; } + + void SetMinOutputSizePixel( const Size& rSize ); + const Size& GetMinOutputSizePixel() const; + virtual bool EventNotify( NotifyEvent& rNEvt ) override; + DECL_DLLPRIVATE_LINK(TimerHdl, Timer *, void); + + SAL_DLLPRIVATE void Initialize_Impl(); + SAL_DLLPRIVATE void SetItemSize_Impl( const Size& rSize ); + SAL_DLLPRIVATE void Disappear_Impl(); + SAL_DLLPRIVATE void Reappear_Impl(); + SAL_DLLPRIVATE bool IsAutoHide_Impl() const; + SAL_DLLPRIVATE void AutoShow_Impl(); + SAL_DLLPRIVATE void ReleaseChildWindow_Impl(); +}; + +class SfxDockingWrapper final : public SfxChildWindow +{ + public: + SfxDockingWrapper( vcl::Window* pParent , + sal_uInt16 nId , + SfxBindings* pBindings , + SfxChildWinInfo* pInfo ); + + SFX_DECL_CHILDWINDOW(SfxDockingWrapper); +}; + +#endif // INCLUDED_SFX2_DOCKWIN_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docmacromode.hxx b/include/sfx2/docmacromode.hxx new file mode 100644 index 000000000..7ed42f6a1 --- /dev/null +++ b/include/sfx2/docmacromode.hxx @@ -0,0 +1,307 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_DOCMACROMODE_HXX +#define INCLUDED_SFX2_DOCMACROMODE_HXX + +#include +#include + +#include + +#include + +namespace com::sun::star::document { class XEmbeddedScripts; } +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::script { class XLibraryContainer; } +namespace com::sun::star::task { class XInteractionHandler; } + + +namespace sfx2 +{ + + + //= IMacroDocumentAccess + + /** provides access to several settings of a document, which are needed by ->DocumentMacroMode + to properly determine the current macro execution mode of this document + */ + class SAL_NO_VTABLE IMacroDocumentAccess + { + public: + /** retrieves the current MacroExecutionMode. + + Usually, this is initialized from the media descriptor used to load the document, + respectively the one passed into the document's XModel::attachResource call. + + If no such mode was passed there, document implementations should return + MacroExecMode::NEVER_EXECUTE. + + @see css::document::MediaDescriptor::MacroExecutionMode + @see css::frame::XComponentLoader::loadComponentFromURL + @see css::frame::XModel::attachResource + + @see setCurrentMacroExecMode + + @todo + Effectively, this is the MacroExecutionMode of the MediaDescriptor of + the document. Thus, this setting could be obtained from the XModel + directly. We should introduce a getDocumentModel method here, which + can be used for this and other purposes. + */ + virtual sal_Int16 + getCurrentMacroExecMode() const = 0; + + /** sets the MacroExecutionMode of the document, as calculated by the DocumentMacroMode + class. + + Effectively, the existence of this method means that the responsibility + to store the current macro execution mode is not with the DocumentMacroMode + instance, but with the document instance itself. + + Usually, a document implementation will simply put the macro execution mode + into its media descriptor, as returned by XModel::getArgs. + + @see css::document::MediaDescriptor::MacroExecutionMode + @see css::frame::XComponentLoader::loadComponentFromURL + @see css::frame::XModel::attachResource + + see getCurrentMacroExecMode + */ + virtual void + setCurrentMacroExecMode( sal_uInt16 ) = 0; + + /** returns the origin of the document + + This usually is the document's location, or, if the document has been + newly created from a template, then the location of the template. Location + here means the complete path of the document, including the file name. + + @todo + This probably can also be obtained from the XModel, by calling getURL + or getLocation. If both are empty, then we need a UNO way to obtain + the URL of the underlying template document - if any. If we have this, + we could replace this method with a newly introduced method + getDocumentModel and some internal code. + */ + virtual OUString + getDocumentLocation() const = 0; + + /** checks whether the document's storage contains sub storages with macros or scripts + + A default implementation of this method will simply call DocumentMacroMode::storageHasMacros + with the document's root storage. However, there might be document types where this + isn't sufficient (e.g. database documents which contain sub documents which can also + contain macro/script storages). + */ + virtual bool + documentStorageHasMacros() const = 0; + + /** checks whether the document's contained calls to macros or scripts after loading + + */ + virtual bool + macroCallsSeenWhileLoading() const = 0; + + /** provides access to the XEmbeddedScripts interface of the document + + Implementations are allowed to return here if and only if they + do not (yet) support embedding scripts. + + @todo + can also be replaced with a call to the (to be introduced) getDocumentModel + method, and a queryInterface. + */ + virtual css::uno::Reference< css::document::XEmbeddedScripts > + getEmbeddedDocumentScripts() const = 0; + + /** returns the state of the signatures for the scripts embedded in the document + + Note: On the medium run, the signature handling of a document should be outsourced + into a dedicated class, instead of being hard-wired into the SfxObjectShell. This + class could then be used outside the SfxObjectShell (e.g. in Base documents), too. + When this happens, this method here becomes should be replaced by a method at this + new class. + + @seealso + */ + virtual SignatureState + getScriptingSignatureState() = 0; + + /** allows to detect whether there is a trusted scripting signature + + Note: On the medium run, the signature handling of a document should be outsourced + into a dedicated class, instead of being hard-wired into the SfxObjectShell. This + class could then be used outside the SfxObjectShell (e.g. in Base documents), too. + When this happens, this method here should be replaced by a method at this + new class. + + @seealso + */ + virtual bool + hasTrustedScriptingSignature( bool bAllowUIToAddAuthor ) = 0; + + protected: + ~IMacroDocumentAccess() {} + }; + + + //= DocumentMacroMode + + struct DocumentMacroMode_Data; + + /** encapsulates handling the macro mode of a document + + @see css::document::MacroExecMode + */ + class SFX2_DLLPUBLIC DocumentMacroMode + { + public: + /** creates an instance + + @param _rDocumentAccess + access to the document which this instance works for. Must live as long as the + DocumentMacroMode instance lives, at least + */ + DocumentMacroMode( IMacroDocumentAccess& _rDocumentAccess ); + + /** allows macro execution in the document + + Effectively, the macro mode is set to MacroExecMode::ALWAYS_EXECUTE_NO_WARN. + + @return + , always + */ + bool allowMacroExecution(); + + /** disallows macro execution in the document + + Effectively, the macro mode is set to MacroExecMode::NEVER_EXECUTE. + + @return + , always + */ + bool disallowMacroExecution(); + + /** checks whether the document allows executing contained macros. + + The method transforms the current macro execution mode into either + ALWAYS_EXECUTE_NO_WARN or NEVER_EXECUTE, depending on the current value, + possible configuration settings, and possible user interaction. + + @param _rxInteraction + A handler for interactions which might become necessary. + This includes +
    • Asking the user for confirmation for macro execution.
    • +
    • Telling the user that macro execution is disabled.
    • +
    + + If the user needs to be asked for macro execution confirmation, and if + this parameter is , the most defensive assumptions will be made, + effectively disabling macro execution. + + @param bHasValidContentSignature + Whether the document content is signed and the signature is valid. + + @return + if and only if macro execution in this document is allowed. + */ + bool adjustMacroMode( + const css::uno::Reference< css::task::XInteractionHandler >& _rxInteraction, + bool bHasValidContentSignature = false + ); + + /** determines whether macro execution is disallowed + + There's a number of reasons why macro execution could be disallowed: +
    • Somebody called ->disallowMacroExecution
    • +
    • Macro execution is disabled globally, via the security options
    • +
    • Macro execution mode was not defined initially, and the user denied + executing macros for this particular document.
    • +
    + + Note that if this method returns , then subsequent calls of + ->adjustMacroMode can still return . + That is, if the current macro execution mode for the document is not yet known + (and in particular not MacroExecMode::NEVER_EXECUTE), then ->isMacroExecutionDisallowed + will return . + However, a subsequent call to ->adjustMacroMode can result in the user + denying macro execution, in which ->adjustMacroMode will return , + and the next call to isMacroExecutionDisallowed will return . + */ + bool isMacroExecutionDisallowed() const; + + /** determines whether the document actually has a macros library + + Effectively, this method checks the Basic library container (as returned by + IMacroDocumentAccess::getEmbeddedDocumentScripts().getBasicLibraries) for + content. + */ + bool hasMacroLibrary() const; + + /** determines whether the given document storage has sub storages containing scripts + or macros. + + Effectively, the method checks for the presence of a sub-storage name "Scripts" (where + BeanShell-/JavaScript-/Python-Scripts are stored, and a sub storage named "Basic" (where + Basic scripts are stored). + */ + static bool storageHasMacros( const css::uno::Reference< css::embed::XStorage >& _rxStorage ); + + static bool containerHasBasicMacros( const css::uno::Reference< css::script::XLibraryContainer >& xContainer ); + /** checks the macro execution mode while loading the document. + + This must be called when the loading is effectively finished, but before any macro action + happened. + + The method will disallow macro execution for this document if it is disabled + globally (SvtSecurityOptions::IsMacroDisabled). Otherwise, it will check whether + the document contains a macro storage or macro libraries. If so, it will + properly calculate the MacroExecutionMode by calling adjustMacroMode. + + If the document doesn't contain macros, yet, then the macro execution for this + document will be allowed (again: unless disabled globally), since in this case + macros which later are newly created by the user should be allowed, of course. + + @return + if and only if macro execution is allowed in the document + + @see isMacroExecutionDisallowed + @see IMacroDocumentAccess::documentStorageHasMacros + @see IMacroDocumentAccess::macroCallsSeenWhileLoading + @see hasMacroLibrary + @see IMacroDocumentAccess::checkForBrokenScriptingSignatures + */ + bool + checkMacrosOnLoading( + const css::uno::Reference< css::task::XInteractionHandler >& _rxInteraction, + bool bHasValidContentSignature = false + ); + + private: + std::shared_ptr< DocumentMacroMode_Data > m_xData; + }; + + +} // namespace sfx2 + + +#endif // INCLUDED_SFX2_DOCMACROMODE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/docstoragemodifylistener.hxx b/include/sfx2/docstoragemodifylistener.hxx new file mode 100644 index 000000000..8530711ca --- /dev/null +++ b/include/sfx2/docstoragemodifylistener.hxx @@ -0,0 +1,82 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_DOCSTORAGEMODIFYLISTENER_HXX +#define INCLUDED_SFX2_DOCSTORAGEMODIFYLISTENER_HXX + +#include + +#include + +#include + +namespace comphelper { class SolarMutex; } + + +namespace sfx2 +{ + + + //= IModifiableDocument + + /** callback for the DocumentStorageModifyListener class + */ + class SAL_NO_VTABLE IModifiableDocument + { + public: + /// indicates the root or a sub storage of the document has been modified + virtual void storageIsModified() = 0; + + protected: + ~IModifiableDocument() {} + }; + + + //= DocumentStorageModifyListener + + class SFX2_DLLPUBLIC DocumentStorageModifyListener final : public cppu::WeakImplHelper + { + IModifiableDocument* m_pDocument; + comphelper::SolarMutex& m_rMutex; + + public: + DocumentStorageModifyListener( IModifiableDocument& _rDocument, comphelper::SolarMutex& _rMutex ); + + void dispose(); + + // XModifyListener + virtual void SAL_CALL modified( const css::lang::EventObject& aEvent ) override; + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + + private: + virtual ~DocumentStorageModifyListener() override; + + DocumentStorageModifyListener( const DocumentStorageModifyListener& ) = delete; + DocumentStorageModifyListener& operator=( const DocumentStorageModifyListener& ) = delete; + }; + + +} // namespace sfx2 + + +#endif // INCLUDED_SFX2_DOCSTORAGEMODIFYLISTENER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/doctempl.hxx b/include/sfx2/doctempl.hxx new file mode 100644 index 000000000..029c8e8b2 --- /dev/null +++ b/include/sfx2/doctempl.hxx @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_DOCTEMPL_HXX +#define INCLUDED_SFX2_DOCTEMPL_HXX + +#include + +#include + +#include +#include +#include +#include + +// CLASS ----------------------------------------------------------------- + +class SfxDocTemplate_Impl; + +// class SfxDocumentTemplates -------------------------------------------- + +class SFX2_DLLPUBLIC SfxDocumentTemplates +{ +private: + tools::SvRef pImp; + + SAL_DLLPRIVATE bool CopyOrMove( sal_uInt16 nTargetRegion, sal_uInt16 nTargetIdx, + sal_uInt16 nSourceRegion, sal_uInt16 nSourceIdx, bool bMove ); +public: + SfxDocumentTemplates(); + SfxDocumentTemplates(const SfxDocumentTemplates &); + ~SfxDocumentTemplates(); + + const SfxDocumentTemplates &operator=(const SfxDocumentTemplates &); + + void ReInitFromComponent(); + + sal_uInt16 GetRegionCount() const; + OUString GetRegionName(sal_uInt16 nIdx) const; //dv! + OUString GetFullRegionName(sal_uInt16 nIdx) const; + + sal_uInt16 GetCount(sal_uInt16 nRegion) const; + OUString GetName(sal_uInt16 nRegion, sal_uInt16 nIdx) const; //dv! + OUString GetPath(sal_uInt16 nRegion, sal_uInt16 nIdx) const; + + // Allows to retrieve the target template URL from the UCB + OUString GetTemplateTargetURLFromComponent(std::u16string_view aGroupName, + std::u16string_view aTitle ); + + // Convert a resource string - a template name - to its localised pair + // if it exists in sfx2/inc/strings.hxx + static OUString ConvertResourceString(const OUString& rString); + + bool Copy(sal_uInt16 nTargetRegion, + sal_uInt16 nTargetIdx, + sal_uInt16 nSourceRegion, + sal_uInt16 nSourceIdx); + bool Move(sal_uInt16 nTargetRegion, + sal_uInt16 nTargetIdx, + sal_uInt16 nSourceRegion, + sal_uInt16 nSourceIdx); + bool Delete(sal_uInt16 nRegion, sal_uInt16 nIdx); + bool InsertDir(const OUString &rText, sal_uInt16 nRegion); + + bool InsertTemplate (sal_uInt16 nSourceRegion, sal_uInt16 nIdx, const OUString &rName, const OUString &rPath); + + /** Change the name of an entry or a directory + + \param rName + The new name to set + \param nRegion + The id of the region to rename or containing the template to rename + \param nIdx + The id of the template to rename or USHRT_MAX to rename the region. + + \return + sal_True if the action could be performed, sal_False otherwise + + */ + bool SetName(const OUString &rName, sal_uInt16 nRegion, sal_uInt16 nIdx); + + bool CopyTo(sal_uInt16 nRegion, sal_uInt16 nIdx, std::u16string_view rName) const; + bool CopyFrom(sal_uInt16 nRegion, sal_uInt16 nIdx, OUString &rName); + + bool GetFull( + std::u16string_view rRegion, std::u16string_view rName, OUString& rPath ); + bool GetLogicNames( std::u16string_view rPath, OUString& rRegion, OUString& rName ) const; + + /** updates the configuration where the document templates structure is stored. + +

    The info about the document templates (which files, which groups etc.) is stored in the + configuration. This means that just by copying files into OOo's template directories, this + change is not reflected in the SfxDocumentTemplates - 'cause the configuration is not synchronous with + the file system. This can be enforced with this method.

    + */ + void Update(); +}; + +#endif // INCLUDED_SFX2_DOCTEMPL_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/event.hxx b/include/sfx2/event.hxx new file mode 100644 index 000000000..9f7cd304a --- /dev/null +++ b/include/sfx2/event.hxx @@ -0,0 +1,268 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_EVENT_HXX +#define INCLUDED_SFX2_EVENT_HXX + +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } + +/** + these values get stored in streams in a 16-bit value +*/ +enum class SvMacroItemId : sal_uInt16 { + NONE = 0, + + // used by SwHTMLForm_Impl + HtmlOnSubmitForm, + HtmlOnResetForm, + HtmlOnGetFocus, + HtmlOnLoseFocus, + HtmlOnClick, + HtmlOnClickItem, + HtmlOnChange, + HtmlOnSelect, + + // used by SwHTMLParser + OpenDoc, + PrepareCloseDoc, + ActivateDoc, + DeactivateDoc, + + // Events for Controls etc. + OnMouseOver = 5100, + OnClick = 5101, + OnMouseOut = 5102, + + OnImageLoadDone = 10000, + OnImageLoadCancel = 10001, + OnImageLoadError = 10002, + + SwObjectSelect = 20000, + SwStartInsGlossary = 20001, + SwEndInsGlossary = 20002, + SwFrmKeyInputAlpha = 20004, + SwFrmKeyInputNoAlpha = 20005, + SwFrmResize = 20006, + SwFrmMove = 20007, +}; + +template< typename charT, typename traits > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const SvMacroItemId& id ) +{ + switch(id) + { + case SvMacroItemId::NONE: return stream << "NONE"; + case SvMacroItemId::HtmlOnSubmitForm: return stream << "HtmlOnSubmitForm"; + case SvMacroItemId::HtmlOnResetForm: return stream << "HtmlOnResetForm"; + case SvMacroItemId::HtmlOnGetFocus: return stream << "HtmlOnGetFocus"; + case SvMacroItemId::HtmlOnLoseFocus: return stream << "HtmlOnLoseFocus"; + case SvMacroItemId::HtmlOnClick: return stream << "HtmlOnClick"; + case SvMacroItemId::HtmlOnClickItem: return stream << "HtmlOnClickItem"; + case SvMacroItemId::HtmlOnChange: return stream << "HtmlOnChange"; + case SvMacroItemId::HtmlOnSelect: return stream << "HtmlOnSelect"; + case SvMacroItemId::OpenDoc: return stream << "OpenDoc"; + case SvMacroItemId::PrepareCloseDoc: return stream << "PrepareCloseDoc"; + case SvMacroItemId::ActivateDoc: return stream << "ActivateDoc"; + case SvMacroItemId::DeactivateDoc: return stream << "DeactivateDoc"; + case SvMacroItemId::OnMouseOver: return stream << "OnMouseOver"; + case SvMacroItemId::OnClick: return stream << "OnClick"; + case SvMacroItemId::OnMouseOut: return stream << "OnMouseOut"; + case SvMacroItemId::OnImageLoadDone: return stream << "OnImageLoadDone"; + case SvMacroItemId::OnImageLoadCancel: return stream << "OnImageLoadCancel"; + case SvMacroItemId::OnImageLoadError: return stream << "OnImageLoadError"; + case SvMacroItemId::SwObjectSelect: return stream << "SwObjectSelect"; + case SvMacroItemId::SwStartInsGlossary: return stream << "SwStartInsGlossary"; + case SvMacroItemId::SwEndInsGlossary: return stream << "SwEndInsGlossary"; + case SvMacroItemId::SwFrmKeyInputAlpha: return stream << "SwFrmKeyInputAlpha"; + case SvMacroItemId::SwFrmKeyInputNoAlpha: return stream << "SwFrmKeyInputNoAlpha"; + case SvMacroItemId::SwFrmResize: return stream << "SwFrmResize"; + case SvMacroItemId::SwFrmMove: return stream << "SwFrmMove"; + default: return stream << "unk(" << std::to_string(int(id)) << ")"; + } +} + +class SfxObjectShell; + +enum class SfxEventHintId { + NONE = 0, + ActivateDoc, + CloseDoc, + CloseView, + CreateDoc, + DeactivateDoc, + DocCreated, + LoadFinished, + ModifyChanged, + OpenDoc, + PrepareCloseDoc, + PrepareCloseView, + PrintDoc, + SaveAsDoc, + SaveAsDocDone, + SaveAsDocFailed, + SaveDoc, + SaveDocDone, + SaveDocFailed, + SaveToDoc, + SaveToDocDone, + SaveToDocFailed, + StorageChanged, + ViewCreated, + VisAreaChanged, + // SW events + SwMailMerge, + SwMailMergeEnd, + SwEventPageCount, + SwEventFieldMerge, + SwEventFieldMergeFinished, + SwEventLayoutFinished, +}; + +template< typename charT, typename traits > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const SfxEventHintId& id ) +{ + switch(id) + { + case SfxEventHintId::NONE: return stream << "NONE"; + case SfxEventHintId::ActivateDoc: return stream << "ActivateDoc"; + case SfxEventHintId::CloseDoc: return stream << "CloseDoc"; + case SfxEventHintId::CloseView: return stream << "CloseView"; + case SfxEventHintId::CreateDoc: return stream << "CreateDoc"; + case SfxEventHintId::DeactivateDoc: return stream << "DeactivateDoc"; + case SfxEventHintId::DocCreated: return stream << "DocCreated"; + case SfxEventHintId::LoadFinished: return stream << "LoadFinished"; + case SfxEventHintId::ModifyChanged: return stream << "ModifyChanged"; + case SfxEventHintId::OpenDoc: return stream << "OpenDoc"; + case SfxEventHintId::PrepareCloseDoc: return stream << "PrepareCloseDoc"; + case SfxEventHintId::PrepareCloseView: return stream << "PrepareCloseView"; + case SfxEventHintId::PrintDoc: return stream << "PrintDoc"; + case SfxEventHintId::SaveAsDoc: return stream << "SaveAsDoc"; + case SfxEventHintId::SaveAsDocDone: return stream << "SaveAsDocDone"; + case SfxEventHintId::SaveAsDocFailed: return stream << "SaveAsDocFailed"; + case SfxEventHintId::SaveDoc: return stream << "SaveDoc"; + case SfxEventHintId::SaveDocDone: return stream << "SaveDocDone"; + case SfxEventHintId::SaveDocFailed: return stream << "SaveDocFailed"; + case SfxEventHintId::SaveToDoc: return stream << "SaveToDoc"; + case SfxEventHintId::SaveToDocDone: return stream << "SaveToDocDone"; + case SfxEventHintId::SaveToDocFailed: return stream << "SaveToDocFailed"; + case SfxEventHintId::StorageChanged: return stream << "StorageChanged"; + case SfxEventHintId::ViewCreated: return stream << "ViewCreated"; + case SfxEventHintId::VisAreaChanged: return stream << "VisAreaChanged"; + case SfxEventHintId::SwMailMerge: return stream << "SwMailMerge"; + case SfxEventHintId::SwMailMergeEnd: return stream << "SwMailMergeEnd"; + case SfxEventHintId::SwEventPageCount: return stream << "SwEventPageCount"; + case SfxEventHintId::SwEventFieldMerge: return stream << "SwEventFieldMerge"; + case SfxEventHintId::SwEventFieldMergeFinished: return stream << "SwEventFieldMergeFinished"; + case SfxEventHintId::SwEventLayoutFinished: return stream << "SwEventLayoutFinished"; + default: return stream << "unk(" << std::to_string(int(id)) << ")"; + } +} + +class SFX2_DLLPUBLIC SfxEventHint : public SfxHint +{ + SfxObjectShell* pObjShell; + OUString aEventName; + SfxEventHintId nEventId; + +public: + SfxEventHint( SfxEventHintId nId, const OUString& aName, SfxObjectShell *pObj ) + : pObjShell(pObj), + aEventName(aName), + nEventId(nId) + {} + + SfxEventHintId GetEventId() const + { return nEventId; } + + const OUString& GetEventName() const + { return aEventName; } + + SfxObjectShell* GetObjShell() const + { return pObjShell; } +}; + + +class SFX2_DLLPUBLIC SfxViewEventHint : public SfxEventHint +{ + css::uno::Reference< css::frame::XController2 > xViewController; + +public: + SfxViewEventHint( SfxEventHintId nId, const OUString& aName, SfxObjectShell *pObj, const css::uno::Reference< css::frame::XController >& xController ) + : SfxEventHint( nId, aName, pObj ) + , xViewController( xController, css::uno::UNO_QUERY ) + {} + + SfxViewEventHint( SfxEventHintId nId, const OUString& aName, SfxObjectShell *pObj, const css::uno::Reference< css::frame::XController2 >& xController ) + : SfxEventHint( nId, aName, pObj ) + , xViewController( xController ) + {} + + const css::uno::Reference< css::frame::XController2 >& GetController() const + { return xViewController; } +}; + +class SfxPrintingHint final : public SfxViewEventHint +{ + css::view::PrintableState mnPrintableState; + css::uno::Sequence < css::beans::PropertyValue > aOpts; +public: + SfxPrintingHint( + css::view::PrintableState nState, + const css::uno::Sequence < css::beans::PropertyValue >& rOpts, + SfxObjectShell *pObj, + const css::uno::Reference< css::frame::XController2 >& xController ) + : SfxViewEventHint( + SfxEventHintId::PrintDoc, + GlobalEventConfig::GetEventName( GlobalEventId::PRINTDOC ), + pObj, + xController ) + , mnPrintableState( nState ) + , aOpts( rOpts ) + {} + + SfxPrintingHint( css::view::PrintableState nState ) + : SfxViewEventHint( + SfxEventHintId::PrintDoc, + GlobalEventConfig::GetEventName( GlobalEventId::PRINTDOC ), + nullptr, + css::uno::Reference< css::frame::XController >() ) + , mnPrintableState( nState ) + {} + + css::view::PrintableState GetWhich() const { return mnPrintableState; } + const css::uno::Sequence < css::beans::PropertyValue >& GetOptions() const { return aOpts; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/evntconf.hxx b/include/sfx2/evntconf.hxx new file mode 100644 index 000000000..8720a7330 --- /dev/null +++ b/include/sfx2/evntconf.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_EVNTCONF_HXX +#define INCLUDED_SFX2_EVNTCONF_HXX + +#include +#include +#include +#include +#include +#include +#include + +class SfxObjectShell; +class SvxMacro; + +struct SFX2_DLLPUBLIC SfxEventName +{ + SvMacroItemId mnId; + OUString maEventName; + OUString maUIName; + + SfxEventName( SvMacroItemId nId, + const OUString& rEventName, + const OUString& rUIName ) + : mnId( nId ) + , maEventName( rEventName ) + , maUIName( rUIName ) {} +}; + +class SFX2_DLLPUBLIC SfxEventNamesList +{ +private: + ::std::vector< SfxEventName > aEventNamesList; + +public: + SfxEventNamesList() {} + SfxEventNamesList( const SfxEventNamesList &rCpy ) { *this = rCpy; } + ~SfxEventNamesList(); + SfxEventNamesList& operator=( const SfxEventNamesList &rCpy ); + + size_t size() const { return aEventNamesList.size(); }; + + SfxEventName& at( size_t Index ) { return aEventNamesList[ Index ]; } + SfxEventName const & at( size_t Index ) const { return aEventNamesList[ Index ]; } + + void push_back( SfxEventName Item ) { aEventNamesList.push_back( std::move(Item) ); } +}; + +class SFX2_DLLPUBLIC SfxEventNamesItem final : public SfxPoolItem +{ + SfxEventNamesList aEventsList; + +public: + + SfxEventNamesItem ( const sal_uInt16 nId ) : SfxPoolItem( nId ) {} + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + virtual SfxEventNamesItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + const SfxEventNamesList& GetEvents() const { return aEventsList;} + void AddEvent( const OUString&, const OUString&, SvMacroItemId ); +}; + + +inline constexpr OUStringLiteral PROP_EVENT_TYPE = u"EventType"; +inline constexpr OUStringLiteral PROP_LIBRARY = u"Library"; +inline constexpr OUStringLiteral PROP_SCRIPT = u"Script"; +inline constexpr OUStringLiteral PROP_MACRO_NAME = u"MacroName"; +#define STAR_BASIC "StarBasic" + +class SFX2_DLLPUBLIC SfxEventConfiguration +{ +public: + static void ConfigureEvent( const OUString& aName, const SvxMacro&, SfxObjectShell const * pObjSh); + static std::unique_ptr ConvertToMacro( const css::uno::Any& rElement, SfxObjectShell* pDoc ); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/fcontnr.hxx b/include/sfx2/fcontnr.hxx new file mode 100644 index 000000000..026f0e1c1 --- /dev/null +++ b/include/sfx2/fcontnr.hxx @@ -0,0 +1,119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_FCONTNR_HXX +#define INCLUDED_SFX2_FCONTNR_HXX + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::beans { struct NamedValue; } +namespace com::sun::star::container { class XNameAccess; } +namespace com::sun::star::uno { template class Sequence; } +namespace com::sun::star::uno { template class Reference; } + +class ErrCode; +class SfxFilter; +class SfxMedium; +class SfxFilterContainer_Impl; + + +class SFX2_DLLPUBLIC SfxFilterContainer +{ + std::unique_ptr pImpl; + +public: + SfxFilterContainer( const OUString& rName ); + ~SfxFilterContainer(); + + + OUString const & GetName() const; + + std::shared_ptr GetAnyFilter( SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4EA( const OUString& rEA, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4Extension( const OUString& rExt, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4FilterName( const OUString& rName, SfxFilterFlags nMust = SfxFilterFlags::NONE, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + + SAL_DLLPRIVATE static void ReadFilters_Impl( bool bUpdate=false ); + SAL_DLLPRIVATE static void ReadSingleFilter_Impl( const OUString& rName, + const css::uno::Reference< css::container::XNameAccess >& xTypeCFG, + const css::uno::Reference< css::container::XNameAccess >& xFilterCFG, + bool bUpdate ); + SAL_DLLPRIVATE static std::shared_ptr GetDefaultFilter_Impl( std::u16string_view ); +}; + +class SfxFilterMatcher_Impl; + +class SFX2_DLLPUBLIC SfxFilterMatcher +{ + friend class SfxFilterMatcherIter; + SfxFilterMatcher_Impl &m_rImpl; +public: + SfxFilterMatcher( const OUString& rFact ); + SfxFilterMatcher(); + ~SfxFilterMatcher(); + SfxFilterMatcher(const SfxFilterMatcher&) = delete; + SfxFilterMatcher& operator=( const SfxFilterMatcher& ) = delete; + + SAL_DLLPRIVATE static bool IsFilterInstalled_Impl( const std::shared_ptr& pFilter ); + DECL_DLLPRIVATE_LINK( MaybeFileHdl_Impl, OUString*, bool ); + + ErrCode GuessFilterIgnoringContent( SfxMedium const & rMedium, std::shared_ptr& ) const; + ErrCode GuessFilter( SfxMedium& rMedium, std::shared_ptr& , SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + ErrCode GuessFilterControlDefaultUI( SfxMedium& rMedium, std::shared_ptr&, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + ErrCode DetectFilter( SfxMedium& rMedium, std::shared_ptr& ) const; + + std::shared_ptr GetFilter4Mime( const OUString& rMime, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED) const; + std::shared_ptr GetFilter4ClipBoardId( SotClipboardFormatId nId, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4EA( const OUString& rEA, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4Extension( const OUString& rExt, SfxFilterFlags nMust = SfxFilterFlags::IMPORT, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4FilterName( const OUString& rName, SfxFilterFlags nMust = SfxFilterFlags::NONE, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilter4UIName( std::u16string_view rName, SfxFilterFlags nMust = SfxFilterFlags::NONE, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetFilterForProps( const css::uno::Sequence < css::beans::NamedValue >& aSeq, SfxFilterFlags nMust = SfxFilterFlags::NONE, SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED ) const; + std::shared_ptr GetAnyFilter( SfxFilterFlags nMustg=SfxFilterFlags::NONE, SfxFilterFlags nDont=SFX_FILTER_NOTINSTALLED ) const; +}; + +class SFX2_DLLPUBLIC SfxFilterMatcherIter + +{ + SfxFilterFlags nOrMask; + SfxFilterFlags nAndMask; + sal_uInt16 nCurrent; + const SfxFilterMatcher_Impl &m_rMatch; + + SAL_DLLPRIVATE std::shared_ptr Find_Impl(); + +public: + SfxFilterMatcherIter( const SfxFilterMatcher& rMatcher, SfxFilterFlags nMask = SfxFilterFlags::NONE, SfxFilterFlags nNotMask = SFX_FILTER_NOTINSTALLED ); + SfxFilterMatcherIter(const SfxFilterMatcherIter&) = delete; + SfxFilterMatcherIter& operator=( const SfxFilterMatcherIter& ) = delete; + std::shared_ptr First(); + std::shared_ptr Next(); +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/filedlghelper.hxx b/include/sfx2/filedlghelper.hxx new file mode 100644 index 000000000..b0b530398 --- /dev/null +++ b/include/sfx2/filedlghelper.hxx @@ -0,0 +1,313 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_FILEDLGHELPER_HXX +#define INCLUDED_SFX2_FILEDLGHELPER_HXX + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace com::sun::star::ui::dialogs +{ + class XFilePicker3; + class XFolderPicker2; + struct FilePickerEvent; + struct DialogClosedEvent; +} +namespace com::sun::star::awt { class XWindow; } +namespace com::sun::star::uno { template class Reference; } +namespace com::sun::star::uno { class XComponentContext; } +namespace weld { class Window; } + +class Graphic; +class SfxFilter; +class SfxItemSet; +class SfxAllItemSet; + +enum class FileDialogFlags { + NONE = 0x00, + Insert = 0x01, // turn Open into Insert dialog + Export = 0x02, // turn Save into Export dialog + SaveACopy = 0x04, // turn Save into Save a Copy dialog + MultiSelection = 0x08, + Graphic = 0x10, // register graphic formats + /// Sign existing PDF. + SignPDF = 0x20, + InsertCompare = 0x40, /// Special insertion ("Compare" caption) + InsertMerge = 0x80, /// Special insertion ("Merge" caption) +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +inline constexpr OUStringLiteral FILEDIALOG_FILTER_ALL = u"*.*"; + +namespace sfx2 { + +class FileDialogHelper_Impl; + +class SFX2_DLLPUBLIC FileDialogHelper +{ +public: + // context where the FileDialogHelper is used + enum Context + { + UnknownContext, + AcceleratorConfig, + AutoRedact, + BaseDataSource, + BaseSaveAs, + BasicExportPackage, + BasicExportDialog, + BasicExportSource, + BasicImportDialog, + BasicImportSource, + BasicInsertLib, + BulletsAddImage, + ExtensionManager, + CalcDataProvider, + CalcDataStream, + CalcExport, + CalcSaveAs, + CalcXMLSource, + DrawExport, + DrawImpressInsertFile, + DrawImpressOpenSound, + DrawSaveAs, + ExportImage, + FormsAddInstance, + FormsInsertImage, + IconImport, + ImpressClickAction, + ImpressExport, + ImpressPhotoDialog, + ImpressSaveAs, + LinkClientOLE, + LinkClientFile, + ImageMap, + InsertDoc, + InsertImage, + InsertMedia, + InsertOLE, + JavaClassPath, + ReportInsertImage, + ScreenshotAnnotation, + SignatureLine, + TemplateImport, + WriterCreateAddressList, + WriterInsertDoc, + WriterInsertImage, + WriterInsertScript, + WriterExport, + WriterImportAutotext, + WriterInsertHyperlink, + WriterLoadTemplate, + WriterMailMerge, + WriterMailMergeSaveAs, + WriterNewHTMLGlobalDoc, + WriterRegisterDataSource, + WriterSaveAs, + WriterSaveHTML, + XMLFilterSettings + }; + static OUString contextToString(Context context); + +private: + Link m_aDialogClosedLink; + ErrCode m_nError; + + rtl::Reference< FileDialogHelper_Impl > mpImpl; + + +public: + FileDialogHelper(sal_Int16 nDialogType, + FileDialogFlags nFlags, + weld::Window* pPreferredParent); + + FileDialogHelper(sal_Int16 nDialogType, + FileDialogFlags nFlags, + const OUString& rFactory, + SfxFilterFlags nMust, + SfxFilterFlags nDont, + weld::Window* pPreferredParent); + + FileDialogHelper(sal_Int16 nDialogType, + FileDialogFlags nFlags, + const OUString& rFactory, + sal_Int16 nDialog, + SfxFilterFlags nMust, + SfxFilterFlags nDont, + const OUString& rStandardDir, + const css::uno::Sequence< OUString >& rDenyList, + weld::Window* pPreferredParent); + + FileDialogHelper(sal_Int16 nDialogType, + FileDialogFlags nFlags, + const OUString& aFilterUIName, + std::u16string_view aExtName, + const OUString& rStandardDir, + const css::uno::Sequence< OUString >& rDenyList, + weld::Window* pPreferredParent); + + virtual ~FileDialogHelper(); + + FileDialogHelper& operator=(const FileDialogHelper &) = delete; + FileDialogHelper(const FileDialogHelper &) = delete; + + ErrCode Execute(); + void StartExecuteModal( const Link& rEndDialogHdl ); + ErrCode const & GetError() const { return m_nError; } + sal_Int16 GetDialogType() const; + bool IsPasswordEnabled() const; + OUString GetRealFilter() const; + + void SetTitle( const OUString& rNewTitle ); + OUString GetPath() const; + + /** @deprecated: Don't use this method to retrieve the selected files + There are file picker which can provide multiple selected file which belong + to different folders. As this method always provides the root folder for all selected + files this cannot work. + */ + css::uno::Sequence< OUString > GetMPath() const; + + /** Provides the selected files with full path information */ + css::uno::Sequence< OUString > GetSelectedFiles() const; + + void AddFilter( const OUString& rFilterName, const OUString& rExtension ); + void SetCurrentFilter( const OUString& rFilter ); + + /** sets an initial display directory/file name + + @deprecated + don't use this method. It contains a lot of magic in determining whether the + last segment of the given path/URL denotes a file name or a folder, and by + definition, it cannot succeed with this magic *all* the time - there will + always be scenarios where it fails. + + Use SetDisplayFolder and SetFileName. + */ + void SetDisplayDirectory( const OUString& rPath ); + + /** sets a new folder whose content is to be displayed in the file picker + + @param _rURL + specifies the URL of the folder whose content is to be displayed.
    + If the URL doesn't denote a valid (existent and accessible) folder, the + request is silently dropped. + @throws css::uno::RuntimeException + if the invocation of any of the file picker or UCB methods throws a RuntimeException. + */ + void SetDisplayFolder( const OUString& _rURL ); + + /** sets an initial file name to display + + This method is usually used in "save-as" contexts, where the application should + suggest an initial name for the file to save. + + Calling this method is nearly equivalent to calling GetFilePicker().setDefaultName( _rFileName ), + with the following differences: +
    • The FileDialogHelper remembers the given file name, and upon execution, + strips its extension if the dialog is set up for "automatic file name extension".
    • +
    • Exceptions thrown from the XFilePicker3 are caught and silenced.
    • +
    + */ + void SetFileName( const OUString& _rFileName ); + + OUString GetCurrentFilter() const; + OUString GetDisplayDirectory() const; + ErrCode GetGraphic( Graphic& rGraphic ) const; + + const css::uno::Reference < css::ui::dialogs::XFilePicker3 >& GetFilePicker() const; + + // XFilePickerListener methods + void FileSelectionChanged(); + void DirectoryChanged(); + virtual void ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent ); + void DialogSizeChanged(); + static OUString HelpRequested( const css::ui::dialogs::FilePickerEvent& aEvent ); + + // XDialogClosedListener methods + void DialogClosed( const css::ui::dialogs::DialogClosedEvent& _rEvent ); + + /** sets help ids for the controls in the dialog + @param _pControlId + Pointer to a 0-terminated array of control ids. They must be recruited from the + CommonFilePickerElementIds and ExtendedFilePickerElementIds values. + @param _pHelpId + Pointer to an array of help ids. For each element in _pControlId, there must be + a corresponding element herein. + */ + void SetControlHelpIds( const sal_Int16* _pControlId, const char** _pHelpId ); + void CreateMatcher( const OUString& rName ); + + /** sets the context of the dialog and trigger necessary actions e.g. loading config, setting help id + This will also store the last used directory for this context, so that the last directory + gets preselected on next filepicker launch (with the same context) + @param _eNewContext + New context for the dialog. + */ + void SetContext( Context _eNewContext ); + + DECL_DLLPRIVATE_LINK( ExecuteSystemFilePicker, void*, void ); + + ErrCode Execute( std::vector& rpURLList, + std::optional& rpSet, + OUString& rFilter, + const OUString& rDirPath ); + ErrCode Execute( std::optional& rpSet, + OUString& rFilter ); +}; + +#define SFX2_IMPL_DIALOG_CONFIG 0 +#define SFX2_IMPL_DIALOG_SYSTEM 1 +#define SFX2_IMPL_DIALOG_OOO 2 +#define SFX2_IMPL_DIALOG_REMOTE 3 + +ErrCode FileOpenDialog_Impl( weld::Window* pParent, + sal_Int16 nDialogType, + FileDialogFlags nFlags, + std::vector& rpURLList, + OUString& rFilter, + std::optional& rpSet, + const OUString* pPath, + sal_Int16 nDialog, + const OUString& rStandardDir, + const css::uno::Sequence< OUString >& rDenyList = css::uno::Sequence< OUString >()); + +css::uno::Reference SFX2_DLLPUBLIC createFolderPicker(const css::uno::Reference& rContext, weld::Window* pPreferredParent); + +ErrCode RequestPassword(const std::shared_ptr& pCurrentFilter, OUString const & aURL, SfxItemSet* pSet, const css::uno::Reference& rParent); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/flatpak.hxx b/include/sfx2/flatpak.hxx new file mode 100644 index 000000000..cf71475fb --- /dev/null +++ b/include/sfx2/flatpak.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_INCLUDE_SFX2_FLATPAK_HXX +#define INCLUDED_INCLUDE_SFX2_FLATPAK_HXX + +#include + +#include +#include + +// Functionality related to the Flatpak version of LibreOffice. + +namespace flatpak +{ +bool isFlatpak(); + +// Must only be called with SolarMutex locked: +bool createTemporaryHtmlDirectory(OUString** url); + +// Must only be called with SolarMutex locked: +SFX2_DLLPUBLIC void removeTemporaryHtmlDirectory(); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/sfx2/frame.hxx b/include/sfx2/frame.hxx new file mode 100644 index 000000000..86b5baaa7 --- /dev/null +++ b/include/sfx2/frame.hxx @@ -0,0 +1,203 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_FRAME_HXX +#define INCLUDED_SFX2_FRAME_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace com::sun::star::frame +{ + class XFrame; + class XController; +} + +class SvBorder; +class SfxWorkWindow; +namespace vcl { class Window; } +class SfxFrame_Impl; +class SfxObjectShell; +class SfxViewFrame; +class SfxFrameDescriptor; +namespace tools { class Rectangle; } +class SystemWindow; + +typedef ::std::vector TargetList; + + +// SfxFrame is a management class for windows and their content. +// A SfxApplication represent a hierarchy of SfxFrames, with which the actual +// content in the derived classes is defined. The base class SfxFrame +// implements two aspects of frames: naming and control of its lifespan. +// Inside a frame hierarchy the parent frame always controls the lifespan of +// its child frames, even though they usually are not even produced by the +// parent. By calling DoCloser() on any frame in the hierarchy, +// a part of the "framework" can be removed, where frames unsubscribe +// from their parent frames. + + +class SFX2_DLLPUBLIC SfxFrame final : public SvCompatWeakBase +{ + friend class SfxFrameIterator; + friend class SfxFrameWindow_Impl; + +private: + std::unique_ptr< SfxFrame_Impl > pImpl; + VclPtr pWindow; + + virtual ~SfxFrame(); + + SAL_DLLPRIVATE SfxFrame( vcl::Window& i_rContainerWindow ); + +public: + static SfxFrame* Create( const css::uno::Reference< css::frame::XFrame >& xFrame ); + static css::uno::Reference< css::frame::XFrame > + CreateBlankFrame(); + static SfxFrame* CreateHidden( SfxObjectShell const & rDoc, vcl::Window& rWindow, SfxInterfaceId nViewId ); + + vcl::Window& GetWindow() const { return *pWindow;} + void CancelTransfers(); + bool DoClose(); + + void SetPresentationMode( bool bSet ); + SystemWindow* GetSystemWindow() const; + + static SfxFrame* GetFirst(); + static SfxFrame* GetNext( SfxFrame& ); + + SfxObjectShell* GetCurrentDocument() const; + SfxViewFrame* GetCurrentViewFrame() const; + + bool GetHasTitle() const; + static void GetDefaultTargetList( TargetList& ); + void UpdateDescriptor( SfxObjectShell const *pDoc ); + void Resize(); + const css::uno::Reference< css::frame::XFrame >& + GetFrameInterface() const; + void Appear(); + void AppearWithUpdate(); + css::uno::Reference< css::frame::XController > + GetController() const; + + bool IsInPlace() const; + + SAL_DLLPRIVATE void DoClose_Impl(); + SAL_DLLPRIVATE void SetFrameInterface_Impl( const css::uno::Reference< css::frame::XFrame >& rFrame ); + SAL_DLLPRIVATE void ReleasingComponent_Impl(); + SAL_DLLPRIVATE void GetViewData_Impl(); + SAL_DLLPRIVATE void SetHasTitle( bool ); + SAL_DLLPRIVATE bool PrepareClose_Impl( bool bUI ); + SAL_DLLPRIVATE bool DocIsModified_Impl(); + SAL_DLLPRIVATE void SetCurrentViewFrame_Impl( SfxViewFrame* ); + bool IsClosing_Impl() const; + SAL_DLLPRIVATE void SetIsClosing_Impl(); + + // Methods for accessing the current set + SAL_DLLPRIVATE SfxFrameDescriptor* GetDescriptor() const; + + SAL_DLLPRIVATE bool IsAutoLoadLocked_Impl() const; + + SAL_DLLPRIVATE static void InsertTopFrame_Impl( SfxFrame* pFrame ); + SAL_DLLPRIVATE static void RemoveTopFrame_Impl( SfxFrame* pFrame ); + SAL_DLLPRIVATE void SetOwnsBindings_Impl( bool bSet ); + SAL_DLLPRIVATE bool OwnsBindings_Impl() const; + SAL_DLLPRIVATE SfxWorkWindow* GetWorkWindow_Impl() const; + SAL_DLLPRIVATE void SetToolSpaceBorderPixel_Impl( const SvBorder& ); + SAL_DLLPRIVATE tools::Rectangle GetTopOuterRectPixel_Impl() const; + SAL_DLLPRIVATE void CreateWorkWindow_Impl(); + SAL_DLLPRIVATE void GrabFocusOnComponent_Impl(); + + SAL_DLLPRIVATE void PrepareForDoc_Impl( const SfxObjectShell& i_rDoc ); + SAL_DLLPRIVATE void LockResize_Impl( bool bLock ); + SAL_DLLPRIVATE void SetMenuBarOn_Impl( bool bOn ); + SAL_DLLPRIVATE bool IsMenuBarOn_Impl() const; + SAL_DLLPRIVATE SystemWindow* GetTopWindow_Impl() const; + SAL_DLLPRIVATE bool IsMarkedHidden_Impl() const; +private: + SAL_DLLPRIVATE void Construct_Impl(); +}; + +typedef SvCompatWeakRef SfxFrameWeakRef; + +class SFX2_DLLPUBLIC SfxFrameItem final : public SfxPoolItem +{ + SfxFrame* pFrame; + SfxFrameWeakRef wFrame; + +public: + + SfxFrameItem( sal_uInt16 nWhich, SfxViewFrame const *p ); + SfxFrameItem( SfxFrame *p ); + SfxFrameItem( sal_uInt16 nWhich, SfxFrame *p ); + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxFrameItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + SfxFrame* GetFrame() const { return wFrame; } +}; + +class SFX2_DLLPUBLIC SfxUnoAnyItem final : public SfxPoolItem +{ + css::uno::Any aValue; +public: + static SfxPoolItem* CreateDefault(); + SfxUnoAnyItem( sal_uInt16 nWhich, const css::uno::Any& rAny ); + const css::uno::Any& GetValue() const + { return aValue; } + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxUnoAnyItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +class SFX2_DLLPUBLIC SfxUnoFrameItem final : public SfxPoolItem +{ + css::uno::Reference< css::frame::XFrame > + m_xFrame; + +public: + static SfxPoolItem* CreateDefault(); + SfxUnoFrameItem(); + SfxUnoFrameItem( sal_uInt16 nWhich, const css::uno::Reference< css::frame::XFrame >& i_rFrame ); + const css::uno::Reference< css::frame::XFrame >& + GetFrame() const + { return m_xFrame; } + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxUnoFrameItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/frmdescr.hxx b/include/sfx2/frmdescr.hxx new file mode 100644 index 000000000..67c0c7e38 --- /dev/null +++ b/include/sfx2/frmdescr.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_FRMDESCR_HXX +#define INCLUDED_SFX2_FRMDESCR_HXX + +#include +#include +#include +#include +#include +#include + +// The SfxFrame descriptors build a recursive structure, that covers all the +// required data in-order to display the frame document. +// Through a SfxFrameSetDescriptor access is given to the whole underlying +// structure. Due to the nature of the SfxFrames document, the +// SfxFramesSetDescriptor is not only the content of this document, but also +// describes the view on it. The FrameSet is made up of lines, which in turn, +// contains the actual window . A line can be horizontally or vertically +// aligned, from which also the alignment of the FrameSet is given. + + +enum class ScrollingMode +{ + Yes, + No, + Auto +}; + +#define SIZE_NOT_SET -1L + +class SfxItemSet; + +class SFX2_DLLPUBLIC SfxFrameDescriptor +{ + INetURLObject aURL; + OUString aName; + Size aMargin; + ScrollingMode eScroll; + bool bHasBorder; + bool bHasBorderSet; + std::unique_ptr m_pArgs; + +public: + SfxFrameDescriptor(); + ~SfxFrameDescriptor(); + + // FileName/URL + SfxItemSet* GetArgs(); + const INetURLObject& GetURL() const + { return aURL; } + void SetURL( std::u16string_view rURL ); + void SetActualURL(); + + // FrameName + const OUString& GetName() const + { return aName; } + void SetName( const OUString& rName ) + { aName = rName; } + + // Margin, Scrolling + const Size& GetMargin() const + { return aMargin; } + void SetMargin( const Size& rMargin ) + { aMargin = rMargin; } + ScrollingMode GetScrollingMode() const + { return eScroll; } + void SetScrollingMode( ScrollingMode eMode ) + { eScroll = eMode; } + + // FrameBorder + bool HasFrameBorder() const + { return bHasBorder; } + bool IsFrameBorderOn() const + { return bHasBorder; } + void SetFrameBorder( bool bBorder ) + { bHasBorder = bBorder; bHasBorderSet = true; } + bool IsFrameBorderSet() const + { return bHasBorderSet; } + void ResetBorder() + { bHasBorder = false; bHasBorderSet = false; } +}; + +#endif // INCLUDED_SFX2_FRMDESCR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/frmhtml.hxx b/include/sfx2/frmhtml.hxx new file mode 100644 index 000000000..205c320fe --- /dev/null +++ b/include/sfx2/frmhtml.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_FRMHTML_HXX +#define INCLUDED_SFX2_FRMHTML_HXX + +#include +#include + +#include + +class SfxFrameDescriptor; + +namespace SfxFrameHTMLParser +{ +// These methods can also be used by other parsers. +SFX2_DLLPUBLIC void ParseFrameOptions(SfxFrameDescriptor*, const HTMLOptions&, std::u16string_view); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/frmhtmlw.hxx b/include/sfx2/frmhtmlw.hxx new file mode 100644 index 000000000..1011327c2 --- /dev/null +++ b/include/sfx2/frmhtmlw.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_FRMHTMLW_HXX +#define INCLUDED_SFX2_FRMHTMLW_HXX + +#include +#include +#include +#include + +class SvStream; + +namespace com::sun::star { + namespace document { + class XDocumentProperties; + } +} + +namespace com::sun::star::beans { class XPropertySet; } +namespace com::sun::star::uno { template class Reference; } + +class SFX2_DLLPUBLIC SfxFrameHTMLWriter +{ + SAL_DLLPRIVATE static void OutMeta( SvStream& rStrm, + const char *pIndent, const OUString& rName, + const OUString& rContent, bool bHTTPEquiv, + OUString *pNonConvertableChars = nullptr ); + SAL_DLLPRIVATE inline static void OutMeta( SvStream& rStrm, + const char *pIndent, const char *pName, + const OUString& rContent, bool bHTTPEquiv, + OUString *pNonConvertableChars = nullptr ); + +public: + static void Out_DocInfo( SvStream& rStrm, const OUString& rBaseURL, + const css::uno::Reference< css::document::XDocumentProperties>&, + const char *pIndent, + OUString *pNonConvertableChars = nullptr ); + + static void Out_FrameDescriptor( + SvStream&, const OUString& rBaseURL, const css::uno::Reference < css::beans::XPropertySet >& xSet, + OUString *pNonConvertableChars = nullptr ); +}; + +inline void SfxFrameHTMLWriter::OutMeta( SvStream& rStrm, + const char *pIndent, const char *pName, + const OUString& rContent, bool bHTTPEquiv, + OUString *pNonConvertableChars ) +{ + OUString sTmp = OUString::createFromAscii(pName); + OutMeta( rStrm, pIndent, sTmp, rContent, bHTTPEquiv, pNonConvertableChars ); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/groupid.hxx b/include/sfx2/groupid.hxx new file mode 100644 index 000000000..fd31785ae --- /dev/null +++ b/include/sfx2/groupid.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_GROUPID_HXX +#define INCLUDED_SFX2_GROUPID_HXX + +#include + +#include + +// !! If you add a new group, please change sfxbasecontroller.cxx and +// !! com.sun.star.frame.CommandGroup accordingly! + +enum class SfxGroupId +{ + NONE = 0, + Intern = 32700, + Application, + Document, + View, + Edit, + Macro, + Options, + Math, + Navigator, + Insert, + Format, + Template, + Text, + Frame, + Graphic, + Table, + Enumeration, + Data, + Special, + Image, + Chart, + Explorer, + Connector, + Modify, + Drawing, + Controls +}; + +// make it hashable for storing in maps +namespace std +{ +template <> struct hash +{ + std::size_t operator()(const SfxGroupId& k) const + { + return std::hash()(static_cast(k)); + } +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/htmlmode.hxx b/include/sfx2/htmlmode.hxx new file mode 100644 index 000000000..cd2b7d1fe --- /dev/null +++ b/include/sfx2/htmlmode.hxx @@ -0,0 +1,31 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_HTMLMODE_HXX +#define INCLUDED_SFX2_HTMLMODE_HXX + +enum +{ + HTMLMODE_ON = 0x0001, + HTMLMODE_SOME_STYLES = 0x0020, /* mind. MS IE */ + HTMLMODE_FULL_STYLES = 0x0040 /* == SW */ +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/infobar.hxx b/include/sfx2/infobar.hxx new file mode 100644 index 000000000..f5b948014 --- /dev/null +++ b/include/sfx2/infobar.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_SFX2_INFOBAR_HXX +#define INCLUDED_SFX2_INFOBAR_HXX + +#include + +#include + +#include +#include +#include + +// These must match the values in offapi/com/sun/star/frame/InfobarType.idl +enum class InfobarType +{ + INFO = 0, + SUCCESS = 1, + WARNING = 2, + DANGER = 3 +}; + +class InfobarData +{ +public: + OUString msId; + OUString msPrimaryMessage; + OUString msSecondaryMessage; + InfobarType maInfobarType; + bool mbShowCloseButton; +}; + +/** SfxChildWindow for positioning the InfoBar in the view. + */ +class SFX2_DLLPUBLIC SfxInfoBarContainerChild final : public SfxChildWindow +{ +private: + SfxBindings* m_pBindings; + +public: + SfxInfoBarContainerChild(vcl::Window* pParent, sal_uInt16 nId, SfxBindings* pBindings, + SfxChildWinInfo* pInfo); + virtual ~SfxInfoBarContainerChild() override; + + SFX_DECL_CHILDWINDOW_WITHID(SfxInfoBarContainerChild); + + void Update(); +}; + +class ExtraButton; + +/** Class representing a single InfoBar to be added in a SfxInfoBarContainerWindow. + */ +class SFX2_DLLPUBLIC SfxInfoBarWindow final : public InterimItemWindow +{ +private: + OUString m_sId; + InfobarType m_eType; + Size m_aMessageSize; + Size m_aOrigMessageSize; + bool m_bLayingOut; + std::unique_ptr m_xImage; + std::unique_ptr m_xPrimaryMessage; + std::unique_ptr m_xSecondaryMessage; + std::unique_ptr m_xButtonBox; + std::unique_ptr m_xCloseBtn; + std::vector> m_aActionBtns; + + DECL_DLLPRIVATE_LINK(SizeAllocHdl, const Size&, void); + + void SetForeAndBackgroundColors(InfobarType eType); + void SetCloseButtonImage(); + +public: + SfxInfoBarWindow(vcl::Window* parent, const OUString& sId, const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, InfobarType InfobarType, + bool bShowCloseButton); + Size DoLayout(); + virtual void Layout() override; + virtual ~SfxInfoBarWindow() override; + virtual void dispose() override; + + const OUString& getId() const { return m_sId; } + void Update(const OUString& sPrimaryMessage, const OUString& sSecondaryMessage, + InfobarType eType); + basegfx::BColor m_aBackgroundColor; + basegfx::BColor m_aForegroundColor; + + /** Add button to Infobar. + * Infobar takes ownership of the button so the button is + * destroyed when the infobar gets destroyed. + * + * The optional "pCommand" is used by extensions, via XInfobarProvider, to + * dispatch pCommand on click. + */ + weld::Button& addButton(const OUString* pCommand = nullptr); + + void SetCommandHandler(weld::Button& rBtn, const OUString& aCommand); + +private: + DECL_DLLPRIVATE_LINK(CloseHandler, const OString&, void); +}; + +class SfxInfoBarContainerWindow final : public vcl::Window +{ +private: + SfxInfoBarContainerChild* m_pChildWin; + std::vector> m_pInfoBars; + Idle m_aLayoutIdle; + bool m_bResizing; + + DECL_LINK(DoUpdateLayout, Timer*, void); + +public: + SfxInfoBarContainerWindow(SfxInfoBarContainerChild* pChildWin); + virtual ~SfxInfoBarContainerWindow() override; + virtual void dispose() override; + + VclPtr appendInfoBar(const OUString& sId, const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, InfobarType ibType, + bool bShowCloseButton); + VclPtr getInfoBar(std::u16string_view sId); + bool hasInfoBarWithID(std::u16string_view sId); + void removeInfoBar(VclPtr const& pInfoBar); + static bool isInfobarEnabled(std::u16string_view sId); + + void TriggerUpdateLayout(); + + virtual void Resize() override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/inputdlg.hxx b/include/sfx2/inputdlg.hxx new file mode 100644 index 000000000..840844d18 --- /dev/null +++ b/include/sfx2/inputdlg.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_SOURCE_INC_INPUTDLG_HXX +#define INCLUDED_SFX2_SOURCE_INC_INPUTDLG_HXX + +#include +#include + +class SFX2_DLLPUBLIC InputDialog final : public weld::GenericDialogController +{ +private: + std::unique_ptr m_xEntry; + std::unique_ptr m_xLabel; + std::unique_ptr m_xHelp; + std::unique_ptr m_xOk; + std::function mCheckEntry; + DECL_DLLPRIVATE_LINK(EntryChangedHdl, weld::Entry&, void); + +public: + InputDialog(weld::Widget* pParent, const OUString& rLabelText); + OUString GetEntryText() const; + void SetEntryText(const OUString& rStr); + void HideHelpBtn(); + void SetEntryMessageType(weld::EntryMessageType aType); + void SetTooltip(const OUString& rStr); + void setCheckEntry(std::function aFunc); +}; + +#endif // INCLUDED_SFX2_SOURCE_INC_INPUTDLG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/ipclient.hxx b/include/sfx2/ipclient.hxx new file mode 100644 index 000000000..6eddf9e9f --- /dev/null +++ b/include/sfx2/ipclient.hxx @@ -0,0 +1,101 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_IPCLIENT_HXX +#define INCLUDED_SFX2_IPCLIENT_HXX + +#include +#include +#include +#include + +#include + +#include +#include + +namespace com::sun::star::embed { class XEmbeddedObject; } +namespace com::sun::star::uno { template class Reference; } +namespace vcl { class Window; } + +class SfxInPlaceClient_Impl; +class SfxViewShell; +class SfxObjectShell; +class Fraction; + + +class SFX2_DLLPUBLIC SfxInPlaceClient +{ +friend class SfxInPlaceClient_Impl; + + rtl::Reference m_xImp; + SfxViewShell* m_pViewSh; + VclPtr m_pEditWin; + + // called after the requested new object area was negotiated + SAL_DLLPRIVATE virtual void ObjectAreaChanged(); + + // an active object was resized by the user and now asks for the new space + SAL_DLLPRIVATE virtual void RequestNewObjectArea( tools::Rectangle& ); + + // notify the client that an active object has changed its VisualAreaSize + SAL_DLLPRIVATE virtual void ViewChanged(); + +public: + SfxInPlaceClient( SfxViewShell* pViewShell, vcl::Window* pDraw, sal_Int64 nAspect ); + virtual ~SfxInPlaceClient(); + + SfxInPlaceClient(const SfxInPlaceClient &) = delete; + SfxInPlaceClient& operator=(const SfxInPlaceClient &) = delete; + + SfxViewShell* GetViewShell() const { return m_pViewSh; } + vcl::Window* GetEditWin() const { return m_pEditWin; } + const css::uno::Reference < css::embed::XEmbeddedObject >& GetObject() const; + void SetObject( const css::uno::Reference < css::embed::XEmbeddedObject >& rObject ); + void SetObjectState( sal_Int32 ); + bool IsObjectUIActive() const; + bool IsObjectInPlaceActive() const; + void DeactivateObject(); + bool SetObjArea( const tools::Rectangle & ); + const tools::Rectangle& GetObjArea() const; + tools::Rectangle GetScaledObjArea() const; + void SetSizeScale( const Fraction & rScaleWidth, const Fraction & rScaleHeight ); + void SetObjAreaAndScale( const tools::Rectangle&, const Fraction&, const Fraction& ); + const Fraction& GetScaleWidth() const; + const Fraction& GetScaleHeight() const; + void Invalidate(); + static SfxInPlaceClient* GetClient( SfxObjectShell const * pDoc, const css::uno::Reference < css::embed::XEmbeddedObject >& xObject ); + sal_Int64 GetAspect() const; + sal_Int64 GetObjectMiscStatus() const; + ErrCode DoVerb(sal_Int32 nVerb); + void VisAreaChanged(); + void ResetObject(); + bool IsUIActive() const; + + /// To indicate that negated document X coordinates are used + void SetNegativeX(bool bSet); + bool IsNegativeX() const; + + virtual void FormatChanged(); // object format was changed (used for StarMath formulas aligning) + + virtual bool IsProtected() const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/linkmgr.hxx b/include/sfx2/linkmgr.hxx new file mode 100644 index 000000000..e4f58a996 --- /dev/null +++ b/include/sfx2/linkmgr.hxx @@ -0,0 +1,187 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_LINKMGR_HXX +#define INCLUDED_SFX2_LINKMGR_HXX + +#include +#include +#include +#include +#include +#include + +#include +#include + +class SfxObjectShell; +class Graphic; + +namespace com::sun::star { + namespace lang { + class XComponent; + } +} + +namespace weld { class Window; } + +namespace sfx2 +{ + // For the link to receive information about the status of graphics that + // will be loaded the FileObject sends a SvData, which contains the + // FormatID "RegisterStatusInfoId" and a string as the data container. + // This contains the following enum. + +typedef std::vector > SvBaseLinks; + +typedef o3tl::sorted_vector SvLinkSources; + +class SFX2_DLLPUBLIC LinkManager +{ + typedef ::std::vector< css::uno::Reference< css::lang::XComponent > > + CompVector; + CompVector maCachedComps; + + SvBaseLinks aLinkTbl; + SvLinkSources aServerTbl; + + SfxObjectShell *pPersist; // LinkMgr must be release before SfxObjectShell + + bool InsertLink( SvBaseLink* pLink, SvBaseLinkObjectType nObjType, SfxLinkUpdateMode nUpdateType, + const OUString* pName ); +public: + + enum LinkState + { + STATE_LOAD_OK, + STATE_LOAD_ERROR, + STATE_LOAD_ABORT + }; + + LinkManager( SfxObjectShell * pCacheCont ); + ~LinkManager(); + + /** + * Insert a component loaded during link update, which needs to be closed + * when the update is complete. + * + * @param xComp component loaded during link update. + */ + void InsertCachedComp(const css::uno::Reference< css::lang::XComponent >& xComp); + + void CloseCachedComps(); + + SfxObjectShell* GetPersist() const { return pPersist; } + void SetPersist( SfxObjectShell * p ) { pPersist = p; } + + void Remove( SvBaseLink const *pLink ); + void Remove( size_t nPos, size_t nCnt = 1 ); + bool Insert( SvBaseLink* pLink ); + + // the links connect to a SvLinkSource and adds to the list + void InsertDDELink( SvBaseLink*, + const OUString& rServer, + std::u16string_view rTopic, + std::u16string_view rItem ); + + // if everything is already set at the link! + void InsertDDELink( SvBaseLink* ); + + // Connect the links to a pseudo-object and add to the list + void InsertFileLink( sfx2::SvBaseLink&, + SvBaseLinkObjectType nFileType, + std::u16string_view rFileNm, + const OUString* pFilterNm = nullptr, + const OUString* pRange = nullptr ); + + void ReconnectDdeLink(SfxObjectShell& rServer); + + /** + * Reconnect the server document shell to a DDE link object. + * + * @param rPath path to the server document + * @param rServer server document shell instance + * @param rLink link object of the client document + */ + static void LinkServerShell(const OUString& rPath, SfxObjectShell& rServer, ::sfx2::SvBaseLink& rLink); + + // Obtain the string for the dialog + static bool GetDisplayNames( const SvBaseLink *, + OUString* pType, + OUString* pFile = nullptr, + OUString* pLink = nullptr, + OUString* pFilter = nullptr ); + + static SvLinkSourceRef CreateObj( SvBaseLink const * ); + + void UpdateAllLinks(bool bAskUpdate, + bool bUpdateGrfLinks, + weld::Window* pParentWin); + + // Call for list of links (eg for link-dialog) + const SvBaseLinks& GetLinks() const { return aLinkTbl; } + + // ----------------- Server-side management -------------------- + + // Call with list of links to server + const SvLinkSources& GetServers() const { return aServerTbl; } + // Link register/delete + bool InsertServer( SvLinkSource* rObj ); + void RemoveServer( SvLinkSource* rObj ); + + // A transfer is aborted, so cancel all download media + // (for the time being this is only of interest for the FileLinks!) + void CancelTransfers(); + + // To send status information from the FileObject to the Baselink, + // for this there exist a separate ClipBoardId. The SvData-object has + // got the appropriate information as a string. + // Is now required for FileObject in conjunction with JavaScript + // this needs information about Load/Abort/Error + static SotClipboardFormatId RegisterStatusInfoId(); + + // if the mimetype says graphic/bitmap/gdimetafile then get the + // graphic from the Any. Return says no errors + bool GetGraphicFromAny(const OUString& rMimeType, + const css::uno::Any & rValue, + Graphic& rGrf, + weld::Window* pParentWin); + +private: + LinkManager( const LinkManager& ) = delete; + LinkManager& operator=( const LinkManager& ) = delete; +}; + +// Separator in the link name for the DDE-/File-/Graphics- links +// (only those who need to construct a SvLinkName) +const sal_Unicode cTokenSeparator = 0xFFFF; + +// create a string for the SvLinkName. For: +// - DDE the first 3 Strings, (Server, Topic, Item) +// - File-/Graphics-LinkNames the last 3 Strings (FileName, Region, Filter) +SFX2_DLLPUBLIC void MakeLnkName( OUString& rName, + const OUString* pType, // Can also be null!! + std::u16string_view rFile, + std::u16string_view rLink, + const OUString* pFilter = nullptr ); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/linksrc.hxx b/include/sfx2/linksrc.hxx new file mode 100644 index 000000000..4f12d72f4 --- /dev/null +++ b/include/sfx2/linksrc.hxx @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_LINKSRC_HXX +#define INCLUDED_SFX2_LINKSRC_HXX + +#include +#include + +#include +#include +#include + +namespace com::sun::star::uno +{ + class Any; +} +namespace weld { class Window; } + +template class Link; +namespace com::sun::star::io { class XInputStream; } + +#ifndef ADVISEMODE_NODATA +// Must be the same value as Ole2 ADVF_* +#define ADVISEMODE_NODATA 0x01 +#define ADVISEMODE_PRIMEFIRST 0x02 +#define ADVISEMODE_ONLYONCE 0x04 +#define ADVISEMODE_DATAONSTOP 0x40 +#endif + +namespace sfx2 +{ + +class SvBaseLink; +struct SvLinkSource_Impl; + +class SFX2_DLLPUBLIC SvLinkSource : public SvRefBase +{ +private: + std::unique_ptr pImpl; // compatible area + +public: + + SvLinkSource(); + virtual ~SvLinkSource() override; + + bool HasDataLinks() const; + + void Closed(); + + sal_uInt64 GetUpdateTimeout() const; + void SetUpdateTimeout( sal_uInt64 nTimeMs ); + // notify the sink, the mime type is not + // a selection criterion + void DataChanged( const OUString & rMimeType, + const css::uno::Any & rVal ); + void SendDataChanged(); + void NotifyDataChanged(); + + virtual bool Connect( SvBaseLink* ); + virtual bool GetData( css::uno::Any & rData /*out param*/, + const OUString & rMimeType, + bool bSynchron = false ); + + // sal_True => waitinmg for data + virtual bool IsPending() const; + // sal_True => data complete loaded + virtual bool IsDataComplete() const; + + virtual void Edit(weld::Window *, SvBaseLink *, const Link& rEndEditHdl); + + + void AddDataAdvise( SvBaseLink *, const OUString & rMimeType, + sal_uInt16 nAdviceMode ); + void RemoveAllDataAdvise( SvBaseLink const * ); + + void AddConnectAdvise( SvBaseLink * ); + void RemoveConnectAdvise( SvBaseLink const * ); + + struct StreamToLoadFrom{ + StreamToLoadFrom( + const css::uno::Reference& xInputStream, bool bIsReadOnly ) + :m_xInputStreamToLoadFrom(xInputStream), + m_bIsReadOnly(bIsReadOnly) + { + } + + css::uno::Reference + m_xInputStreamToLoadFrom; + bool m_bIsReadOnly; + }; + + StreamToLoadFrom getStreamToLoadFrom(); + void setStreamToLoadFrom(const css::uno::Reference& xInputStream, bool bIsReadOnly ); + void clearStreamToLoadFrom(); +}; + +typedef tools::SvRef SvLinkSourceRef; + +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/listview.hxx b/include/sfx2/listview.hxx new file mode 100644 index 000000000..fbcdd0cbd --- /dev/null +++ b/include/sfx2/listview.hxx @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +enum TemplateViewMode +{ + eListView, + eThumbnailView +}; +class SfxDocumentTemplates; +class TemplateContainerItem; +struct ListViewItem; + +class ListView +{ +public: + ListView(std::unique_ptr xTreeView); + ~ListView(); + + void AppendItem(const OUString& rId, const OUString& rTitle, const OUString& rSubtitle, + const OUString& rPath, bool bDefault); + + void AppendRow(const OUString& rImage, const OUString& rTitle, const OUString& rSubtitle, + const OUString& rApplication, const OUString& rModify, const OUString& rSize, + const OUString& rId); + + void UpdateRow(int nIndex, const OUString& rImage, const OUString& rTitle, + const OUString& rSubtitle, const OUString& rApplication, const OUString& rModify, + const OUString& rSize, const OUString& rId); + + void ReloadRows(); + + bool UpdateRows(); + + void sortColumn(const int col); + + void sort(); + + void clearListView(); + + void ShowListView() { mxTreeView->show(); } + + void HideListView() { mxTreeView->hide(); } + + void unselect_all() { mxTreeView->unselect_all(); } + + void grab_focus() { mxTreeView->grab_focus(); } + + void rename(const OUString& rId, const OUString& rTitle); + + void refreshDefaultColumn(); + +protected: + sal_uInt16 get_nId(int pos) const; + + void select_id(const OUString& sId) { mxTreeView->select_id(sId); } + + int get_selected_index() const { return mxTreeView->get_selected_index(); } + + std::vector get_selected_rows() const { return mxTreeView->get_selected_rows(); } + + bool IsListViewVisible() const { return mxTreeView->is_visible(); } + + OUString get_id(int pos) const { return mxTreeView->get_id(pos); } + + void set_cursor(int pos) { mxTreeView->set_cursor(pos); } + + int get_cursor_index() const { return mxTreeView->get_cursor_index(); } + + sal_uInt16 get_cursor_nId() const { return get_nId(mxTreeView->get_cursor_index()); } + + void select(int pos) { mxTreeView->select(pos); } + + int get_index(sal_uInt16 nId) const { return mxTreeView->find_id(OUString::number(nId)); } + + DECL_LINK(ColumnClickedHdl, const int, void); + + DECL_LINK(QueryTooltipHdl, const weld::TreeIter&, OUString); + +protected: + std::unique_ptr mxTreeView; + std::vector> mListViewItems; + Link maSelectionChangedHdl; + int mnSortColumn; +}; + +struct ListViewItem +{ +public: + OUString maId; + OUString maTitle; + OUString maSubtitle; + OUString maApplication; + OUString maPath; + bool mbDefault; + + /** Last modify time in seconds since 1/1/1970. */ + sal_uInt32 mnModify; + /** Size in bytes of the file. */ + sal_uInt64 mnSize; + + OUString maDisplayModify; + OUString maDisplaySize; + OUString maDisplayPath; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/lnkbase.hxx b/include/sfx2/lnkbase.hxx new file mode 100644 index 000000000..cf1083197 --- /dev/null +++ b/include/sfx2/lnkbase.hxx @@ -0,0 +1,179 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::uno +{ + class Any; +} + +namespace com::sun::star::io { class XInputStream; } + +enum class SfxLinkUpdateMode { + NONE = 0, + // Ole2 compatible and persistent + ALWAYS = 1, + ONCALL = 3 +}; + +namespace sfx2 +{ + +struct ImplBaseLinkData; +class LinkManager; +class FileDialogHelper; + +enum class SvBaseLinkObjectType { + Internal = 0x00, + DdeExternal = 0x02, + ClientSo = 0x80, // a Link + ClientDde = 0x81, + ClientFile = 0x90, + ClientGraphic = 0x91, + ClientOle = 0x92 // embedded link +}; + +constexpr bool isClientType(SvBaseLinkObjectType t) +{ + return static_cast(t) & static_cast(SvBaseLinkObjectType::ClientSo); +} +constexpr bool isClientFileType(SvBaseLinkObjectType t) +{ + auto check = static_cast(SvBaseLinkObjectType::ClientFile); + return (static_cast(t) & check) == check; +} + +class SFX2_DLLPUBLIC SvBaseLink : public SvRefBase +{ +private: + friend class LinkManager; + friend class SvLinkSource; + + Link m_aEndEditLink; + LinkManager* m_pLinkMgr; + weld::Window* m_pParentWin; + std::unique_ptr + m_pFileDlg; + SvLinkSourceRef xObj; + OUString aLinkName; + std::unique_ptr pImplData; + SvBaseLinkObjectType mnObjType; + bool bVisible : 1; + bool bSynchron : 1; + bool bWasLastEditOK : 1; + bool m_bIsConnect : 1; + + DECL_DLLPRIVATE_LINK( EndEditHdl, const OUString&, void ); + + bool ExecuteEdit( const OUString& _rNewName ); + +protected: + void SetObjType( SvBaseLinkObjectType ); + + // Set LinkSourceName without action + void SetName( const OUString & rLn ); + + bool m_bIsReadOnly; + css::uno::Reference + m_xInputStreamToLoadFrom; + + SvBaseLink(); + SvBaseLink( SfxLinkUpdateMode nLinkType, SotClipboardFormatId nContentType ); + virtual ~SvBaseLink() override; + + void GetRealObject_( bool bConnect = true ); + + SvLinkSource* GetRealObject() + { + if( !xObj.is() ) + GetRealObject_(); + return xObj.get(); + } + +public: + + virtual void Closed(); + +#if defined(_WIN32) + SvBaseLink( const OUString& rNm, SvBaseLinkObjectType nObjectType, + SvLinkSource* ); +#endif + + SvBaseLinkObjectType GetObjType() const { return mnObjType; } + + void SetObj( SvLinkSource * pObj ); + SvLinkSource* GetObj() const { return xObj.get(); } + + void SetLinkSourceName( const OUString & rName ); + const OUString& GetLinkSourceName() const { return aLinkName;} + + enum UpdateResult { + SUCCESS = 0, + ERROR_GENERAL = 1 + }; + + virtual UpdateResult DataChanged( + const OUString & rMimeType, const css::uno::Any & rValue ); + + void SetUpdateMode( SfxLinkUpdateMode ); + SfxLinkUpdateMode GetUpdateMode() const; + SotClipboardFormatId GetContentType() const; + void SetContentType( SotClipboardFormatId nType ); + + LinkManager* GetLinkManager(); + const LinkManager* GetLinkManager() const; + void SetLinkManager( LinkManager* _pMgr ); + + bool Update(); + void Disconnect(); + + virtual void Edit(weld::Window*, const Link& rEndEditHdl); + + // should the link appear in the dialog? (to the left in the link in the...) + bool IsVisible() const { return bVisible; } + void SetVisible( bool bFlag ) { bVisible = bFlag; } + // should the Link be loaded synchronous or asynchronous? + bool IsSynchron() const { return bSynchron; } + void SetSynchron( bool bFlag ) { bSynchron = bFlag; } + + void setStreamToLoadFrom( + const css::uno::Reference& xInputStream, + bool bIsReadOnly ) + { m_xInputStreamToLoadFrom = xInputStream; + m_bIsReadOnly = bIsReadOnly; } + // #i88291# + void clearStreamToLoadFrom(); + + bool WasLastEditOK() const { return bWasLastEditOK; } + FileDialogHelper & GetInsertFileDialog(const OUString& rFactory); +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/lokcallback.hxx b/include/sfx2/lokcallback.hxx new file mode 100644 index 000000000..32b6c08f8 --- /dev/null +++ b/include/sfx2/lokcallback.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +namespace tools +{ +class Rectangle; +} + +// An extended callback type that allows passing in also some binary data, +// so that post-processing the messages does not require conversions +// from and to strings. + +// TODO: It might possibly make sense to drop the generic type/payload function +// and have only a dedicated function for each message type? + +class SAL_NO_VTABLE SAL_DLLPUBLIC_RTTI SfxLokCallbackInterface +{ +public: + virtual ~SfxLokCallbackInterface() {} + // LibreOfficeKitCallback equivalent. + virtual void libreOfficeKitViewCallback(int nType, const char* pPayload) = 0; + // Callback that explicitly provides view id (which is also included in the payload). + virtual void libreOfficeKitViewCallbackWithViewId(int nType, const char* pPayload, int nViewId) + = 0; + // LOK_CALLBACK_INVALIDATE_TILES + // nPart is either part, -1 for all-parts, or INT_MIN if + // comphelper::LibreOfficeKit::isPartInInvalidation() is not set + virtual void libreOfficeKitViewInvalidateTilesCallback(const tools::Rectangle* pRect, int nPart) + = 0; + // A message of the given type should be sent, for performance purpose only a notification + // is given here, details about the message should be queried from SfxViewShell when necessary. + // This is used for messages that are generated often but only the last one is needed. + virtual void libreOfficeKitViewUpdatedCallback(int nType) = 0; + // Like libreOfficeKitViewUpdatedCallback(), but a last message is needed for each nViewId value. + // SfxViewShell:getLOKPayload() will be called on nSourceViewId view. + virtual void libreOfficeKitViewUpdatedCallbackPerViewId(int nType, int nViewId, + int nSourceViewId) + = 0; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/lokcomponenthelpers.hxx b/include/sfx2/lokcomponenthelpers.hxx new file mode 100644 index 000000000..6a3d96468 --- /dev/null +++ b/include/sfx2/lokcomponenthelpers.hxx @@ -0,0 +1,90 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_LOKCHARTHELPER_HXX +#define INCLUDED_SFX2_LOKCHARTHELPER_HXX + +#include +#include +#include +#include + +namespace com::sun::star::frame { class XController; } +namespace com::sun::star::frame { class XDispatch; } + +class SfxViewShell; +class VirtualDevice; + +/// A class for chart editing support via LibreOfficeKit. +class SFX2_DLLPUBLIC LokChartHelper +{ +private: + SfxViewShell* mpViewShell; + css::uno::Reference mxController; + css::uno::Reference mxDispatcher; + VclPtr mpWindow; + bool mbNegativeX; + +public: + LokChartHelper(SfxViewShell* pViewShell, bool bNegativeX = false) + : mpViewShell(pViewShell) + , mpWindow(nullptr) + , mbNegativeX(bNegativeX) + {} + + css::uno::Reference& GetXController(); + css::uno::Reference& GetXDispatcher(); + vcl::Window* GetWindow(); + tools::Rectangle GetChartBoundingBox(); + void Invalidate(); + + bool Hit(const Point& aPos); + static bool HitAny(const Point& aPos, bool bNegativeX = false); + void PaintTile(VirtualDevice& rRenderContext, const tools::Rectangle& rTileRect); + static void PaintAllChartsOnTile(VirtualDevice& rDevice, + int nOutputWidth, int nOutputHeight, + int nTilePosX, int nTilePosY, + tools::Long nTileWidth, tools::Long nTileHeight, + bool bNegativeX = false); + bool postMouseEvent(int nType, int nX, int nY, + int nCount, int nButtons, int nModifier, + double fScaleX = 1.0, double fScaleY = 1.0); + bool setTextSelection(int nType, int nX, int nY); + bool setGraphicSelection(int nType, int nX, int nY, + double fScaleX = 1.0, double fScaleY = 1.0); +}; + +/// A class for math editing support via LibreOfficeKit. +class SFX2_DLLPUBLIC LokStarMathHelper +{ +public: + LokStarMathHelper(SfxViewShell* pViewShell) + : mpViewShell(pViewShell) + { + } + + vcl::Window* GetGraphicWindow(); + vcl::Window* GetWidgetWindow(); + + bool postMouseEvent(int nType, int nX, int nY, int nCount, int nButtons, int nModifier, + double fScaleX = 1.0, double fScaleY = 1.0); + +private: + css::uno::Reference& GetXController(); + tools::Rectangle GetBoundingBox(); + + SfxViewShell* mpViewShell; + css::uno::Reference mxController; + VclPtr mpGraphicWindow; + VclPtr mpWidgetWindow; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/lokhelper.hxx b/include/sfx2/lokhelper.hxx new file mode 100644 index 000000000..4ac50a19c --- /dev/null +++ b/include/sfx2/lokhelper.hxx @@ -0,0 +1,171 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_LOKHELPER_HXX +#define INCLUDED_SFX2_LOKHELPER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct SFX2_DLLPUBLIC LokMouseEventData +{ + int mnType; + Point maPosition; + int mnCount; + MouseEventModifiers meModifiers; + int mnButtons; + int mnModifier; + std::optional maLogicPosition; + + LokMouseEventData(int nType, Point aPosition, int nCount, MouseEventModifiers eModifiers, int nButtons, int nModifier) + : mnType(nType) + , maPosition(aPosition) + , mnCount(nCount) + , meModifiers(eModifiers) + , mnButtons(nButtons) + , mnModifier(nModifier) + {} +}; + +#include + +class SFX2_DLLPUBLIC SfxLokHelper +{ +public: + /// Create a new view shell from the current view frame. + /// This assumes a single document is ever loaded. + static int createView(); + /// Create a new view shell for the given DocId, for multi-document support. + static int createView(int nDocId); + /// Destroy a view shell from the global shell list. + static void destroyView(int nId); + /// Set a view shell as current one. + static void setView(int nId); + /// Get view shell with id + static SfxViewShell* getViewOfId(int nId); + /// Get the currently active view. + static int getView(const SfxViewShell* pViewShell = nullptr); + /// Get the number of views of the current DocId. + static std::size_t getViewsCount(int nDocId); + /// Get viewIds of views of the current DocId. + static bool getViewIds(int nDocId, int* pArray, size_t nSize); + /// Set View Blocked for some uno commands + static void setBlockedCommandList(int nViewId, const char* blockedCommandList); + /// Get the document id for a view + static int getDocumentIdOfView(int nViewId); + /// Get the default language that should be used for views + static const LanguageTag & getDefaultLanguage(); + /// Set language of the given view. + static void setViewLanguage(int nId, const OUString& rBcp47LanguageTag); + /// Set the default language for views. + static void setDefaultLanguage(const OUString& rBcp47LanguageTag); + /// Set the locale for the given view. + static void setViewLocale(int nId, const OUString& rBcp47LanguageTag); + /// Get the device form factor that should be used for a new view. + static LOKDeviceFormFactor getDeviceFormFactor(); + /// Set the device form factor that should be used for a new view. + static void setDeviceFormFactor(std::u16string_view rDeviceFormFactor); + + /// Iterate over any view shell, except pThisViewShell, passing it to the f function. + template + static void forEachOtherView(ViewShellType* pThisViewShell, FunctionType f); + + /// Invoke the LOK callback of all other views showing the same document as pThisView, with a payload of rKey-rPayload. + static void notifyOtherViews(const SfxViewShell* pThisView, int nType, std::string_view rKey, + const OString& rPayload); + /// Invoke the LOK callback of all views except pThisView, with a JSON payload created from the given property tree. + static void notifyOtherViews(const SfxViewShell* pThisView, int nType, + const boost::property_tree::ptree& rTree); + /// Same as notifyOtherViews(), but works on a selected "other" view, not on all of them. + static void notifyOtherView(const SfxViewShell* pThisView, SfxViewShell const* pOtherView, + int nType, std::string_view rKey, const OString& rPayload); + /// Same as notifyOtherViews(), the property-tree version, but works on a selected "other" view, not on all of them. + static void notifyOtherView(const SfxViewShell* pThisView, SfxViewShell const* pOtherView, + int nType, const boost::property_tree::ptree& rTree); + + /// Emits a LOK_CALLBACK_STATE_CHANGED + static void sendUnoStatus(const SfxViewShell* pShell, const SfxPoolItem* pItem); + /// Emits a LOK_CALLBACK_WINDOW + static void notifyWindow(const SfxViewShell* pThisView, + vcl::LOKWindowId nWindowId, + std::u16string_view rAction, + const std::vector& rPayload = std::vector()); + /// Emits a LOK_CALLBACK_DOCUMENT_SIZE_CHANGED - if @bInvalidateAll - first invalidates all parts + static void notifyDocumentSizeChanged(SfxViewShell const* pThisView, const OString& rPayload, vcl::ITiledRenderable* pDoc, bool bInvalidateAll = true); + /// Emits a LOK_CALLBACK_DOCUMENT_SIZE_CHANGED for all views of the same document - if @bInvalidateAll - first invalidates all parts + static void notifyDocumentSizeChangedAllViews(vcl::ITiledRenderable* pDoc, bool bInvalidateAll = true); + /// Emits a LOK_CALLBACK_INVALIDATE_TILES, but tweaks it according to setOptionalFeatures() if needed. + static void notifyInvalidation(SfxViewShell const* pThisView, tools::Rectangle const *); + /// Notifies all views with the given type and payload. + static void notifyAllViews(int nType, const OString& rPayload); + + /// Notify about the editing context change. + static void notifyContextChange(SfxViewShell const* pViewShell, const OUString& aApplication, const OUString& aContext); + + // Notify about the given type needing an update. + static void notifyUpdate(SfxViewShell const* pViewShell, int nType); + // Notify about the given type needing a per-viewid update. + static void notifyUpdatePerViewId(SfxViewShell const* pViewShell, int nType); + /// Same as notifyUpdatePerViewId(), pTargetShell will be notified, relevant viewId in pViewShell, + /// pSourceView->getLOKPayload() will be called to get the data. + static void notifyUpdatePerViewId(SfxViewShell const* pTargetShell, SfxViewShell const* pViewShell, + SfxViewShell const* pSourceShell, int nType); + // Notify other views about the given type needing a per-viewid update. + static void notifyOtherViewsUpdatePerViewId(SfxViewShell const* pViewShell, int nType); + + static OString makePayloadJSON(const SfxViewShell* pThisView, int nViewId, std::string_view rKey, const OString& rPayload); + /// Makes a LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR payload, but tweaks it according to setOptionalFeatures() if needed. + static OString makeVisCursorInvalidation(int nViewId, const OString& rRectangle, + bool bMispelledWord = false, const OString& rHyperlink = ""); + + /// Helper for posting async key event + static void postKeyEventAsync(const VclPtr &xWindow, + int nType, int nCharCode, int nKeyCode, int nRepeat = 0); + + /// Helper for posting input event + static void postExtTextEventAsync(const VclPtr &xWindow, + int nType, const OUString &rText); + + /// Helper for posting async mouse event + static void postMouseEventAsync(const VclPtr &xWindow, LokMouseEventData const & rLokMouseEventData); + + /// A special value to signify 'infinity'. + /// This value is chosen such that sal_Int32 will not overflow when manipulated. + static const tools::Long MaxTwips = 1e9; + +private: + static int createView(SfxViewFrame* pViewFrame, ViewShellDocId docId); +}; + +template +void SfxLokHelper::forEachOtherView(ViewShellType* pThisViewShell, FunctionType f) +{ + SfxViewShell* pViewShell = SfxViewShell::GetFirst(); + while (pViewShell) + { + auto pOtherViewShell = dynamic_cast(pViewShell); + if (pOtherViewShell != nullptr && pOtherViewShell != pThisViewShell && pOtherViewShell->GetDocId() == pThisViewShell->GetDocId()) + { + f(pOtherViewShell); + } + pViewShell = SfxViewShell::GetNext(*pViewShell); + } +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/mailmodelapi.hxx b/include/sfx2/mailmodelapi.hxx new file mode 100644 index 000000000..47d5b4086 --- /dev/null +++ b/include/sfx2/mailmodelapi.hxx @@ -0,0 +1,104 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_MAILMODELAPI_HXX +#define INCLUDED_SFX2_MAILMODELAPI_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::frame { class XFrame; } +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::lang { class XMultiServiceFactory; } +namespace com::sun::star::uno { class XInterface; } +namespace com::sun::star::uno { template class Sequence; } + +// class AddressList_Impl ------------------------------------------------ +typedef ::std::vector< OUString > AddressList_Impl; + +// class SfxMailModel_Impl ----------------------------------------------- + +class SFX2_DLLPUBLIC SfxMailModel +{ +protected: + enum SaveResult + { + SAVE_SUCCESSFUL, + SAVE_CANCELLED, + SAVE_ERROR + }; + ::std::vector< OUString > maAttachedDocuments; + static SaveResult SaveDocumentAsFormat( const OUString& aSaveFileName, + const css::uno::Reference< css::uno::XInterface >& xFrameOrModel, + const OUString& rType, + OUString& rFileNamePath ); + +private: + std::unique_ptr mpToList; + OUString maFromAddress; + + static SaveResult ShowFilterOptionsDialog( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR, + const css::uno::Reference< css::frame::XModel >& xModel, + const OUString& rFilterName, + std::u16string_view rType, + bool bModified, + sal_Int32& rNumArgs, + css::uno::Sequence< css::beans::PropertyValue >& rArgs ); + +public: + enum SendMailResult + { + SEND_MAIL_OK, + SEND_MAIL_CANCELLED, + SEND_MAIL_ERROR + }; + + SfxMailModel(); + ~SfxMailModel(); + + void AddToAddress( const OUString& rAddress ); + + /** attaches a document to the current attachment list, can be called more than once. + * at the moment there will be a dialog for export executed for every model which is going to be attached. + * + * \param xModel + The current model to attach + * \param sAttachmentTitle + The title which will be used as attachment title + * \return @see error code + */ + SendMailResult AttachDocument( const css::uno::Reference< css::uno::XInterface >& xFrameOrModel, + const OUString& sAttachmentTitle ); + + SendMailResult SaveAndSend( const css::uno::Reference< css::frame::XFrame >& xFrame, + const OUString& rType ); + SendMailResult Send( const css::uno::Reference< css::frame::XFrame >& xFrame ); + + bool IsEmpty() const; +}; + +bool CreateFromAddress_Impl( OUString& rFrom ); + +#endif // INCLUDED_SFX2_MAILMODELAPI_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/mieclip.hxx b/include/sfx2/mieclip.hxx new file mode 100644 index 000000000..bc2a431b3 --- /dev/null +++ b/include/sfx2/mieclip.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_MIECLIP_HXX +#define INCLUDED_SFX2_MIECLIP_HXX + +#include +#include +#include +#include +#include + +class SFX2_DLLPUBLIC MSE40HTMLClipFormatObj +{ + std::unique_ptr pStrm; + OUString sBaseURL; + +public: + MSE40HTMLClipFormatObj() {} + ~MSE40HTMLClipFormatObj(); + + SvStream* IsValid(SvStream&); +}; + +#endif // INCLUDED_SFX2_MIECLIP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/minfitem.hxx b/include/sfx2/minfitem.hxx new file mode 100644 index 000000000..ce6f8b25a --- /dev/null +++ b/include/sfx2/minfitem.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +#if HAVE_FEATURE_SCRIPTING + +class BasicManager; + +class SFX2_DLLPUBLIC SfxMacroInfoItem final : public SfxPoolItem +{ + const BasicManager* pBasicManager; + OUString aLibName; + OUString aModuleName; + OUString aMethodName; + OUString aCommentText; + +public: + static SfxPoolItem* CreateDefault(); + SfxMacroInfoItem( sal_uInt16 nWhich, + const BasicManager* pMgr, + const OUString &rLibName, + const OUString &rModuleName, + const OUString &rMethodName, + const OUString &rComment); + + virtual SfxMacroInfoItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + const OUString& GetMethod() const + { return aMethodName; } + void SetMethod( const OUString& r ) + { aMethodName = r; } + const OUString& GetModule() const + { return aModuleName; } + void SetModule( const OUString& r ) + { aModuleName = r; } + const OUString& GetLib() const + { return aLibName; } + void SetLib( const OUString& r ) + { aLibName = r; } + const BasicManager* GetBasicManager() const + { return pBasicManager; } + OUString GetQualifiedName() const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/module.hxx b/include/sfx2/module.hxx new file mode 100644 index 000000000..099222c1a --- /dev/null +++ b/include/sfx2/module.hxx @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_MODULE_HXX +#define INCLUDED_SFX2_MODULE_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SfxObjectFactory; +class SfxModule_Impl; +class SfxSlotPool; +struct SfxChildWinFactory; +struct SfxStbCtrlFactory; +struct SfxTbxCtrlFactory; +class SfxTabPage; + +namespace com::sun::star::frame { + class XFrame; +} + +namespace weld { + class Container; + class DialogController; +} + +class SFX2_DLLPUBLIC SfxModule : public SfxShell +{ +private: + // Warning this cannot be turned into a unique_ptr. + // SfxInterface destruction in the SfxSlotPool refers again to pImpl after deletion of pImpl has commenced. See tdf#100270 + SfxModule_Impl* pImpl; + + SAL_DLLPRIVATE void Construct_Impl(const OString& rResName); + +public: + SFX_DECL_INTERFACE(SFX_INTERFACE_SFXMODULE) + +private: + /// SfxInterface initializer. + static void InitInterface_Impl() {} + +public: + + SfxModule(const OString& rResName, std::initializer_list pFactoryList); + virtual ~SfxModule() override; + + std::locale GetResLocale() const; + SfxSlotPool* GetSlotPool() const; + + void RegisterToolBoxControl(const SfxTbxCtrlFactory&); + void RegisterChildWindow(const SfxChildWinFactory&); + void RegisterStatusBarControl(const SfxStbCtrlFactory&); + + virtual std::unique_ptr CreateTabPage( sal_uInt16 nId, + weld::Container* pPage, weld::DialogController* pController, + const SfxItemSet& rSet ); + virtual void Invalidate(sal_uInt16 nId = 0) override; + + virtual std::optional CreateStyleFamilies() { return {}; } + + static SfxModule* GetActiveModule( SfxViewFrame* pFrame=nullptr ); + static FieldUnit GetCurrentFieldUnit(); + /** retrieves the field unit of the module belonging to the document displayed in the given frame + + Effectively, this method looks up the SfxViewFrame belonging to the given XFrame, then the SfxModule belonging to + the document in this frame, then this module's field unit. + + Failures in any of those steps are reported as assertion in non-product builds, and then FieldUnit::MM_100TH is returned. + */ + static FieldUnit GetModuleFieldUnit( css::uno::Reference< css::frame::XFrame > const & i_frame ); + FieldUnit GetFieldUnit() const; + + SAL_DLLPRIVATE SfxTbxCtrlFactory* GetTbxCtrlFactory(const std::type_info& rSlotType, sal_uInt16 nSlotID) const; + SAL_DLLPRIVATE SfxStbCtrlFactory* GetStbCtrlFactory(const std::type_info& rSlotType, sal_uInt16 nSlotID) const; + SAL_DLLPRIVATE SfxChildWinFactory* GetChildWinFactoryById(sal_uInt16 nId) const; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/msg.hxx b/include/sfx2/msg.hxx new file mode 100644 index 000000000..e628e572c --- /dev/null +++ b/include/sfx2/msg.hxx @@ -0,0 +1,264 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_MSG_HXX +#define INCLUDED_SFX2_MSG_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +class SfxItemPool; + +enum class SfxSlotMode { + NONE = 0x0000, // default + + TOGGLE = 0x0004, // inverted for Execute old value + AUTOUPDATE = 0x0008, // invalidated the status automatically after execute + ASYNCHRON = 0x0020, // via Post-Message + + NORECORD = 0x0100, // no recording + RECORDPERITEM = 0x0200, // each item, one statement + RECORDPERSET = 0x0400, // The whole Set is a Statement, default + RECORDABSOLUTE = 0x1000000, // Recording with absolute Target + + METHOD = 0x4000, + + FASTCALL = 0x8000, // No test if disabled before Execute + + MENUCONFIG = 0x20000, // configurable Menu + TOOLBOXCONFIG = 0x40000, // configurable Toolboxen + ACCELCONFIG = 0x80000, // configurable keys + + CONTAINER = 0x100000, // Operated by the container at InPlace + READONLYDOC = 0x200000 // also available for read-only Documents +}; + +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +#define SFX_EXEC_STUB( aShellClass, aExecMethod) \ + void SfxStub##aShellClass##aExecMethod( \ + SfxShell *pShell, SfxRequest& rReq) \ + { \ + ::tools::detail::castTo(pShell)->aExecMethod( rReq ); \ + } + +#define SFX_STATE_STUB( aShellClass, aStateMethod) \ + void SfxStub##aShellClass##aStateMethod( \ + SfxShell *pShell, SfxItemSet& rSet) \ + { \ + static_cast(pShell)->aStateMethod( rSet ); \ + } + +#define SFX_STUB_PTR( aShellClass, aMethod ) \ + &SfxStub##aShellClass##aMethod + +#define SFX_STUB_PTR_EXEC_NONE &SfxShell::EmptyExecStub + +#define SFX_STUB_PTR_STATE_NONE &SfxShell::EmptyStateStub + + +enum class SfxSlotKind +{ + Standard, + Attribute +}; + + +struct SfxTypeAttrib +{ + sal_uInt16 nAID; + const char* pName; +}; + +template SfxPoolItem* createSfxPoolItem() +{ + return T::CreateDefault(); +} +struct SfxType +{ + std::function createSfxPoolItemFunc; + const std::type_info* pType; + sal_uInt16 nAttribs; + SfxTypeAttrib aAttrib[1]; // variable length + + const std::type_info* Type() const{return pType;} + std::unique_ptr CreateItem() const + { return std::unique_ptr(createSfxPoolItemFunc()); } +}; + +struct SfxType0 +{ + std::function createSfxPoolItemFunc; + const std::type_info* pType; + sal_uInt16 nAttribs; + const std::type_info* Type() const { return pType;} +}; +#define SFX_DECL_TYPE(n) struct SfxType##n \ + { \ + std::function createSfxPoolItemFunc; \ + const std::type_info* pType; \ + sal_uInt16 nAttribs; \ + SfxTypeAttrib aAttrib[n]; \ + } + +#define SFX_TYPE(Class) &a##Class##_Impl + +SFX_DECL_TYPE(1); +SFX_DECL_TYPE(2); +SFX_DECL_TYPE(3); +SFX_DECL_TYPE(4); +SFX_DECL_TYPE(5); +SFX_DECL_TYPE(6); +SFX_DECL_TYPE(7); +SFX_DECL_TYPE(8); +SFX_DECL_TYPE(10); // for SfxDocInfoItem +SFX_DECL_TYPE(11); + +SFX_DECL_TYPE(13); // for SwAddPrinterItem, Sd... +SFX_DECL_TYPE(14); +SFX_DECL_TYPE(16); // for SwDocDisplayItem +SFX_DECL_TYPE(17); // for SvxAddressItem +SFX_DECL_TYPE(23); // for SvxSearchItem + +// all SfxTypes must be in this header +#undef SFX_DECL_TYPE + +#define SFX_SLOT_ARG( aShellClass, id, GroupId, ExecMethodPtr, StateMethodPtr, Flags, ItemClass, nArg0, nArgs, Name, Prop ) \ + { id, GroupId, Flags | Prop, \ + USHRT_MAX, 0, \ + ExecMethodPtr, \ + StateMethodPtr, \ + (const SfxType*) &a##ItemClass##_Impl, \ + 0, \ + &a##aShellClass##Args_Impl[nArg0], nArgs, SfxDisableFlags::NONE, Name \ + } + +#define SFX_NEW_SLOT_ARG( aShellClass, id, GroupId, pNext, ExecMethodPtr, StateMethodPtr, Flags, DisableFlags, ItemClass, nArg0, nArgs, Prop, UnoName ) \ + { id, GroupId, Flags | Prop, \ + USHRT_MAX, 0, \ + ExecMethodPtr, \ + StateMethodPtr, \ + (const SfxType*) &a##ItemClass##_Impl, \ + pNext, \ + &a##aShellClass##Args_Impl[nArg0], nArgs, DisableFlags, UnoName \ + } + +struct SfxFormalArgument +{ + const SfxType* pType; // Type of the parameter (SfxPoolItem subclass) + const char* pName; // Name of the sParameters + sal_uInt16 nSlotId; // Slot-Id for identification of the Parameters + + std::unique_ptr CreateItem() const + { return pType->CreateItem(); } +}; + + +class SfxSlot +{ +public: + sal_uInt16 nSlotId; // Unique slot-ID in Shell + SfxGroupId nGroupId; // for configuration region + SfxSlotMode nFlags; // arithmetic ordered Flags + + sal_uInt16 nMasterSlotId; // Enum-Slot for example Which-Id + sal_uInt16 nValue; // Value, in case of Enum-Slot + + SfxExecFunc fnExec; // Function to be executed + SfxStateFunc fnState; // Function for Status + + const SfxType* pType; // SfxPoolItem-Type (Status) + + const SfxSlot* pNextSlot; // with the same Status-Method + + const SfxFormalArgument* pFirstArgDef; // first formal Argument-Definition + sal_uInt16 nArgDefCount; // Number of formal Arguments + SfxDisableFlags nDisableFlags; // DisableFlags that need to be + // present, so that the Slot + // can be enabled + const char* pUnoName; // UnoName for the Slots + +public: + + SfxSlotKind GetKind() const; + sal_uInt16 GetSlotId() const; + SfxSlotMode GetMode() const; + bool IsMode( SfxSlotMode nMode ) const; + SfxGroupId GetGroupId() const; + sal_uInt16 GetWhich( const SfxItemPool &rPool ) const; + const SfxType* GetType() const { return pType; } + const char* GetUnoName() const { return pUnoName; } + SFX2_DLLPUBLIC OString GetCommand() const; + SFX2_DLLPUBLIC OUString GetCommandString() const; + + sal_uInt16 GetFormalArgumentCount() const { return nArgDefCount; } + const SfxFormalArgument& GetFormalArgument( sal_uInt16 nNo ) const + { return pFirstArgDef[nNo]; } + + SfxExecFunc GetExecFnc() const { return fnExec; } + SfxStateFunc GetStateFnc() const { return fnState; } + + const SfxSlot* GetNextSlot() const { return pNextSlot; } +}; + + +// returns the id of the function + +inline sal_uInt16 SfxSlot::GetSlotId() const +{ + return nSlotId; +} + +// returns a bitfield with flags + +inline SfxSlotMode SfxSlot::GetMode() const +{ + return nFlags; +} + + +// determines if the specified mode is assigned + +inline bool SfxSlot::IsMode( SfxSlotMode nMode ) const +{ + return bool(nFlags & nMode); +} + + +// returns the id of the associated group + +inline SfxGroupId SfxSlot::GetGroupId() const +{ + return nGroupId; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/msgpool.hxx b/include/sfx2/msgpool.hxx new file mode 100644 index 000000000..7aa38904c --- /dev/null +++ b/include/sfx2/msgpool.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_MSGPOOL_HXX +#define INCLUDED_SFX2_MSGPOOL_HXX + +#include +#include +#include +#include +#include +#include + +class SfxInterface; +class SfxSlot; +class SfxViewFrame; + +class SFX2_DLLPUBLIC SfxSlotPool +{ + std::vector _vGroups; + SfxSlotPool* _pParentPool; + std::vector _vInterfaces; + sal_uInt16 _nCurGroup; + sal_uInt16 _nCurInterface; + sal_uInt16 _nCurMsg; + +private: + const SfxSlot* SeekSlot( sal_uInt16 nObject ); + +public: + SfxSlotPool(SfxSlotPool* pParent=nullptr); + ~SfxSlotPool(); + + void RegisterInterface( SfxInterface& rFace ); + + static SfxSlotPool& GetSlotPool( SfxViewFrame *pFrame=nullptr ); + + sal_uInt16 GetGroupCount() const; + OUString SeekGroup( sal_uInt16 nNo ); + const SfxSlot* FirstSlot(); + const SfxSlot* NextSlot(); + const SfxSlot* GetSlot( sal_uInt16 nId ) const; + const SfxSlot* GetUnoSlot( const OUString& rUnoName ) const; + const std::type_info* GetSlotType( sal_uInt16 nSlotId ) const; +}; + + +// seeks to the first func in the current group + +inline const SfxSlot* SfxSlotPool::FirstSlot() +{ + return SeekSlot(0); +} + +#define SFX_SLOTPOOL() SfxSlotPool::GetSlotPool() + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/navigat.hxx b/include/sfx2/navigat.hxx new file mode 100644 index 000000000..febdefa81 --- /dev/null +++ b/include/sfx2/navigat.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_NAVIGAT_HXX +#define INCLUDED_SFX2_NAVIGAT_HXX + +#include +#include + +class SFX2_DLLPUBLIC SfxNavigatorWrapper : public SfxChildWindow +{ +protected: + void Initialize(); +public: + SfxNavigatorWrapper(vcl::Window* pParent, sal_uInt16 nId); +}; + +class SFX2_DLLPUBLIC SfxNavigator : public SfxDockingWindow +{ +public: + SfxNavigator(SfxBindings* pBindings, SfxChildWindow* pChildWin, + vcl::Window* pParent, SfxChildWinInfo* pInfo); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/new.hxx b/include/sfx2/new.hxx new file mode 100644 index 000000000..8cb2bd9b4 --- /dev/null +++ b/include/sfx2/new.hxx @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_NEW_HXX +#define INCLUDED_SFX2_NEW_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace weld { class Button; } +namespace weld { class CheckButton; } +namespace weld { class CustomWeld; } +namespace weld { class Expander; } +namespace weld { class Label; } +namespace weld { class TreeView; } +namespace weld { class Window; } + +class SfxPreviewWin_Impl; + +enum class SfxNewFileDialogMode { + NONE, Preview, LoadTemplate +}; + +enum class SfxTemplateFlags +{ + NONE = 0x00, + LOAD_TEXT_STYLES = 0x01, + LOAD_FRAME_STYLES = 0x02, + LOAD_PAGE_STYLES = 0x04, + LOAD_NUM_STYLES = 0x08, + MERGE_STYLES = 0x10, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +#define RET_TEMPLATE_LOAD 100 + +class SFX2_DLLPUBLIC SfxNewFileDialog final : public SfxDialogController +{ +private: + Idle m_aPrevIdle; + SfxNewFileDialogMode m_nFlags; + SfxDocumentTemplates m_aTemplates; + SfxObjectShellLock m_xDocShell; + + std::unique_ptr m_xPreviewController; + + std::unique_ptr m_xRegionLb; + std::unique_ptr m_xTemplateLb; + std::unique_ptr m_xTextStyleCB; + std::unique_ptr m_xFrameStyleCB; + std::unique_ptr m_xPageStyleCB; + std::unique_ptr m_xNumStyleCB; + std::unique_ptr m_xMergeStyleCB; + std::unique_ptr m_xLoadFilePB; + std::unique_ptr m_xMoreBt; + std::unique_ptr m_xPreviewWin; + std::unique_ptr m_xAltTitleFt; + + DECL_DLLPRIVATE_LINK( Update, Timer *, void ); + + DECL_DLLPRIVATE_LINK(RegionSelect, weld::TreeView&, void); + DECL_DLLPRIVATE_LINK(TemplateSelect, weld::TreeView&, void); + DECL_DLLPRIVATE_LINK(DoubleClick, weld::TreeView&, bool); + DECL_DLLPRIVATE_LINK(Expand, weld::Expander&, void); + sal_uInt16 GetSelectedTemplatePos() const; + +public: + SfxNewFileDialog(weld::Window *pParent, SfxNewFileDialogMode nFlags); + virtual ~SfxNewFileDialog() override; + + // Returns false, when '- No -' is set as Template + // Template names can only be obtained when IsTemplate() returns true. + bool IsTemplate() const; + OUString GetTemplateFileName() const; + + // load template methods + SfxTemplateFlags GetTemplateFlags() const; + void SetTemplateFlags(SfxTemplateFlags nSet); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/newstyle.hxx b/include/sfx2/newstyle.hxx new file mode 100644 index 000000000..23dbfa612 --- /dev/null +++ b/include/sfx2/newstyle.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_NEWSTYLE_HXX +#define INCLUDED_SFX2_NEWSTYLE_HXX + +#include +#include +#include +#include +#include + +class SFX2_DLLPUBLIC SfxNewStyleDlg final : public weld::GenericDialogController +{ +private: + SfxStyleSheetBasePool& m_rPool; + SfxStyleFamily m_eSearchFamily; + + std::unique_ptr m_xColBox; + std::unique_ptr m_xOKBtn; + + std::unique_ptr m_xQueryOverwriteBox; + + DECL_DLLPRIVATE_LINK(OKHdl, weld::TreeView&, bool); + DECL_DLLPRIVATE_LINK(OKClickHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(ModifyHdl, weld::ComboBox&, void); + +public: + SfxNewStyleDlg(weld::Widget* pParent, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFam); + virtual ~SfxNewStyleDlg() override; + + OUString GetName() const + { + return comphelper::string::stripStart(m_xColBox->get_active_text(), ' '); + } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/notebookbar/SfxNotebookBar.hxx b/include/sfx2/notebookbar/SfxNotebookBar.hxx new file mode 100644 index 000000000..66286b87c --- /dev/null +++ b/include/sfx2/notebookbar/SfxNotebookBar.hxx @@ -0,0 +1,89 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_NOTEBOOKBAR_SFXNOTEBOOKBAR_HXX +#define INCLUDED_SFX2_NOTEBOOKBAR_SFXNOTEBOOKBAR_HXX + +#include +#include +#include +#include + +#include +#include +#include + +namespace com::sun::star::frame +{ +class XFrame; +} +namespace com::sun::star::uno +{ +template class Reference; +} + +class SfxBindings; +class SfxViewFrame; +class SfxViewShell; +class SystemWindow; +class WeldedTabbedNotebookbar; + +namespace sfx2 +{ +/** Helpers for easier access to NotebookBar via the sfx2 infrastructure. +*/ +class SFX2_DLLPUBLIC SfxNotebookBar +{ +public: + static void CloseMethod(SfxBindings& rBindings); + static void CloseMethod(SystemWindow* pSysWindow); + + static bool IsActive(); + + /// Function to be called from the sdi's ExecMethod. + static void ExecMethod(SfxBindings& rBindings, const OUString& rUIName); + + /// Function to be called from the sdi's StateMethod. + static bool StateMethod(SfxBindings& rBindings, std::u16string_view rUIFile, + bool bReloadNotebookbar = false); + static bool StateMethod(SystemWindow* pSysWindow, + const css::uno::Reference& xFrame, + std::u16string_view rUIFile, bool bReloadNotebookbar = false); + + /// Method temporarily blocks showing of the NotebookBar + static void LockNotebookBar(); + /// Method restores normal behaviour of the Notebookbar + static void UnlockNotebookBar(); + + static void RemoveListeners(SystemWindow const* pSysWindow); + + /** Show menu bar in all frames of current application */ + static void ShowMenubar(bool bShow); + /** Show menu bar only in current frame */ + static void ShowMenubar(SfxViewFrame const* pViewFrame, bool bShow); + static void ToggleMenubar(); + static void ReloadNotebookBar(std::u16string_view sUIPath); + +private: + static bool m_bLock; + static bool m_bHide; + + static std::map> + m_pNotebookBarWeldedWrapper; + + static void ResetActiveToolbarModeToDefault(vcl::EnumContext::Application eApp); + + DECL_DLLPRIVATE_STATIC_LINK(SfxNotebookBar, VclDisposeHdl, const SfxViewShell*, void); +}; + +} // namespace sfx2 + +#endif // INCLUDED_SFX2_NOTEBOOKBAR_SFXNOTEBOOKBAR_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/objface.hxx b/include/sfx2/objface.hxx new file mode 100644 index 000000000..fadf510ca --- /dev/null +++ b/include/sfx2/objface.hxx @@ -0,0 +1,121 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_OBJFACE_HXX +#define INCLUDED_SFX2_OBJFACE_HXX + +#include +#include +#include +#include +#include +#include +#include + +struct SfxInterface_Impl; +class SfxModule; + +#define SFX_OBJECTBAR_APPLICATION 0 +#define SFX_OBJECTBAR_OBJECT 1 +#define SFX_OBJECTBAR_TOOLS 2 +#define SFX_OBJECTBAR_MACRO 3 +#define SFX_OBJECTBAR_FULLSCREEN 4 +#define SFX_OBJECTBAR_RECORDING 5 +#define SFX_OBJECTBAR_COMMONTASK 6 +#define SFX_OBJECTBAR_OPTIONS 7 +#define SFX_OBJECTBAR_NAVIGATION 12 +#define SFX_OBJECTBAR_MAX 13 + +enum class StatusBarId : sal_uInt32 +{ + None = 0, + GenericStatusBar = 4, + WriterStatusBar = 20013, + MathStatusBar = 20816, + DrawStatusBar = 23007, + CalcStatusBar = 26005, + BasicIdeStatusBar = 30805 +}; + +class SFX2_DLLPUBLIC SfxInterface final +{ +friend class SfxSlotPool; + + const char* pName; // Sfx-internal name of interface + const SfxInterface* pGenoType; // base interface + SfxSlot* pSlots; // SlotMap + sal_uInt16 nCount; // number of slots in SlotMap + SfxInterfaceId nClassId; // Id of interface + bool bSuperClass; // Whether children inherit its toolbars etc + std::unique_ptr pImplData; + +public: + SfxInterface( const char *pClass, + bool bSuperClass, + SfxInterfaceId nClassId, + const SfxInterface* pGeno, + SfxSlot &rMessages, sal_uInt16 nMsgCount ); + ~SfxInterface(); + + void SetSlotMap( SfxSlot& rMessages, sal_uInt16 nMsgCount ); + inline sal_uInt16 Count() const; + + const SfxSlot* GetRealSlot( const SfxSlot * ) const; + const SfxSlot* GetSlot( sal_uInt16 nSlotId ) const; + const SfxSlot* GetSlot( const OUString& rCommand ) const; + + const char* GetClassName() const { return pName; } + bool UseAsSuperClass() const { return bSuperClass; } + + const SfxInterface* GetGenoType() const { return pGenoType; } + + void RegisterObjectBar(sal_uInt16, SfxVisibilityFlags nFlags, ToolbarId eId); + void RegisterObjectBar(sal_uInt16, SfxVisibilityFlags nFlags, ToolbarId eId, SfxShellFeature nFeature); + void RegisterChildWindow(sal_uInt16, bool bContext = false); + void RegisterChildWindow(sal_uInt16, bool bContext, SfxShellFeature nFeature); + void RegisterStatusBar(StatusBarId eId); + ToolbarId GetObjectBarId(sal_uInt16 nNo) const; + sal_uInt16 GetObjectBarPos( sal_uInt16 nNo ) const; + SfxVisibilityFlags GetObjectBarFlags( sal_uInt16 nNo ) const; + SfxShellFeature GetObjectBarFeature(sal_uInt16 nNo) const; + sal_uInt16 GetObjectBarCount() const; + bool IsObjectBarVisible( sal_uInt16 nNo) const; + SfxShellFeature GetChildWindowFeature(sal_uInt16 nNo) const; + sal_uInt32 GetChildWindowId( sal_uInt16 nNo ) const; + sal_uInt16 GetChildWindowCount() const; + void RegisterPopupMenu( const OUString& ); + const OUString& GetPopupMenuName() const; + StatusBarId GetStatusBarId() const; + + void Register( const SfxModule* ); + + SAL_DLLPRIVATE bool ContainsSlot_Impl( const SfxSlot *pSlot ) const + { return pSlot >= pSlots && pSlot < pSlots + Count(); } +}; + + +// returns the number of functions in this cluster + +inline sal_uInt16 SfxInterface::Count() const +{ + return nCount; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/objitem.hxx b/include/sfx2/objitem.hxx new file mode 100644 index 000000000..17b7f0cf1 --- /dev/null +++ b/include/sfx2/objitem.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_OBJITEM_HXX +#define INCLUDED_SFX2_OBJITEM_HXX + +#include +#include +#include + +class SfxShell; + +class SFX2_DLLPUBLIC SfxObjectItem final : public SfxPoolItem +{ + SfxShell* _pSh; + +public: + static SfxPoolItem* CreateDefault(); + SfxObjectItem( sal_uInt16 nWhich=0, SfxShell *pSh=nullptr ); + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxObjectItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool QueryValue(css::uno::Any&, sal_uInt8 nMemberId = 0) const override; + virtual bool PutValue(const css::uno::Any&, sal_uInt8) override; + + SfxShell* GetShell() const + { return _pSh; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/objsh.hxx b/include/sfx2/objsh.hxx new file mode 100644 index 000000000..428995bff --- /dev/null +++ b/include/sfx2/objsh.hxx @@ -0,0 +1,918 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_OBJSH_HXX +#define INCLUDED_SFX2_OBJSH_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace weld {class Button; } +class SbxValue; +class SbxArray; +class BasicManager; +class SfxMedium; +class SfxObjectFactory; +class SfxDocumentInfoDialog; +class SfxStyleSheetBasePool; +class StarBASIC; +class Printer; +class SvKeyValueIterator; +class SfxBaseModel; +class SfxModule; +class SfxProgress; +class GDIMetaFile; +class INetURLObject; +class IndexBitSet; +class JobSetup; +class OutputDevice; +class Color; +class Fraction; +class SvGlobalName; +class InfobarData; +class VirtualDevice; + +enum class SfxModelFlags; +enum class SfxEventHintId; +enum class InfobarType; + +// These values presumably must match exactly the corresponding +// css::embed::Aspects ones (in offapi/com/sun/star/embed/Aspects.idl) +// and the DVASPECT_* ones in the Win32 API. + +#define ASPECT_CONTENT 1 +#define ASPECT_THUMBNAIL 2 /* 120 * 120, 6 Colors DIB in MetaFile */ +#define ASPECT_ICON 4 +#define ASPECT_DOCPRINT 8 + +namespace sfx2 +{ + class SvLinkSource; + class StyleManager; +} + +namespace com::sun::star::awt { class XWindow; } +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::document { struct CmisVersion; } +namespace com::sun::star::document { class XDocumentProperties; } +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::graphic { class XGraphic; } +namespace com::sun::star::io { class XStream; } +namespace com::sun::star::script { class XLibraryContainer; } +namespace com::sun::star::security { class XCertificate; } +namespace com::sun::star::security { class XDocumentDigitalSignatures; } +namespace com::sun::star::security { struct DocumentSignatureInformation; } +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::lang { class XComponent; } +namespace com::sun::star::text { class XTextRange; } + +namespace sfx2 { class IXmlIdRegistry; } + +#define SFX_TITLE_TITLE 0 +#define SFX_TITLE_FILENAME 1 +#define SFX_TITLE_FULLNAME 2 +#define SFX_TITLE_APINAME 3 +#define SFX_TITLE_DETECT 4 +#define SFX_TITLE_CAPTION 5 +#define SFX_TITLE_PICKLIST 6 +#define SFX_TITLE_HISTORY 7 +#define SFX_TITLE_MAXLEN 10 // this gives the limits on length + +enum class SfxLoadedFlags +{ + NONE = 0, + MAINDOCUMENT = 1, + IMAGES = 2, + ALL = MAINDOCUMENT | IMAGES +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +enum class HiddenInformation +{ + NONE = 0x0000, + RECORDEDCHANGES = 0x0001, + NOTES = 0x0002, + DOCUMENTVERSIONS = 0x0004 +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace weld { class Window; } + +enum class HiddenWarningFact +{ + WhenSaving = 0, + WhenPrinting, + WhenSigning, + WhenCreatingPDF +}; + +enum class SfxObjectCreateMode +{ + EMBEDDED, + STANDARD, + ORGANIZER, + INTERNAL +}; + +/* + The class SfxObjectShell is the base class for SFx-objects, ie documents + and parts of documents that can be integrated as separate objects + into foreign objects. + There can be multiple edit windows (SfxViewShell) for one SfxObjectShell. +*/ + +struct TransferableObjectDescriptor; +template bool checkSfxObjectShell(const SfxObjectShell* pShell) +{ + return dynamic_cast(pShell) != nullptr; +} + +class SFX2_DLLPUBLIC SfxObjectShell : + public SfxShell, virtual public SotObject, + public ::comphelper::IEmbeddedHelper +{ +friend struct ModifyBlocker_Impl; +friend class SfxObjectShellLock; + +private: + std::unique_ptr pImpl; // internal data + + SfxMedium * pMedium; // Description of the file for example + // storage that contains the object + SfxObjectCreateMode eCreateMode; // Purpose of the object + bool bHasName :1; // sal_True := existing object, + // sal_False := new object + bool bIsInGenerateThumbnail; //optimize thumbnail generate and store procedure to improve odt saving performance, i120030 + bool mbAvoidRecentDocs; ///< Avoid adding to the recent documents list, if not necessary. + + enum TriState {undefined, yes, no}; + TriState mbContinueImportOnFilterExceptions = undefined; // try to import as much as possible + + bool CloseInternal(); + + SAL_DLLPRIVATE void UpdateTime_Impl(const css::uno::Reference< + css::document::XDocumentProperties> & i_xDocProps); + + SAL_DLLPRIVATE bool SaveTo_Impl(SfxMedium &rMedium, const SfxItemSet* pSet ); + +protected: + SfxObjectShell(SfxObjectCreateMode); + SfxObjectShell(SfxModelFlags); // see sfxmodelfactory.hxx + virtual ~SfxObjectShell() override; + + void ModifyChanged(); + virtual bool Close() override; + + /// template method, called by FlushDocInfo; this implementation is empty + virtual void DoFlushDocInfo(); + + // helper method + void AddToRecentlyUsedList(); + + // Parent class for actual guard objects that would do useful work + class LockAllViewsGuard + { + public: + virtual ~LockAllViewsGuard() {} + }; + +public: + SFX_DECL_INTERFACE(SFX_INTERFACE_SFXDOCSH) + +private: + /// SfxInterface initializer. + static void InitInterface_Impl(); + +public: + static const css::uno::Sequence& getUnoTunnelId(); + /* Stampit disable/enable cancel button for print jobs + default = true = enable! */ + void Stamp_SetPrintCancelState(bool bState); + bool Stamp_GetPrintCancelState() const; + + static OUString CreateShellID( const SfxObjectShell* pShell ); + + // Document-Shell Iterator + static SfxObjectShell* GetFirst( const std::function& isObjectShell = nullptr, + bool bOnlyVisible = true ); + static SfxObjectShell* GetNext( const SfxObjectShell& rPrev, + const std::function& isObjectShell = nullptr, + bool bOnlyVisible = true ); + static SfxObjectShell* Current(); + static css::uno::Reference< css::uno::XInterface > + GetCurrentComponent(); + static void SetCurrentComponent( const css::uno::Reference< css::uno::XInterface >& _rxComponent ); + + virtual void Invalidate(sal_uInt16 nId = 0) override; + + SfxModule* GetModule() const; + + virtual SfxObjectFactory& GetFactory() const=0; + SfxMedium * GetMedium() const { return pMedium; } + css::uno::Reference< css::document::XDocumentProperties > + getDocProperties() const; + void UpdateDocInfoForSave( ); + void FlushDocInfo(); + bool HasName() const { return bHasName; } + OUString GetAPIName() const; + void SetReadOnly(); + bool IsReadOnly() const; + bool IsReadOnlyMedium() const; + bool IsOriginallyReadOnlyMedium() const; + bool IsOriginallyLoadedReadOnlyMedium() const; + void SetReadOnlyUI( bool bReadOnly = true ); + bool IsReadOnlyUI() const; + void SetNoName(); + bool IsInModalMode() const; + bool IsInPrepareClose() const; + bool AcceptStateUpdate() const; + bool IsHelpDocument() const; + + bool IsDocShared() const; + OUString GetSharedFileURL() const; + bool SwitchToShared( bool bShared, bool bSave ); + SAL_DLLPRIVATE void FreeSharedFile( const OUString& aTempFileURL ); + SAL_DLLPRIVATE void DoNotCleanShareControlFile(); + void SetSharedXMLFlag( bool bFlag ) const; + bool HasSharedXMLFlagSet() const; + + SAL_DLLPRIVATE void SetModalMode_Impl(bool bModal); + SAL_DLLPRIVATE void SetMacroMode_Impl(bool bModal=true); + + void ResetError(); + ErrCode GetError() const; + ErrCode GetErrorCode() const; + void SetError(ErrCode rErr); + + /** + * Initialize bare minimum just enough for unit test runs. + * + * @return true if the initialization is successful, false otherwise. + */ + void DoInitUnitTest(); + bool DoInitNew(); + bool DoLoad( SfxMedium* pMedium ); + bool DoLoadExternal( SfxMedium* pMed ); + bool DoSave(); + bool DoSaveAs( SfxMedium &rNewStor ); + bool DoSaveObjectAs( SfxMedium &rNewStor, bool bCommit ); + + // TODO/LATER: currently only overridden in Calc, should be made non-virtual + virtual bool DoSaveCompleted( SfxMedium* pNewStor=nullptr, bool bRegisterRecent=true ); + /// Terminate any in-flight editing. Used before saving, primarily by Calc to commit cell changes. + virtual void TerminateEditing() {} + + bool LoadOwnFormat( SfxMedium& pMedium ); + virtual bool SaveAsOwnFormat( SfxMedium& pMedium ); + virtual bool ConvertFrom( SfxMedium &rMedium ); + virtual bool ConvertTo( SfxMedium &rMedium ); + virtual bool InitNew( const css::uno::Reference< css::embed::XStorage >& xStorage ); + virtual bool Load( SfxMedium &rMedium ); + virtual bool LoadFrom( SfxMedium& rMedium ); + virtual bool Save(); + virtual bool SaveAs( SfxMedium &rMedium ); + virtual bool SaveCompleted( const css::uno::Reference< css::embed::XStorage >& xStorage ); + bool SwitchPersistence( + const css::uno::Reference< css::embed::XStorage >& xStorage ); + virtual void UpdateLinks(); + virtual bool LoadExternal( SfxMedium& rMedium ); + bool IsConfigOptionsChecked() const; + void SetConfigOptionsChecked( bool bChecked ); + + // called for a few slots like SID_SAVE[AS]DOC, SID_PRINTDOC[DIRECT], derived classes may abort the action + virtual bool QuerySlotExecutable( sal_uInt16 nSlotId ); + + void SaveChildren(bool bObjectsOnly=false); + bool SaveAsChildren( SfxMedium &rMedium ); + bool SwitchChildrenPersistence( + const css::uno::Reference< css::embed::XStorage >& xStorage, + bool bForceNonModified = false ); + bool SaveCompletedChildren(); + + /** a very special case to insert at a position in Writer from UNO, + via OwnSubFilterService */ + virtual bool InsertGeneratedStream(SfxMedium& rMedium, + css::uno::Reference const& xInsertPosition); + virtual bool ImportFrom( SfxMedium &rMedium, + css::uno::Reference const& xInsertPosition); + bool ExportTo( SfxMedium &rMedium ); + + /** Returns true if preparing was successful, else false. */ + bool PrepareForSigning(weld::Window* pDialogParent); + bool CheckIsReadonly(bool bSignScriptingContent, weld::Window* pDialogParent = nullptr); + void RecheckSignature(bool bAlsoRecheckScriptingSignature); + void AfterSigning(bool bSignSuccess, bool bSignScriptingContent); + bool HasValidSignatures() const; + SignatureState GetDocumentSignatureState(); + void SignDocumentContent(weld::Window* pDialogParent); + css::uno::Sequence GetDocumentSignatureInformation( + bool bScriptingContent, + const css::uno::Reference& xSigner + = css::uno::Reference()); + + bool SignDocumentContentUsingCertificate(const css::uno::Reference& xCertificate); + + void SignSignatureLine(weld::Window* pDialogParent, const OUString& aSignatureLineId, + const css::uno::Reference& xCert, + const css::uno::Reference& xValidGraphic, + const css::uno::Reference& xInvalidGraphic, + const OUString& aComment); + SignatureState GetScriptingSignatureState(); + void SignScriptingContent(weld::Window* pDialogParent); + DECL_DLLPRIVATE_LINK(SignDocumentHandler, weld::Button&, void); + + virtual std::shared_ptr CreateDocumentInfoDialog(weld::Window* pParent, const SfxItemSet& rItemSet); + + ErrCode CallBasic( std::u16string_view rMacro, std::u16string_view rBasicName, + SbxArray* pArgs, SbxValue* pRet = nullptr ); + + ErrCode CallXScript( + const OUString& rScriptURL, + const css::uno::Sequence< css::uno::Any >& aParams, + css::uno::Any& aRet, + css::uno::Sequence< sal_Int16 >& aOutParamIndex, + css::uno::Sequence< css::uno::Any >& aOutParam, + bool bRaiseError = true, + const css::uno::Any* aCaller = nullptr ); + + static ErrCode CallXScript( + const css::uno::Reference< css::uno::XInterface >& _rxScriptContext, + const OUString& rScriptURL, + const css::uno::Sequence< css::uno::Any >& aParams, + css::uno::Any& aRet, + css::uno::Sequence< sal_Int16 >& aOutParamIndex, + css::uno::Sequence< css::uno::Any >& aOutParam, + bool bRaiseError = true, + const css::uno::Any* aCaller = nullptr + ); + + /** adjusts the internal macro mode, according to the current security settings + + Finally, the macro mode is either NEVER_EXECUTE or ALWAYS_EXECUTE_NO_WARN. + + @return + whether macros from this document should be executed + */ + bool AdjustMacroMode(); + + static bool UnTrustedScript(const OUString& rScriptURL); + + static bool isScriptAccessAllowed(const css::uno::Reference& rScriptContext); + + SvKeyValueIterator* GetHeaderAttributes(); + void ClearHeaderAttributesForSourceViewHack(); + void SetHeaderAttributesForSourceViewHack(); + + bool IsQueryLoadTemplate() const; + bool IsUseUserData() const; + bool IsUseThumbnailSave() const; + bool IsLoadReadonly() const; + bool IsSaveVersionOnClose() const; + void SetQueryLoadTemplate( bool b ); + void SetUseUserData( bool bNew ); + void SetUseThumbnailSave( bool _bNew ); + void SetLoadReadonly( bool _bReadonly ); + void SetSaveVersionOnClose( bool bSet ); + void ResetFromTemplate( const OUString& rTemplateName, const OUString& rFileName ); + + // TODO/LATER: the following two methods should be replaced by Get/SetModifPasswordInfo in future + sal_uInt32 GetModifyPasswordHash() const; + bool SetModifyPasswordHash( sal_uInt32 nHash ); + + void SetMacroCallsSeenWhileLoading(); + bool GetMacroCallsSeenWhileLoading() const; + + const css::uno::Sequence< css::beans::PropertyValue >& GetModifyPasswordInfo() const; + bool SetModifyPasswordInfo( const css::uno::Sequence< css::beans::PropertyValue >& aInfo ); + + static ErrCode HandleFilter( SfxMedium* pMedium, SfxObjectShell const * pDoc ); + + virtual bool PrepareClose(bool bUI = true); + virtual HiddenInformation GetHiddenInformationState( HiddenInformation nStates ); + sal_Int16 QueryHiddenInformation( HiddenWarningFact eFact, weld::Window* pParent ); + bool IsSecurityOptOpenReadOnly() const; + void SetSecurityOptOpenReadOnly( bool bOpenReadOnly ); + + Size GetFirstPageSize() const; + bool DoClose(); + std::shared_ptr GetPreviewMetaFile( bool bFullContent = false ) const; + BitmapEx GetPreviewBitmap() const; + virtual void CancelTransfers(); + + bool GenerateAndStoreThumbnail( + bool bEncrypted, + const css::uno::Reference< css::embed::XStorage >& xStor ); + + bool WriteThumbnail( + bool bEncrypted, + const css::uno::Reference< css::io::XStream >& xStream ); + + bool IsInGenerateAndStoreThumbnail() const {return bIsInGenerateThumbnail;}//optimize thumbnail generate and store procedure to improve odt saving performance, i120030 + + /// Don't add to the recent documents - it's an expensive operation, sometimes it is not wanted. + bool IsAvoidRecentDocs() const { return mbAvoidRecentDocs; } + + /// Don't add to the recent documents - it's an expensive operation, sometimes it is not wanted. + void AvoidRecentDocs(bool bAvoid) { mbAvoidRecentDocs = bAvoid; } + + /// On first error ask user if import should continue; return saved answer. + bool IsContinueImportOnFilterExceptions(std::u16string_view aErrMessage); + + // Transfer IFace + bool IsAbortingImport() const; + void FinishedLoading( SfxLoadedFlags nWhich = SfxLoadedFlags::ALL ); + + void TemplateDisconnectionAfterLoad(); + void SetLoading(SfxLoadedFlags nFlags); + bool IsLoading() const; + bool IsLoadingFinished() const; + void SetAutoLoad( const INetURLObject&, sal_uInt32 nTime, bool bReload ); + bool IsAutoLoadLocked() const; + + // Misc + bool IsPreview() const; + SfxObjectCreateMode GetCreateMode() const { return eCreateMode; } + SfxProgress* GetProgress() const; + void SetWaitCursor( bool bSet ) const; + + // Naming Interface + void SetTitle( const OUString& rTitle ); + /* Small non-zero values of nMaxLen don't mean length, but have a magic meaning: + 0 (default) + the title itself, as it is + + 1 (==SFX_TITLE_FILENAME) + provides the logical file name without path + (under WNT depending on the system settings + without extension) + + 2 (==SFX_TITLE_FULLNAME) + provides the logical file names with full path + (remote =>:: com:: sun:: star:: util:: URL) + + 3 (==SFX_TITLE_APINAME) + provides the logical filename without path + and extension + + 4 (==SFX_TITLE_DETECT) + provides the complete title, if not set yet + it will be created from DocInfo or the name of + the medium. + + 5 (==SFX_TITLE_CAPTION) + provides the Title just like MB now in the + CaptionBar view + + 6 (==SFX_TITLE_PICKLIST) + returns the Title, just like MB now would + display it in the PickList + + 7 (==SFX_TITLE_HISTORY) + returns the Title just like MB now would + display it in the History + + 10 bis USHRT_MAX + provides the 'nMaxLength' of the logical + file name including the path + (remote => css::util::URL) + */ + OUString GetTitle( sal_uInt16 nMaxLen = 0 ) const; + void InvalidateName(); // Re-set to unnamed + +#if defined(_WIN32) + // DDE-Interface + bool DdeExecute( const OUString& rCmd ); + virtual bool DdeGetData( const OUString& rItem, + const OUString& rMimeType, + css::uno::Any & rValue ); + virtual bool DdeSetData( const OUString& rItem, + const OUString& rMimeType, + const css::uno::Any & rValue ); +#endif + virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const OUString& rItem ); + virtual void ReconnectDdeLink(SfxObjectShell& rServer); + + static void ReconnectDdeLinks(SfxObjectShell& rServer); + + // Contents + virtual SfxStyleSheetBasePool* GetStyleSheetPool(); + + virtual void LoadStyles(SfxObjectShell &rSource); + + virtual sfx2::StyleManager* GetStyleManager(); + + // Determine the position of the "Automatic" filter in the stylist + void SetAutoStyleFilterIndex(sal_uInt16 nSet); + sal_uInt16 GetAutoStyleFilterIndex() const; + bool HasBasic() const; + BasicManager* GetBasicManager() const; + css::uno::Reference< css::script::XLibraryContainer > + GetBasicContainer(); + css::uno::Reference< css::script::XLibraryContainer > + GetDialogContainer(); + StarBASIC* GetBasic() const; + + virtual std::set GetDocColors(); + virtual std::vector GetThemeColors(); + + // Accessibility Check + virtual sfx::AccessibilityIssueCollection runAccessibilityCheck(); + + // Documents, for which to format the view size + + virtual SfxObjectShell* GetObjectShell() override; + + css::uno::Reference< css::frame::XModel3 > + GetModel() const; + // Only temporarily for the applications! + void SetBaseModel( SfxBaseModel* pModel ); + css::uno::Reference< css::frame::XModel3 > GetBaseModel() const; + // Only temporarily for the applications! + + virtual css::uno::Sequence< OUString > GetEventNames(); + + css::uno::Reference GetDialogParent(SfxMedium const* pMedium = nullptr); + static SfxObjectShell* CreateObject( const OUString& rServiceName, SfxObjectCreateMode = SfxObjectCreateMode::STANDARD ); + static SfxObjectShell* CreateObjectByFactoryName( const OUString& rURL, SfxObjectCreateMode = SfxObjectCreateMode::STANDARD ); + static css::uno::Reference< css::lang::XComponent > + CreateAndLoadComponent( const SfxItemSet& rSet ); + static SfxObjectShell* GetShellFromComponent(const css::uno::Reference< css::uno::XInterface >& xComp); + static SfxObjectShell* GetParentShell(const css::uno::Reference& xChild); + static OUString GetServiceNameFromFactory( const OUString& rFact ); + bool IsInPlaceActive() const; + bool IsUIActive() const; + + static bool CopyStoragesOfUnknownMediaType( + const css::uno::Reference< css::embed::XStorage >& xSource, + const css::uno::Reference& xTarget, + const css::uno::Sequence& rExceptions = css::uno::Sequence()); + + bool isEditDocLocked() const; + bool isContentExtractionLocked() const; + bool isExportLocked() const; + bool isPrintLocked() const; + bool isSaveLocked() const; + + // The functions from SvPersist + void EnableSetModified( bool bEnable = true ); + bool IsEnableSetModified() const; + virtual void SetModified( bool bModified = true ); + bool IsModified() const; + + /** + * @param bChart true if the file is a chart doc and FillClass should not be called + */ + void SetupStorage( + const css::uno::Reference< css::embed::XStorage >& xStorage, + sal_Int32 nVersion, bool bTemplate ) const; + + css::uno::Reference< css::embed::XStorage > const & GetStorage(); + + SvGlobalName const & GetClassName() const; + + // comphelper::IEmbeddedHelper + virtual css::uno::Reference< css::task::XInteractionHandler > getInteractionHandler() const override; + virtual css::uno::Reference < css::embed::XStorage > getStorage() const override + { + return const_cast(this)->GetStorage(); + } + virtual comphelper::EmbeddedObjectContainer& getEmbeddedObjectContainer() const override + { + return GetEmbeddedObjectContainer(); + } + bool isEnableSetModified() const override + { + return IsEnableSetModified(); + } + virtual OUString getDocumentBaseURL() const override; + + comphelper::EmbeddedObjectContainer& GetEmbeddedObjectContainer() const; + void ClearEmbeddedObjects(); + + // The functions from SvEmbeddedObject + virtual Printer * GetDocumentPrinter(); + virtual OutputDevice* GetDocumentRefDev(); + virtual void OnDocumentPrinterChanged( Printer * pNewPrinter ); + virtual tools::Rectangle GetVisArea( sal_uInt16 nAspect ) const; + virtual void SetVisArea( const tools::Rectangle & rVisArea ); + const tools::Rectangle & GetVisArea() const; + void SetVisAreaSize( const Size & rVisSize ); + + MapUnit GetMapUnit() const; + void SetMapUnit( MapUnit nMUnit ); + + void FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc ) const; + void DoDraw( OutputDevice *, const Point & rObjPos, + const Size & rSize, + const JobSetup & rSetup, + sal_uInt16 nAspect = ASPECT_CONTENT ); + virtual void Draw( OutputDevice *, const JobSetup & rSetup, + sal_uInt16 nAspect ) = 0; + + + virtual void FillClass( SvGlobalName * pClassName, + SotClipboardFormatId * pFormat, + OUString * pFullTypeName, + sal_Int32 nVersion, + bool bTemplate = false) const = 0; + + // change recording and respective passwword protection for Writer and Calc + // slots available for Writer: FN_REDLINE_ON, FN_REDLINE_ON + // slots used for Calc: FID_CHG_RECORD, SID_CHG_PROTECT + virtual bool IsChangeRecording() const; + virtual bool HasChangeRecordProtection() const; + virtual void SetChangeRecording( bool bActivate, bool bLockAllViews = false ); + virtual void SetProtectionPassword( const OUString &rPassword ); + virtual bool GetProtectionHash( /*out*/ css::uno::Sequence< sal_Int8 > &rPasswordHash ); + + static bool IsOwnStorageFormat(const SfxMedium &); + + /** Append Infobar once the frame is ready. + Useful when you want to register an Infobar before the doc/frame is fully loaded. */ + void AppendInfoBarWhenReady(const OUString& sId, const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, InfobarType aInfobarType, + bool bShowCloseButton = true); + std::vector& getPendingInfobars(); + + SAL_DLLPRIVATE bool CreatePreview_Impl(bool bFullContent, VirtualDevice* pDevice, GDIMetaFile* pFile) const; + + SAL_DLLPRIVATE static bool IsPackageStorageFormat_Impl(const SfxMedium &); + + SAL_DLLPRIVATE bool ConnectTmpStorage_Impl( const css::uno::Reference< css::embed::XStorage >& xStorage, SfxMedium* pMedium ); + SAL_DLLPRIVATE bool DisconnectStorage_Impl( SfxMedium& rSrcMedium, SfxMedium& rTargetMedium ); + + SAL_DLLPRIVATE bool PutURLContentsToVersionStream_Impl( + const OUString& aURL, + const css::uno::Reference< css::embed::XStorage >& xDocStorage, + const OUString& aStreamName ); + + SAL_DLLPRIVATE OUString CreateTempCopyOfStorage_Impl( + const css::uno::Reference< css::embed::XStorage >& xStorage ); + + SAL_DLLPRIVATE void InitOwnModel_Impl(); + SAL_DLLPRIVATE void BreakMacroSign_Impl( bool bBreakMacroSing ); + SAL_DLLPRIVATE void CheckSecurityOnLoading_Impl(); + SAL_DLLPRIVATE void CheckForBrokenDocSignatures_Impl(); + SAL_DLLPRIVATE void CheckEncryption_Impl( const css::uno::Reference< css::task::XInteractionHandler >& xHandler ); + SAL_DLLPRIVATE void SetModifyPasswordEntered( bool bEntered = true ); + SAL_DLLPRIVATE bool IsModifyPasswordEntered() const; + + SAL_DLLPRIVATE void InitBasicManager_Impl(); + SAL_DLLPRIVATE SfxObjectShell_Impl* Get_Impl() { return pImpl.get(); } + + SAL_DLLPRIVATE static bool UseInteractionToHandleError( + const css::uno::Reference< css::task::XInteractionHandler >& xHandler, + ErrCode nError ); + SAL_DLLPRIVATE const SfxObjectShell_Impl* Get_Impl() const { return pImpl.get(); } + + SAL_DLLPRIVATE void SetCreateMode_Impl( SfxObjectCreateMode nMode ); + + SAL_DLLPRIVATE void DoDraw_Impl( OutputDevice* pDev, + const Point & rViewPos, + const Fraction & rScaleX, + const Fraction & rScaleY, + const JobSetup & rSetup, + sal_uInt16 nAspect ); + + // Shell Interface + SAL_DLLPRIVATE void ExecFile_Impl(SfxRequest &); + SAL_DLLPRIVATE void GetState_Impl(SfxItemSet&); + SAL_DLLPRIVATE void PrintExec_Impl(SfxRequest &); + SAL_DLLPRIVATE void PrintState_Impl(SfxItemSet&); + SAL_DLLPRIVATE void ExecProps_Impl(SfxRequest &); + SAL_DLLPRIVATE void StateProps_Impl(SfxItemSet &); + SAL_DLLPRIVATE void ExecView_Impl(SfxRequest &); + SAL_DLLPRIVATE static void StateView_Impl(SfxItemSet &); + + // Load/Save public internals + SAL_DLLPRIVATE bool ImportFromGeneratedStream_Impl( + const css::uno::Reference< css::io::XStream >& xStream, + const css::uno::Sequence< css::beans::PropertyValue >& aMediaDescr ); + SAL_DLLPRIVATE void UpdateFromTemplate_Impl(); + SAL_DLLPRIVATE bool CanReload_Impl(); + SAL_DLLPRIVATE void SetNamedVisibility_Impl(); + SAL_DLLPRIVATE bool DoSave_Impl( const SfxItemSet* pSet ); + SAL_DLLPRIVATE bool Save_Impl( const SfxItemSet* pSet ); + SAL_DLLPRIVATE bool + PreDoSaveAs_Impl(const OUString& rFileName, const OUString& rFiltName, + SfxItemSet const& rItemSet, + const css::uno::Sequence& rArgs); + SAL_DLLPRIVATE bool APISaveAs_Impl(std::u16string_view aFileName, SfxItemSet& rItemSet, + const css::uno::Sequence& rArgs); + SAL_DLLPRIVATE bool + CommonSaveAs_Impl(const INetURLObject& aURL, const OUString& aFilterName, SfxItemSet& rItemSet, + const css::uno::Sequence& rArgs); + SAL_DLLPRIVATE bool GeneralInit_Impl( + const css::uno::Reference< css::embed::XStorage >& xStorage, + bool bTypeMustBeSetAlready ); + SAL_DLLPRIVATE void PrepareSecondTryLoad_Impl(); + SAL_DLLPRIVATE void SetInitialized_Impl( const bool i_fromInitNew ); + + // public-internals + SAL_DLLPRIVATE IndexBitSet& GetNoSet_Impl(); + SAL_DLLPRIVATE void SetProgress_Impl( SfxProgress *pProgress ); + SAL_DLLPRIVATE void PostActivateEvent_Impl( SfxViewFrame const * ); + SAL_DLLPRIVATE void SetActivateEvent_Impl(SfxEventHintId ); + + // configuration items + SAL_DLLPRIVATE SignatureState ImplGetSignatureState( bool bScriptingContent = false ); + + SAL_DLLPRIVATE bool QuerySaveSizeExceededModules_Impl( const css::uno::Reference< css::task::XInteractionHandler >& xHandler ); + SAL_DLLPRIVATE static bool QueryAllowExoticFormat_Impl( const css::uno::Reference< css::task::XInteractionHandler >& xHandler, + const OUString& rURL, + const OUString& rFilterUIName); + + SAL_DLLPRIVATE void CheckOut( ); + SAL_DLLPRIVATE void CancelCheckOut( ); + SAL_DLLPRIVATE void CheckIn( ); + SAL_DLLPRIVATE css::uno::Sequence< css::document::CmisVersion > GetCmisVersions() const; + + /** override this if you have a XmlIdRegistry. */ + virtual const sfx2::IXmlIdRegistry* GetXmlIdRegistry() const { return nullptr; } + + /// Is this read-only object shell opened via .uno:SignPDF? + bool IsSignPDF() const; + + /// Gets the certificate that is already picked by the user but not yet used for signing. + css::uno::Reference GetSignPDFCertificate() const; + + /// Gets grab-bagged password info to unprotect change tracking with verification + css::uno::Sequence< css::beans::PropertyValue > GetDocumentProtectionFromGrabBag() const; + + // Lock all unlocked views, and returns a guard object which unlocks those views when destructed + virtual std::unique_ptr LockAllViews() + { + return std::make_unique(); + } + +}; + +#define SFX_GLOBAL_CLASSID \ + 0x9eaba5c3, 0xb232, 0x4309, \ + 0x84, 0x5f, 0x5f, 0x15, 0xea, 0x50, 0xd0, 0x74 + + struct ModifyBlocker_Impl + { + SfxObjectShell* pPersist; + bool bWasEnabled; + ModifyBlocker_Impl( SfxObjectShell* pPersistP ) : pPersist( pPersistP ) + { + bWasEnabled = pPersistP->IsEnableSetModified(); + if ( bWasEnabled ) + pPersistP->EnableSetModified( false ); + } + ~ModifyBlocker_Impl() + { + if ( bWasEnabled ) + pPersist->EnableSetModified( bWasEnabled ); + } + }; + + +typedef tools::SvRef SfxObjectShellRef; + +class SfxObjectShellLock +{ + SfxObjectShell * pObj; +public: + SfxObjectShellLock() { pObj = nullptr; } + inline SfxObjectShellLock( const SfxObjectShellLock & rObj ); + inline SfxObjectShellLock( SfxObjectShellLock && rObj ) noexcept; + inline SfxObjectShellLock( SfxObjectShell * pObjP ); + inline void Clear(); + inline ~SfxObjectShellLock(); + inline SfxObjectShellLock & operator = ( const SfxObjectShellLock & rObj ); + inline SfxObjectShellLock & operator = ( SfxObjectShellLock && rObj ); + inline SfxObjectShellLock & operator = ( SfxObjectShell * pObj ); + bool Is() const { return pObj != nullptr; } + SfxObjectShell * operator & () const { return pObj; } + SfxObjectShell * operator -> () const { return pObj; } + SfxObjectShell & operator * () const { return *pObj; } + operator SfxObjectShell * () const { return pObj; } +}; +inline SfxObjectShellLock::SfxObjectShellLock( const SfxObjectShellLock & rObj ) +{ + pObj = rObj.pObj; + if( pObj ) + pObj->OwnerLock( true ); +} +inline SfxObjectShellLock::SfxObjectShellLock( SfxObjectShellLock && rObj ) noexcept +{ + pObj = rObj.pObj; + rObj.pObj = nullptr; +} +inline SfxObjectShellLock::SfxObjectShellLock( SfxObjectShell * pObjP ) +{ + pObj = pObjP; + if( pObj ) + pObj->OwnerLock( true ); +} +inline void SfxObjectShellLock::Clear() +{ + if( pObj ) + { + SfxObjectShell* const pRefObj = pObj; + pObj = nullptr; + pRefObj->OwnerLock( false ); + } +} +inline SfxObjectShellLock::~SfxObjectShellLock() +{ + if( pObj ) + pObj->OwnerLock( false ); +} +inline SfxObjectShellLock & SfxObjectShellLock::operator=( const SfxObjectShellLock & rObj ) +{ + if( rObj.pObj ) + rObj.pObj->OwnerLock( true ); + SfxObjectShell* const pRefObj = pObj; + pObj = rObj.pObj; + if( pRefObj ) + pRefObj->OwnerLock( false ); + return *this; +} +inline SfxObjectShellLock & SfxObjectShellLock::operator=( SfxObjectShellLock && rObj ) +{ + if (pObj) + pObj->OwnerLock( false ); + pObj = rObj.pObj; + rObj.pObj = nullptr; + return *this; +} +inline SfxObjectShellLock & SfxObjectShellLock::operator=( SfxObjectShell * pObjP ) +{ + *this = SfxObjectShellLock( pObjP ); + return *this; +} + +class SFX2_DLLPUBLIC SfxObjectShellItem final : public SfxPoolItem +{ + SfxObjectShell* pObjSh; + +public: + static SfxPoolItem* CreateDefault(); + + SfxObjectShellItem() : + SfxPoolItem( 0 ), + pObjSh( nullptr ) + {} + SfxObjectShellItem( sal_uInt16 nWhichId, + SfxObjectShell *pObjShell ): + SfxPoolItem( nWhichId ), + pObjSh( pObjShell ) + {} + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxObjectShellItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/opengrf.hxx b/include/sfx2/opengrf.hxx new file mode 100644 index 000000000..d28f88c4f --- /dev/null +++ b/include/sfx2/opengrf.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_OPENGRF_HXX +#define INCLUDED_SFX2_OPENGRF_HXX + +#include +#include +#include +#include + +namespace com::sun::star::ui::dialogs { class XFilePickerControlAccess; } +namespace com::sun::star::uno { template class Reference; } +namespace weld { class Window; } + +class Graphic; +struct SvxOpenGrf_Impl; + +class SFX2_DLLPUBLIC SvxOpenGraphicDialog +{ +public: + SvxOpenGraphicDialog(const OUString& rTitle, weld::Window* pPreferredParent); + SvxOpenGraphicDialog(const OUString& rTitle, weld::Window* pPreferredParent, + sal_Int16 nDialogType); + ~SvxOpenGraphicDialog(); + + ErrCode Execute(); + + void SetPath( const OUString& rPath, bool bLinkState ); + OUString GetPath() const; + + ErrCode GetGraphic(Graphic&) const; + + void EnableLink(bool); + void AsLink(bool); + bool IsAsLink() const; + + //what the dialog thought the format was + OUString GetCurrentFilter() const; + void SetCurrentFilter(const OUString&); + + //what was subsequently found to be the format + OUString const & GetDetectedFilter() const; + void SetDetectedFilter(const OUString&); + + css::uno::Reference const & GetFilePickerControlAccess() const; + +private: + SvxOpenGraphicDialog (const SvxOpenGraphicDialog&) = delete; + SvxOpenGraphicDialog& operator = ( const SvxOpenGraphicDialog & ) = delete; + + const std::unique_ptr< SvxOpenGrf_Impl > mpImpl; +}; + +#endif // _SVX_OPENGRF_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/pageids.hxx b/include/sfx2/pageids.hxx new file mode 100644 index 000000000..9371848b7 --- /dev/null +++ b/include/sfx2/pageids.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_PAGEIDS_HXX +#define INCLUDED_SFX2_PAGEIDS_HXX + +#include + +#define RID_OPTIONS_START (SID_LIB_START + 2000) +// RID_OPTIONS_END (RID_OPTIONS_START + 100) + +// ResId's ------------------------------------------------------------------ + +#define RID_SFXPAGE_SAVE (RID_OPTIONS_START + 0) +#define RID_SFXPAGE_GENERAL (RID_OPTIONS_START + 1) +#define RID_SFXPAGE_PATH (RID_OPTIONS_START + 6) +#define RID_SFXPAGE_LINGU (RID_OPTIONS_START + 7) + +#define RID_SFXPAGE_PRINTOPTIONS (RID_OPTIONS_START + 12) + +// treeopt +#define RID_SVXPAGE_COLOR (RID_SVX_START + 60) +#define OFA_TP_LANGUAGES_FOR_SET_DOCUMENT_LANGUAGE ( RID_OFA_START + 256 ) + +// options +#define RID_SVXPAGE_ONLINEUPDATE (RID_SVX_START + 298) +#define RID_SVXPAGE_INET_SECURITY (RID_SVX_START + 200) +#define RID_SVXPAGE_INET_PROXY (RID_SVX_START + 157) +#define RID_SVXPAGE_INET_MAIL (RID_SVX_START + 155) +#define RID_OFAPAGE_HTMLOPT (RID_OFA_START + 100) +#define OFA_TP_LANGUAGES (RID_OFA_START + 205) +#define OFA_TP_MISC (RID_OFA_START + 200) +#define OFA_TP_VIEW (RID_OFA_START + 202) +#define RID_OFAPAGE_MSFILTEROPT2 (RID_OFA_START + 121) +#define RID_SVXPAGE_OPTIONS_CTL (RID_SVX_START + 252) +#define RID_SVXPAGE_OPTIONS_JAVA (RID_SVX_START + 253) +#define RID_SVXPAGE_ACCESSIBILITYCONFIG (RID_SVX_START + 250) +#define RID_SVXPAGE_ASIAN_LAYOUT (RID_SVX_START + 246) +#define RID_OPTPAGE_CHART_DEFCOLORS (RID_SVX_START + 299) +#define RID_SVXPAGE_PERSONALIZATION (RID_SVX_START + 247) +#define RID_SVXPAGE_COLORCONFIG (RID_SVX_START + 249) +#define RID_SVXPAGE_BASICIDE_OPTIONS (RID_SVX_START + 209) +#define RID_SVXPAGE_LANGTOOL_OPTIONS (RID_SVX_START + 210) + +// Resource-Id's ------------------------------------------------------------ + +// options +#define RID_SVXPAGE_JSEARCH_OPTIONS (RID_SVX_START + 840) +#define RID_SVX_FONT_SUBSTITUTION (RID_SVX_START + 18) + +#define RID_SVXPAGE_OPENCL (RID_SVX_START + 254) + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/passwd.hxx b/include/sfx2/passwd.hxx new file mode 100644 index 000000000..3302c370b --- /dev/null +++ b/include/sfx2/passwd.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_PASSWD_HXX +#define INCLUDED_SFX2_PASSWD_HXX + +#include +#include +#include +#include + +// defines --------------------------------------------------------------- + +enum class SfxShowExtras +{ + NONE = 0x0000, + USER = 0x0001, + CONFIRM = 0x0002, + PASSWORD2 = 0x0004, + CONFIRM2 = 0x0008, + ALL = USER | CONFIRM +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +// class SfxPasswordDialog ----------------------------------------------- + +class SFX2_DLLPUBLIC SfxPasswordDialog final : public weld::GenericDialogController +{ +private: + std::unique_ptr m_xPassword1Box; + std::unique_ptr m_xUserFT; + std::unique_ptr m_xUserED; + std::unique_ptr m_xPassword1FT; + std::unique_ptr m_xPassword1ED; + std::unique_ptr m_xConfirm1FT; + std::unique_ptr m_xConfirm1ED; + + std::unique_ptr m_xPassword2Box; + std::unique_ptr m_xPassword2FT; + std::unique_ptr m_xPassword2ED; + std::unique_ptr m_xConfirm2FT; + std::unique_ptr m_xConfirm2ED; + + std::unique_ptr m_xMinLengthFT; + std::unique_ptr m_xOnlyAsciiFT; + + std::unique_ptr m_xOKBtn; + + OUString maMinLenPwdStr; + OUString maMinLenPwdStr1; + OUString maEmptyPwdStr; + OUString maMainPwdStr; + sal_uInt16 mnMinLen; + SfxShowExtras mnExtras; + + bool mbAsciiOnly; + DECL_DLLPRIVATE_LINK(OKHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(InsertTextHdl, OUString&, bool); + DECL_DLLPRIVATE_LINK(EditModifyHdl, weld::Entry&, void); + void ModifyHdl(); + + void SetPasswdText(); + +public: + SfxPasswordDialog(weld::Widget* pParent, const OUString* pGroupText = nullptr); + + OUString GetUser() const + { + return m_xUserED->get_text(); + } + OUString GetPassword() const + { + return m_xPassword1ED->get_text(); + } + OUString GetConfirm() const + { + return m_xConfirm1ED->get_text(); + } + OUString GetPassword2() const + { + return m_xPassword2ED->get_text(); + } + void SetGroup2Text(const OUString& i_rText) + { + m_xPassword2Box->set_label(i_rText); + } + void SetMinLen(sal_uInt16 Len); + void SetEditHelpId(const OString& rId) + { + m_xPassword1ED->set_help_id(rId); + } + /* tdf#60874 we need a custom help ID for the Confirm + field of the Protect Document window */ + void SetConfirmHelpId(const OString& rId) + { + m_xConfirm1ED->set_help_id(rId); + } + + void ShowExtras(SfxShowExtras nExtras) + { + mnExtras = nExtras; + } + + void AllowAsciiOnly(); + void ShowMinLengthText(bool bShow); + + virtual short run() override; +}; + +#endif // INCLUDED_SFX2_PASSWD_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/printer.hxx b/include/sfx2/printer.hxx new file mode 100644 index 000000000..8d10b2cc7 --- /dev/null +++ b/include/sfx2/printer.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_PRINTER_HXX +#define INCLUDED_SFX2_PRINTER_HXX + +#include +#include +#include +#include + +class SfxItemSet; + +// class SfxPrinter ------------------------------------------------------ + +class SFX2_DLLPUBLIC SfxPrinter final : public Printer +{ +private: + std::unique_ptr pOptions; + bool bKnown; + + SfxPrinter& operator =(SfxPrinter const &) = delete; + +public: + SfxPrinter( std::unique_ptr &&pTheOptions ); + SfxPrinter( std::unique_ptr &&pTheOptions, + const OUString &rPrinterName ); + SfxPrinter( std::unique_ptr &&pTheOptions, + const JobSetup &rTheOrigJobSetup ); + SfxPrinter( const SfxPrinter &rPrinter ); + virtual ~SfxPrinter() override; + virtual void dispose() override; + + VclPtr Clone() const; + + static VclPtr Create( SvStream &rStream, std::unique_ptr &&pOptions ); + void Store( SvStream &rStream ) const; + + const SfxItemSet& GetOptions() const { return *pOptions; } + void SetOptions( const SfxItemSet &rNewOptions ); + + bool IsKnown() const { return bKnown; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/printopt.hxx b/include/sfx2/printopt.hxx new file mode 100644 index 000000000..ef7fd4683 --- /dev/null +++ b/include/sfx2/printopt.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_PRINTOPT_HXX +#define INCLUDED_SFX2_PRINTOPT_HXX + +#include +#include +#include +#include +#include + +class SFX2_DLLPUBLIC SfxCommonPrintOptionsTabPage final : public SfxTabPage +{ +private: + + std::unique_ptr m_xPrinterOutputRB; + std::unique_ptr m_xPrintFileOutputRB; + std::unique_ptr m_xReduceTransparencyCB; + std::unique_ptr m_xReduceTransparencyAutoRB; + std::unique_ptr m_xReduceTransparencyNoneRB; + std::unique_ptr m_xReduceGradientsCB; + std::unique_ptr m_xReduceGradientsStripesRB; + std::unique_ptr m_xReduceGradientsColorRB; + std::unique_ptr m_xReduceGradientsStepCountNF; + std::unique_ptr m_xReduceBitmapsCB; + std::unique_ptr m_xReduceBitmapsOptimalRB; + std::unique_ptr m_xReduceBitmapsNormalRB; + std::unique_ptr m_xReduceBitmapsResolutionRB; + std::unique_ptr m_xReduceBitmapsResolutionLB; + std::unique_ptr m_xReduceBitmapsTransparencyCB; + std::unique_ptr m_xConvertToGreyscalesCB; + std::unique_ptr m_xPDFCB; + std::unique_ptr m_xPaperSizeCB; + std::unique_ptr m_xPaperOrientationCB; + std::unique_ptr m_xTransparencyCB; + +private: + + vcl::printer::Options maPrinterOptions; + vcl::printer::Options maPrintFileOptions; + + DECL_DLLPRIVATE_LINK( ToggleOutputPrinterRBHdl, weld::Toggleable&, void ); + DECL_DLLPRIVATE_LINK( ToggleOutputPrintFileRBHdl, weld::Toggleable&, void); + + DECL_DLLPRIVATE_LINK( ClickReduceTransparencyCBHdl, weld::Toggleable&, void ); + DECL_DLLPRIVATE_LINK( ClickReduceGradientsCBHdl, weld::Toggleable&, void ); + DECL_DLLPRIVATE_LINK( ClickReduceBitmapsCBHdl, weld::Toggleable&, void ); + + DECL_DLLPRIVATE_LINK( ToggleReduceGradientsStripesRBHdl, weld::Toggleable&, void ); + DECL_DLLPRIVATE_LINK( ToggleReduceBitmapsResolutionRBHdl, weld::Toggleable&, void ); + + SAL_DLLPRIVATE void ImplUpdateControls( const vcl::printer::Options* pCurrentOptions ); + SAL_DLLPRIVATE void ImplSaveControls( vcl::printer::Options* pCurrentOptions ); + + virtual DeactivateRC DeactivatePage( SfxItemSet* pSet ) override; + +public: + + SfxCommonPrintOptionsTabPage(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet& rSet); + virtual ~SfxCommonPrintOptionsTabPage() override; + virtual bool FillItemSet( SfxItemSet* rSet ) override; + virtual void Reset( const SfxItemSet* rSet ) override; + + static std::unique_ptr Create(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet*); +}; + +#endif // INCLUDED_SFX2_PRINTOPT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/progress.hxx b/include/sfx2/progress.hxx new file mode 100644 index 000000000..ceee49b6c --- /dev/null +++ b/include/sfx2/progress.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_PROGRESS_HXX +#define INCLUDED_SFX2_PROGRESS_HXX + +#include +#include +#include +#include +#include + + +class SfxObjectShell; +struct SfxProgress_Impl; + +class SFX2_DLLPUBLIC SfxProgress +{ + std::unique_ptr< SfxProgress_Impl > pImpl; + sal_uInt32 nVal; + bool bSuspended; + +public: + SfxProgress( SfxObjectShell* pObjSh, + const OUString& rText, + sal_uInt32 nRange, + bool bWait = true); + virtual ~SfxProgress(); + + void SetState( sal_uInt32 nVal, sal_uInt32 nNewRange = 0 ); + sal_uInt32 GetState() const { return nVal; } + + void Resume(); + void Suspend(); + bool IsSuspended() const { return bSuspended; } + + static void Reschedule(); + + void Stop(); + + static SfxProgress* GetActiveProgress( SfxObjectShell const *pDocSh = nullptr ); + static void EnterLock(); + static void LeaveLock(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/request.hxx b/include/sfx2/request.hxx new file mode 100644 index 000000000..5a97cb9e6 --- /dev/null +++ b/include/sfx2/request.hxx @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_REQUEST_HXX +#define INCLUDED_SFX2_REQUEST_HXX + +#include +#include +#include +#include +#include + +#include + +class SfxPoolItem; +class SfxItemPool; +class SfxShell; +class SfxSlot; +class SfxViewFrame; +struct SfxRequest_Impl; +enum class SfxCallMode : sal_uInt16; + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::frame { class XDispatchRecorder; } +namespace com::sun::star::uno { template class Sequence; } +namespace weld { class Window; } + +class SFX2_DLLPUBLIC SfxRequest final : public SfxHint +{ +friend struct SfxRequest_Impl; + + sal_uInt16 nSlot; + std::unique_ptr pArgs; + std::unique_ptr< SfxRequest_Impl > pImpl; + +public: + SAL_DLLPRIVATE void Record_Impl( SfxShell &rSh, const SfxSlot &rSlot, + const css::uno::Reference< css::frame::XDispatchRecorder >& xRecorder, + SfxViewFrame* ); +private: + SAL_DLLPRIVATE void Done_Impl( const SfxItemSet *pSet ); + +public: + SfxRequest( SfxViewFrame*, sal_uInt16 nSlotId ); + SfxRequest( sal_uInt16 nSlot, SfxCallMode nCallMode, SfxItemPool &rPool ); + SfxRequest( const SfxSlot* pSlot, const css::uno::Sequence < css::beans::PropertyValue >& rArgs, + SfxCallMode nCallMode, SfxItemPool &rPool ); + SfxRequest(sal_uInt16 nSlot, SfxCallMode nCallMode, const SfxAllItemSet& rSfxArgs); + SfxRequest( sal_uInt16 nSlot, SfxCallMode nCallMode, const SfxAllItemSet& rSfxArgs, const SfxAllItemSet& rSfxInternalArgs ); + SfxRequest( const SfxRequest& rOrig ); + virtual ~SfxRequest() override; + + sal_uInt16 GetSlot() const { return nSlot; } + void SetSlot(sal_uInt16 nNewSlot) { nSlot = nNewSlot; } + + sal_uInt16 GetModifier() const; + void SetModifier( sal_uInt16 nModi ); + void SetInternalArgs_Impl( const SfxAllItemSet& rArgs ); + SAL_DLLPRIVATE const SfxItemSet* GetInternalArgs_Impl() const; + const SfxItemSet* GetArgs() const { return pArgs.get(); } + void SetArgs( const SfxAllItemSet& rArgs ); + void AppendItem(const SfxPoolItem &); + void RemoveItem( sal_uInt16 nSlotId ); + + /** Templatized access to the individual parameters of the SfxRequest. + + Use like: const SfxInt32Item *pPosItem = rReq.GetArg(SID_POS); + */ + template const T* GetArg(sal_uInt16 nSlotId) const + { + if (!pArgs) + return nullptr; + return pArgs->GetItem(nSlotId, false); + } + template const T* GetArg(TypedWhichId nSlotId) const + { + if (!pArgs) + return nullptr; + return pArgs->GetItem(nSlotId, false); + } + + void ReleaseArgs(); + void SetReturnValue(const SfxPoolItem &); + const SfxPoolItem* GetReturnValue() const; + + static css::uno::Reference< css::frame::XDispatchRecorder > GetMacroRecorder( SfxViewFrame const * pFrame ); + static bool HasMacroRecorder( SfxViewFrame const * pFrame ); + SfxCallMode GetCallMode() const; + void AllowRecording( bool ); + bool AllowsRecording() const; + bool IsAPI() const; + bool IsSynchronCall() const; + void SetSynchronCall( bool bSynchron ); + + bool IsDone() const; + void Done( bool bRemove = false ); + + void Ignore(); + void Cancel(); + bool IsCancelled() const; + void Done(const SfxItemSet &); + + void ForgetAllArgs(); + + /** Return the window that should be used as the parent for any dialogs this request creates + */ + weld::Window* GetFrameWeld() const; +private: + const SfxRequest& operator=(const SfxRequest &) = delete; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/safemode.hxx b/include/sfx2/safemode.hxx new file mode 100644 index 000000000..34602c4ea --- /dev/null +++ b/include/sfx2/safemode.hxx @@ -0,0 +1,73 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_SAFEMODE_HXX +#define INCLUDED_SFX2_SAFEMODE_HXX + +#include + +#include + +namespace sfx2 +{ +class SFX2_DLLPUBLIC SafeMode +{ +public: + /** + * Write a flag file to the user profile indicating that the next launch should be in safe mode. + * + * @return Whether the file could be written successfully + */ + static bool putFlag(); + + /** + * Check the existence of the safe mode flag file. + * + * @return Whether the flag file for the safe mode exists + */ + static bool hasFlag(); + + /** + * Remove the flag file for the safe mode. + * + * @return Whether the flag file could be removed successfully + */ + static bool removeFlag(); + + /** + * Write a flag to the user profile indicating that we are currently restarting from safe mode - + * that means we don't want to enter safe mode again. + * + * @return Whether the file could be written successfully + */ + static bool putRestartFlag(); + + /** + * Check the existence of the restart flag file. + * + * @return Whether the restart flag file exists + */ + static bool hasRestartFlag(); + + /** + * Remove the restart flag file. + * + * @return Whether the flag file could be removed successfully + */ + static bool removeRestartFlag(); + +private: + /** Returns the path of the safe mode flag file.*/ + static OUString getFilePath(const OUString& sFilename); +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxbasecontroller.hxx b/include/sfx2/sfxbasecontroller.hxx new file mode 100644 index 000000000..ac4950e5a --- /dev/null +++ b/include/sfx2/sfxbasecontroller.hxx @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_SFXBASECONTROLLER_HXX +#define INCLUDED_SFX2_SFXBASECONTROLLER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::awt { class XKeyHandler; } +namespace com::sun::star::awt { class XMouseClickHandler; } +namespace com::sun::star::frame { class XDispatch; } +namespace com::sun::star::frame { class XFrame; } +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::frame { struct DispatchDescriptor; } +namespace com::sun::star::ui { class XContextMenuInterceptor; } +namespace com::sun::star::ui { class XSidebarProvider; } +namespace com::sun::star::util { struct URL; } +namespace weld { class Button; } + +struct IMPL_SfxBaseController_DataContainer ; // impl. struct to hold member of class SfxBaseController + +class NotifyEvent; +class SfxViewFrame; +class SfxViewShell; + +sal_Int16 MapGroupIDToCommandGroup( SfxGroupId nGroupID ); + + + + +typedef ::cppu::WeakImplHelper < css::frame::XController2 + , css::frame::XControllerBorder + , css::frame::XDispatchProvider + , css::task::XStatusIndicatorSupplier + , css::ui::XContextMenuInterception + , css::awt::XUserInputInterception + , css::frame::XDispatchInformationProvider + , css::frame::XInfobarProvider + , css::frame::XTitle + , css::frame::XTitleChangeBroadcaster + , css::lang::XInitialization + > SfxBaseController_Base; + +class SFX2_DLLPUBLIC SfxBaseController :public SfxBaseController_Base + ,public ::cppu::BaseMutex +{ + +// public methods + + +public: + + + // constructor/destructor + + + SfxBaseController( SfxViewShell* pView ) ; + + virtual ~SfxBaseController() override ; + + SAL_DLLPRIVATE void ReleaseShell_Impl(); + SAL_DLLPRIVATE void BorderWidthsChanged_Impl(); + + css::uno::Reference< css::task::XStatusIndicator > SAL_CALL getStatusIndicator( ) override; + + + // XController2 + virtual css::uno::Reference< css::awt::XWindow > SAL_CALL getComponentWindow() override; + virtual OUString SAL_CALL getViewControllerName() override; + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getCreationArguments() override; + + virtual css::uno::Reference< css::ui::XSidebarProvider > SAL_CALL getSidebar() override; + + + // XController + + + virtual void SAL_CALL attachFrame( const css::uno::Reference< css::frame::XFrame >& xFrame ) override ; + + virtual sal_Bool SAL_CALL attachModel( const css::uno::Reference< css::frame::XModel >& xModel ) override ; + + virtual sal_Bool SAL_CALL suspend( sal_Bool bSuspend ) override ; + + css::uno::Any SAL_CALL getViewData() override ; + + void SAL_CALL restoreViewData( const css::uno::Any& aValue ) override ; + + css::uno::Reference< css::frame::XFrame > SAL_CALL getFrame() override ; + + css::uno::Reference< css::frame::XModel > SAL_CALL getModel() override ; + + + // XDispatchProvider + + + virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL queryDispatch( const css::util::URL & aURL , + const OUString & sTargetFrameName, + sal_Int32 eSearchFlags ) override ; + + virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& seqDescriptor ) override ; + + + // XControllerBorder + + + virtual css::frame::BorderWidths SAL_CALL getBorder() override; + virtual void SAL_CALL addBorderResizeListener( const css::uno::Reference< css::frame::XBorderResizeListener >& xListener ) override; + virtual void SAL_CALL removeBorderResizeListener( const css::uno::Reference< css::frame::XBorderResizeListener >& xListener ) override; + virtual css::awt::Rectangle SAL_CALL queryBorderedArea( const css::awt::Rectangle& aPreliminaryRectangle ) override; + + + // XComponent + + + virtual void SAL_CALL dispose() override ; + + virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override ; + + virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override ; + virtual void SAL_CALL registerContextMenuInterceptor( const css::uno::Reference< css::ui::XContextMenuInterceptor >& xInterceptor ) override; + virtual void SAL_CALL releaseContextMenuInterceptor( const css::uno::Reference< css::ui::XContextMenuInterceptor >& xInterceptor ) override; + + virtual void SAL_CALL addKeyHandler( const css::uno::Reference< css::awt::XKeyHandler >& xHandler ) override; + virtual void SAL_CALL removeKeyHandler( const css::uno::Reference< css::awt::XKeyHandler >& xHandler ) override; + virtual void SAL_CALL addMouseClickHandler( const css::uno::Reference< css::awt::XMouseClickHandler >& xHandler ) override; + virtual void SAL_CALL removeMouseClickHandler( const css::uno::Reference< css::awt::XMouseClickHandler >& xHandler ) override; + + + // XDispatchInformationProvider + virtual css::uno::Sequence< sal_Int16 > SAL_CALL getSupportedCommandGroups() override; + virtual css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL getConfigurableDispatchInformation( sal_Int16 nCommandGroup ) override; + + // css::frame::XTitle + virtual OUString SAL_CALL getTitle( ) override; + virtual void SAL_CALL setTitle( const OUString& sTitle ) override; + + // css::frame::XTitleChangeBroadcaster + virtual void SAL_CALL addTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener ) override; + virtual void SAL_CALL removeTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener ) override; + + // css::lang::XInitialization + virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& aArguments ) override; + + // XInfobarProvider + virtual void SAL_CALL + appendInfobar(const OUString& sId, const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, sal_Int32 aInfobarType, + const css::uno::Sequence& actionButtons, + sal_Bool bShowCloseButton) override; + virtual void SAL_CALL updateInfobar(const OUString& sId, const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, + sal_Int32 aInfobarType) override; + virtual void SAL_CALL removeInfobar(const OUString& sId) override; + virtual sal_Bool SAL_CALL hasInfobar(const OUString& sId) override; + + // FIXME: TL needs this in sw/source/ui/uno/unotxdoc.cxx now; + // either the _Impl name should vanish or there should be an "official" API + SfxViewShell* GetViewShell_Impl() const; + SAL_DLLPRIVATE bool HandleEvent_Impl( NotifyEvent const & rEvent ); + SAL_DLLPRIVATE bool HasKeyListeners_Impl() const; + SAL_DLLPRIVATE bool HasMouseClickListeners_Impl() const; + SAL_DLLPRIVATE void SetCreationArguments_Impl( const css::uno::Sequence< css::beans::PropertyValue >& i_rCreationArgs ); + SAL_DLLPRIVATE css::uno::Reference< css::frame::XTitle > impl_getTitleHelper (); +private: + enum ConnectSfxFrame + { + E_CONNECT, + E_DISCONNECT, + E_RECONNECT + }; + SAL_DLLPRIVATE void ConnectSfxFrame_Impl( const ConnectSfxFrame i_eConnect ); + SAL_DLLPRIVATE SfxViewFrame& GetViewFrame_Impl() const; + SAL_DLLPRIVATE void ShowInfoBars( ); + + DECL_DLLPRIVATE_LINK( CheckOutHandler, weld::Button&, void ); + + std::unique_ptr m_pData ; + +} ; // class SfxBaseController + +#endif // _SFX_SFXBASECONTROLLER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxbasemodel.hxx b/include/sfx2/sfxbasemodel.hxx new file mode 100644 index 000000000..8ccd59292 --- /dev/null +++ b/include/sfx2/sfxbasemodel.hxx @@ -0,0 +1,753 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +class ErrCode; +class SfxMedium; +class SfxObjectShell ; +class SfxViewFrame; +struct IMPL_SfxBaseModel_DataContainer ; // impl. struct to hold member of class SfxBaseModel + +namespace sfx::intern { + class ViewCreationGuard; +} + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::container { class XNameContainer; } +namespace com::sun::star::container { class XNameReplace; } +namespace com::sun::star::document { class XEventListener; } +namespace com::sun::star::document { struct CmisProperty; } +namespace com::sun::star::document { struct CmisVersion; } +namespace com::sun::star::document { struct EventObject; } +namespace com::sun::star::frame { class XController2; } +namespace com::sun::star::task { class XInteractionHandler; } +namespace com::sun::star::ui { class XUIConfigurationManager2; } +namespace com::sun::star::util { class XCloseListener; } +namespace com::sun::star::util { class XModifyListener; } + + + +/**_______________________________________________________________________________________________________ + @implements XChild + XComponent + document::XDocumentPropertiesSupplier + rdf::XDocumentMetadataAccess + XEventListener + XModel + XModifiable2 + XPrintable + XStorable2 + document::XEventBroadcaster + document::XEventsSupplier + document::XEmbeddedScripts + document::XScriptInvocationContext + XCloseable + XCloseBroadcaster + + @base cppu::BaseMutex + SfxListener +*/ + +typedef ::cppu::WeakImplHelper < css::container::XChild + , css::document::XDocumentPropertiesSupplier + , css::document::XCmisDocument + , css::rdf::XDocumentMetadataAccess + , css::document::XDocumentRecovery + , css::document::XUndoManagerSupplier + , css::document::XShapeEventBroadcaster + , css::document::XDocumentEventBroadcaster + , css::lang::XEventListener + , css::document::XEventsSupplier + , css::document::XEmbeddedScripts + , css::document::XScriptInvocationContext + , css::frame::XModel3 + , css::util::XModifiable2 + , css::view::XPrintable + , css::view::XPrintJobBroadcaster + , css::frame::XStorable2 + , css::frame::XLoadable + , css::script::XStarBasicAccess + , css::document::XViewDataSupplier + , css::util::XCloseable // => css::util::XCloseBroadcaster + , css::datatransfer::XTransferable + , css::document::XDocumentSubStorageSupplier + , css::document::XStorageBasedDocument + , css::script::provider::XScriptProviderSupplier + , css::ui::XUIConfigurationManagerSupplier + , css::embed::XVisualObject + , css::lang::XUnoTunnel + , css::frame::XModule + , css::frame::XTitle + , css::frame::XTitleChangeBroadcaster + , css::frame::XUntitledNumbers + > SfxBaseModel_Base; + +class SFX2_DLLPUBLIC SfxBaseModel : protected ::cppu::BaseMutex + , public SfxBaseModel_Base + , public SfxListener +{ + + +// public methods + + +public: + + + // constructor/destructor + + + SfxBaseModel( SfxObjectShell *pObjectShell ) ; + + virtual ~SfxBaseModel() override ; + + + // XInterface + + + /**___________________________________________________________________________________________________ + @short give answer, if interface is supported + @descr The interfaces are searched by type. + + @seealso XInterface + + @param "rType" is the type of searched interface. + + @return Any information about found interface + + @onerror A RuntimeException is thrown. + */ + + virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) override ; + + /**___________________________________________________________________________________________________ + @short increment refcount + @seealso XInterface + @seealso release() + @onerror A RuntimeException is thrown. + */ + + virtual void SAL_CALL acquire() noexcept override + { OWeakObject::acquire(); } + + /**___________________________________________________________________________________________________ + @short decrement refcount + @seealso XInterface + @seealso acquire() + @onerror A RuntimeException is thrown. + */ + + virtual void SAL_CALL release() noexcept override + { OWeakObject::release(); } + + + // XTypeProvider + + + /**___________________________________________________________________________________________________ + @short get information about supported interfaces + @seealso XTypeProvider + @return Sequence of types of all supported interfaces + + @onerror A RuntimeException is thrown. + */ + + virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override ; + + /**___________________________________________________________________________________________________ + @short get implementation id + @descr This ID is necessary for UNO-caching. If there no ID, cache is disabled. + Another way, cache is enabled. + + @seealso XTypeProvider + @return ID as Sequence of byte + + @onerror A RuntimeException is thrown. + */ + + virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() override ; + + + // XStarBasicAccess + + + /**___________________________________________________________________________________________________ + @seealso XStarBasicAccess + */ + virtual css::uno::Reference< css::container::XNameContainer > SAL_CALL getLibraryContainer() override; + + /**___________________________________________________________________________________________________ + @seealso XStarBasicAccess + */ + virtual void SAL_CALL createLibrary( const OUString& LibName, const OUString& Password, + const OUString& ExternalSourceURL, const OUString& LinkTargetURL ) override; + + /**___________________________________________________________________________________________________ + @seealso XStarBasicAccess + */ + virtual void SAL_CALL addModule( const OUString& LibraryName, const OUString& ModuleName, + const OUString& Language, const OUString& Source ) override; + + /**___________________________________________________________________________________________________ + @seealso XStarBasicAccess + */ + virtual void SAL_CALL addDialog( const OUString& LibraryName, const OUString& DialogName, + const css::uno::Sequence< sal_Int8 >& Data ) override; + + + // XChild + + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL getParent() override ; + + virtual void SAL_CALL setParent( const css::uno::Reference< css::uno::XInterface >& xParent ) override; + + + // XComponent + + + virtual void SAL_CALL dispose() override; + + virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener >& aListener) override; + + virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener >& aListener ) override; + + // XDocumentPropertiesSupplier + virtual css::uno::Reference< css::document::XDocumentProperties > + SAL_CALL getDocumentProperties() override; + + + // XEventListener + + + virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) override; + + + // XModel + + + virtual sal_Bool SAL_CALL attachResource(const OUString& sURL, + const css::uno::Sequence< css::beans::PropertyValue >& aArgs) override; + + virtual OUString SAL_CALL getURL() override; + + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getArgs() override; + + virtual void SAL_CALL connectController( const css::uno::Reference< css::frame::XController >& xController ) override; + + virtual void SAL_CALL disconnectController( const css::uno::Reference< css::frame::XController >& xController ) override; + + virtual void SAL_CALL lockControllers() override; + + virtual void SAL_CALL unlockControllers() override; + + virtual sal_Bool SAL_CALL hasControllersLocked() override; + + virtual css::uno::Reference< css::frame::XController > SAL_CALL getCurrentController() override; + + virtual void SAL_CALL setCurrentController( const css::uno::Reference< css::frame::XController >& xController ) override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL getCurrentSelection() override; + + + // XModel2 + + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL getControllers() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getAvailableViewControllerNames() override; + + virtual css::uno::Reference< css::frame::XController2 > SAL_CALL createDefaultViewController(const css::uno::Reference< css::frame::XFrame >& Frame ) override; + + virtual css::uno::Reference< css::frame::XController2 > SAL_CALL createViewController(const OUString& ViewName , + const css::uno::Sequence< css::beans::PropertyValue >& Arguments , + const css::uno::Reference< css::frame::XFrame >& Frame ) override; + + virtual void SAL_CALL setArgs(const css::uno::Sequence& aArgs) override; + + + // XModel3 + + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getArgs2( const css::uno::Sequence< OUString > & requestedArgs ) override; + + // XModifiable2 + + + virtual sal_Bool SAL_CALL disableSetModified( ) override; + virtual sal_Bool SAL_CALL enableSetModified( ) override; + virtual sal_Bool SAL_CALL isSetModifiedEnabled( ) override; + + virtual sal_Bool SAL_CALL isModified() override; + + virtual void SAL_CALL setModified( sal_Bool bModified ) override; + + virtual void SAL_CALL addModifyListener( const css::uno::Reference< css::util::XModifyListener >& xListener ) override ; + + virtual void SAL_CALL removeModifyListener(const css::uno::Reference< css::util::XModifyListener > & xListener) override ; + + + // XCloseable + + + virtual void SAL_CALL close( sal_Bool bDeliverOwnership ) override; + + + // XCloseBroadcaster + + + virtual void SAL_CALL addCloseListener( const css::uno::Reference< css::util::XCloseListener >& xListener ) override; + virtual void SAL_CALL removeCloseListener( const css::uno::Reference< css::util::XCloseListener >& xListener ) override; + + + // XPrintJobBroadcaster + + + virtual void SAL_CALL addPrintJobListener( const css::uno::Reference< css::view::XPrintJobListener >& xListener ) override; + virtual void SAL_CALL removePrintJobListener( const css::uno::Reference< css::view::XPrintJobListener >& xListener ) override; + + + // XPrintable + + + virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL getPrinter() override; + + virtual void SAL_CALL setPrinter( const css::uno::Sequence< css::beans::PropertyValue >& seqPrinter ) override; + virtual void SAL_CALL print( const css::uno::Sequence< css::beans::PropertyValue >& seqOptions ) override; + + + // XStorable2 + + + virtual void SAL_CALL storeSelf( const css::uno::Sequence< css::beans::PropertyValue >& seqArguments ) override; + + + // XStorable + + + virtual sal_Bool SAL_CALL hasLocation() override; + + virtual OUString SAL_CALL getLocation() override; + + virtual sal_Bool SAL_CALL isReadonly() override; + + virtual void SAL_CALL store() override; + + virtual void SAL_CALL storeAsURL( const OUString& sURL, + const css::uno::Sequence< css::beans::PropertyValue >& seqArguments ) override ; + + virtual void SAL_CALL storeToURL( const OUString& sURL, + const css::uno::Sequence< css::beans::PropertyValue >& seqArguments ) override; + + SAL_DLLPRIVATE void + impl_store(const OUString& sURL, + const css::uno::Sequence& seqArguments, bool bSaveTo); + + // XLoadable + + + virtual void SAL_CALL initNew() override; + + virtual void SAL_CALL load( const css::uno::Sequence< css::beans::PropertyValue >& seqArguments ) override; + + + // XDocumentSubStorageSupplier + + + virtual css::uno::Reference< css::embed::XStorage > SAL_CALL getDocumentSubStorage( const OUString& aStorageName, sal_Int32 nMode ) override; + + virtual css::uno::Sequence< OUString > SAL_CALL getDocumentSubStoragesNames() override; + + + // XStorageBasedDocument + + + virtual void SAL_CALL loadFromStorage( const css::uno::Reference< css::embed::XStorage >& xStorage, + const css::uno::Sequence< css::beans::PropertyValue >& aMediaDescriptor ) override; + + virtual void SAL_CALL storeToStorage( const css::uno::Reference< css::embed::XStorage >& xStorage, + const css::uno::Sequence< css::beans::PropertyValue >& aMediaDescriptor ) override; + + virtual void SAL_CALL switchToStorage( const css::uno::Reference< css::embed::XStorage >& xStorage ) override; + + virtual css::uno::Reference< css::embed::XStorage > SAL_CALL getDocumentStorage() override; + + virtual void SAL_CALL addStorageChangeListener( + const css::uno::Reference< css::document::XStorageChangeListener >& xListener ) override; + + virtual void SAL_CALL removeStorageChangeListener( + const css::uno::Reference< css::document::XStorageChangeListener >& xListener ) override; + + + // XVisualObject + + + virtual void SAL_CALL setVisualAreaSize( sal_Int64 nAspect, const css::awt::Size& aSize ) override; + + virtual css::awt::Size SAL_CALL getVisualAreaSize( sal_Int64 nAspect ) override; + + virtual css::embed::VisualRepresentation SAL_CALL getPreferredVisualRepresentation( ::sal_Int64 nAspect ) override; + + virtual sal_Int32 SAL_CALL getMapUnit( sal_Int64 nAspect ) override; + + + // XScriptProviderSupplier + + + virtual css::uno::Reference< css::script::provider::XScriptProvider > SAL_CALL getScriptProvider() override; + + + // XUIConfigurationManagerSupplier + virtual css::uno::Reference< css::ui::XUIConfigurationManager > SAL_CALL getUIConfigurationManager() override; + + + // XTransferable + + + virtual css::uno::Any SAL_CALL getTransferData( const css::datatransfer::DataFlavor& aFlavor ) override; + + virtual css::uno::Sequence< css::datatransfer::DataFlavor > SAL_CALL getTransferDataFlavors() override; + + virtual sal_Bool SAL_CALL isDataFlavorSupported( const css::datatransfer::DataFlavor& aFlavor ) override; + + + // XEventsSupplier + + + /**___________________________________________________________________________________________________ + @descr - offers a list of event handlers which are be bound to events of + this object. + @return - an Events object. + */ + + virtual css::uno::Reference< css::container::XNameReplace > SAL_CALL getEvents() override; + + + // XEmbeddedScripts + + + virtual css::uno::Reference< css::script::XStorageBasedLibraryContainer > SAL_CALL getBasicLibraries() override; + virtual css::uno::Reference< css::script::XStorageBasedLibraryContainer > SAL_CALL getDialogLibraries() override; + virtual sal_Bool SAL_CALL getAllowMacroExecution() override; + + + // XScriptInvocationContext + + + virtual css::uno::Reference< css::document::XEmbeddedScripts > SAL_CALL getScriptContainer() override; + + + // document::XEventBroadcaster + + /**___________________________________________________________________________________________________ + @descr - registers the given XEventListener. + */ + virtual void SAL_CALL addEventListener( const css::uno::Reference< css::document::XEventListener >& xListener ) override; + + /**___________________________________________________________________________________________________ + @descr - unregisters the given XEventListener. + */ + virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::document::XEventListener >& xListener ) override; + + + // document::XShapeEventBroadcaster + + /**___________________________________________________________________________________________________ + @descr - registers the given XEventListener. + */ + virtual void SAL_CALL addShapeEventListener( const css::uno::Reference< css::drawing::XShape >& xShape, const css::uno::Reference< css::document::XShapeEventListener >& xListener ) override; + + /**___________________________________________________________________________________________________ + @descr - unregisters the given XEventListener. + */ + virtual void SAL_CALL removeShapeEventListener( const css::uno::Reference< css::drawing::XShape >& xShape, const css::uno::Reference< css::document::XShapeEventListener >& xListener ) override; + + + // XDocumentEventBroadcaster + + virtual void SAL_CALL addDocumentEventListener( const css::uno::Reference< css::document::XDocumentEventListener >& Listener ) override; + virtual void SAL_CALL removeDocumentEventListener( const css::uno::Reference< css::document::XDocumentEventListener >& Listener ) override; + virtual void SAL_CALL notifyDocumentEvent( const OUString& EventName, const css::uno::Reference< css::frame::XController2 >& ViewController, const css::uno::Any& Supplement ) override; + + + // XUnoTunnel + + + virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; + + // css.frame.XModule + virtual void SAL_CALL setIdentifier(const OUString& sIdentifier) override; + + // css.frame.XModule + virtual OUString SAL_CALL getIdentifier() override; + + // css.frame.XTitle + virtual OUString SAL_CALL getTitle() override; + + // css.frame.XTitle + virtual void SAL_CALL setTitle( const OUString& sTitle ) override; + + // css.frame.XTitleChangeBroadcaster + virtual void SAL_CALL addTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener ) override; + + // css.frame.XTitleChangeBroadcaster + virtual void SAL_CALL removeTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener ) override; + + // css.frame.XUntitledNumbers + virtual ::sal_Int32 SAL_CALL leaseNumber( const css::uno::Reference< css::uno::XInterface >& xComponent ) override; + + // css.frame.XUntitledNumbers + virtual void SAL_CALL releaseNumber( ::sal_Int32 nNumber ) override; + + // css.frame.XUntitledNumbers + virtual void SAL_CALL releaseNumberForComponent( const css::uno::Reference< css::uno::XInterface >& xComponent ) override; + + // css.frame.XUntitledNumbers + virtual OUString SAL_CALL getUntitledPrefix() override; + + // css.document.XDocumentRecovery + virtual sal_Bool SAL_CALL wasModifiedSinceLastSave() override; + virtual void SAL_CALL storeToRecoveryFile( const OUString& i_TargetLocation, const css::uno::Sequence< css::beans::PropertyValue >& i_MediaDescriptor ) override; + virtual void SAL_CALL recoverFromFile( const OUString& i_SourceLocation, const OUString& i_SalvagedFile, const css::uno::Sequence< css::beans::PropertyValue >& i_MediaDescriptor ) override; + + // css.document.XUndoManagerSupplier + virtual css::uno::Reference< css::document::XUndoManager > SAL_CALL getUndoManager( ) override; + + + // css::rdf::XNode: + virtual OUString SAL_CALL getStringValue() override; + + // css::rdf::XURI: + virtual OUString SAL_CALL getNamespace() override; + virtual OUString SAL_CALL getLocalName() override; + + // css::rdf::XRepositorySupplier: + virtual css::uno::Reference< + css::rdf::XRepository > SAL_CALL getRDFRepository() override; + + // css::rdf::XDocumentMetadataAccess: + virtual css::uno::Reference< + css::rdf::XMetadatable > SAL_CALL + getElementByMetadataReference( + const css::beans::StringPair & i_rReference) override; + virtual css::uno::Reference< + css::rdf::XMetadatable > SAL_CALL + getElementByURI(const css::uno::Reference< + css::rdf::XURI > & i_xURI) override; + virtual css::uno::Sequence< css::uno::Reference< + css::rdf::XURI > > SAL_CALL getMetadataGraphsWithType( + const css::uno::Reference< + css::rdf::XURI > & i_xType) override; + virtual css::uno::Reference< + css::rdf::XURI> SAL_CALL + addMetadataFile(const OUString & i_rFileName, + const css::uno::Sequence< + css::uno::Reference< css::rdf::XURI > + > & i_rTypes) override; + virtual css::uno::Reference< + css::rdf::XURI> SAL_CALL + importMetadataFile(::sal_Int16 i_Format, + const css::uno::Reference< + css::io::XInputStream > & i_xInStream, + const OUString & i_rFileName, + const css::uno::Reference< + css::rdf::XURI > & i_xBaseURI, + const css::uno::Sequence< + css::uno::Reference< css::rdf::XURI > + > & i_rTypes) override; + virtual void SAL_CALL removeMetadataFile( + const css::uno::Reference< + css::rdf::XURI > & i_xGraphName) override; + virtual void SAL_CALL addContentOrStylesFile( + const OUString & i_rFileName) override; + virtual void SAL_CALL removeContentOrStylesFile( + const OUString & i_rFileName) override; + + virtual void SAL_CALL loadMetadataFromStorage( + const css::uno::Reference< + css::embed::XStorage > & i_xStorage, + const css::uno::Reference< + css::rdf::XURI > & i_xBaseURI, + const css::uno::Reference< + css::task::XInteractionHandler> & i_xHandler) override; + virtual void SAL_CALL storeMetadataToStorage( + const css::uno::Reference< + css::embed::XStorage > & i_xStorage) override; + virtual void SAL_CALL loadMetadataFromMedium( + const css::uno::Sequence< + css::beans::PropertyValue > & i_rMedium) override; + virtual void SAL_CALL storeMetadataToMedium( + const css::uno::Sequence< + css::beans::PropertyValue > & i_rMedium) override; + + // XCmisDocument + + virtual css::uno::Sequence< css::document::CmisProperty > + SAL_CALL getCmisProperties() override; + virtual void SAL_CALL setCmisProperties( + const css::uno::Sequence< + css::document::CmisProperty >& _cmisproperties ) override; + + virtual void SAL_CALL updateCmisProperties( + const css::uno::Sequence< + css::document::CmisProperty >& _cmisproperties ) override; + + virtual css::uno::Sequence< css::document::CmisVersion > SAL_CALL getAllVersions ( ) override; + + virtual void SAL_CALL checkOut( ) override; + virtual void SAL_CALL cancelCheckOut( ) override; + virtual void SAL_CALL checkIn( sal_Bool bIsMajor, const OUString & rMessage ) override; + + virtual sal_Bool SAL_CALL isVersionable( ) override; + virtual sal_Bool SAL_CALL canCheckOut( ) override; + virtual sal_Bool SAL_CALL canCancelCheckOut( ) override; + virtual sal_Bool SAL_CALL canCheckIn( ) override; + + /// @throws css::uno::RuntimeException + bool getBoolPropertyValue( const OUString& rName ); + + + // SfxListener + + + void Notify( SfxBroadcaster& aBC , + const SfxHint& aHint ) override ; + + + // public IMPL? + + + void changing() ; + + SfxObjectShell* GetObjectShell() const ; + + SAL_DLLPRIVATE bool impl_isDisposed() const ; + bool IsInitialized() const; + void MethodEntryCheck( const bool i_mustBeInitialized ) const; + + css::uno::Reference < css::container::XIndexAccess > SAL_CALL getViewData() override; + void SAL_CALL setViewData( const css::uno::Reference < css::container::XIndexAccess >& aData ) override; + + /** calls all XEventListeners */ + void notifyEvent( const css::document::EventObject& aEvent ) const; + + /** returns true if someone added a XEventListener to this XEventBroadcaster */ + bool hasEventListeners() const; + +protected: + + /* returns a unique id for the model that is valid as long as the document + is loaded. The id is not saved across document close/reload. */ + OUString const & getRuntimeUID() const; + + /* returns true if the document signatures are valid, otherwise false */ + bool hasValidSignatures() const; + + /* GrabBagItem for interim interop purposes */ + void getGrabBagItem(css::uno::Any& rVal) const; + + void setGrabBagItem(const css::uno::Any& rVal); + + +// private methods + + +private: + /// @throws css::uno::RuntimeException + css::uno::Reference< css::ui::XUIConfigurationManager2 > getUIConfigurationManager2(); + void impl_getPrintHelper(); + SAL_DLLPRIVATE void ListenForStorage_Impl( const css::uno::Reference< css::embed::XStorage >& xStorage ); + SAL_DLLPRIVATE OUString GetMediumFilterName_Impl() const; + + SAL_DLLPRIVATE void postEvent_Impl( const OUString& aName, const css::uno::Reference< css::frame::XController2 >& xController = css::uno::Reference< css::frame::XController2 >(), const css::uno::Any& aSupplement = css::uno::Any()); + + SAL_DLLPRIVATE css::uno::Reference< css::frame::XTitle > impl_getTitleHelper (); + SAL_DLLPRIVATE css::uno::Reference< css::frame::XUntitledNumbers > impl_getUntitledHelper (); + + SAL_DLLPRIVATE SfxViewFrame* FindOrCreateViewFrame_Impl( + const css::uno::Reference< css::frame::XFrame >& i_rFrame, + ::sfx::intern::ViewCreationGuard& i_rGuard + ) const; + + SAL_DLLPRIVATE void NotifyModifyListeners_Impl() const; + + SAL_DLLPRIVATE void loadCmisProperties(); + + SAL_DLLPRIVATE SfxMedium* handleLoadError( ErrCode nError, SfxMedium* pMedium ); + + +// private variables and methods + + +private: + + std::shared_ptr m_pData; + // cannot be held in m_pData, since it needs to be accessed in non-threadsafe context + const bool m_bSupportEmbeddedScripts; + const bool m_bSupportDocRecovery; + +} ; // class SfxBaseModel + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxdlg.hxx b/include/sfx2/sfxdlg.hxx new file mode 100644 index 000000000..ba3062693 --- /dev/null +++ b/include/sfx2/sfxdlg.hxx @@ -0,0 +1,155 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_SFXDLG_HXX +#define INCLUDED_SFX2_SFXDLG_HXX + +#include +#include + +#include + +#include +#include +#include + +class SfxItemSet; +class SfxItemPool; +class SvObjectServerList; +class TransferableDataHelper; +class SvGlobalName; + +namespace sfx2 +{ + class LinkManager; + class SvBaseLink; +} + +namespace com::sun::star::embed { class XEmbeddedObject; } +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::uno { class Any; } + +class SfxAbstractDialog : virtual public VclAbstractDialog +{ +protected: + virtual ~SfxAbstractDialog() override = default; +public: + /** Get a set of items changed in the dialog. + */ + virtual const SfxItemSet* GetOutputItemSet() const = 0; + virtual void SetText( const OUString& rStr ) = 0; +}; + +class SfxAbstractTabDialog : virtual public SfxAbstractDialog +{ +protected: + virtual ~SfxAbstractTabDialog() override = default; +public: + virtual void SetCurPageId( const OString &rName ) = 0; + virtual WhichRangesContainer GetInputRanges( const SfxItemPool& ) = 0; + virtual void SetInputSet( const SfxItemSet* pInSet ) = 0; +}; + +class SfxAbstractApplyTabDialog : virtual public SfxAbstractTabDialog +{ +protected: + virtual ~SfxAbstractApplyTabDialog() override = default; +public: + virtual void SetApplyHdl( const Link& rLink ) = 0; +}; + +class SfxAbstractInsertObjectDialog : virtual public VclAbstractDialog +{ +protected: + virtual ~SfxAbstractInsertObjectDialog() override = default; +public: + virtual css::uno::Reference < css::embed::XEmbeddedObject > GetObject()=0; + virtual css::uno::Reference< css::io::XInputStream > GetIconIfIconified( OUString* pGraphicMediaType )=0; + virtual bool IsCreateNew()=0; +}; + +class SfxAbstractPasteDialog : virtual public VclAbstractDialog +{ +protected: + virtual ~SfxAbstractPasteDialog() override = default; +public: + virtual void Insert( SotClipboardFormatId nFormat, const OUString & rFormatName ) = 0; + virtual void InsertUno( const OUString& sCmd, const OUString& sLabel ) = 0; + virtual void SetObjName( const SvGlobalName & rClass, const OUString & rObjName ) = 0; + virtual void PreGetFormat( const TransferableDataHelper& aHelper ) = 0; + virtual SotClipboardFormatId GetFormatOnly() = 0; + virtual SotClipboardFormatId GetFormat( const TransferableDataHelper& aHelper ) = 0; +}; + +class SfxAbstractLinksDialog : virtual public VclAbstractDialog +{ +protected: + virtual ~SfxAbstractLinksDialog() override = default; +}; + +class AbstractScriptSelectorDialog : virtual public VclAbstractDialog +{ +protected: + virtual ~AbstractScriptSelectorDialog() override = default; +public: + virtual OUString GetScriptURL() const = 0; + virtual void SetRunLabel() = 0; +}; + +namespace com::sun::star::frame { class XFrame; } + +class SFX2_DLLPUBLIC SfxAbstractDialogFactory : virtual public VclAbstractDialogFactory +{ +public: + virtual ~SfxAbstractDialogFactory() override; // needed for export of vtable + static SfxAbstractDialogFactory* Create(); + virtual VclPtr CreateFrameDialog(weld::Window* pParent, const css::uno::Reference< css::frame::XFrame >& rFrame, sal_uInt32 nResId, const OUString& rParameter) = 0; + virtual VclPtr CreateAutoCorrTabDialog(weld::Window* pParent, const SfxItemSet* pAttrSet) = 0; + virtual VclPtr CreateCustomizeTabDialog(weld::Window* pParent, + const SfxItemSet* pAttrSet, + const css::uno::Reference< css::frame::XFrame >& xViewFrame ) = 0; + virtual CreateTabPage GetTabPageCreatorFunc( sal_uInt16 nId ) = 0; + virtual GetTabPageRanges GetTabPageRangesFunc( sal_uInt16 nId ) = 0; + virtual VclPtr CreateInsertObjectDialog(weld::Window* pParent, const OUString& rCommand, + const css::uno::Reference < css::embed::XStorage >& xStor, + const SvObjectServerList* pList )=0; + virtual VclPtr CreateEditObjectDialog(weld::Window* pParent, const OUString& rCommand, + const css::uno::Reference < css::embed::XEmbeddedObject >& xObj )=0; + virtual VclPtr CreatePasteDialog(weld::Window* pParent) = 0; + virtual VclPtr CreateLinksDialog(weld::Window* pParent, sfx2::LinkManager* pMgr, bool bHTML=false, sfx2::SvBaseLink* p=nullptr) = 0; + virtual VclPtr CreateSvxScriptOrgDialog(weld::Window* pParent, const OUString& rLanguage) = 0; + + virtual VclPtr CreateScriptSelectorDialog(weld::Window* pParent, + const css::uno::Reference< css::frame::XFrame >& rxFrame) = 0; + + virtual void ShowAsyncScriptErrorDialog( weld::Window* pParent, const css::uno::Any& rException ) = 0; + + virtual VclPtr CreateOptionsDialog( + weld::Window* pParent, const OUString& rExtensionId ) = 0; + + virtual VclPtr CreateAboutDialog(weld::Window* _pParent) = 0; + + virtual VclPtr CreateTipOfTheDayDialog(weld::Window* _pParent) = 0; + + virtual VclPtr CreateToolbarmodeDialog(weld::Window* _pParent) = 0; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxhelp.hxx b/include/sfx2/sfxhelp.hxx new file mode 100644 index 000000000..212188063 --- /dev/null +++ b/include/sfx2/sfxhelp.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_SFXHELP_HXX +#define INCLUDED_SFX2_SFXHELP_HXX + +#include + +#include + +#include +#include +#include +#include + +class SFX2_DLLPUBLIC SfxHelp final : public Help +{ + bool bIsDebug; + bool bLaunchingHelp; // tdf#140539 don't allow help to be re-launched during help launch + +private: + SAL_DLLPRIVATE static bool Start_Impl(const OUString& rURL, weld::Widget* pWidget, const OUString& rKeyword); + SAL_DLLPRIVATE virtual void SearchKeyword( const OUString& rKeyWord ) override; + SAL_DLLPRIVATE virtual bool Start(const OUString& rURL, weld::Widget* pWidget = nullptr) override; + SAL_DLLPRIVATE static OUString GetHelpModuleName_Impl(std::u16string_view rHelpId); + SAL_DLLPRIVATE static OUString CreateHelpURL_Impl( const OUString& aCommandURL, const OUString& rModuleName ); + + SAL_DLLPRIVATE static bool Start_Impl( const OUString& rURL, const vcl::Window* pWindow ); + SAL_DLLPRIVATE virtual bool Start( const OUString& rURL, const vcl::Window* pWindow ) override; + +public: + SfxHelp(); + virtual ~SfxHelp() override; + + virtual OUString GetHelpText(const OUString&, const vcl::Window* pWindow) override; + virtual OUString GetHelpText(const OUString&, const weld::Widget* pWindow) override; + + static OUString CreateHelpURL( const OUString& aCommandURL, const OUString& rModuleName ); + static OUString GetDefaultHelpModule(); + static OUString GetCurrentModuleIdentifier(); + // Check for built-in help + static bool IsHelpInstalled(); + + static OUString GetURLHelpText(std::u16string_view); +}; + +#endif // INCLUDED_SFX2_SFXHELP_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxhtml.hxx b/include/sfx2/sfxhtml.hxx new file mode 100644 index 000000000..9f5a03f5b --- /dev/null +++ b/include/sfx2/sfxhtml.hxx @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_SFXHTML_HXX +#define INCLUDED_SFX2_SFXHTML_HXX + +#include +#include +#include +#include +#include +#include +#include + + +class ImageMap; +class SfxMedium; +class SvNumberFormatter; + +class SFX2_DLLPUBLIC SfxHTMLParser : public HTMLParser +{ + OUString aScriptType; + + SfxMedium* pMedium; + std::unique_ptr pDLMedium; // Medium for Download Files + + ScriptType eScriptType; + + SAL_DLLPRIVATE void GetScriptType_Impl( SvKeyValueIterator* ); + +protected: + + SfxHTMLParser( SvStream& rStream, bool bNewDoc, SfxMedium *pMedium ); + + virtual ~SfxHTMLParser() override; + +public: + // Read the options of an image map + // : sal_True = Image-Map has a name + // : sal_True = Image-Map has now one vcl::Region more + static bool ParseMapOptions(ImageMap* pImageMap, const HTMLOptions& rOptions); + bool ParseMapOptions(ImageMap * pImageMap) + { return ParseMapOptions(pImageMap, GetOptions()); } + static bool ParseAreaOptions(ImageMap * pImageMap, std::u16string_view rBaseURL, + const HTMLOptions& rOptions, + SvMacroItemId nEventMouseOver, + SvMacroItemId nEventMouseOut ); + inline bool ParseAreaOptions(ImageMap * pImageMap, std::u16string_view rBaseURL, + SvMacroItemId nEventMouseOver, + SvMacroItemId nEventMouseOut); + + // + static double GetTableDataOptionsValNum( sal_uInt32& nNumForm, + LanguageType& eNumLang, const OUString& aValStr, + std::u16string_view aNumStr, SvNumberFormatter& rFormatter ); + +protected: + // Start a file download. This is done asynchronously or synchronously. + // In the synchronous case, the parser is in the working state after + // it has been called. The read file can then be picked up directly with + // FinishFileDownload. In the asynchronous case, the parser is in the + // pending state after it hs been called. The parser then has to leave + // over the Continue (without Reschedule!). If the file is loaded, + // a Continue is called with passed on token. The file can then be picked + // up by FinishFileDownload. To cancel the download should a shell be + // left. It can only exist a single download at the same time, For every + // started download FinishFileDownload must be called. + void StartFileDownload(const OUString& rURL); + + // End of an asynchronous file download. Returns TRUE if the download + // was successful. The read file is then passed into String. + bool FinishFileDownload( OUString& rStr ); + + // Returns TRUE if a file was downloaded and if FileDownloadFinished + // has not yet been called + bool ShouldFinishFileDownload() const { return pDLMedium != nullptr; } + + SfxMedium *GetMedium() { return pMedium; } + const SfxMedium *GetMedium() const { return pMedium; } + + // Default (without iterator) is JavaScript + ScriptType GetScriptType( SvKeyValueIterator* ) const; + const OUString& GetScriptTypeString( SvKeyValueIterator* ) const; +}; + +inline bool SfxHTMLParser::ParseAreaOptions(ImageMap * pImageMap, std::u16string_view rBaseURL, + SvMacroItemId nEventMouseOver, + SvMacroItemId nEventMouseOut) +{ + return ParseAreaOptions( pImageMap, rBaseURL, GetOptions(), + nEventMouseOver, nEventMouseOut ); +} + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxmodelfactory.hxx b/include/sfx2/sfxmodelfactory.hxx new file mode 100644 index 000000000..4d166c4d4 --- /dev/null +++ b/include/sfx2/sfxmodelfactory.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_SFXMODELFACTORY_HXX +#define INCLUDED_SFX2_SFXMODELFACTORY_HXX + +#include + +#include +#include +#include + +namespace com::sun::star::lang { class XMultiServiceFactory; } +namespace com::sun::star::lang { class XSingleServiceFactory; } +namespace com::sun::star::uno { class XInterface; } +namespace com::sun::star::uno { class XComponentContext; } +namespace com::sun::star::uno { template class Sequence; } + +enum class SfxModelFlags +{ + NONE = 0x00, + EMBEDDED_OBJECT = 0x01, + EXTERNAL_LINK = 0x02, + DISABLE_EMBEDDED_SCRIPTS = 0x04, + DISABLE_DOCUMENT_RECOVERY = 0x08, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace sfx2 +{ + /** + * Intended to be called from UNO constructor functions + * This evaluates certain creation arguments (passed to createInstanceWithArguments) + * and passes them to the factory function of the derived class. + */ + css::uno::Reference + SFX2_DLLPUBLIC createSfxModelInstance( + const css::uno::Sequence & rxArgs, + std::function( SfxModelFlags )> creationFunc + ); + +} // namespace sfx2 + + +#endif // INCLUDED_SFX2_SFXMODELFACTORY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxresid.hxx b/include/sfx2/sfxresid.hxx new file mode 100644 index 000000000..f5cd1aca4 --- /dev/null +++ b/include/sfx2/sfxresid.hxx @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_SFXRESID_HXX +#define INCLUDED_SFX2_SFXRESID_HXX + +#include +#include +#include + +SFX2_DLLPUBLIC OUString SfxResId(TranslateId aId); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxsids.hrc b/include/sfx2/sfxsids.hrc new file mode 100644 index 000000000..b48f827ae --- /dev/null +++ b/include/sfx2/sfxsids.hrc @@ -0,0 +1,739 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_SFXSIDS_HRC +#define INCLUDED_SFX2_SFXSIDS_HRC + +#include +#include +#include + +class SfxAllEnumItem; +class SfxBoolItem; +class SfxDocumentInfoItem; +class SfxEventNamesItem; +class SfxFlagItem; +class SfxInt16Item; +class SfxInt32Item; +class SfxHyphenRegionItem; +class SfxMacroInfoItem; +class SfxScriptOrganizerItem; +class SfxStringItem; +class SfxStringListItem; +class SfxUInt16Item; +class SfxUnoAnyItem; +class SfxUnoFrameItem; +class SfxWatermarkItem; +class SvxClipboardFormatItem; +class SvxHyperlinkItem; +class SvxLanguageItem; +class SvxSearchItem; +class SvxZoomItem; + +// Please be careful: +// Changing just one part here doesn't add new +// docking windows automatically! + +#define SID_DOCKWIN_0 SID_DOCKWIN_START +#define SID_DOCKWIN_1 SID_DOCKWIN_START+1 +#define SID_DOCKWIN_2 SID_DOCKWIN_START+2 +#define SID_DOCKWIN_3 SID_DOCKWIN_START+3 +#define SID_DOCKWIN_4 SID_DOCKWIN_START+4 +#define SID_DOCKWIN_5 SID_DOCKWIN_START+5 +#define SID_DOCKWIN_6 SID_DOCKWIN_START+6 +#define SID_DOCKWIN_7 SID_DOCKWIN_START+7 +#define SID_DOCKWIN_8 SID_DOCKWIN_START+8 +#define SID_DOCKWIN_9 SID_DOCKWIN_START+9 + +// default-ids for application +#define SID_QUITAPP (SID_SFX_START + 300) +#define SID_ABOUT (SID_SFX_START + 301) +#define SID_SETUPPRINTER (SID_SFX_START + 302) +#define SID_SAFE_MODE (SID_SFX_START + 303) + +#define SID_DEVELOPMENT_TOOLS_DOCKING_WINDOW (SID_SFX_START + 306) +#define SID_INSPECT_SELECTED_OBJECT (SID_SFX_START + 307) + +#define SID_CONTEXT (SID_SFX_START + 310) + +#define SID_PASTE_SPECIAL (SID_SFX_START + 311) +#define SID_CLIPBOARD_FORMAT_ITEMS TypedWhichId(SID_SFX_START + 312) + +#define SID_PASTE_UNFORMATTED (SID_SFX_START + 314) +#define SID_PRINTER_NOTFOUND_WARN TypedWhichId(SID_SFX_START + 320) +#define SID_PRINTER_NAME (SID_SFX_START + 322) +#define SID_PRINTER_CHANGESTODOC TypedWhichId(SID_SFX_START + 324) +#define SID_PRINTPREVIEW (SID_SFX_START + 325) + +#define SID_MAIL_SUBJECT (SID_SFX_START + 328) +#define SID_MAIL_SENDDOC (SID_SFX_START + 331) +#define SID_MAIL_SENDDOCASPDF (SID_SFX_START + 1672) + +#define SID_MAIL_RECIPIENT (SID_SFX_START + 334) +#define SID_MAIL_TEXT (SID_SFX_START + 335) +#define SID_MAIL_PRIORITY (SID_SFX_START + 337) + +#define SID_MAIL_PREPAREEXPORT (SID_SFX_START + 385) + +#define SID_MAIL_EXPORT_FINISHED (SID_SFX_START + 388) +#define SID_WEBHTML (SID_SFX_START + 393) +#define SID_MAIL_SCROLLBODY_PAGEDOWN (SID_SFX_START + 1588) + +#define SID_PROGRESS_STATUSBAR_CONTROL TypedWhichId(SID_SFX_START + 1597) + +#define SID_SELECTION TypedWhichId(SID_SFX_START + 346) + +// 360-400 see SID_MAIL_... + +// default-ids for help +#define SID_HELPINDEX (SID_SFX_START + 401) +#define SID_EXTENDEDHELP (SID_SFX_START + 402) +#define SID_HELPBALLOONS TypedWhichId(SID_SFX_START + 403) +#define SID_HELPTIPS TypedWhichId(SID_SFX_START + 404) +#define SID_EMOJI_CONTROL (SID_SFX_START + 405) +#define SID_CHARMAP_CONTROL (SID_SFX_START + 406) +#define SID_TIPOFTHEDAY (SID_SFX_START + 407) + +// free (SID_SFX_START + 410) +#define SID_SEND_FEEDBACK (SID_SFX_START + 421) +#define SID_Q_AND_A (SID_SFX_START + 422) +#define SID_DOCUMENTATION (SID_SFX_START + 423) +#define SID_DONATION (SID_SFX_START + 424) +#define SID_GETINVOLVED (SID_SFX_START + 425) +#define SID_WHATSNEW (SID_SFX_START + 426) +#define SID_HYPHENATIONMISSING (SID_SFX_START + 427) + +#define SID_SHOW_LICENSE (SID_SFX_START + 1683) +#define SID_SHOW_CREDITS (SID_SFX_START + 1711) + +// default-ids for document +#define SID_NEWDOC (SID_SFX_START + 500) +#define SID_OPENDOC (SID_SFX_START + 501) +#define SID_OPENREMOTE (SID_SFX_START + 517) +#define SID_OPENURL (SID_SFX_START + 596) +#define SID_JUMPTOMARK (SID_SFX_START + 598) +#define SID_OPENTEMPLATE (SID_SFX_START + 594) +#define SID_SAVEASDOC (SID_SFX_START + 502) +#define SID_SAVEASREMOTE (SID_SFX_START + 516) +#define SID_SAVESIMPLE (SID_SFX_START + 518) +#define SID_SIGNPDF (SID_SFX_START + 519) +#define SID_SAVEACOPY (SID_SFX_START + 999) +#define SID_SAVEACOPYITEM (SID_SFX_START + 998) +#define SID_CONVERT_IMAGES TypedWhichId(SID_SFX_START + 997) +#define SID_CLOSING (SID_SFX_START +1539) +#define SID_CLOSEDOC (SID_SFX_START + 503) +#define SID_CLOSEDOCS (SID_SFX_START + 595) +#define SID_CLOSEDOC_SAVE (SID_SFX_START + 1) +#define SID_CLOSEDOC_FILENAME (SID_SFX_START + 2) +#define SID_PRINTDOC (SID_SFX_START + 504) +#define SID_PRINT_COPIES (SID_SFX_START + 3) +#define SID_PRINT_PAGES (SID_SFX_START +1589) +#define SID_PRINT_COLLATE (SID_SFX_START +1590) +#define SID_PRINT_SORT (SID_SFX_START +1591) +#define SID_SAVEDOC (SID_SFX_START + 505) +#define SID_FILE_NAME TypedWhichId(SID_SFX_START + 507) +#define SID_DOCINFO_TITLE TypedWhichId(SID_SFX_START + 557) +#define SID_FILE_FILTEROPTIONS TypedWhichId(SID_SFX_START + 527) +#define SID_RELOAD (SID_SFX_START + 508) +#define SID_PRINTDOCDIRECT (SID_SFX_START + 509) +#define SID_DOC_REPAIR TypedWhichId(SID_SFX_START + 510) +#define SID_DOC_SERVICE TypedWhichId(SID_SFX_START + 511) +#define SID_PLUGIN_MODE TypedWhichId(SID_SFX_START + 827) +#define SID_EXPORTDOC (SID_SFX_START + 829) +#define SID_EXPORTDOCASPDF (SID_SFX_START + 1673) +#define SID_DIRECTEXPORTDOCASPDF (SID_SFX_START + 1674) +#define SID_EXPORTDOCASEPUB (SID_SFX_START + 1677) +#define SID_DIRECTEXPORTDOCASEPUB (SID_SFX_START + 1678) +#define SID_REDACTDOC (SID_SFX_START + 1732) +#define SID_AUTOREDACTDOC (SID_SFX_START + 1736) +#define SID_UPDATEDOCMODE TypedWhichId(SID_SFX_START + 1668) +#define SID_CHECKOUT (SID_SFX_START + 512) +#define SID_CANCELCHECKOUT (SID_SFX_START + 513) +#define SID_CHECKIN (SID_SFX_START + 514) +#define SID_FILTER_PROVIDER TypedWhichId(SID_SFX_START + 515) + +#define SID_FORCERELOAD (SID_SFX_START + 1502) +#define SID_FILE_DIALOG TypedWhichId(SID_SFX_START + 304) +#define SID_REMOTE_DIALOG (SID_SFX_START + 305) +#define SID_PATH TypedWhichId(SID_SFX_START + 308) +#define SID_SAVEDOCS (SID_SFX_START + 309) +#define SID_STANDARD_DIR TypedWhichId(SID_SFX_START + 450) +#define SID_DENY_LIST TypedWhichId(SID_SFX_START + 451) + +// browse-ids +#define SID_BROWSE_FORWARD (SID_SFX_START + 1300) +#define SID_BROWSE_BACKWARD (SID_SFX_START + 1301) +#define SID_CREATELINK (SID_SFX_START + 1309) +#define SID_EDITDOC TypedWhichId(SID_SFX_START + 1312) +#define SID_BROWSER_MODE (SID_SFX_START + 1313) +#define SID_READONLYDOC (SID_SFX_START + 1314) +#define SID_BROWSER (SID_SFX_START + 1318) +#define SID_MACROEXECMODE TypedWhichId(SID_SFX_START + 1319) + +#define SID_FILTER_DATA TypedWhichId(SID_SFX_START + 1375) + +#define SID_EXPLORER_FILEPROPS_START (SID_SFX_START + 1390) +// SID_EXPLORER_FILEPROPS_END (SID_SFX_START + 1399) + +#define SID_ATTR_ZOOM TypedWhichId(SID_SVX_START + 0) + +#define SID_EXPLORER_PROPS_START TypedWhichId(SID_SFX_START + 1410) +// SID_EXPLORER_PROPS_END (SID_SFX_START + 1499) + +#define SID_AUTOLOAD (SID_SFX_START + 1509) +#define SID_FILLFRAME TypedWhichId(SID_SFX_START + 1516) +#define SID_BASEURL (SID_SFX_START + 1518) +#define SID_TEMPLATE TypedWhichId(SID_SFX_START + 1519) + +#define SID_CONTENTTYPE TypedWhichId(SID_SFX_START + 1541) + +#define SID_SAVETO TypedWhichId(SID_SFX_START + 1546) + +#define SID_VERSION TypedWhichId(SID_SFX_START + 1583) + +#define SID_DOCUMENT_COMPARE (SID_SFX_START + 1586) +#define SID_DOCUMENT_MERGE (SID_SFX_START + 1587) + +#define SID_OFFICE_CHECK_PLZ (SID_SFX_START + 1610) +#define SID_CURRENT_URL (SID_SFX_START + 1613) + +#define SID_CHARSET TypedWhichId(SID_SFX_START + 1633) +#define SID_OVERWRITE (SID_SFX_START + 1634) + // FREE (was: SID_CRASH) +#define SID_FAIL_ON_WARNING TypedWhichId(SID_SFX_START + 1646) +#define SID_INPUTSTREAM TypedWhichId(SID_SFX_START + 1648) +#define SID_LOGOUT (SID_SFX_START + 1652) +#define SID_JUMPMARK TypedWhichId(SID_SFX_START + 1654) +#define SID_BROWSE (SID_SFX_START + 1658) + // FREE (was: SID_BACKTOWEBTOP) +#define SID_VIEW_DATA_SOURCE_BROWSER (SID_SFX_START + 1660) +#define SID_UNPACK (SID_SFX_START + 1662) +// (SID_SFX_START + 1663) used further down + // FREE +#define SID_OUTPUTSTREAM TypedWhichId(SID_SFX_START + 1666) +#define SID_IMAGE_ORIENTATION (SID_SFX_START + 1667) + +#define SID_STOP_RECORDING (SID_SFX_START + 1671) +#define SID_INTERACTIONHANDLER TypedWhichId(SID_SFX_START + 1675) +#define SID_OPENHYPERLINK (SID_SFX_START + 1676) +#define SID_CONTENT TypedWhichId(SID_SFX_START + 1679) +#define SID_VIEWONLY TypedWhichId(SID_SFX_START + 1682) +#define SID_REPAIRPACKAGE TypedWhichId(SID_SFX_START + 1683) +#define SID_MINIMIZED TypedWhichId(SID_SFX_START + 1687) +#define SID_COMPONENTDATA TypedWhichId(SID_SFX_START + 1688) +#define SID_COMPONENTCONTEXT TypedWhichId(SID_SFX_START + 1689) +#define SID_SCRIPTORGANIZER TypedWhichId(SID_SFX_START + 1690) +#define SID_MACROORGANIZER TypedWhichId(SID_SFX_START + 1691) +#define SID_RUNMACRO (SID_SFX_START + 1692) +#define SID_AVMEDIA_TOOLBOX TypedWhichId<::avmedia::MediaItem>(SID_SFX_START + 1693) +#define SID_AVMEDIA_PLAYER (SID_SFX_START + 1694) +#define SID_INSERT_AVMEDIA (SID_SFX_START + 1696) +#define SID_RECENTFILELIST (SID_SFX_START + 1697) +#define SID_AVAILABLE_TOOLBARS (SID_SFX_START + 1698) +#define SID_STREAM TypedWhichId(SID_SFX_START + 1699) +#define SID_DOC_BASEURL TypedWhichId(SID_SFX_START + 1700) +#define SID_DOC_HIERARCHICALNAME TypedWhichId(SID_SFX_START + 1701) +#define SID_TERMINATE_INPLACEACTIVATION (SID_SFX_START + 1702) +#define SID_APPLY_STYLE (SID_SFX_START + 1703) +#define SID_MACRO_SIGNATURE (SID_SFX_START + 1704) +#define SID_ATTR_WARNALIENFORMAT TypedWhichId(SID_SFX_START + 1705) +#define SID_COPY_STREAM_IF_POSSIBLE TypedWhichId(SID_SFX_START + 1706) +#define SID_MAIL_SENDDOCASFORMAT (SID_SFX_START + 1707) +#define SID_MAIL_SENDDOCASMS (SID_SFX_START + 1708) +#define SID_MAIL_SENDDOCASOOO (SID_SFX_START + 1709) +#define SID_NO_ACCEPT_DIALOG TypedWhichId(SID_SFX_START + 1710) +#define SID_NOAUTOSAVE TypedWhichId(SID_SFX_START + 1711) +#define SID_PRINT_SELECTEDSHEET TypedWhichId(SID_SFX_START + 1712) +#define SID_OPTIONS_PAGEURL (SID_SFX_START + 1713) +#define SID_MORE_DICTIONARIES (SID_SFX_START + 1714) +#define SID_ACTIVATE_STYLE_APPLY (SID_SFX_START + 1715) +#define SID_FONT_NAME (SID_SFX_START + 1716) +#define SID_DEFAULTFILENAME (SID_SFX_START + 1717) +#define SID_MODIFYPASSWORDINFO TypedWhichId(SID_SFX_START + 1718) +#define SID_RECOMMENDREADONLY (SID_SFX_START + 1719) +#define SID_SUGGESTEDSAVEASDIR TypedWhichId(SID_SFX_START + 1720) +#define SID_SUGGESTEDSAVEASNAME TypedWhichId(SID_SFX_START + 1721) +#define SID_ENCRYPTIONDATA TypedWhichId(SID_SFX_START + 1722) +#define SID_PASSWORDINTERACTION (SID_SFX_START + 1723) +#define SID_GOTOLINE (SID_SFX_START + 1724) +#define SID_SHOWLINES (SID_SFX_START + 1725) +#define SID_BLUETOOTH_SENDDOC (SID_SFX_START + 1726) +#define SID_TEMPLATE_MANAGER (SID_SFX_START + 1727) +#define SID_TOOLBAR_MODE (SID_SFX_START + 1728) +#define SID_NO_FILE_SYNC (SID_SFX_START + 1729) +#define SID_NO_THUMBNAIL (SID_SFX_START + 1730) +#define SID_LOCK_CONTENT_EXTRACTION TypedWhichId(SID_SFX_START + 1731) +#define SID_LOCK_EXPORT TypedWhichId(SID_SFX_START + 1732) +// Used to export a temporary file for preview in Mail Merge Wizard, where saving the data source is +// not required for preview, but interferes with not-yet-saved embedded data source for main document. +#define SID_NO_EMBEDDED_DS TypedWhichId(SID_SFX_START + 1731) +#define SID_IS_REDACT_MODE (SID_SFX_START + 1733) +#define SID_REDACTION_STYLE (SID_SFX_START + 1734) +#define SID_DIALOG_PARENT TypedWhichId(SID_SFX_START + 1735) +#define SID_LOCK_PRINT TypedWhichId(SID_SFX_START + 1736) +#define SID_LOCK_SAVE TypedWhichId(SID_SFX_START + 1737) +#define SID_LOCK_EDITDOC TypedWhichId(SID_SFX_START + 1738) +#define SID_REPLACEABLE TypedWhichId(SID_SFX_START + 1739) +#define SID_ADDITIONS_DIALOG (SID_SFX_START + 1740) +#define FN_PARAM_ADDITIONS_TAG TypedWhichId(SID_SFX_START + 1741) +#define SID_TOOLBAR_MODE_UI (SID_SFX_START + 1742) +#define SID_TOOLBAR_LOCK (SID_SFX_START + 1743) + +// SID_SFX_free_END (SID_SFX_START + 3999) + +#define SID_OPEN_NEW_VIEW TypedWhichId(SID_SFX_START + 520) + // FREE, was SID_VIEW_ZOOM_MODE + // FREE, was SID_VIEW_POS_SIZE +#define SID_VIEW_ID TypedWhichId(SID_SFX_START + 523) + // FREE, was SID_USER_DATA +#define SID_VIEW_DATA TypedWhichId(SID_SFX_START + 1582) +#define SID_SILENT TypedWhichId(SID_SFX_START + 528) +#define SID_HIDDEN TypedWhichId(SID_SFX_START + 534) +#define SID_PREVIEW TypedWhichId(SID_SFX_START + 1404) + +#define SID_FOCUSURLBOX (SID_SFX_START + 1406) + +#define SID_ACTIVATE (SID_SFX_START + 525) +#define SID_PRINTOUT (SID_SFX_START + 526) + +#define SID_FILTER_NAME TypedWhichId(SID_SFX_START + 530) +#define SID_DOC_SALVAGE TypedWhichId(SID_SFX_START + 531) +#define SID_INSERTDOC (SID_SFX_START + 532) +#define SID_TYPE_NAME TypedWhichId(SID_SFX_START + 533) + +#define SID_DOC_READONLY TypedWhichId(SID_SFX_START + 590) +#define SID_DOC_MODIFIED (SID_SFX_START + 584) +#define SID_DOC_LOADING (SID_SFX_START + 585) +#define SID_IMG_LOADING (SID_SFX_START + 586) +#define SID_DOC_SAVED (SID_SFX_START + 599) +#define SID_DOCINFO TypedWhichId(SID_SFX_START + 535) +#define SID_DOCINFO_KEYWORDS (SID_SFX_START + 591) +#define SID_DOCINFO_COMMENTS (SID_SFX_START + 592) +#define SID_DOCINFO_AUTHOR (SID_SFX_START + 593) +#define SID_DOCINFO_MAJOR (SID_SFX_START + 594) +#define SID_NEWDOCDIRECT (SID_SFX_START + 537) +#define SID_DOCFRAME (SID_SFX_START + 598) +#define SID_TARGETNAME TypedWhichId(SID_SFX_START + 560) +#define SID_POSTDATA TypedWhichId(SID_SFX_START + 1536) +#define SID_DONELINK (SID_SFX_START + 646) +#define SID_REFERER (SID_SFX_START + 654) +#define SID_PAGE_NUMBER (SID_SFX_START + 655) +#define SID_MODIFIER TypedWhichId(SID_SFX_START + 669) +#define SID_SETOPTIONS (SID_SFX_START + 670) +#define SID_SOURCEVIEW (SID_SFX_START + 675) +#define SID_DOC_STARTPRESENTATION TypedWhichId(SID_SFX_START + 695) +#define SID_DDE_RECONNECT_ONLOAD TypedWhichId(SID_SFX_START + 696) + +#define SID_DOCTEMPLATE (SID_SFX_START + 538) +#define SID_AUTOPILOTMENU (SID_SFX_START + 1381) + +// Floating Window Template +#define SID_STYLE_DESIGNER TypedWhichId(SID_SFX_START + 539) + +#define SID_SIDEBAR_DECK (SID_SFX_START + 850) + +#define SID_TEMPLATE_ADDRESSBOOKSOURCE (SID_SFX_START + 1655) + +// Ruby dialog +#define SID_RUBY_DIALOG (SID_SFX_START + 1656) + +#define SID_STYLE_FAMILY_START (SID_SFX_START + 541) +#define SID_STYLE_FAMILY1 (SID_STYLE_FAMILY_START) +#define SID_STYLE_FAMILY2 (SID_STYLE_FAMILY_START + 1) +#define SID_STYLE_FAMILY3 (SID_STYLE_FAMILY_START + 2) +#define SID_STYLE_FAMILY4 (SID_STYLE_FAMILY_START + 3) +#define SID_STYLE_FAMILY5 (SID_STYLE_FAMILY_START + 4) +#define SID_STYLE_FAMILY6 (SID_STYLE_FAMILY_START + 5) + +#define SID_STYLE_NEW (SID_SFX_START + 549) +#define SID_STYLE_EDIT (SID_SFX_START + 550) +#define SID_STYLE_DELETE (SID_SFX_START + 551) +#define SID_STYLE_APPLY (SID_SFX_START + 552) +#define SID_STYLE_FAMILY TypedWhichId(SID_SFX_START + 553) +#define SID_STYLE_FAMILYNAME TypedWhichId(SID_SFX_START + 566) +#define SID_STYLE_WATERCAN (SID_SFX_START + 554) +#define SID_STYLE_NEW_BY_EXAMPLE (SID_SFX_START + 555) +#define SID_STYLE_UPDATE_BY_EXAMPLE (SID_SFX_START + 556) +#define SID_STYLE_DRAGHIERARCHIE (SID_SFX_START + 565) +#define SID_STYLE_MASK (SID_SFX_START + 562) +#define SID_STYLE_PREVIEW (SID_SFX_START + 567) +#define SID_STYLE_END_PREVIEW (SID_SFX_START + 568) +#define SID_STYLE_HIDE (SID_SFX_START + 1603) +#define SID_STYLE_SHOW (SID_SFX_START + 1604) +#define SID_STYLE_UPD_BY_EX_NAME TypedWhichId(SID_SFX_START + 1585) +#define SID_STYLE_REFERENCE TypedWhichId(SID_SFX_START + 1602) + +#define SID_TEMPLATE_NAME TypedWhichId(SID_SFX_START + 660) +#define SID_TEMPLATE_REGIONNAME TypedWhichId(SID_SFX_START + 662) +#define SID_TEMPLATE_LOAD (SID_SFX_START + 663) + +#define SID_INSERT_OBJECT (SID_SFX_START + 561) +#define SID_INSERT_FLOATINGFRAME (SID_SFX_START + 563) +#define SID_CLASSIFICATION_APPLY (SID_SFX_START + 672) +#define SID_WATERMARK TypedWhichId(SID_SFX_START + 676) +#define SID_WATERMARK_FONT TypedWhichId(SID_SFX_START + 677) +#define SID_WATERMARK_TRANSPARENCY TypedWhichId(SID_SFX_START + 805) +#define SID_WATERMARK_COLOR TypedWhichId(SID_SFX_START + 806) +#define SID_WATERMARK_ANGLE TypedWhichId(SID_SFX_START + 807) + +#define SID_HYPERLINK_DIALOG (SID_SFX_START + 678) + +#define SID_DEFAULTFILEPATH (SID_SFX_START + 571) +#define SID_OBJECT (SID_SFX_START + 575) + +// Doc-Properties +#define SID_DOCFULLNAME (SID_SFX_START + 581) +#define SID_DOCPATH (SID_SFX_START + 582) +#define SID_DOCTITLE TypedWhichId(SID_SFX_START + 583) + +#define SID_DOCUMENT TypedWhichId(SID_SFX_START + 588) + +// default-ids for windows + +#define SID_COMMAND_POPUP (SID_SFX_START + 610) +#define SID_NEWWINDOW (SID_SFX_START + 620) +#define SID_CLOSEWIN (SID_SFX_START + 621) +#define SID_VIEWSHELL TypedWhichId(SID_SFX_START + 623) +#define SID_WIN_FULLSCREEN TypedWhichId(SID_SFX_START + 627) + +#define SID_VIEWSHELL0 (SID_SFX_START + 630) +#define SID_VIEWSHELL1 (SID_SFX_START + 631) +#define SID_VIEWSHELL2 (SID_SFX_START + 632) +#define SID_VIEWSHELL3 (SID_SFX_START + 633) +#define SID_VIEWSHELL4 (SID_SFX_START + 634) + +// id for thesaurus entry in context menu +#define SID_THES (SID_SFX_START + 698) +#define FN_PARAM_THES_WORD_REPLACE TypedWhichId(SID_SFX_START + 699) + +// default-ids for editing, cursor travelling and selection +#define SID_REDO (SID_SFX_START + 700) +#define SID_UNDO (SID_SFX_START + 701) +#define SID_REPEAT (SID_SFX_START + 702) +#define SID_CLEARHISTORY (SID_SFX_START + 703) +#define SID_CUT (SID_SFX_START + 710) +#define SID_COPY (SID_SFX_START + 711) +#define SID_PASTE (SID_SFX_START + 712) +#define SID_DELETE (SID_SFX_START + 713) + +#define SID_BACKSPACE (SID_SFX_START + 714) +#define SID_FORMATPAINTBRUSH TypedWhichId(SID_SFX_START + 715) +#define SID_SELECT (SID_SFX_START + 720) +#define SID_SELECTALL (SID_SFX_START + 723) +#define SID_CURSORDOWN (SID_SFX_START + 731) +#define SID_CURSORUP (SID_SFX_START + 732) +#define SID_CURSORLEFT (SID_SFX_START + 733) +#define SID_CURSORRIGHT (SID_SFX_START + 734) +#define SID_CURSORPAGEDOWN (SID_SFX_START + 735) +#define SID_CURSORPAGEUP (SID_SFX_START + 736) +#define SID_CURSORENDOFFILE (SID_SFX_START + 741) +#define SID_CURSORTOPOFFILE (SID_SFX_START + 742) +#define SID_CURSORENDOFSCREEN (SID_SFX_START + 743) +#define SID_CURSORTOPOFSCREEN (SID_SFX_START + 744) +#define SID_CURSORHOME (SID_SFX_START + 745) +#define SID_CURSOREND (SID_SFX_START + 746) +#define SID_UNICODE_NOTATION_TOGGLE (SID_SFX_START + 792) + +// default-ids for macros +#define SID_RECORDING_FLOATWINDOW (SID_SFX_START + 800) +#define SID_RECORDMACRO TypedWhichId(SID_SFX_START + 1669) + +// Paste Special +#define SID_PASTE_ONLY_TEXT (SID_SFX_START + 802) +#define SID_PASTE_ONLY_FORMULA (SID_SFX_START + 803) +#define SID_PASTE_ONLY_VALUE (SID_SFX_START + 804) +#define SID_PASTE_TEXTIMPORT_DIALOG (SID_SFX_START + 805) +#define SID_PASTE_TRANSPOSED (SID_SFX_START + 812) +#define SID_PASTE_AS_LINK (SID_SFX_START + 813) + +// Used for redaction +#define SID_SHAPE_NAME (SID_SFX_START + 808) + // FREE: SID_SFX_START + 809 +#define SID_GRAPHIC_SIZE_CHECK (SID_SFX_START + 809) +#define SID_ACCESSIBILITY_CHECK (SID_SFX_START + 810) +#define SID_ASYNCHRON (SID_SFX_START + 811) + +// default-ids for configuration +#define SID_CONFIG (SID_SFX_START + 904) +#define SID_TOOLBOXOPTIONS (SID_SFX_START + 907) +#define SID_TOGGLEFUNCTIONBAR (SID_SFX_START + 910) +#define SID_MACROINFO TypedWhichId(SID_SFX_START + 919) +#define SID_TOGGLESTATUSBAR (SID_SFX_START + 920) +#define SID_CONFIGSTATUSBAR (SID_SFX_START + 921) +#define SID_CONFIGMENU (SID_SFX_START + 924) +#define SID_CONFIGACCEL (SID_SFX_START + 925) +#define SID_CONFIGEVENT (SID_SFX_START + 926) +#define SID_CFGFILE (SID_SFX_START + 927) +#define SID_SHOWPOPUPS (SID_SFX_START + 929) + +// Item-Id for the assigned event Tabpage. +// FIXME this has two different associated pool item types, SvxMacroItem and SfxBoolItem +#define SID_ATTR_MACROITEM TypedWhichId(SID_SFX_START + 934) + +#define SID_OPTIONS (SID_SFX_START + 940) +#define SID_BASICLOAD (SID_SFX_START + 951) +#define SID_BASICSAVEAS (SID_SFX_START + 953) +#define SID_BASICCOMPILE (SID_SFX_START + 954) +#define SID_BASICRUN (SID_SFX_START + 955) +#define SID_BASICSTEPINTO (SID_SFX_START + 956) +#define SID_BASICSTEPOVER (SID_SFX_START + 957) +#define SID_BASICSTEPOUT (SID_SFX_START + 963) +#define SID_BASICSTOP (SID_SFX_START + 958) +#define SID_BASICCHOOSER (SID_SFX_START + 959) +#define SID_GALLERY (SID_SFX_START + 960) +#define SID_SEARCH_DLG (SID_SFX_START + 961) +#define SID_SEARCH_QUIET (SID_SFX_START + 1684) +#define SID_EXPORT_DIALOG (SID_SFX_START + 965) +#define SID_IMPORT_DIALOG (SID_SFX_START + 966) + +#define SID_BASICBREAK (SID_SFX_START +1521) + +#define SID_OBJECTRESIZE TypedWhichId(SID_SFX_START + 1000) + +#define SID_EVENTCONFIG TypedWhichId(SID_SFX_START + 1101) +#define SID_VERB_START (SID_SFX_START + 1100) +#define SID_VERB_END (SID_SFX_START + 1121) + +#define SID_SIGNATURE (SID_SFX_START + 1643) + +// SaveTabPage +#define SID_ATTR_DOCINFO TypedWhichId(SID_OPTIONS_START + 0) +#define SID_ATTR_BACKUP TypedWhichId(SID_OPTIONS_START + 1) +#define SID_ATTR_AUTOSAVE TypedWhichId(SID_OPTIONS_START + 2) +#define SID_ATTR_AUTOSAVEPROMPT TypedWhichId(SID_OPTIONS_START + 3) +#define SID_ATTR_USERAUTOSAVE TypedWhichId(SID_OPTIONS_START + 4) +#define SID_ATTR_AUTOSAVEMINUTE TypedWhichId(SID_OPTIONS_START + 5) +#define SID_ATTR_WORKINGSET TypedWhichId(SID_OPTIONS_START + 13) +#define SID_ATTR_UNDO_COUNT TypedWhichId(SID_OPTIONS_START + 16) + // unused +#define SID_ATTR_SAVEDOCVIEW TypedWhichId(SID_OPTIONS_START + 18) + +// GeneralTabPage + +#define SID_ATTR_METRIC TypedWhichId(SID_OPTIONS_START + 8) +#define SID_ATTR_DEFTABSTOP TypedWhichId(SID_OPTIONS_START + 14) +#define SID_ATTR_BUTTON_BIGSIZE TypedWhichId(SID_OPTIONS_START + 63) +#define SID_ATTR_QUICKLAUNCHER TypedWhichId(SID_OPTIONS_START + 74) +#define SID_ATTR_YEAR2000 TypedWhichId(SID_OPTIONS_START + 87) +#define SID_ATTR_APPLYCHARUNIT TypedWhichId(SID_OPTIONS_START + 88) + +// PathTabPage +#define SID_ATTR_PATHNAME TypedWhichId(SID_OPTIONS_START + 11) + +// LinguTabPage +#define SID_ATTR_LANGUAGE TypedWhichId(SID_OPTIONS_START + 7) +#define SID_ATTR_HYPHENREGION TypedWhichId(SID_OPTIONS_START + 12) +#define SID_AUTOSPELL_CHECK TypedWhichId(SID_OPTIONS_START + 21) + +// InetTabPage + +#define SID_INET_PROXY_TYPE TypedWhichId(SID_OPTIONS_START + 23) + +#define SID_SAVEREL_INET TypedWhichId(SID_OPTIONS_START + 30) +#define SID_SAVEREL_FSYS TypedWhichId(SID_OPTIONS_START + 31) + +#define SID_PASSWORD TypedWhichId(SID_OPTIONS_START + 36) + +#define SID_INET_NOPROXY TypedWhichId(SID_OPTIONS_START + 37) + +#define SID_INET_HTTP_PROXY_NAME TypedWhichId(SID_OPTIONS_START + 38) +#define SID_INET_HTTP_PROXY_PORT TypedWhichId(SID_OPTIONS_START + 39) +#define SID_INET_FTP_PROXY_NAME TypedWhichId(SID_OPTIONS_START + 40) +#define SID_INET_FTP_PROXY_PORT TypedWhichId(SID_OPTIONS_START + 41) + +// Automatic update of Styles - manage TabPage +#define SID_ATTR_AUTO_STYLE_UPDATE TypedWhichId(SID_OPTIONS_START + 65) + +#define SID_SECURE_URL TypedWhichId(SID_OPTIONS_START + 66) + +// configured locale changed +#define SID_OPT_LOCALE_CHANGED (SID_OPTIONS_START + 94) +//middle mouse button +#define SID_ATTR_PRETTYPRINTING TypedWhichId(SID_OPTIONS_START + 98) +#define SID_HELP_STYLESHEET TypedWhichId(SID_OPTIONS_START + 99) + +// slot IDs from SVX (svxids.hrc) --------------------------------------------- +// These SID_SVX_START entries came from include/svx/svxids.hrc, avoid +// accidentally colliding entries with include/svx/svxids.hrc and +// include/editeng/editids.hrc. Only add new SID_SVX_START entries +// to include/svx/svxids.hrc + +#define SID_ZOOM_TOOLBOX (SID_SVX_START + 96) +#define SID_ZOOM_OUT (SID_SVX_START + 97) +#define SID_ZOOM_IN (SID_SVX_START + 98) +#define SID_SIZE_REAL (SID_SVX_START + 99) +#define SID_SIZE_PAGE (SID_SVX_START + 100) +#define SID_GALLERY_BG_BRUSH (SID_SVX_START + 279) +#define SID_SEARCH_OPTIONS (SID_SVX_START + 281) +#define SID_SEARCH_ITEM TypedWhichId(SID_SVX_START + 291) +#define SID_SIDEBAR (SID_SVX_START + 336) +#define SID_NOTEBOOKBAR (SID_SVX_START + 338) +#define SID_MENUBAR (SID_SVX_START + 339) +#define SID_HYPERLINK_GETLINK TypedWhichId(SID_SVX_START + 361) +#define SID_HYPERLINK_SETLINK TypedWhichId(SID_SVX_START + 362) +#define SID_INFOBAR (SID_SVX_START + 365) +#define SID_NAVIGATOR (SID_SVX_START + 366) +#define SID_ZOOM_NEXT (SID_SVX_START + 402) +#define SID_ZOOM_PREV (SID_SVX_START + 403) +#define SID_INET_DLG (SID_SVX_START + 416) +#define SID_AUTO_CORRECT_DLG (SID_SVX_START + 424) +#define SID_ATTR_CHAR_COLOR_EXT (SID_SVX_START + 488) +#define SID_ATTR_CHAR_COLOR_BACKGROUND (SID_SVX_START + 489) +#define SID_ATTR_CHAR_COLOR_BACKGROUND_EXT (SID_SVX_START + 490) +#define SID_ATTR_CHAR_COLOR2 (SID_SVX_START + 537) +#define SID_ATTR_COLOR_STR TypedWhichId(SID_SVX_START + 540) +#define SID_COMP_BIBLIOGRAPHY (SID_SVX_START + 880) +#define SID_ADDRESS_DATA_SOURCE (SID_SVX_START + 934) +#define SID_OPEN_SMARTTAGOPTIONS TypedWhichId(SID_SVX_START + 1062) +#define SID_RULER_MARGIN1 TypedWhichId(SID_SVX_START + 1063) +#define SID_RULER_MARGIN2 TypedWhichId(SID_SVX_START + 1064) +#define SID_TABLE_BORDER_TYPE TypedWhichId(SID_SVX_START + 1065) +#define SID_TABLE_BORDER_INDEX TypedWhichId(SID_SVX_START + 1066) +#define SID_TABLE_BORDER_OFFSET TypedWhichId(SID_SVX_START + 1067) + +#define FID_SVX_START (SID_LIB_START + 500) +#define FID_SEARCH_NOW (FID_SVX_START + 2) +#define SID_BASICIDE_REPEAT_SEARCH (FID_SVX_START + 3) + +// SlotIds for Basic ------------------------------------------------------- +#define SID_BASICIDE_TOGGLEBRKPNT ( SID_BASICIDE_START + 0 ) +#define SID_BASICIDE_ADDWATCH ( SID_BASICIDE_START + 1 ) +#define SID_BASICIDE_CHOOSEMACRO ( SID_BASICIDE_START + 2 ) +#define SID_BASICIDE_EDITMACRO ( SID_BASICIDE_START + 3 ) +#define SID_BASICIDE_CREATEMACRO ( SID_BASICIDE_START + 4 ) +#define SID_BASICIDE_MODULEDLG ( SID_BASICIDE_START + 5 ) +#define SID_BASICIDE_OBJCAT ( SID_BASICIDE_START + 6 ) +#define SID_BASICIDE_REMOVEWATCH ( SID_BASICIDE_START + 7 ) +#define SID_BASICIDE_SHOWSBX ( SID_BASICIDE_START + 9 ) +#define SID_BASICIDE_HIDECURPAGE ( SID_BASICIDE_START + 10 ) +#define SID_BASICIDE_NAMECHANGEDONTAB ( SID_BASICIDE_START + 11 ) +#define SID_BASICIDE_UPDATEMODULESOURCE ( SID_BASICIDE_START + 12 ) +#define SID_BASICIDE_STOREMODULESOURCE ( SID_BASICIDE_START + 13 ) +#define SID_BASICIDE_MATCHGROUP ( SID_BASICIDE_START + 14 ) +#define SID_BASICIDE_APPEAR ( SID_BASICIDE_START + 15 ) +#define SID_BASICIDE_STOREALLMODULESOURCES ( SID_BASICIDE_START + 16 ) +#define SID_BASICIDE_UPDATEALLMODULESOURCES ( SID_BASICIDE_START + 17 ) +#define SID_BASICIDE_LIBSELECTED ( SID_BASICIDE_START + 18 ) +#define SID_BASICIDE_LIBSELECTOR ( SID_BASICIDE_START + 19 ) +#define SID_BASICIDE_NEWDIALOG ( SID_BASICIDE_START + 20 ) +#define SID_BASICIDE_NEWMODULE ( SID_BASICIDE_START + 21 ) +#define SID_BASICIDE_DELETECURRENT ( SID_BASICIDE_START + 22 ) +#define SID_BASICIDE_RENAMECURRENT ( SID_BASICIDE_START + 23 ) +#define SID_BASICIDE_SBXDELETED ( SID_BASICIDE_START + 24 ) +#define SID_BASICIDE_SBXINSERTED ( SID_BASICIDE_START + 25 ) +#define SID_BASICIDE_SBXRENAMED ( SID_BASICIDE_START + 26 ) +#define SID_BASICIDE_LIBLOADED ( SID_BASICIDE_START + 27 ) +#define SID_BASICIDE_LIBREMOVED ( SID_BASICIDE_START + 28 ) +#define SID_BASICIDE_ARG_TABID TypedWhichId( SID_BASICIDE_START + 30 ) +#define SID_BASICIDE_ARG_SBX TypedWhichId( SID_BASICIDE_START + 31 ) +#define SID_BASICIDE_ARG_MACROINFO TypedWhichId( SID_BASICIDE_START + 32 ) +#define SID_BASICIDE_ARG_LIBNAME TypedWhichId( SID_BASICIDE_START + 34 ) +#define SID_BASICIDE_ARG_MODULENAME TypedWhichId( SID_BASICIDE_START + 35 ) +#define SID_BASICIDE_BRKPNTSCHANGED ( SID_BASICIDE_START + 36 ) +#define SID_BASICIDE_STAT_POS ( SID_BASICIDE_START + 38 ) +#define SID_BASICIDE_STAT_DATE ( SID_BASICIDE_START + 39 ) +#define SID_BASICIDE_STAT_TITLE ( SID_BASICIDE_START + 40 ) +#define SID_BASICIDE_MANAGEBRKPNTS ( SID_BASICIDE_START + 42 ) +#define SID_BASICIDE_TOGGLEBRKPNTENABLED ( SID_BASICIDE_START + 43 ) +#define SID_BASICIDE_SHOWWINDOW ( SID_BASICIDE_START + 44 ) +#define SID_BASICIDE_ARG_DOCUMENT TypedWhichId( SID_BASICIDE_START + 45 ) +#define SID_BASICIDE_ARG_NAME ( SID_BASICIDE_START + 46 ) +#define SID_BASICIDE_ARG_TYPE ( SID_BASICIDE_START + 47 ) +#define SID_BASICIDE_ARG_LINE ( SID_BASICIDE_START + 48 ) +#define SID_BASICIDE_ARG_COLUMN1 ( SID_BASICIDE_START + 49 ) +#define SID_BASICIDE_ARG_COLUMN2 ( SID_BASICIDE_START + 50 ) +#define SID_BASICIDE_ARG_DOCUMENT_MODEL TypedWhichId( SID_BASICIDE_START + 51 ) +#define SID_BASICIDE_MANAGE_LANG ( SID_BASICIDE_START + 52 ) +#define SID_BASICIDE_CURRENT_LANG ( SID_BASICIDE_START + 53 ) +#define SID_OPTIONS_TREEDIALOG ( SID_BASICIDE_START + 862) + +// SlotIds for Apps -------------------------------------------------------- +#define FN_PARAM (SID_SW_START + 1100) +#define FN_PARAM_1 (FN_PARAM+60) +#define FN_PARAM_2 (FN_PARAM+61) +#define FN_PARAM_3 (FN_PARAM+62) +#define FN_PARAM_4 (FN_PARAM+63) +#define FN_PARAM_5 (FN_PARAM+64) +#define FN_PARAM_6 (FN_PARAM+65) +#define FN_FAX (SID_SW_START + 28) /* Fax */ + +#define SID_KEYFUNC_START (SID_SC_START + 521) +#define SID_CURSORDOWN_SEL (SID_KEYFUNC_START + 0) +#define SID_CURSORUP_SEL (SID_KEYFUNC_START + 1) +#define SID_CURSORLEFT_SEL (SID_KEYFUNC_START + 2) +#define SID_CURSORRIGHT_SEL (SID_KEYFUNC_START + 3) +#define SID_CURSORPAGEDOWN_SEL (SID_KEYFUNC_START + 4) +#define SID_CURSORPAGEUP_SEL (SID_KEYFUNC_START + 5) +#define SID_CURSORPAGELEFT_SEL (SID_KEYFUNC_START + 7) +#define SID_CURSORPAGERIGHT_SEL (SID_KEYFUNC_START + 9) +#define SID_CURSORTOPOFFILE_SEL (SID_KEYFUNC_START + 10) +#define SID_CURSORENDOFFILE_SEL (SID_KEYFUNC_START + 11) +#define SID_CURSORHOME_SEL (SID_KEYFUNC_START + 12) +#define SID_CURSOREND_SEL (SID_KEYFUNC_START + 13) +#define SID_REPAINT (SID_SC_START + 12) + +#define SID_MODIFIED TypedWhichId(SID_SD_START+89) +#define ID_VAL_DUMMY0 (SID_SD_START+230) +#define SID_SIZE_OPTIMAL (SID_SD_START+99) + +#define SID_ZOOM_OPTIMAL (SID_SIZE_OPTIMAL) +#define SID_ZOOM_ENTIRE_PAGE (SID_SIZE_PAGE) +#define SID_ZOOM_PAGE_WIDTH (SID_SVX_START + 1420) +#define SID_ZOOM_50_PERCENT (SID_SVX_START + 1421) +#define SID_ZOOM_75_PERCENT (SID_SVX_START + 1422) +#define SID_ZOOM_100_PERCENT (SID_SIZE_REAL) +#define SID_ZOOM_150_PERCENT (SID_SVX_START + 1423) +#define SID_ZOOM_200_PERCENT (SID_SVX_START + 1424) + +// SfxScriptOrganizerItem +#define MID_SCRIPT_ORGANIZER_LANGUAGE 1 // Don't use zero for MID's. It's forbidden to do it! + +#define SID_NEWSD (SID_SFX_START + 1686) +#define FN_LABEL (SID_SW_START + 1051 ) +#define FN_BUSINESS_CARD (SID_SW_START + 1052) +#define FN_XFORMS_INIT (SID_SW_START + 1053) + +#define SID_RESTORE_EDITING_VIEW (SID_SFX_START + 1663) + +// SfxSecurityPage related stuff + +#define FN_EDIT2 (SID_SW_START + 1800) +#define FN_REDLINE_PROTECT TypedWhichId(FN_EDIT2 + 23) +#define FN_REDLINE_ON TypedWhichId(FN_EDIT2 + 25) + +#define SID_HTML_MODE TypedWhichId(SID_SVX_START + 414) + +// Calc-Id's used for SfxSecurityPage +#ifndef SC_FUNCTION_START +#define SC_FUNCTION_START (SID_SC_START + 200) +#endif +#ifndef FILE_MENU_END +#define FILE_MENU_END (SC_FUNCTION_START + 20) +#endif +#ifndef EDIT_MENU_START +#define EDIT_MENU_START (FILE_MENU_END) +#endif +#ifndef SC_VIEW_START +#define SC_VIEW_START (SID_SC_START) +#endif +#define FID_CHG_RECORD TypedWhichId(EDIT_MENU_START + 18) +#define SID_CHG_PROTECT TypedWhichId(SC_VIEW_START + 84) + +#endif // #ifndef INCLUDED_SFX2_SFXSIDS_HRC + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxstatuslistener.hxx b/include/sfx2/sfxstatuslistener.hxx new file mode 100644 index 000000000..384d5ac19 --- /dev/null +++ b/include/sfx2/sfxstatuslistener.hxx @@ -0,0 +1,74 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_SFXSTATUSLISTENER_HXX +#define INCLUDED_SFX2_SFXSTATUSLISTENER_HXX + +#include +#include +#include +#include +#include + +#include + +namespace com::sun::star::frame { class XDispatch; } +namespace com::sun::star::frame { class XDispatchProvider; } +namespace com::sun::star::frame { struct FeatureStateEvent; } + +class SFX2_DLLPUBLIC SfxStatusListener : public cppu::WeakImplHelper< + css::frame::XStatusListener, + css::lang::XComponent> +{ + public: + + SfxStatusListener( const css::uno::Reference< css::frame::XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const OUString& aCommand ); + virtual ~SfxStatusListener() override; + + // old methods from SfxControllerItem + sal_uInt16 GetId() const { return m_nSlotID; } + void UnBind(); + void ReBind(); + + virtual void StateChangedAtStatusListener( SfxItemState eState, const SfxPoolItem* pState ); + + // XComponent + virtual void SAL_CALL dispose() override; + virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) override; + virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override; + + // XEventListener + virtual void SAL_CALL disposing(const css::lang::EventObject& Source) override; + + // XStatusListener + virtual void SAL_CALL statusChanged(const css::frame::FeatureStateEvent& Event) override; + + private: + SfxStatusListener( const SfxStatusListener& ) = delete; + SfxStatusListener& operator=( const SfxStatusListener& ) = delete; + + sal_uInt16 m_nSlotID; + css::util::URL m_aCommand; + css::uno::Reference< css::frame::XDispatchProvider > m_xDispatchProvider; + css::uno::Reference< css::frame::XDispatch > m_xDispatch; +}; + +#endif // INCLUDED_SFX2_SFXSTATUSLISTENER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sfxuno.hxx b/include/sfx2/sfxuno.hxx new file mode 100644 index 000000000..6c6253f37 --- /dev/null +++ b/include/sfx2/sfxuno.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_SFXUNO_HXX +#define INCLUDED_SFX2_SFXUNO_HXX + +#include +#include + +namespace com::sun::star::beans { struct NamedValue; } +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::uno { template class Sequence; } + +class SfxAllItemSet ; +class SfxItemSet ; +class SfxSlot ; + +SFX2_DLLPUBLIC void TransformParameters( sal_uInt16 nSlotId , + const css::uno::Sequence< css::beans::PropertyValue >& seqArgs , + SfxAllItemSet& aSet , + const SfxSlot* pSlot = nullptr ); + +SFX2_DLLPUBLIC void TransformItems( sal_uInt16 nSlotId , + const SfxItemSet& aSet , + css::uno::Sequence< css::beans::PropertyValue >& seqArgs , + const SfxSlot* pSlot = nullptr ); + +bool GetEncryptionData_Impl( const SfxItemSet* pSet, css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ); + +typedef sal_Int32 FrameSearchFlags; + +#endif // INCLUDED_SFX2_SFXUNO_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/shell.hxx b/include/sfx2/shell.hxx new file mode 100644 index 000000000..2da1472a8 --- /dev/null +++ b/include/sfx2/shell.hxx @@ -0,0 +1,587 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_SHELL_HXX +#define INCLUDED_SFX2_SHELL_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::embed { struct VerbDescriptor; } +namespace com::sun::star::uno { template class Sequence; } + +class SfxItemPool; +class SfxPoolItem; +class SfxRequest; +class SfxItemSet; +class SfxInterface; +class SfxViewShell; +class SfxObjectShell; + +class SfxShell; +struct SfxShell_Impl; +class SfxDispatcher; +class SfxViewFrame; +class SfxSlot; +class SfxRepeatTarget; +class SfxBindings; +class SfxModule; +class SfxUndoManager; + +/** + Id for s, gives a quasi-static access to the interface + through an array to . +*/ +typedef o3tl::strong_int SfxInterfaceId; + +constexpr auto SFX_INTERFACE_NONE = SfxInterfaceId(0); +constexpr auto SFX_INTERFACE_SFXAPP = SfxInterfaceId(1); +constexpr auto SFX_INTERFACE_SFXDOCSH = SfxInterfaceId(2); +constexpr auto SFX_INTERFACE_SFXVIEWSH = SfxInterfaceId(3); +constexpr auto SFX_INTERFACE_SFXVIEWFRM = SfxInterfaceId(4); +constexpr auto SFX_INTERFACE_SFXMODULE = SfxInterfaceId(5); +constexpr auto SFX_INTERFACE_SC_START = SfxInterfaceId(150); +constexpr auto SFX_INTERFACE_SD_START = SfxInterfaceId(200); +constexpr auto SFX_INTERFACE_SW_START = SfxInterfaceId(250); +constexpr auto SFX_INTERFACE_SMA_START = SfxInterfaceId(340); +constexpr auto SFX_INTERFACE_IDE_START = SfxInterfaceId(400); +constexpr auto SFX_INTERFACE_IDE_END = SfxInterfaceId(409); + +enum class SfxShellFeature +{ + NONE = 0x0000, + // Writer only, class SwView + SwChildWindowLabel = 0x0001, + // Basic only, class Shell + BasicShowBrowser = 0x0004, + // Forms only, class FmFormShell + FormShowDatabaseBar = 0x0008, + FormShowField = 0x0010, + FormShowProperties = 0x0020, + FormShowExplorer = 0x0040, + FormShowFilterBar = 0x0080, + FormShowFilterNavigator = 0x0100, + FormShowTextControlBar = 0x0200, + FormTBControls = 0x0400, + FormTBDesign = 0x1000, + FormShowDataNavigator = 0x2000, + // masks to make sure modules don't use flags from another + SwMask = 0x0001, + BasicMask = 0x0004, + FormMask = 0x3ff8 +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +/* Flags that are being used in the slot definitions for the disable-features */ +enum class SfxDisableFlags { + NONE, + SwOnProtectedCursor = 0x0001, + SwOnMailboxEditor = 0x0002, +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +typedef void (*SfxExecFunc)(SfxShell *, SfxRequest &rReq); +typedef void (*SfxStateFunc)(SfxShell *, SfxItemSet &rSet); + +/** + The class SfxShell is the base class for all classes, which provide + the functionality of the form s. + + Each instance has a reference to an interface description, which is + obtainable through . This interface + provides the connection to specific methods and contains some other + descriptive data for controllers like menus and toolboxes, but also + for the various APIs. The main part of the interface description is in + the form of a , which is generated from an IDL-file by + the . For each SfxShell Subclass-File there is one + such IDL-file to write. +*/ +class SFX2_DLLPUBLIC SfxShell: public SfxBroadcaster +{ + friend class SfxObjectItem; + + std::unique_ptr< SfxShell_Impl > pImpl; + SfxItemPool* pPool; + SfxUndoManager* pUndoMgr; + +private: + SfxShell( const SfxShell & ) = delete; + SfxShell& operator = ( const SfxShell & ) = delete; + +protected: + /** + The constructor of the SfxShell class initializes only simple types, + the corresponding SbxObject is only created on-demand. Therefore, + the application of a SfxShell instance is very cheap. + */ + SfxShell(); + + /** + The constructor of the SfxShell class initializes only simple types, + the corresponding SbxObject is only created on-demand. Therefore, + the application of a SfxShell instance is very cheap. + */ + SfxShell( SfxViewShell *pViewSh ); + + void SetViewShell_Impl( SfxViewShell* pView ); + SAL_DLLPRIVATE void Invalidate_Impl( SfxBindings& rBindings, sal_uInt16 nId ); + static void HandleOpenXmlFilterSettings(SfxRequest &); + +public: + + /** + The connection to a possible corresponding SbxObject is dissolved. + The SbxObject may continue to exist, but can not any longer perform + any functions and can not provide any properties. + */ + virtual ~SfxShell() override; + + /** + With this virtual method, which is automatically overridden by each subclass + with its own slots through the macro , one can access + each of the instance belonging to the subclass. + + The class SfxShell itself has no own SfxInterface (no slots), therefore a + NULL-pointer is returned. + */ + virtual SfxInterface* GetInterface() const; + static SfxInterface* GetStaticInterface() { return nullptr; } + + /** + Sets the name of the Shell object. With this name, the SfxShell instance + of BASIC can be expressed. + */ + void SetName( const OUString &rName ); + + /** + Returns the name of the Shell object. With this name, the SfxShell instance + of BASIC can be expressed. + */ + const OUString& GetName() const; + + /** + Returns the SfxViewShell in which they are located in the subshells. + Otherwise, and if not specified by the App developer, this method + returns NULL. + */ + SfxViewShell* GetViewShell() const; + + static void EmptyExecStub(SfxShell *pShell, SfxRequest &); + static void EmptyStateStub(SfxShell *pShell, SfxItemSet &); + + /** + This method returns the status of the slot with the specified slot ID + on the specified interface. + + If the slot is disabled or in this SfxShell (and their parent shells) are + not known, a Null-pointer is returned. + + If the slot does not have a Status, a SfxVoidItem is returned. + + The status is set directly in this Set when pStateSet != 0 , so that + overridden Slots of the Subclasses and also in the Status + method of the base implementation can be called. + + [Example] + + In a derived class of SfxViewShell the SID_PRINTDOCDIRECT will be + intercepted. Under certain circumstances a query should appear before + you print, and the request will be aborted if necessary. + + Also in the IDL of this subclass of the above slot is entered. The status + method will contain in outline: + + void SubViewShell::PrintState( SfxItemSet &rState ) + { + if ( rState.GetItemState( SID_PRINTDOCDIRECT ) != SfxItemState::UNKNOWN ) + GetSlotState( SID_PRINTDOCDIRECT, SfxViewShell::GetInterface(), + &rState ); + ... + } + + [Cross-reference] + + + */ + const SfxPoolItem* GetSlotState( sal_uInt16 nSlotId, const SfxInterface *pIF = nullptr, SfxItemSet *pStateSet = nullptr ); + + /** + This method allows you to forward a to the specified + base . + + [Example] + + In a derived class of SfxViewShell the SID_PRINTDOCDIRECT will be + intercepted. Under certain circumstances a query should appear before + you print, and the request will be aborted if necessary. + + Also in the IDL of this subclass of the above slot is entered. The status + method will contain in outline: + + void SubViewShell::Exec( SfxRequest &rReq ) + { + if ( rReq.GetSlot() == SID_PRINTDOCDIRECT ) + { + 'dialog' + if ( 'condition' ) + ExecuteSlot( rReq, SfxViewShell::GetInterface() ); + } + } + + It usually takes no rReq.Done() to be called as that is already completed + in implementation of the SfxViewShell, for instance it has been canceled. + + [Cross-reference] + + + */ + const SfxPoolItem* ExecuteSlot( SfxRequest &rReq, const SfxInterface *pIF = nullptr ); + + /** + Asynchronous ExecuteSlot for the RELOAD + */ + void ExecuteSlot( SfxRequest &rReq, bool bAsync ); + + inline SfxItemPool& GetPool() const; + inline void SetPool( SfxItemPool *pNewPool ) ; + + /** + Each Subclass of SfxShell can have a . This can be set in + the derived class with . + + The class SfxShell itself does not have a SfxUndoManager, a NULL-pointer + is therefore returned. + */ + virtual SfxUndoManager* GetUndoManager(); + + /** + Sets a for this Instance. For the undo + is only the undo-manager used for SfxShell at the top of the stack of each + . + + On the given is automatically the current + Max-Undo-Action-Count setting set from the options. + + 'pNewUndoMgr' must exist until the Destructor of SfxShell instance is called + or until the next 'SetUndoManager()'. + */ + void SetUndoManager( SfxUndoManager *pNewUndoMgr ); + + /** + Returns a pointer to the instance that is used in + SID_REPEAT as repeat target when it is addressed from the + supplied by this SfxShell. The return value can be NULL. + + [Note] + + A derivation of or one of its subclasses of + is not recommended, as compiler errors are provoked. + (due to Call-to-Pointer-to-Member-Function to the subclass). + */ + SfxRepeatTarget* GetRepeatTarget() const; + + /** + Sets the instance that is used in SID_REPEAT as + RepeatTarget, when the current supplied by this is + addressed. By 'pTarget==0' the SID_REPEAT is disabled for this SfxShell. + The instance '*pTarget' must live as long as it is registered. + + [Note] + + A derivation of or one of its subclasses of + is not recommended, as compiler errors are provoked. + (due to Call-to-Pointer-to-Member-Function to the subclass). + */ + void SetRepeatTarget( SfxRepeatTarget *pTarget ); + + /** + With this method can the slots of the subclasses be invalidated through the + slot Id or alternatively through the Which ID. Slot IDs, which are + inherited by the subclass are also invalidated. + + [Cross-reference] + + + + */ + virtual void Invalidate(sal_uInt16 nId = 0); + + virtual bool IsDesignMode() const { return false; }; + + bool IsActive() const; + + /** + Virtual method that is called when enabling the SfxShell instance, + in order to give the Subclasses the opportunity to respond to the + to the enabling. + + [Cross-reference] + + StarView SystemWindow::Activate(bool) + */ + virtual void Activate(bool bMDI); + + /** + Virtual method that is called when disabling the SfxShell instance, + to give the Subclasses the opportunity to respond to the disabling. + + [Cross-reference] + + StarView SystemWindow::Deactivate(bool) + */ + virtual void Deactivate(bool bMDI); + + /** + This method returns a pointer to the , when the SfxShell + is currently or a NULL-pointer if it is not UI-active. + + The returned pointer is only valid in the immediate context of the method + call. + */ + SfxDispatcher* GetDispatcher() const; + + /** + This method returns a pointer to the to which this SfxShell + instance is associated or in which they currently is . + A NULL pointer is returned if this SfxShell instance is not UI-active at + the moment and also no SfxViewFrame is permanently assigned. + + The returned pointer is only valid in the immediate context of the method + call. + + [Note] + + Only instances of a subclass of SfxApplication and SfxObjectShell + should here provide a NULL-pointer. Otherwise, there is an error in the + application program (wrong constructor was called from SfxShell). + + [Cross-reference] + + + */ + SfxViewFrame* GetFrame() const; + + virtual bool HasUIFeature(SfxShellFeature nFeature) const; + void UIFeatureChanged(); + + // Items + /** + With this method any objects of subclasses can be accessed. + This exchange method is needed if, for example special + subclasses need access to certain data such as the . + + The returned instance belongs to the particular SfxShell and may be + used only in the immediate context of the method call. + + [Cross-reference] + + + + */ + const SfxPoolItem* GetItem( sal_uInt16 nSlotId ) const; + template const T* GetItem( TypedWhichId nWhich ) const + { + return static_cast(GetItem(sal_uInt16(nWhich))); + } + + /** + With this method, any objects of subclasses of can be made + available. This exchange technology is needed if, for example, special + Subclasses need access to certain data such as the + + + If a SfxPoolItem exists with the same slot ID, it is deleted automatically. + + [Cross-reference] + + + + */ + void PutItem( const SfxPoolItem& rItem ); + + // TODO/CLEANUP: still needed?! + void SetVerbs(const css::uno::Sequence < css::embed::VerbDescriptor >& aVerbs); + const css::uno::Sequence < css::embed::VerbDescriptor >& GetVerbs() const; + void VerbExec (SfxRequest&); + static void VerbState (SfxItemSet&); + SAL_DLLPRIVATE const SfxSlot* GetVerbSlot_Impl(sal_uInt16 nId) const; + + virtual SfxObjectShell* GetObjectShell(); + void SetDisableFlags( SfxDisableFlags nFlags ); + SfxDisableFlags GetDisableFlags() const; + + virtual std::optional CreateItemSet( sal_uInt16 nId ); + virtual void ApplyItemSet( sal_uInt16 nId, const SfxItemSet& rSet ); + + /** Set the name of the sidebar context that is broadcast on calls + to Activation(). + */ + void SetContextName (const OUString& rsContextName); + + /** Broadcast a sidebar context change. + This method is typically called from Activate() or + Deactivate(). + @param bIsActivated + When then broadcast the context name that was + defined with an earlier call to SetContextName(). + When then broadcast the 'default' context. + */ + void BroadcastContextForActivation (const bool bIsActivated); + + /** Enabled or disable the context broadcaster. Returns the old state. + */ + bool SetContextBroadcasterEnabled (const bool bIsEnabled); + + /** + + This method determines by calling the status function whether 'rSlot' + can be executed currently. + */ + SAL_DLLPRIVATE bool CanExecuteSlot_Impl( const SfxSlot &rSlot ); + + /** + + This method determines whether we need to execute without checking + the disabled state of the slot. This is used for dynamic conditions + while you can use SfxSlotMode::FASTCALL for a specific slotid in general. + */ + virtual bool IsConditionalFastCall( const SfxRequest &rReq ); + + /** + + This method controls the activation of SfxShell instance. First, by calling + the virtual method which gives the subclass the + opportunity to respond to the event. + + When bMDI == TRUE, the associated SbxObject is being 'armed', so that + unqualified methods of the object (without the name of the object) + from BASIC are found. + */ + SAL_DLLPRIVATE void DoActivate_Impl( SfxViewFrame *pFrame, bool bMDI); + + /** + + This method controls the deactivation of the SfxShell instance. When + bMDI == TRUE the SbxObject is first set to a status that only qualified + BASIC methods can be called. + + Then the subclass gets the opportunity in every case to respond to the + event by calling the virtual method . + */ + SAL_DLLPRIVATE void DoDeactivate_Impl( SfxViewFrame const *pFrame, bool bMDI); +}; + +/** + Each Subclass of SfxShell must reference a pool. This is partly set by + SFx's own set of subclasses (eg ). In particular however + this must be set directly from one derived SfxShell class and ny + derivatives of SfxObjectShell. + + The SfxShell class itself does not have any SfxItemPool, therefore a + null-pointer is returned. +*/ +SfxItemPool& SfxShell::GetPool() const +{ + assert(pPool && "no pool"); + return *pPool; +} + +/** + With this method, the subclasses register their special + in the SfxShell. Each SfxShell instance must have access to a SfxItemPool. + Usually this is the SfxItemPool of the SfxDocumentShell. The SfxShell + subclass does not take ownership of the orphaned pool. Before it is + deleted it has to be deregistered with SetPool(0). +*/ +inline void SfxShell::SetPool +( + SfxItemPool* pNewPool // Pointer to the new Pool or null +) +{ + pPool = pNewPool; +} + +#define SFX_DECL_INTERFACE(nId) \ + static SfxInterface* s_pInterface; \ + static SfxInterface* GetStaticInterface(); \ + static SfxInterfaceId GetInterfaceId() {return nId;} \ + static void RegisterInterface(const SfxModule* pMod=nullptr); \ + virtual SfxInterface* GetInterface() const override; + +#define SFX_TMPL_INTERFACE(Class,SuperClass,Abstract) \ + \ + SfxInterface* Class::s_pInterface = nullptr; \ + SfxInterface* Class::GetStaticInterface() \ + { \ + if ( !s_pInterface ) \ + { \ + s_pInterface = \ + new SfxInterface( \ + #Class, Abstract, GetInterfaceId(), \ + SuperClass::GetStaticInterface(), \ + a##Class##Slots_Impl[0], \ + sal_uInt16(sizeof(a##Class##Slots_Impl) / sizeof(SfxSlot) ) ); \ + InitInterface_Impl(); \ + } \ + return s_pInterface; \ + } \ + \ + SfxInterface* Class::GetInterface() const \ + { \ + return GetStaticInterface(); \ + } \ + \ + void Class::RegisterInterface(const SfxModule* pMod) \ + { \ + GetStaticInterface()->Register(pMod); \ + } + +#define SFX_IMPL_INTERFACE(Class,SuperClass) \ +SFX_TMPL_INTERFACE(Class,SuperClass,false) \ + +#define SFX_IMPL_SUPERCLASS_INTERFACE(Class,SuperClass) \ +SFX_TMPL_INTERFACE(Class,SuperClass,true) \ + +enum class SfxVisibilityFlags { + Invisible = 0x0000, // Never visible + Viewer = 0x0040, + ReadonlyDoc = 0x0400, + Standard = 0x1000, + FullScreen = 0x2000, + Client = 0x4000, + Server = 0x8000, +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/AsynchronousCall.hxx b/include/sfx2/sidebar/AsynchronousCall.hxx new file mode 100644 index 000000000..0f2377abc --- /dev/null +++ b/include/sfx2/sidebar/AsynchronousCall.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +struct ImplSVEvent; + +namespace sfx2::sidebar +{ +/** A simple asynchronous call via Application::PostUserCall. +*/ +class AsynchronousCall +{ +public: + typedef ::std::function Action; + + AsynchronousCall(const Action& rAction); + ~AsynchronousCall(); + + void RequestCall(); + void CancelRequest(); + void Sync(); + +private: + Action maAction; + ImplSVEvent* mnCallId; + + DECL_LINK(HandleUserCall, void*, void); +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/Context.hxx b/include/sfx2/sidebar/Context.hxx new file mode 100644 index 000000000..f4ca42d75 --- /dev/null +++ b/include/sfx2/sidebar/Context.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +namespace sfx2::sidebar +{ +class SFX2_DLLPUBLIC Context +{ +public: + OUString msApplication; + OUString msContext; + + Context(); + Context(const OUString& rsApplication, const OUString& rsContext); + + /** When two contexts are matched against each other, then + application or context name may have the wildcard value 'any'. + In order to prefer matches without wildcards over matches with + wildcards we introduce an integer evaluation for matches. + */ + const static sal_Int32 NoMatch; + const static sal_Int32 OptimalMatch; + const static sal_Int32 ApplicationWildcardMatch; + const static sal_Int32 ContextWildcardMatch; + + /** Return the numeric value that describes how good the match + between two contexts is. + Smaller values represent better matches. + */ + sal_Int32 EvaluateMatch(const Context& rOther) const; + + bool operator==(const Context& rOther) const; + bool operator!=(const Context& rOther) const; +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/ControllerItem.hxx b/include/sfx2/sidebar/ControllerItem.hxx new file mode 100644 index 000000000..a8f82195a --- /dev/null +++ b/include/sfx2/sidebar/ControllerItem.hxx @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +namespace com::sun::star::lang { class XComponent; } + + +namespace sfx2::sidebar { + +/** The sfx2::sidebar::ControllerItem is a wrapper around the + SfxControllerItem that becomes necessary to allow objects (think + sidebar panels) to receive state changes without having one + SfxControllerItem per supported item as base class (which is not + possible in C++ anyway). + + It also gives access to the label and icon of a slot/command. +*/ +class SFX2_DLLPUBLIC ControllerItem final + : public SfxControllerItem +{ +public: + class SFX2_DLLPUBLIC ItemUpdateReceiverInterface + { + public: + virtual void NotifyItemUpdate( + const sal_uInt16 nSId, + const SfxItemState eState, + const SfxPoolItem* pState) = 0; + virtual void GetControlState( + const sal_uInt16 nSId, + boost::property_tree::ptree& rState) = 0; + virtual ~ItemUpdateReceiverInterface(); + }; + + /** This is the simpler constructor variant that still exists for + compatibility reasons. Note that GetLabel() and GetIcon() will + return empty strings/images. + */ + ControllerItem ( + const sal_uInt16 nId, + SfxBindings &rBindings, + ItemUpdateReceiverInterface& rItemUpdateReceiver); + + virtual ~ControllerItem() override; + + /** Force the controller item to call its NotifyItemUpdate + callback with up-to-date data. + */ + void RequestUpdate(); + +private: + + virtual void StateChangedAtToolBoxControl (sal_uInt16 nSId, SfxItemState eState, const SfxPoolItem* pState) override; + virtual void GetControlState (sal_uInt16 nSId, boost::property_tree::ptree& rState) override; + + ItemUpdateReceiverInterface& mrItemUpdateReceiver; +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/Deck.hxx b/include/sfx2/sidebar/Deck.hxx new file mode 100644 index 000000000..fe73e6332 --- /dev/null +++ b/include/sfx2/sidebar/Deck.hxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +namespace sfx2::sidebar +{ +class DeckDescriptor; +class DeckTitleBar; +class SidebarDockingWindow; + +/** This is the parent window of the panels. + It displays the deck title. + + A deck consists of multiple panels. + E.g. Properties, Styles, Navigator. +*/ +class Deck final : public InterimItemWindow +{ +public: + Deck(const DeckDescriptor& rDeckDescriptor, SidebarDockingWindow* pParentWindow, + const std::function& rCloserAction); + virtual ~Deck() override; + virtual void dispose() override; + + const OUString& GetId() const { return msId; } + + DeckTitleBar* GetTitleBar() const; + tools::Rectangle GetContentArea() const; + void ResetPanels(SharedPanelContainer&& rPanels); + const SharedPanelContainer& GetPanels() const { return maPanels; } + + std::shared_ptr GetPanel(std::u16string_view panelId); + + void RequestLayout(); + weld::Widget* GetPanelParentWindow(); + + /** Try to make the panel completely visible. + When the whole panel does not fit then make its top visible + and it off at the bottom. + */ + void ShowPanel(const Panel& rPanel); + + virtual void DataChanged(const DataChangedEvent& rEvent) override; + + virtual void DumpAsPropertyTree(tools::JsonWriter&) override; + + sal_Int32 GetMinimalWidth() const { return mnMinimalWidth; } + +private: + void RequestLayoutInternal(); + +private: + const OUString msId; + sal_Int32 mnMinimalWidth; + sal_Int32 mnScrolledWindowExtraWidth; + sal_Int32 mnMinimalHeight; + SharedPanelContainer maPanels; + + VclPtr mxParentWindow; + std::unique_ptr mxTitleBar; + std::unique_ptr mxVerticalScrollBar; + std::unique_ptr mxContents; +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/FocusManager.hxx b/include/sfx2/sidebar/FocusManager.hxx new file mode 100644 index 000000000..c51ccbfa8 --- /dev/null +++ b/include/sfx2/sidebar/FocusManager.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +namespace weld { +class Widget; +} + +namespace sfx2::sidebar { + +class DeckTitleBar; + +/** Concentrate all focus handling in this class. + + There is one ring of windows that accept the input focus which are + cycled through with the arrow keys: + - the closer in the deck title (present only when docked) + - the panel title bars + - the tab bar items + + When the focus is in a panel title then focus travels over + - the panel title + - the panel closer + - the panel content + + Once the focus is in the panel content then focus cycles through + all controls inside the panel but not back to the title bar of + the panel. Escape places the focus back in the panel title. +*/ +class FocusManager +{ +public: + FocusManager(const std::function& rShowPanelFunctor); + ~FocusManager(); + + /** Forget all panels and buttons. Remove all window listeners. + */ + void Clear(); + + /** Transfer the focus into the sidebar tree of windows. This is + typically called from the SidebarChildWindow as result of + pressing the F6 key. + */ + void GrabFocus(); + void GrabFocusPanel(); + + void SetDeck(Deck* pDeck); + void SetPanels(const SharedPanelContainer& rPanels); + void SetButtons(const std::vector& rButtons); + +private: + VclPtr mxDeck; + DeckTitleBar* mpDeckTitleBar; + SharedPanelContainer maPanels; + std::vector maButtons; + const std::function maShowPanelFunctor; + + enum PanelComponent + { + PC_DeckToolBox, + PC_PanelTitle, + PC_PanelToolBox, + PC_PanelContent, + PC_TabBar, + PC_None + }; + class FocusLocation + { + public: + PanelComponent meComponent; + sal_Int32 mnIndex; + FocusLocation(const PanelComponent eComponent, const sal_Int32 nIndex); + }; + + /** Listen for key events for panels and buttons. + */ + DECL_LINK(KeyInputHdl, const KeyEvent&, bool); + + void ClearPanels(); + void ClearButtons(); + + /** Let the focus manager listen for window events for the given + window. + */ + void RegisterWindow(weld::Widget& rWidget); + static void UnregisterWindow(weld::Widget& rWidget); + + void FocusDeckTitle(); + bool IsDeckTitleVisible() const; + bool IsPanelTitleVisible(const sal_Int32 nPanelIndex) const; + + /** Set the focus to the title bar of the panel or, if the + title bar is not visible, directly to the panel. + @param nPanelIndex + Index of the panel to focus. + @param bFallbackToDeckTitle + When the panel title bar is not visible then The fallback + bias defines whether to focus the deck (true) or the panel + content (false) will be focused instead. + */ + void FocusPanel(const sal_Int32 nPanelIndex, + const bool bFallbackToDeckTitle); + + void FocusPanelContent(const sal_Int32 nPanelIndex); + void FocusButton(const sal_Int32 nButtonIndex); + void MoveFocusInsidePanel(const FocusLocation& rLocation, + const sal_Int32 nDirection); + bool MoveFocusInsideDeckTitle(const FocusLocation& rLocation, + const sal_Int32 nDirection); + + bool HandleKeyEvent(const vcl::KeyCode& rKeyCode, + const FocusLocation& rLocation); + + FocusLocation GetFocusLocation() const; + +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/IContextChangeReceiver.hxx b/include/sfx2/sidebar/IContextChangeReceiver.hxx new file mode 100644 index 000000000..784193c04 --- /dev/null +++ b/include/sfx2/sidebar/IContextChangeReceiver.hxx @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +namespace vcl +{ +class EnumContext; +} + +namespace sfx2::sidebar +{ +class SFX2_DLLPUBLIC IContextChangeReceiver +{ +public: + virtual ~IContextChangeReceiver(); + + virtual void HandleContextChange(const vcl::EnumContext& rContext) = 0; +}; + +} // end of namespace ::sd::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/ILayoutableWindow.hxx b/include/sfx2/sidebar/ILayoutableWindow.hxx new file mode 100644 index 000000000..344e7fd4f --- /dev/null +++ b/include/sfx2/sidebar/ILayoutableWindow.hxx @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +namespace sfx2::sidebar +{ +class SFX2_DLLPUBLIC ILayoutableWindow +{ +public: + virtual ~ILayoutableWindow(); + + /** Return the preferred height with the constraint, that the + window will be set to the given width. + */ + virtual css::ui::LayoutSize GetHeightForWidth(const sal_Int32 nWidth) = 0; +}; + +} // end of namespace ::sd::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/Panel.hxx b/include/sfx2/sidebar/Panel.hxx new file mode 100644 index 000000000..1c0af8ad2 --- /dev/null +++ b/include/sfx2/sidebar/Panel.hxx @@ -0,0 +1,123 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +namespace com::sun::star::frame +{ +class XFrame; +} +namespace com::sun::star::ui +{ +class XSidebarPanel; +} +namespace com::sun::star::ui +{ +class XUIElement; +} +namespace com::sun::star::awt +{ +class XWindow; +} + +namespace sfx2::sidebar +{ +class Context; +class Deck; +class PanelDescriptor; +class PanelTitleBar; + +/** + * Multiple panels form a single deck. + * E.g. the Properties deck has panels like Styles, Character, paragraph. + */ +class SFX2_DLLPUBLIC Panel final +{ +public: + Panel(const PanelDescriptor& rPanelDescriptor, weld::Widget* pParentWindow, + const bool bIsInitiallyExpanded, Deck* pDeck, + const std::function& rContextAccess, + const css::uno::Reference& rxFrame); + + ~Panel(); + + PanelTitleBar* GetTitleBar() const; + weld::Box* GetContents() const; + void Show(bool bShow); + bool IsTitleBarOptional() const { return mbIsTitleBarOptional; } + void SetUIElement(const css::uno::Reference& rxElement); + const css::uno::Reference& GetPanelComponent() const + { + return mxPanelComponent; + } + const css::uno::Reference& GetElementParentWindow(); + css::uno::Reference GetElementWindow(); + void SetExpanded(const bool bIsExpanded); + bool IsExpanded() const { return mbIsExpanded; } + bool HasIdPredicate(std::u16string_view rsId) const; + const OUString& GetId() const { return msPanelId; } + const OUString& GetTitle() const { return msTitle; } + void TriggerDeckLayouting(); + + void SetHeightPixel(int nHeight); + + bool get_extents(tools::Rectangle& rExtents) const; + + /// Set whether a panel should be present but invisible / inactive + void SetLurkMode(bool bLurk); + bool IsLurking() const { return mbLurking; } + + void set_margin_top(int nMargin); + void set_margin_bottom(int nMargin); + void set_vexpand(bool bExpand); + + weld::Window* GetFrameWeld(); + + void DataChanged(); + +private: + std::unique_ptr mxBuilder; + const OUString msPanelId; + const OUString msTitle; + const bool mbIsTitleBarOptional; + const bool mbWantsAWT; + css::uno::Reference mxElement; + css::uno::Reference mxPanelComponent; + bool mbIsExpanded; + bool mbLurking; + const std::function maContextAccess; + const css::uno::Reference& mxFrame; + weld::Widget* mpParentWindow; + VclPtr mxDeck; + std::unique_ptr mxContainer; + std::unique_ptr mxTitleBar; + std::unique_ptr mxContents; + css::uno::Reference mxXWindow; + + DECL_DLLPRIVATE_LINK(DumpAsPropertyTreeHdl, tools::JsonWriter&, void); +}; + +typedef std::vector> SharedPanelContainer; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/PanelLayout.hxx b/include/sfx2/sidebar/PanelLayout.hxx new file mode 100644 index 000000000..301159362 --- /dev/null +++ b/include/sfx2/sidebar/PanelLayout.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include + +class DataChangedEvent; +class VclSimpleEvent; +namespace sfx2 { namespace sidebar { class Panel; } } +namespace tools { class JsonWriter; } + +/// This class is the base for the Widget Layout-based sidebar panels. +class SFX2_DLLPUBLIC PanelLayout +{ +protected: + std::unique_ptr m_xBuilder; + std::unique_ptr m_xContainer; + sfx2::sidebar::Panel* m_pPanel; + + virtual void DataChanged(const DataChangedEvent& rEvent); + virtual void DumpAsPropertyTree(tools::JsonWriter&); + + virtual weld::Window* GetFrameWeld() const; + +private: + DECL_DLLPRIVATE_LINK(DataChangedEventListener, VclSimpleEvent&, void); + DECL_DLLPRIVATE_LINK(DumpAsPropertyTreeHdl, tools::JsonWriter&, void); + +public: + PanelLayout(weld::Widget* pParent, const OString& rID, const OUString& rUIXMLDescription); + + void SetPanel(sfx2::sidebar::Panel* pPanel); + + virtual ~PanelLayout(); + + Size get_preferred_size() const + { + return m_xContainer->get_preferred_size(); + } + + void queue_resize(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/ResourceManager.hxx b/include/sfx2/sidebar/ResourceManager.hxx new file mode 100644 index 000000000..9ac1130cc --- /dev/null +++ b/include/sfx2/sidebar/ResourceManager.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include + +#include + +namespace com::sun::star::frame { class XController; } +namespace com::sun::star::frame { class XModel; } +namespace sfx2::sidebar { class DeckDescriptor; } +namespace sfx2::sidebar { class PanelDescriptor; } + +namespace sfx2::sidebar { + +class Context; +class ContextList; + +/** Read the content of the Sidebar.xcu file and provide access + methods so that the sidebar can easily decide which content panels + to display for a certain context. +*/ +class SFX2_DLLPUBLIC ResourceManager +{ +public: + + ResourceManager(); + ~ResourceManager(); + + std::shared_ptr GetDeckDescriptor(std::u16string_view rsDeckId) const; + std::shared_ptr GetPanelDescriptor(std::u16string_view rsPanelId) const; + + void UpdateModel(const css::uno::Reference& xModel); + + void InitDeckContext(const Context& rContex); + void SaveDecksSettings(const Context& rContext); + void SaveDeckSettings(const DeckDescriptor* pDeckDesc); + void SaveLastActiveDeck(const Context& rContext, const OUString& rActiveDeck); + + void disposeDecks(); + + class DeckContextDescriptor + { + public: + OUString msId; + bool mbIsEnabled; + }; + typedef std::vector DeckContextDescriptorContainer; + + class PanelContextDescriptor + { + public: + OUString msId; + OUString msMenuCommand; + bool mbIsInitiallyVisible; + bool mbShowForReadOnlyDocuments; + }; + typedef std::vector PanelContextDescriptorContainer; + + const DeckContextDescriptorContainer& GetMatchingDecks( + DeckContextDescriptorContainer& rDeckDescriptors, + const Context& rContext, + const bool bIsDocumentReadOnly, + const css::uno::Reference& rxController); + + const PanelContextDescriptorContainer& GetMatchingPanels( + PanelContextDescriptorContainer& rPanelDescriptors, + const Context& rContext, + std::u16string_view rsDeckId, + const css::uno::Reference& rxController); + + const OUString& GetLastActiveDeck( const Context& rContext ); + void SetLastActiveDeck( const Context& rContext, const OUString& rsDeckId ); + + /** Remember the expansions state per panel and context. + */ + void StorePanelExpansionState(std::u16string_view rsPanelId, + const bool bExpansionState, + const Context& rContext); + +private: + + + typedef std::vector> DeckContainer; + DeckContainer maDecks; + + typedef std::vector> PanelContainer; + PanelContainer maPanels; + mutable std::set maProcessedApplications; + std::map maLastActiveDecks; + + void ReadDeckList(); + void ReadPanelList(); + void ReadLastActive(); + static void ReadContextList(const utl::OConfigurationNode& rNode, + ContextList& rContextList, + const OUString& rsDefaultMenuCommand); + + void ReadLegacyAddons(const css::uno::Reference& rxController); + static utl::OConfigurationTreeRoot GetLegacyAddonRootNode(const OUString& rsModuleName); + static void GetToolPanelNodeNames(std::vector& rMatchingNames, + const utl::OConfigurationTreeRoot& aRoot); + bool IsDeckEnabled(std::u16string_view rsDeckId, + const Context& rContext, + const css::uno::Reference& rxController); + + std::shared_ptr ImplGetDeckDescriptor(std::u16string_view rsDeckId) const; + std::shared_ptr ImplGetPanelDescriptor(std::u16string_view rsPanelId) const; +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/Sidebar.hxx b/include/sfx2/sidebar/Sidebar.hxx new file mode 100644 index 000000000..2520a80a4 --- /dev/null +++ b/include/sfx2/sidebar/Sidebar.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include + +namespace com::sun::star::frame { class XFrame; } +namespace com::sun::star::uno { template class Reference; } + + +namespace sfx2::sidebar { + +/** Accept requests for switching to certain panels or decks. +*/ +class SFX2_DLLPUBLIC Sidebar +{ +public: + static void ToggleDeck(std::u16string_view rsDeckId, SfxViewFrame *pViewFrame); + + /** Switch to the deck that contains the specified panel and make + sure that the panel is visible (expanded and scrolled into the + visible area.) + Note that most of the work is done asynchronously and that + this function probably returns before the requested panel is visible. + */ + static void ShowPanel ( + std::u16string_view rsPanelId, + const css::uno::Reference& rxFrame, bool bFocus = false); + + /** Switch to the deck that contains the specified panel and toggle + the visibility of the panel (expanded and scrolled into the + visible area when visible) + Note that most of the work is done asynchronously and that + this function probably returns before the requested panel is visible. + */ + static void TogglePanel ( + std::u16string_view rsPanelId, + const css::uno::Reference& rxFrame); + + static bool IsPanelVisible( + std::u16string_view rsPanelId, + const css::uno::Reference& rxFrame); +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/SidebarChildWindow.hxx b/include/sfx2/sidebar/SidebarChildWindow.hxx new file mode 100644 index 000000000..279aa79b5 --- /dev/null +++ b/include/sfx2/sidebar/SidebarChildWindow.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + + +namespace sfx2::sidebar { + +/** Outer container of the sidebar window. + + Has to be registered for every application via the + RegisterChildWindow() method from the RegisterControllers() method + of the applications DLL. +*/ +class SFX2_DLLPUBLIC SidebarChildWindow final : public SfxChildWindow +{ +public: + SidebarChildWindow(vcl::Window* pParent, sal_uInt16 nId, + SfxBindings* pBindings, SfxChildWinInfo* pInfo); + + SFX_DECL_CHILDWINDOW_WITHID(SidebarChildWindow); + + static sal_Int32 GetDefaultWidth(vcl::Window const * pWindow); +}; + + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/SidebarController.hxx b/include/sfx2/sidebar/SidebarController.hxx new file mode 100644 index 000000000..8d8dcf215 --- /dev/null +++ b/include/sfx2/sidebar/SidebarController.hxx @@ -0,0 +1,302 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::awt { class XWindow; } +namespace com::sun::star::frame { class XDispatch; } +namespace com::sun::star::ui { class XUIElement; } + +typedef comphelper::WeakComponentImplHelper < + css::ui::XContextChangeEventListener, + css::beans::XPropertyChangeListener, + css::ui::XSidebar, + css::frame::XStatusListener, + css::frame::XFrameActionListener + > SidebarControllerInterfaceBase; + +class SfxSplitWindow; +class SfxViewShell; + +namespace sfx2::sidebar { + +class DeckDescriptor; +class SidebarDockingWindow; + +class SFX2_DLLPUBLIC SidebarController final + : public SidebarControllerInterfaceBase +{ +public: + static rtl::Reference create(SidebarDockingWindow* pParentWindow, + const SfxViewFrame* pViewFrame); + virtual ~SidebarController() override; + SidebarController(const SidebarController&) = delete; + SidebarController& operator=( const SidebarController& ) = delete; + + /** Return the SidebarController object that is associated with + the given XFrame. + @return + When there is no SidebarController object for the given + XFrame then is returned. + */ + static SidebarController* GetSidebarControllerForFrame ( + const css::uno::Reference& rxFrame); + + static void registerSidebarForFrame(SidebarController* pController, const css::uno::Reference& xFrame); + + static void unregisterSidebarForFrame(SidebarController* pController, const css::uno::Reference& xFrame); + + // ui::XContextChangeEventListener + virtual void SAL_CALL notifyContextChangeEvent (const css::ui::ContextChangeEventObject& rEvent) override; + + // XEventListener + virtual void SAL_CALL disposing (const css::lang::EventObject& rEventObject) override; + + // beans::XPropertyChangeListener + virtual void SAL_CALL propertyChange (const css::beans::PropertyChangeEvent& rEvent) override; + + // frame::XStatusListener + virtual void SAL_CALL statusChanged (const css::frame::FeatureStateEvent& rEvent) override; + + // frame::XFrameActionListener + virtual void SAL_CALL frameAction (const css::frame::FrameActionEvent& rEvent) override; + + // ui::XSidebar + virtual void SAL_CALL requestLayout() override; + + void NotifyResize(); + + /** In some situations it is necessary to force an update of the + current deck and its panels. One reason is a change of the + view scale. Some panels can handle this only when + constructed. In this case we have to a context change and + also force that all panels are destroyed and created new. + */ + const static sal_Int32 SwitchFlag_NoForce = 0x00; + const static sal_Int32 SwitchFlag_ForceSwitch = 0x01; + const static sal_Int32 SwitchFlag_ForceNewDeck = 0x02; + const static sal_Int32 SwitchFlag_ForceNewPanels = 0x02; + + void OpenThenSwitchToDeck(std::u16string_view rsDeckId); + void OpenThenToggleDeck(const OUString& rsDeckId); + + /** Show only the tab bar, not the deck. + */ + void RequestCloseDeck(); + + /** Open the deck area and restore the parent window to its old width. + */ + void RequestOpenDeck(); + + /** Returns true when the given deck is the currently visible deck + */ + bool IsDeckVisible(std::u16string_view rsDeckId); + + bool IsDeckOpen(const sal_Int32 nIndex = -1); + + FocusManager& GetFocusManager() { return maFocusManager;} + + ResourceManager* GetResourceManager() { return mpResourceManager.get();} + + // std::unique_ptr GetResourceManager() { return mpResourceManager;} + + const Context& GetCurrentContext() const { return maCurrentContext;} + bool IsDocumentReadOnly (void) const { return mbIsDocumentReadOnly;} + + void SwitchToDeck(std::u16string_view rsDeckId); + void SwitchToDefaultDeck(); + bool WasFloatingDeckClosed() const { return mbFloatingDeckClosed; } + void SetFloatingDeckClosed(bool bWasClosed) { mbFloatingDeckClosed = bWasClosed; } + + void CreateDeck(std::u16string_view rDeckId); + void CreateDeck(std::u16string_view rDeckId, const Context& rContext, bool bForceCreate = false); + + ResourceManager::DeckContextDescriptorContainer GetMatchingDecks(); + ResourceManager::PanelContextDescriptorContainer GetMatchingPanels(std::u16string_view rDeckId); + + void notifyDeckTitle(std::u16string_view targetDeckId); + + void updateModel(const css::uno::Reference& xModel); + + void disposeDecks(); + + void FadeIn(); + void FadeOut(); + + tools::Rectangle GetDeckDragArea() const; + + css::uno::Reference const & getXFrame() const {return mxFrame;} + + sal_Int32 getMaximumWidth() const { return mnMaximumSidebarWidth; } + void setMaximumWidth(sal_Int32 nMaximumWidth) { mnMaximumSidebarWidth = nMaximumWidth; } + + void saveDeckState(); + + void SyncUpdate(); + + bool hasChartContextCurrently() const; + + static SidebarController* GetSidebarControllerForView(const SfxViewShell* pViewShell); + +private: + SidebarController(SidebarDockingWindow* pParentWindow, const SfxViewFrame* pViewFrame); + + VclPtr mpCurrentDeck; + VclPtr mpParentWindow; + const SfxViewFrame* mpViewFrame; + css::uno::Reference mxFrame; + VclPtr mpTabBar; + Context maCurrentContext; + Context maRequestedContext; + css::uno::Reference mxCurrentController; + /// Use a combination of SwitchFlag_* as value. + sal_Int32 mnRequestedForceFlags; + sal_Int32 mnMaximumSidebarWidth; + bool mbMinimumSidebarWidth; + OUString msCurrentDeckId; + AsynchronousCall maPropertyChangeForwarder; + AsynchronousCall maContextChangeUpdate; + css::uno::Reference mxThemePropertySet; + + /** Two flags control whether the deck is displayed or if only the + tab bar remains visible. + The mbIsDeckOpen flag stores the current state while + mbIsDeckRequestedOpen stores how this state should be. User + actions like clicking on the deck closer affect the + mbIsDeckRequestedOpen. Normally both flags have the same + value. A document being read-only can prevent the deck from opening. + */ + ::std::optional mbIsDeckRequestedOpen; + ::std::optional mbIsDeckOpen; + + bool mbFloatingDeckClosed; + + /** Before the deck is closed the sidebar width is saved into this variable, + so that it can be restored when the deck is reopened. + */ + sal_Int32 mnSavedSidebarWidth; + FocusManager maFocusManager; + css::uno::Reference mxReadOnlyModeDispatch; + bool mbIsDocumentReadOnly; + VclPtr mpSplitWindow; + /** When the user moves the splitter then we remember the + width at that time. + */ + sal_Int32 mnWidthOnSplitterButtonDown; + /** Control that is temporarily used as replacement for the deck + to indicate that when the current mouse drag operation ends, the + sidebar will only show the tab bar. + */ + VclPtr mpCloseIndicator; + + DECL_DLLPRIVATE_LINK(WindowEventHandler, VclWindowEvent&, void); + /** Make maRequestedContext the current context. + */ + void UpdateConfigurations(); + + css::uno::Reference CreateUIElement ( + const css::uno::Reference& rxWindow, + const OUString& rsImplementationURL, + const bool bWantsCanvas, + const Context& rContext); + + void CreatePanels( + std::u16string_view rDeckId, + const Context& rContext); + std::shared_ptr CreatePanel ( + std::u16string_view rsPanelId, + weld::Widget* pParentWindow, + const bool bIsInitiallyExpanded, + const Context& rContext, + const VclPtr& pDeck); + + void SwitchToDeck ( + const DeckDescriptor& rDeckDescriptor, + const Context& rContext); + + void ShowPopupMenu ( + weld::Menu& rMainMenu, + weld::Menu& rSubMenu, + const ::std::vector& rMenuData) const; + void PopulatePopupMenus( + weld::Menu& rMainButton, + weld::Menu& rSubMenu, + const ::std::vector& rMenuData) const; + DECL_DLLPRIVATE_LINK(OnMenuItemSelected, const OString&, void); + DECL_DLLPRIVATE_LINK(OnSubMenuItemSelected, const OString&, void); + void BroadcastPropertyChange(); + + /** The close of the deck changes the width of the child window. + That is only possible if there is no other docking window docked above or below the sidebar. + Return whether the width of the child window can be modified. + */ + bool CanModifyChildWindowWidth(); + + /** Set the child window container to a new width. + Return the old width. + */ + sal_Int32 SetChildWindowWidth (const sal_Int32 nNewWidth); + + /** Update the icons displayed in the title bars of the deck and + the panels. This is called once when a deck is created and + every time when a data change event is processed. + */ + void UpdateTitleBarIcons(); + + void UpdateDeckOpenState(); + void RestrictWidth (sal_Int32 nWidth); + SfxSplitWindow* GetSplitWindow(); + void ProcessNewWidth (const sal_Int32 nNewWidth); + void UpdateCloseIndicator (const bool bIsIndicatorVisible); + + /** Typically called when a panel is focused via keyboard. + Tries to scroll the deck up or down to make the given panel + completely visible. + */ + void ShowPanel (const Panel& rPanel); + + virtual void disposing(std::unique_lock&) override; + + std::unique_ptr mpResourceManager; + +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/SidebarDockingWindow.hxx b/include/sfx2/sidebar/SidebarDockingWindow.hxx new file mode 100644 index 000000000..9bad1f5a8 --- /dev/null +++ b/include/sfx2/sidebar/SidebarDockingWindow.hxx @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +class SfxViewShell; + +namespace svt { class AcceleratorExecute; } + +namespace sfx2::sidebar { + +class SidebarChildWindow; + +class SidebarController; + +class SFX2_DLLPUBLIC SidebarDockingWindow final : public SfxDockingWindow +{ +public: + SidebarDockingWindow(SfxBindings* pBindings, SidebarChildWindow& rChildWindow, + vcl::Window* pParent, WinBits nBits); + virtual ~SidebarDockingWindow() override; + virtual void dispose() override; + virtual bool EventNotify(NotifyEvent& rEvent) override; + virtual bool Close() override; + + /// Force generation of all panels by completion. + void SyncUpdate(); + + auto& GetSidebarController() const { return mpSidebarController; } + using SfxDockingWindow::Close; + +private: + // Window overridables + virtual void GetFocus() override; + + virtual SfxChildAlignment CheckAlignment ( + SfxChildAlignment eCurrentAlignment, + SfxChildAlignment eRequestedAlignment) override; + + ::rtl::Reference mpSidebarController; + bool mbIsReadyToDrag; + std::unique_ptr mpAccel; +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/SidebarModelUpdate.hxx b/include/sfx2/sidebar/SidebarModelUpdate.hxx new file mode 100644 index 000000000..988478bce --- /dev/null +++ b/include/sfx2/sidebar/SidebarModelUpdate.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +namespace com::sun::star::frame +{ +class XModel; +} +namespace com::sun::star::uno +{ +template class Reference; +} + +namespace sfx2::sidebar +{ +class SFX2_DLLPUBLIC SidebarModelUpdate +{ +public: + virtual ~SidebarModelUpdate(); + virtual void updateModel(css::uno::Reference xModel) = 0; +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/SidebarPanelBase.hxx b/include/sfx2/sidebar/SidebarPanelBase.hxx new file mode 100644 index 000000000..b00d4ca3c --- /dev/null +++ b/include/sfx2/sidebar/SidebarPanelBase.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +#include + +#include + +#include +#include +#include +#include +#include + +class PanelLayout; + +namespace sfx2::sidebar { + +class Panel; + +typedef comphelper::WeakComponentImplHelper + SidebarPanelBaseInterfaceBase; + +/** Base class for sidebar panels that provides some convenience + functionality. +*/ +class SFX2_DLLPUBLIC SidebarPanelBase final : public SidebarPanelBaseInterfaceBase +{ +public: + static css::uno::Reference Create(const OUString& rsResourceURL, + const css::uno::Reference& rxFrame, + std::unique_ptr xControl, + const css::ui::LayoutSize& rLayoutSize); + + // XContextChangeEventListener + virtual void SAL_CALL notifyContextChangeEvent (const css::ui::ContextChangeEventObject& rEvent) override; + + // XEventListener + virtual void SAL_CALL disposing (const css::lang::EventObject& rEvent) override; + + // XUIElement + virtual css::uno::Reference SAL_CALL getFrame() override; + virtual OUString SAL_CALL getResourceURL() override; + virtual sal_Int16 SAL_CALL getType() override; + virtual css::uno::Reference SAL_CALL getRealInterface() override; + + // XToolPanel + virtual css::uno::Reference SAL_CALL createAccessible( + const css::uno::Reference& rxParentAccessible) override; + virtual css::uno::Reference SAL_CALL getWindow() override; + + // XSidebarPanel + virtual css::ui::LayoutSize SAL_CALL getHeightForWidth(sal_Int32 nWidth) override; + virtual sal_Int32 SAL_CALL getMinimalWidth() override; + + // XUpdateModel + virtual void SAL_CALL updateModel(const css::uno::Reference& xModel) override; + + void SetParentPanel(sfx2::sidebar::Panel* pPanel); + +private: + SidebarPanelBase(const OUString& rsResourceURL, const css::uno::Reference& rxFrame, + std::unique_ptr xControl, const css::ui::LayoutSize& rLayoutSize); + virtual ~SidebarPanelBase() override; + SidebarPanelBase(const SidebarPanelBase&) = delete; + SidebarPanelBase& operator=( const SidebarPanelBase& ) = delete; + + virtual void disposing(std::unique_lock&) override; + + css::uno::Reference mxFrame; + std::unique_ptr mxControl; + const OUString msResourceURL; + const css::ui::LayoutSize maLayoutSize; +}; + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/TabBar.hxx b/include/sfx2/sidebar/TabBar.hxx new file mode 100644 index 000000000..5cc092c23 --- /dev/null +++ b/include/sfx2/sidebar/TabBar.hxx @@ -0,0 +1,136 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include + +#include + +namespace com::sun::star::frame { class XFrame; } + +namespace svt { class AcceleratorExecute; } + +namespace weld { class Toolbar; } + +namespace sfx2::sidebar { + +class FocusManager; +class SidebarController; + +/** The tab bar is the container for the individual tabs. +*/ +class TabBar final : public InterimItemWindow +{ +public: + /** DeckMenuData has entries for display name, and a flag: + - isCurrentDeck for the deck selection data + - isEnabled for the show/hide menu + */ + class DeckMenuData + { + public: + OUString msDisplayName; + bool mbIsCurrentDeck; + bool mbIsActive; + bool mbIsEnabled; + }; + typedef ::std::function& rMenuData)> PopupMenuProvider; + TabBar ( + vcl::Window* pParentWindow, + const css::uno::Reference& rxFrame, + const ::std::function& rDeckActivationFunctor, + const PopupMenuProvider& rPopupMenuProvider, + SidebarController* rParentSidebarController); + + weld::Container* GetContainer() { return m_xContainer.get(); } + + virtual ~TabBar() override; + virtual void dispose() override; + + virtual void DataChanged (const DataChangedEvent& rDataChangedEvent) override; + virtual bool EventNotify (NotifyEvent& rEvent) override; + + static sal_Int32 GetDefaultWidth(); + + void SetDecks ( + const ResourceManager::DeckContextDescriptorContainer& rDecks); + void HighlightDeck (std::u16string_view rsDeckId); + void RemoveDeckHighlight (); + OUString const & GetDeckIdForIndex (const sal_Int32 nIndex) const; + void ToggleHideFlag (const sal_Int32 nIndex); + void RestoreHideFlags(); + + void UpdateFocusManager (FocusManager& rFocusManager); + + /// Enables/Disables the menu button. Used by LoKit. + void EnableMenuButton(const bool bEnable); + +private: + css::uno::Reference mxFrame; + + // This unusual auxiliary builder is because without a toplevel GtkWindow + // gtk will warn on loading a .ui with an accelerator defined, so use a + // temporary toplevel to suppress that and move the contents after load + std::unique_ptr mxAuxBuilder; + std::unique_ptr mxTempToplevel; + std::unique_ptr mxContents; + + std::unique_ptr mxMenuButton; + std::unique_ptr mxMainMenu; + std::unique_ptr mxSubMenu; + std::unique_ptr mxMeasureBox; + class Item + { + private: + TabBar& mrTabBar; + std::unique_ptr mxBuilder; + public: + Item(TabBar& rTabBar); + ~Item(); + DECL_LINK(HandleClick, const OString&, void); + std::unique_ptr mxButton; + OUString msDeckId; + ::std::function maDeckActivationFunctor; + bool mbIsHidden; + bool mbIsHiddenByDefault; + }; + typedef ::std::vector> ItemContainer; + ItemContainer maItems; + const ::std::function maDeckActivationFunctor; + PopupMenuProvider maPopupMenuProvider; + + void CreateTabItem(weld::Toolbar& rButton, const DeckDescriptor& rDeckDescriptor); + css::uno::Reference GetItemImage(const DeckDescriptor& rDeskDescriptor) const; + void UpdateButtonIcons(); + + DECL_LINK(OnToolboxClicked, weld::Toggleable&, void); + + SidebarController* pParentSidebarController; + std::unique_ptr mpAccel; + +}; + + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/sidebar/Theme.hxx b/include/sfx2/sidebar/Theme.hxx new file mode 100644 index 000000000..a3f827f4a --- /dev/null +++ b/include/sfx2/sidebar/Theme.hxx @@ -0,0 +1,184 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include + +#include + +#include +#include + + +namespace sfx2::sidebar { + +typedef comphelper::WeakComponentImplHelper < + css::beans::XPropertySet, + css::beans::XPropertySetInfo + > ThemeInterfaceBase; + +/** Simple collection of colors, gradients, fonts that define the + look of the sidebar and its controls. +*/ +class SFX2_DLLPUBLIC Theme final + : public ThemeInterfaceBase +{ +public: + enum ThemeItem + { + Begin_, + Pre_Color_ = Begin_, + + AnyItem_ = Pre_Color_, + + Image_Color_, + + Color_Highlight, + Color_HighlightText, + Color_DeckBackground, + Color_DeckTitleBarBackground, + Color_PanelBackground, + Color_PanelTitleBarBackground, + Color_TabBarBackground, + + Color_Int_, + + Int_DeckBorderSize, + Int_DeckSeparatorHeight, + Int_DeckLeftPadding, + Int_DeckTopPadding, + Int_DeckRightPadding, + Int_DeckBottomPadding, + + Int_Bool_, + + Bool_UseSystemColors, + Bool_IsHighContrastModeActive, + + Post_Bool_, + End_=Post_Bool_ + }; + + static Color GetColor (const ThemeItem eItem); + static sal_Int32 GetInteger (const ThemeItem eItem); + + static bool IsHighContrastMode(); + + static void HandleDataChange(); + + void InitializeTheme(); + + Theme(); + virtual ~Theme() override; + Theme(const Theme&) = delete; + Theme& operator=( const Theme& ) = delete; + + virtual void disposing(std::unique_lock&) override; + + static css::uno::Reference GetPropertySet(); + + // beans::XPropertySet + virtual css::uno::Reference SAL_CALL getPropertySetInfo() override; + virtual void SAL_CALL setPropertyValue ( + const OUString& rsPropertyName, + const css::uno::Any& rValue) override; + virtual css::uno::Any SAL_CALL getPropertyValue ( + const OUString& rsPropertyName) override; + virtual void SAL_CALL addPropertyChangeListener( + const OUString& rsPropertyName, + const css::uno::Reference& rxListener) override; + virtual void SAL_CALL removePropertyChangeListener( + const OUString& rsPropertyName, + const css::uno::Reference& rxListener) override; + virtual void SAL_CALL addVetoableChangeListener( + const OUString& rsPropertyName, + const css::uno::Reference& rxListener) override; + virtual void SAL_CALL removeVetoableChangeListener( + const OUString& rsPropertyName, + const css::uno::Reference& rxListener) override; + + // beans::XPropertySetInfo + virtual css::uno::Sequence SAL_CALL getProperties() override; + virtual css::beans::Property SAL_CALL getPropertyByName (const OUString& rsName) override; + virtual sal_Bool SAL_CALL hasPropertyByName (const OUString& rsName) override; + +private: + static Theme& GetCurrentTheme(); + + std::vector maColors; + std::vector maIntegers; + std::vector maBooleans; + bool mbIsHighContrastMode; + bool mbIsHighContrastModeSetManually; + + typedef std::unordered_map PropertyNameToIdMap; + PropertyNameToIdMap maPropertyNameToIdMap; + typedef std::vector PropertyIdToNameMap; + PropertyIdToNameMap maPropertyIdToNameMap; + typedef ::std::vector RawValueContainer; + RawValueContainer maRawValues; + + typedef std::vector > ChangeListenerContainer; + typedef std::map ChangeListeners; + ChangeListeners maChangeListeners; + typedef std::vector > VetoableListenerContainer; + typedef std::map VetoableListeners; + VetoableListeners maVetoableListeners; + + enum PropertyType + { + PT_Color, + PT_Integer, + PT_Boolean, + PT_Invalid + }; + + void SetupPropertyMaps(); + void UpdateTheme(); + static PropertyType GetPropertyType (const ThemeItem eItem); + static css::uno::Type const & GetCppuType (const PropertyType eType); + static sal_Int32 GetIndex ( + const ThemeItem eItem, + const PropertyType eType); + + VetoableListenerContainer* GetVetoableListeners ( + const ThemeItem eItem, + const bool bCreate); + ChangeListenerContainer* GetChangeListeners ( + const ThemeItem eItem, + const bool bCreate); + static bool DoVetoableListenersVeto ( + const VetoableListenerContainer* pListeners, + const css::beans::PropertyChangeEvent& rEvent); + static void BroadcastPropertyChange ( + const ChangeListenerContainer* pListeners, + const css::beans::PropertyChangeEvent& rEvent); + void ProcessNewValue ( + const css::uno::Any& rValue, + const ThemeItem eItem, + const PropertyType eType); +}; + + +} // end of namespace sfx2::sidebar + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/signaturestate.hxx b/include/sfx2/signaturestate.hxx new file mode 100644 index 000000000..d63498d1c --- /dev/null +++ b/include/sfx2/signaturestate.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_SIGNATURESTATE_HXX +#define INCLUDED_SFX2_SIGNATURESTATE_HXX + +#include + +#include + +enum class SignatureState +{ + // FIXME: Do these values have to be these, and given at all, or is this just cargo cult? + UNKNOWN = 0xffff, // used to be -1 when this was a sal_uInt16 + NOSIGNATURES = 0, + OK = 1, + BROKEN = 2, + // State was SignatureState::OK, but doc is modified now + INVALID = 3, + // signature is OK, but certificate could not be validated + NOTVALIDATED = 4, + // signature and certificate are ok, but not all files are signed, as it was the case in + // OOo 2.x - OOo 3.1.1. This state is only used together with document signatures. + PARTIAL_OK = 5, + /// Certificate could not be validated and the document is only partially signed. + NOTVALIDATED_PARTIAL_OK = 6 +}; + +namespace DocumentSignatures +{ +/** Get document signature state */ +SFX2_DLLPUBLIC SignatureState +getSignatureState(const css::uno::Sequence& aInfos); +} + +#endif // INCLUDED_SFX2_SIGNATURESTATE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/stbitem.hxx b/include/sfx2/stbitem.hxx new file mode 100644 index 000000000..67c88c687 --- /dev/null +++ b/include/sfx2/stbitem.hxx @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_STBITEM_HXX +#define INCLUDED_SFX2_STBITEM_HXX + +#include +#include +#include +#include +#include + +class SfxModule; +class SfxStatusBarControl; +class StatusBar; + +rtl::Reference SfxStatusBarControllerFactory( + const css::uno::Reference< css::frame::XFrame >& rFrame, + StatusBar* pStatusBar, + unsigned short nID, + const OUString& aCommandURL ); +typedef rtl::Reference (*SfxStatusBarControlCtor)( sal_uInt16 nSlotId, sal_uInt16 nId, StatusBar &rStb ); + +struct SfxStbCtrlFactory +{ + SfxStatusBarControlCtor pCtor; + const std::type_info& nTypeId; + sal_uInt16 nSlotId; + + SfxStbCtrlFactory( SfxStatusBarControlCtor pTheCtor, + const std::type_info& nTheTypeId, sal_uInt16 nTheSlotId ): + pCtor(pTheCtor), + nTypeId(nTheTypeId), + nSlotId(nTheSlotId) + {} +}; + + +class CommandEvent; +class MouseEvent; +class UserDrawEvent; + +class SFX2_DLLPUBLIC SfxStatusBarControl: public svt::StatusbarController +{ + sal_uInt16 nSlotId; + sal_uInt16 nId; + VclPtr pBar; + +public: + // new controller API + // XInterface + virtual void SAL_CALL acquire() noexcept override; + virtual void SAL_CALL release() noexcept override; + +protected: + // XEventListener + using svt::StatusbarController::disposing; + + // XComponent + using svt::StatusbarController::dispose; + + // XStatusListener + virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& Event ) override; + + // XStatusbarController + virtual sal_Bool SAL_CALL mouseButtonDown( const css::awt::MouseEvent& aMouseEvent ) override; + virtual sal_Bool SAL_CALL mouseMove( const css::awt::MouseEvent& aMouseEvent ) override; + virtual sal_Bool SAL_CALL mouseButtonUp( const css::awt::MouseEvent& aMouseEvent ) override; + virtual void SAL_CALL command( const css::awt::Point& aPos, + ::sal_Int32 nCommand, + sal_Bool bMouseEvent, + const css::uno::Any& aData ) override; + virtual void SAL_CALL paint( const css::uno::Reference< css::awt::XGraphics >& xGraphics, + const css::awt::Rectangle& rOutputRectangle, + ::sal_Int32 nStyle ) override; + virtual void SAL_CALL click( const css::awt::Point& aPos ) override; + virtual void SAL_CALL doubleClick( const css::awt::Point& aPos ) override; + + // Old sfx2 interface + virtual void StateChangedAtStatusBarControl( sal_uInt16 nSID, SfxItemState eState, + const SfxPoolItem* pState ); + virtual void Click(); + virtual void Command( const CommandEvent& rCEvt ); + virtual bool MouseButtonDown( const MouseEvent & ); + virtual bool MouseMove( const MouseEvent & ); + virtual bool MouseButtonUp( const MouseEvent & ); + virtual void Paint( const UserDrawEvent &rUDEvt ); + + static sal_uInt16 convertAwtToVCLMouseButtons( sal_Int16 nAwtMouseButtons ); + +public: + SfxStatusBarControl( sal_uInt16 nSlotID, sal_uInt16 nId, StatusBar& rBar ); + virtual ~SfxStatusBarControl() override; + + sal_uInt16 GetSlotId() const { return nSlotId; } + sal_uInt16 GetId() const { return nId; } + StatusBar& GetStatusBar() const { return *pBar; } + + static rtl::Reference CreateControl( sal_uInt16 nSlotID, sal_uInt16 nId, StatusBar *pBar, SfxModule const * ); + static void RegisterStatusBarControl(SfxModule*, const SfxStbCtrlFactory&); + +}; + + +#define SFX_DECL_STATUSBAR_CONTROL() \ + static rtl::Reference CreateImpl( sal_uInt16 nSlotId, sal_uInt16 nId, StatusBar &rStb ); \ + static void RegisterControl(sal_uInt16 nSlotId = 0, SfxModule *pMod=nullptr) + +#define SFX_IMPL_STATUSBAR_CONTROL(Class, nItemClass) \ + rtl::Reference Class::CreateImpl( sal_uInt16 nSlotId, sal_uInt16 nId, StatusBar &rStb ) \ + { return new Class( nSlotId, nId, rStb ); } \ + void Class::RegisterControl(sal_uInt16 nSlotId, SfxModule *pMod) \ + { SfxStatusBarControl::RegisterStatusBarControl( pMod, SfxStbCtrlFactory( \ + Class::CreateImpl, typeid(nItemClass), nSlotId ) ); } + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/strings.hrc b/include/sfx2/strings.hrc new file mode 100644 index 000000000..e392b1d03 --- /dev/null +++ b/include/sfx2/strings.hrc @@ -0,0 +1,361 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_INC_STRINGS_HRC +#define INCLUDED_SFX2_INC_STRINGS_HRC + +#define NC_(Context, String) TranslateId(Context, reinterpret_cast(u8##String)) + +#define STR_TEMPLATE_FILTER NC_("STR_TEMPLATE_FILTER", "Templates") +#define STR_SAVEDOC NC_("STR_SAVEDOC", "~Save") +#define STR_SAVEASDOC NC_("STR_SAVEASDOC", "Save ~As...") +#define STR_SAVEACOPY NC_("STR_SAVEACOPY", "Save a Copy...") +#define STR_CLOSEDOC NC_("STR_CLOSEDOC", "~Close") +#define STR_OPEN NC_("STR_OPEN", "~Open") +#define STR_EDIT_TEMPLATE NC_("STR_EDIT_TEMPLATE", "~Edit") +#define STR_DEFAULT_TEMPLATE NC_("STR_DEFAULT_TEMPLATE", "Set as De~fault") +#define STR_RESET_DEFAULT NC_("STR_RESET_DEFAULT", "Reset De~fault") +#define STR_DELETE_TEMPLATE NC_("STR_DELETE_TEMPLATE", "~Delete") +#define STR_SFX_RENAME NC_("STR_SFX_RENAME", "~Rename") +#define STR_MOVE NC_("STR_ACTION_MOVE","~Move") +#define STR_EXPORT NC_("STR_ACTION_EXPORT","E~xport") +#define STR_CATEGORY_RENAME NC_("STR_CATEGORY_RENAME", "Ren~ame Category") +#define STR_RENAME_TEMPLATE NC_("STR_RENAME_TEMPLATE", "Enter new template name:") +#define STR_TEMPLATE_TOOLTIP NC_("STR_TEMPLATE_TOOLTIP", "Title: $1\nCategory: $2") +#define STR_TEMPLATE_SELECTION NC_("STR_TEMPLATE_SELECTION", "Select a Template") +#define STR_AUTOMATICVERSION NC_("STR_AUTOMATICVERSION", "Automatically saved version") +#define STR_EXPORTBUTTON NC_("STR_EXPORTBUTTON", "Export") +#define STR_LABEL_FILEFORMAT NC_("STR_LABEL_FILEFORMAT", "File format:") +#define STR_HIDDENINFO_CONTAINS NC_("STR_HIDDENINFO_CONTAINS", "This document contains:\n\n") +#define STR_HIDDENINFO_RECORDCHANGES NC_("STR_HIDDENINFO_RECORDCHANGES", "Recorded changes") +#define STR_HIDDENINFO_NOTES NC_("STR_HIDDENINFO_NOTES", "Notes") +#define STR_HIDDENINFO_DOCVERSIONS NC_("STR_HIDDENINFO_DOCVERSIONS", "Document versions") +#define STR_HIDDENINFO_CONTINUE_SAVING NC_("STR_HIDDENINFO_CONTINUE_SAVING", "Do you want to continue saving the document?") +#define STR_HIDDENINFO_CONTINUE_PRINTING NC_("STR_HIDDENINFO_CONTINUE_PRINTING", "Do you want to continue printing the document?") +#define STR_HIDDENINFO_CONTINUE_SIGNING NC_("STR_HIDDENINFO_CONTINUE_SIGNING", "Do you want to continue signing the document?") +#define STR_HIDDENINFO_CONTINUE_CREATEPDF NC_("STR_HIDDENINFO_CONTINUE_CREATEPDF", "Do you want to continue creating a PDF file?") +#define STR_NEW_FILENAME_SAVE NC_("STR_NEW_FILENAME_SAVE", "If you do not want to overwrite the original document, you should save your work under a new filename.") +// Used in the title of a shared document. +#define STR_SHARED NC_("STR_SHARED", " (shared)") +#define STR_XMLSEC_ODF12_EXPECTED NC_("STR_XMLSEC_ODF12_EXPECTED", "The document format version is set to ODF 1.1 (OpenOffice.org 2.x) in Tools-Options-Load/Save-General. Signing documents requires ODF 1.2 (OpenOffice.org 3.x).") +#define STR_XMLSEC_QUERY_SAVESIGNEDBEFORESIGN NC_("STR_XMLSEC_QUERY_SAVESIGNEDBEFORESIGN", "The document has to be saved before it can be signed. Saving the document removes all present signatures.\nDo you want to save the document?") +#define STR_QRYTEMPL_MESSAGE NC_("STR_QRYTEMPL_MESSAGE", "The template '$(ARG1)' on which this document is based, has been modified. Do you want to update the styles of the current document, using the modified template?") +#define STR_QRYTEMPL_UPDATE_BTN NC_("STR_QRYTEMPL_UPDATE_BTN", "~Update Styles") +#define STR_QRYTEMPL_KEEP_BTN NC_("STR_QRYTEMPL_KEEP_BTN", "~Keep Old Styles") +#define STR_CATEGORY_NEW NC_("STR_CATEGORY_NEW", "~New Category") +#define STR_CATEGORY_DELETE NC_("STR_CATEGORY_DELETE", "~Delete Category") +#define STR_MSG_EXPORT_SUCCESS NC_("STR_MSG_EXPORT_SUCCESS", "$1 templates successfully exported.") +#define STR_MSG_QUERY_COPY NC_("STR_MSG_QUERY_COPY", "$1 could not be moved to the category \"$2\". Do you want to copy the template instead?") +#define STR_CREATE_ERROR NC_("STR_CREATE_ERROR", "Cannot create category: $1") +#define STR_ERROR_SAVEAS NC_("STR_ERROR_SAVEAS", "Cannot save template: $1") +#define STR_INPUT_NEW NC_("STR_INPUT_NEW", "Enter new category name:") +#define STR_MSG_ERROR_LOCAL_MOVE NC_("STR_MSG_ERROR_LOCAL_MOVE", "Error moving the following templates to $1.\n$2") +#define STR_MSG_ERROR_EXPORT NC_("STR_MSG_ERROR_EXPORT", "Error exporting the following templates:\n$1") +#define STR_MSG_ERROR_IMPORT NC_("STR_MSG_ERROR_IMPORT", "Error importing the following templates to $1:\n$2") +#define STR_MSG_ERROR_DELETE_TEMPLATE NC_("STR_MSG_ERROR_DELETE_TEMPLATE", "The following templates cannot be deleted:\n$1") +#define STR_MSG_ERROR_DELETE_FOLDER NC_("STR_MSG_ERROR_DELETE_FOLDER", "The following folders cannot be deleted:\n$1") +#define STR_TOOLTIP_ERROR_RENAME_TEMPLATE NC_("STR_TOOLTIP_ERROR_RENAME_TEMPLATE", "There is another template with the name $1 in $2.") +#define STR_QMSG_SEL_FOLDER_DELETE NC_("STR_QMSG_SEL_FOLDER_DELETE", "Do you want to delete the selected category?") +#define STR_QMSG_TEMPLATE_OVERWRITE NC_("STR_QMSG_TEMPLATE_OVERWRITE", "A template named $1 already exists in $2. Do you want to overwrite it?") +#define STR_QMSG_SEL_TEMPLATE_DELETE NC_("STR_QMSG_SEL_TEMPLATE_DELETE", "Do you want to delete the selected templates?") +#define STR_QMSG_ERROR_OPENING_FILE NC_("STR_QMSG_ERROR_OPENING_FILE", "An error occurred during opening the file. This may be caused by incorrect file contents.\n") +#define STR_QMSG_ERROR_OPENING_FILE_DETAILS NC_("STR_QMSG_ERROR_OPENING_FILE_DETAILS", "The error details are:\n") +#define STR_QMSG_ERROR_OPENING_FILE_CONTINUE NC_("STR_QMSG_ERROR_OPENING_FILE_CONTINUE", "\nProceeding with import may cause data loss or corruption, and application may become unstable or crash.\n\nDo you want to ignore the error and attempt to continue loading the file?") + +#define STR_HELP_WINDOW_TITLE NC_("STR_HELP_WINDOW_TITLE", "%PRODUCTNAME Help") +#define STR_HELP_BUTTON_INDEX_ON NC_("STR_HELP_BUTTON_INDEX_ON", "Show Navigation Pane") +#define STR_HELP_BUTTON_INDEX_OFF NC_("STR_HELP_BUTTON_INDEX_OFF", "Hide Navigation Pane") +#define STR_HELP_BUTTON_START NC_("STR_HELP_BUTTON_START", "First Page") +#define STR_HELP_BUTTON_PREV NC_("STR_HELP_BUTTON_PREV", "Previous Page") +#define STR_HELP_BUTTON_NEXT NC_("STR_HELP_BUTTON_NEXT", "Next Page") +#define STR_HELP_BUTTON_PRINT NC_("STR_HELP_BUTTON_PRINT", "Print...") +#define STR_HELP_BUTTON_ADDBOOKMARK NC_("STR_HELP_BUTTON_ADDBOOKMARK", "Add to Bookmarks...") +#define STR_HELP_BUTTON_SEARCHDIALOG NC_("STR_HELP_BUTTON_SEARCHDIALOG", "Find on this Page...") +#define STR_HELP_BUTTON_SOURCEVIEW NC_("STR_HELP_BUTTON_SOURCEVIEW", "HTML Source") +#define STR_HELP_MENU_TEXT_SELECTION_MODE NC_("STR_HELP_MENU_TEXT_SELECTION_MODE", "Select Text") +#define STR_HELP_MENU_TEXT_COPY NC_("STR_HELP_MENU_TEXT_COPY", "~Copy") +#define STR_INFO_NOSEARCHRESULTS NC_("STR_INFO_NOSEARCHRESULTS", "No topics found.") +#define STR_INFO_NOSEARCHTEXTFOUND NC_("STR_INFO_NOSEARCHTEXTFOUND", "The text you entered was not found.") +#define RID_HELP_ONSTARTUP_TEXT NC_("RID_HELP_ONSTARTUP_TEXT", "~Display %PRODUCTNAME %MODULENAME Help at Startup") + +#define STR_NONAME NC_("STR_NONAME", "Untitled") +#define STR_STANDARD_SHORTCUT NC_("STR_STANDARD_SHORTCUT", "Standard") +#define STR_BYTES NC_("STR_BYTES", "Bytes") +#define STR_KB NC_("STR_KB", "kB") +#define STR_MB NC_("STR_MB", "MB") +#define STR_GB NC_("STR_GB", "GB") +#define STR_QUERY_LASTVERSION NC_("STR_QUERY_LASTVERSION", "Cancel all changes?") +#define STR_NO_WEBBROWSER_FOUND NC_("STR_NO_WEBBROWSER_FOUND", "Opening \"$(ARG1)\" failed with error code $(ARG2) and message: \"$(ARG3)\"\nMaybe no web browser could be found on your system. In that case, please check your Desktop Preferences or install a web browser (for example, Firefox) in the default location requested during the browser installation.") +#define STR_DANGEROUS_TO_OPEN NC_("STR_DANGEROUS_TO_OPEN", "It might be dangerous to open \"$(ARG1)\".\nDo you really want to open it?") +#define STR_NO_ABS_URI_REF NC_("STR_NO_ABS_URI_REF", "\"$(ARG1)\" cannot be passed to an external application to open it (e.g., it might not be an absolute URL, or might denote no existing file).") +#define STR_GID_INTERN NC_("STR_GID_INTERN", "Internal") +#define STR_GID_APPLICATION NC_("STR_GID_APPLICATION", "Application") +#define STR_GID_VIEW NC_("STR_GID_VIEW", "View") +#define STR_GID_DOCUMENT NC_("STR_GID_DOCUMENT", "Documents") +#define STR_GID_EDIT NC_("STR_GID_EDIT", "Edit") +#define STR_GID_MACRO NC_("STR_GID_MACRO", "BASIC") +#define STR_GID_OPTIONS NC_("STR_GID_OPTIONS", "Options") +#define STR_GID_MATH NC_("STR_GID_MATH", "Math") +#define STR_GID_NAVIGATOR NC_("STR_GID_NAVIGATOR", "Navigate") +#define STR_GID_INSERT NC_("STR_GID_INSERT", "Insert") +#define STR_GID_FORMAT NC_("STR_GID_FORMAT", "Format") +#define STR_GID_TEMPLATE NC_("STR_GID_TEMPLATE", "Templates") +#define STR_GID_TEXT NC_("STR_GID_TEXT", "Text") +#define STR_GID_FRAME NC_("STR_GID_FRAME", "Frame") +#define STR_GID_GRAPHIC NC_("STR_GID_GRAPHIC", "Image") +#define STR_GID_TABLE NC_("STR_GID_TABLE", "Table") +#define STR_GID_ENUMERATION NC_("STR_GID_ENUMERATION", "Numbering") +#define STR_GID_DATA NC_("STR_GID_DATA", "Data") +#define STR_GID_SPECIAL NC_("STR_GID_SPECIAL", "Special Functions") +#define STR_GID_IMAGE NC_("STR_GID_IMAGE", "Image") +#define STR_GID_CHART NC_("STR_GID_CHART", "Chart") +#define STR_GID_EXPLORER NC_("STR_GID_EXPLORER", "Explorer") +#define STR_GID_CONNECTOR NC_("STR_GID_CONNECTOR", "Connector") +#define STR_GID_MODIFY NC_("STR_GID_MODIFY", "Modify") +#define STR_GID_DRAWING NC_("STR_GID_DRAWING", "Drawing") +#define STR_GID_CONTROLS NC_("STR_GID_CONTROLS", "Controls") +#define STR_QUITAPP NC_("STR_QUITAPP", "E~xit %PRODUCTNAME") +#define RID_STR_HELP NC_("RID_STR_HELP", "Help") +#define RID_STR_HLPFILENOTEXIST NC_("RID_STR_HLPFILENOTEXIST", "The help file for this topic is not installed.") +#define STR_QUICKSTART_EXIT NC_("STR_QUICKSTART_EXIT", "Exit Quickstarter") +#define STR_QUICKSTART_TIP NC_("STR_QUICKSTART_TIP", "%PRODUCTNAME %PRODUCTVERSION Quickstarter") +#define STR_QUICKSTART_FILEOPEN NC_("STR_QUICKSTART_FILEOPEN", "Open Document...") +#define STR_QUICKSTART_FROMTEMPLATE NC_("STR_QUICKSTART_FROMTEMPLATE", "From Template...") +#define STR_QUICKSTART_PRELAUNCH NC_("STR_QUICKSTART_PRELAUNCH", "Load %PRODUCTNAME During System Start-Up") +#define STR_QUICKSTART_LNKNAME NC_("STR_QUICKSTART_LNKNAME", "%PRODUCTNAME %PRODUCTVERSION") +#define STR_QUICKSTART_FILE NC_("STR_QUICKSTART_FILE", "File") +#define STR_QUICKSTART_STARTCENTER NC_("STR_QUICKSTART_STARTCENTER", "Startcenter") +#define STR_QUICKSTART_RECENTDOC NC_("STR_QUICKSTART_RECENTDOC", "Recent Documents") +#define STR_QUERY_UPDATE_LINKS NC_("STR_QUERY_UPDATE_LINKS", "The document %{filename} contains one or more links to external data.\n\nWould you like to change the document, and update all links\nto get the most recent data?") +#define STR_DDE_ERROR NC_("STR_DDE_ERROR", "DDE link to %1 for %2 area %3 are not available.") +#define STR_SECURITY_WARNING_NO_HYPERLINKS NC_("STR_SECURITY_WARNING_NO_HYPERLINKS", "For security reasons, the hyperlink cannot be executed.\nThe stated address will not be opened.") +#define RID_SECURITY_WARNING_TITLE NC_("RID_SECURITY_WARNING_TITLE", "Security Warning") +#define RID_SVXSTR_XMLSEC_QUERY_LOSINGSIGNATURE NC_("RID_SVXSTR_XMLSEC_QUERY_LOSINGSIGNATURE", "Saving will remove all existing signatures.\nDo you want to continue saving the document?") +#define RID_SVXSTR_XMLSEC_QUERY_SAVEBEFORESIGN NC_("RID_SVXSTR_XMLSEC_QUERY_SAVEBEFORESIGN", "The document has to be saved before it can be signed.\nDo you want to save the document?") +#define STR_QUERY_CANCELCHECKOUT NC_("STR_QUERY_CANCELCHECKOUT", "This will discard all changes on the server since check-out.\nDo you want to proceed?") +#define STR_INFO_WRONGDOCFORMAT NC_("STR_INFO_WRONGDOCFORMAT", "This document must be saved in OpenDocument file format before it can be digitally signed.") +#define RID_XMLSEC_DOCUMENTSIGNED NC_("RID_XMLSEC_DOCUMENTSIGNED", " (Signed)") +#define STR_EMBEDDED_TITLE NC_("STR_EMBEDDED_TITLE", " (Embedded document)") +#define STR_STANDARD NC_("STR_STANDARD", "Standard") +#define RID_SVXSTR_FILELINK NC_("RID_SVXSTR_FILELINK", "Document") +#define STR_NONE NC_("STR_NONE", "- None -") +#define STR_CATEGORY_NONE NC_("saveastemplatedlg|categorylist", "None") +#define RID_SVXSTR_GRAPHICLINK NC_("RID_SVXSTR_GRAPHICLINK", "Image") +#define STR_SFX_FILTERNAME_ALL NC_("STR_SFX_FILTERNAME_ALL", "All files") +#define STR_SFX_FILTERNAME_PDF NC_("STR_SFX_FILTERNAME_PDF", "PDF files") +#define RID_SVXSTR_EDITGRFLINK NC_("RID_SVXSTR_EDITGRFLINK", "Link Image") +// i66948 used in project scripting +#define STR_ERRUNOEVENTBINDUNG NC_("STR_ERRUNOEVENTBINDUNG", "An appropriate component method %1\ncould not be found.\n\nCheck spelling of method name.") +#define RID_SVXSTR_GRFILTER_OPENERROR NC_("RID_SVXSTR_GRFILTER_OPENERROR", "Image file cannot be opened") +#define RID_SVXSTR_GRFILTER_IOERROR NC_("RID_SVXSTR_GRFILTER_IOERROR", "Image file cannot be read") +#define RID_SVXSTR_GRFILTER_FORMATERROR NC_("RID_SVXSTR_GRFILTER_FORMATERROR", "Unknown image format") +#define RID_SVXSTR_GRFILTER_VERSIONERROR NC_("RID_SVXSTR_GRFILTER_VERSIONERROR", "This version of the image file is not supported") +#define RID_SVXSTR_GRFILTER_FILTERERROR NC_("RID_SVXSTR_GRFILTER_FILTERERROR", "Image filter not found") +#define RID_SVXSTR_TXTFILTER_FILTERERROR NC_("RID_SVXSTR_TXTFILTER_FILTERERROR", "This is not a text document") +#define RID_SVXSTR_END_REDLINING_WARNING NC_("RID_SVXSTR_END_REDLINING_WARNING", "This action will exit the change recording mode.\nNo information about changes will be recorded from now on.\n\nExit change recording mode?\n\n") +#define RID_SVXSTR_INCORRECT_PASSWORD NC_("RID_SVXSTR_INCORRECT_PASSWORD", "Incorrect password") +#define RID_SVXSTR_GPG_ENCRYPT_FAILURE NC_("RID_SVXSTR_GPG_ENCRYPT_FAILURE", "OpenPGP key not trusted, damaged, or encryption failure. Please try again.") + +#define STR_PASSWD_MIN_LEN NC_("STR_PASSWD_MIN_LEN", "(Minimum $(MINLEN) characters)") +#define STR_PASSWD_MIN_LEN1 NC_("STR_PASSWD_MIN_LEN1", "(Minimum 1 character)") +#define STR_PASSWD_EMPTY NC_("STR_PASSWD_EMPTY", "(The password can be empty)") +#define STR_MODULENOTINSTALLED NC_("STR_MODULENOTINSTALLED", "The action could not be executed. The %PRODUCTNAME program module needed for this action is currently not installed.") + +#define STR_FILTER_NOT_INSTALLED NC_("STR_FILTER_NOT_INSTALLED", "The selected filter $(FILTER) has not been installed.\nWould you like to do this now?") +#define STR_FILTER_CONSULT_SERVICE NC_("STR_FILTER_CONSULT_SERVICE", "The selected filter $(FILTER) is not included in your edition.\nYou can find information about orders on our homepage.") + +#define STR_WELCOME_LINE1 NC_("STR_WELCOME_LINE1", "Welcome to %PRODUCTNAME.") +#define STR_WELCOME_LINE2 NC_("STR_WELCOME_LINE2", "Drop a document here or open an app to create one.") + +// Translators: Target types in Auto-redaction dialog +#define STR_REDACTION_TARGET_TYPE_TEXT NC_("STR_REDACTION_TARGET_TYPE_TEXT", "Text") +#define STR_REDACTION_TARGET_TYPE_REGEX NC_("STR_REDACTION_TARGET_TYPE_REGEX", "Regular expression") +#define STR_REDACTION_TARGET_TYPE_PREDEF NC_("STR_REDACTION_TARGET_TYPE_PREDEF", "Predefined") +#define STR_REDACTION_TARGET_TYPE_UNKNOWN NC_("STR_REDACTION_TARGET_TYPE_UNKNOWN", "Unknown") + +// Translators: Values for the Case Sensitive and the Whole Words columns in Auto-redaction dialog +#define STR_REDACTION_YES NC_("STR_REDACTION_YES", "Yes") +#define STR_REDACTION_NO NC_("STR_REDACTION_NO", "No") + +// Translators: Misc strings of the Auto Redaction dialog +#define STR_REDACTION_TARGET NC_("STR_REDACTION_TARGET", "Target") +#define STR_REDACTION_LOAD_TARGETS NC_("STR_REDACTION_LOAD_TARGETS", "Load Targets") +#define STR_REDACTION_SAVE_TARGETS NC_("STR_REDACTION_SAVE_TARGETS", "Save Targets") +#define STR_REDACTION_FIELDS_REQUIRED NC_("STR_REDACTION_FIELDS_REQUIRED", "All fields are required") +#define STR_REDACTION_TARGET_NAME_CLASH NC_("STR_REDACTION_TARGET_NAME_CLASH", "There is already a target with this name") +#define STR_REDACTION_MULTI_EDIT NC_("STR_REDACTION_MULTI_EDIT", "You have selected multiple targets, but only one target can be edited at once.") +#define STR_REDACTION_MULTI_DELETE NC_("STR_REDACTION_MULTI_DELETE", "Are you sure you would like to delete $(TARGETSCOUNT) targets at once?") +#define STR_REDACTION_JSON_FILE_FILTER NC_("STR_REDACTION_JSON_FILE_FILTER", "Target Set (*.json)") +#define STR_REDACTION_EDIT_TARGET NC_("STR_REDACTION_EDIT_TARGET", "Edit Target") +#define STR_REDACTION_TARGET_ADD_ERROR NC_("STR_REDACTION_TARGET_ADD_ERROR", "An error occurred while adding new target. Please report this incident.") +#define STR_REDACTION_NO_DRAW_WARNING NC_("STR_REDACTION_NO_DRAW_WARNING", "Draw module is needed for redaction. Please make sure you have %PRODUCTNAME Draw installed and working correctly.") + +#define STR_SFX_FILEDLG_ACTUALVERSION NC_("STR_SFX_FILEDLG_ACTUALVERSION", "Current version") +#define STR_SFX_EXPLORERFILE_EXPORT NC_("STR_SFX_EXPLORERFILE_EXPORT", "Export") +#define STR_SFX_EXPLORERFILE_INSERT NC_("STR_SFX_EXPLORERFILE_INSERT", "Insert") +#define STR_SFX_EXPLORERFILE_BUTTONINSERT NC_("STR_SFX_EXPLORERFILE_BUTTONINSERT", "~Insert") +#define STR_SFX_IMPORT_ALL_IMAGES NC_("STR_SFX_IMPORT_ALL_IMAGES", "") +#define STR_PB_SAVEACOPY NC_("STR_PB_SAVEACOPY", "Save a Copy") +#define STR_PB_COMPAREDOC NC_("STR_PB_COMPAREDOC", "Compare to") +#define STR_PB_MERGEDOC NC_("STR_PB_MERGEDOC", "Merge with") + +#define STR_SFX_NEWOFFICEDOC NC_("STR_SFX_NEWOFFICEDOC", "%PRODUCTNAME document") +#define SFX_ST_DURATION_FORMAT NC_("SFX_ST_DURATION_FORMAT", " Y: %1 M: %2 D: %3 H: %4 M: %5 S: %6") +#define STR_SFX_QUERY_WRONG_TYPE NC_("STR_SFX_QUERY_WRONG_TYPE", "The value entered does not match the specified type.\nThe value will be stored as text.") + +#define STR_QUERY_OVERWRITE NC_("STR_QUERY_OVERWRITE", "Style already exists. Overwrite?") + +#define STR_RESET NC_("STR_RESET", "~Reset") +#define STR_TABPAGE_INVALIDNAME NC_("STR_TABPAGE_INVALIDNAME", "This name is already in use.") +#define STR_TABPAGE_INVALIDSTYLE NC_("STR_TABPAGE_INVALIDSTYLE", "This Style does not exist.") +#define STR_TABPAGE_INVALIDPARENT NC_("STR_TABPAGE_INVALIDPARENT", "This Style cannot be used as a base Style,\nbecause it would result in a recursive reference.") +#define STR_POOL_STYLE_NAME NC_("STR_POOL_STYLE_NAME", "Name already exists as a default Style.\nPlease choose another name.") +#define STR_DELETE_STYLE_USED NC_("STR_DELETE_STYLE_USED", "One or more of the selected styles is in use in this document.\nIf you will delete it, text or objects using these styles will revert to the parent style.\nDo you still wish to delete these styles?\n") +#define STR_DELETE_STYLE NC_("STR_DELETE_STYLE", "Styles in use: ") +#define STR_SID_NAVIGATOR NC_("STR_SID_NAVIGATOR", "Navigator") +#define STR_ERROR_WRONG_CONFIRM NC_("STR_ERROR_WRONG_CONFIRM", "Faulty password confirmation") +#define STR_PDF_EXPORT_SEND NC_("STR_PDF_EXPORT_SEND", "Send") +#define STR_FONT_TABPAGE NC_("STR_FONT_TABPAGE", "Font") + +#define STR_VIEWVERSIONCOMMENT NC_("STR_VIEWVERSIONCOMMENT", "View Version Comment") +#define STR_NO_NAME_SET NC_("STR_NO_NAME_SET", "(no name set)") + +#define STR_STYLE_FILTER_HIERARCHICAL NC_("STR_STYLE_FILTER_HIERARCHICAL", "Hierarchical") + +#define STR_MACRO_LOSS NC_("STR_MACRO_LOSS", "Do you really want to cancel the recording? Any steps recorded up to this point will be lost.") +#define STR_CANCEL_RECORDING NC_("STR_CANCEL_RECORDING", "Cancel Recording") + +#define RID_CNT_STR_WAITING NC_("RID_CNT_STR_WAITING", "The templates are being initialized for first-time usage.") + +#define STR_NODEFPRINTER NC_("STR_NODEFPRINTER", "No default printer found.\nPlease choose a printer and try again.") +#define STR_NOSTARTPRINTER NC_("STR_NOSTARTPRINTER", "Could not start printer.\nPlease check your printer configuration.") +#define STR_ERROR_PRINTER_BUSY NC_("STR_ERROR_PRINTER_BUSY", "Printer busy") +#define STR_READONLY NC_("STR_READONLY", " (read-only)") +#define STR_PRINT_NEWORI NC_("STR_PRINT_NEWORI", "The page size and orientation have been modified.\nWould you like to save the new settings in the\nactive document?") +#define STR_PRINT_NEWSIZE NC_("STR_PRINT_NEWSIZE", "The page size has been modified.\nShould the new settings be saved\nin the active document?") +#define STR_PRINT_NEWORISIZE NC_("STR_PRINT_NEWORISIZE", "The page size and orientation have been modified.\nWould you like to save the new settings in the\nactive document?") +#define STR_CANT_CLOSE NC_("STR_CANT_CLOSE", "The document cannot be closed because a\n print job is being carried out.") +#define STR_ERROR_SEND_MAIL NC_("STR_ERROR_SEND_MAIL", "An error occurred in sending the message. Possible errors could be a missing user account or a defective setup.\nPlease check the %PRODUCTNAME settings or your email program settings.") +// Error codes look like "MAPI_E_FAILURE" or "1234" +#define STR_ERROR_SEND_MAIL_CODE NC_("STR_ERROR_SEND_MAIL_CODE", "An error occurred in sending the message. Possible errors could be a missing user account or a defective setup.\n\nError code is $1") +#define STR_ERROR_SEND_MAIL_HEADER NC_("STR_ERROR_SEND_MAIL_HEADER", "Error sending mail") +#define STR_QUERY_OPENASTEMPLATE NC_("STR_QUERY_OPENASTEMPLATE", "This document cannot be edited, possibly due to missing access rights. Do you want to edit a copy of the document?") +#define STR_QUERY_OPENASTEMPLATE_LOCKED NC_("STR_QUERY_OPENASTEMPLATE_LOCKED", "This document cannot be edited, because it is locked in another session.%LOCKINFO\nDo you want to edit a copy of the document?") +#define STR_QUERY_OPENASTEMPLATE_ALLOW_IGNORE NC_("STR_QUERY_OPENASTEMPLATE_ALLOW_IGNORE", "You can also try to ignore the lock and open the file for editing.") +#define STR_QUERY_OPENASTEMPLATE_OPENCOPY_BTN NC_("STR_QUERY_OPENASTEMPLATE_OPENCOPY_BTN", "Open ~Copy") +#define STR_QUERY_OPENASTEMPLATE_OPEN_BTN NC_("STR_QUERY_OPENASTEMPLATE_OPEN_BTN", "~Open") +#define STR_REPAIREDDOCUMENT NC_("STR_REPAIREDDOCUMENT", " (repaired document)") +#define STR_NONCHECKEDOUT_DOCUMENT NC_("STR_NONCHECKEDOUT_DOCUMENT", "This document is not checked out on the server.") +#define STR_GET_INVOLVED_TEXT NC_("STR_GET_INVOLVED_TEXT", "Help us make %PRODUCTNAME even better!") +#define STR_GET_INVOLVED_BUTTON NC_("STR_GET_INVOLVED_BUTTON", "Get involved") +#define STR_DONATE_TEXT NC_("STR_DONATE_TEXT", "Your donations support our worldwide community.") +#define STR_DONATE_BUTTON NC_("STR_DONATE_BUTTON", "Donate") +#define STR_WHATSNEW_TEXT NC_("STR_WHATSNEW", "You are running version %PRODUCTVERSION of %PRODUCTNAME for the first time. Do you want to learn what's new?") +#define STR_WHATSNEW_BUTTON NC_("STR_WHATSNEW_BUTTON", "Release Notes") +#define STR_READONLY_DOCUMENT NC_("STR_READONLY_DOCUMENT", "This document is open in read-only mode.") +#define STR_READONLY_PDF NC_("STR_READONLY_PDF", "This PDF is open in read-only mode to allow signing the existing file.") +#define STR_CLASSIFIED_DOCUMENT NC_("STR_CLASSIFIED_DOCUMENT", "The classification label of this document is %1.") +#define STR_TARGET_DOC_NOT_CLASSIFIED NC_("STR_TARGET_DOC_NOT_CLASSIFIED", "This document must be classified before the clipboard can be pasted.") +#define STR_DOC_CLASSIFICATION_TOO_LOW NC_("STR_DOC_CLASSIFICATION_TOO_LOW", "This document has a lower classification level than the clipboard.") +#define STR_CLASSIFIED_INTELLECTUAL_PROPERTY NC_("STR_CLASSIFIED_INTELLECTUAL_PROPERTY", "Level") +#define STR_CLASSIFIED_NATIONAL_SECURITY NC_("STR_CLASSIFIED_NATIONAL_SECURITY", "National Security:") +#define STR_CLASSIFIED_EXPORT_CONTROL NC_("STR_CLASSIFIED_EXPORT_CONTROL", "Export Control:") +#define STR_CHECKOUT NC_("STR_CHECKOUT", "Check Out") +#define STR_READONLY_EDIT NC_("STR_READONLY_EDIT", "Edit Document") +#define STR_READONLY_SIGN NC_("STR_READONLY_SIGN", "Sign Document") +#define STR_READONLY_FINISH_SIGN NC_("STR_READONLY_FINISH_SIGN", "Finish Signing") +#define STR_SIGNATURE_BROKEN NC_("STR_SIGNATURE_BROKEN", "This document has an invalid signature.") +#define STR_SIGNATURE_INVALID NC_("STR_SIGNATURE_INVALID", "The signature was valid, but the document has been modified") +#define STR_SIGNATURE_NOTVALIDATED NC_("STR_SIGNATURE_NOTVALIDATED", "At least one signature has problems: the certificate could not be validated.") +#define STR_SIGNATURE_PARTIAL_OK NC_("STR_SIGNATURE_PARTIAL_OK", "At least one signature has problems: the document is only partially signed.") +#define STR_SIGNATURE_NOTVALIDATED_PARTIAL_OK NC_("STR_SIGNATURE_NOTVALIDATED_PARTIAL_OK", "The certificate could not be validated and the document is only partially signed.") +#define STR_SIGNATURE_OK NC_("STR_SIGNATURE_OK", "This document is digitally signed and the signature is valid.") +#define STR_SIGNATURE_SHOW NC_("STR_SIGNATURE_SHOW", "Show Signatures") +#define STR_TRACK_CHANGES_BUTTON NC_("STR_TRACK_CHANGES_BUTTON", "Show Toolbar") +#define STR_TRACK_CHANGES_BUTTON_HIDE NC_("STR_TRACK_CHANGES_BUTTON_HIDE", "Hide Toolbar") +#define STR_HYPHENATION_BUTTON NC_("STR_HYPHENATION_BUTTON", "Learn more") +#define STR_REFRESH_MASTER_PASSWORD NC_("STR_REFRESH_MASTER_PASSWORD", "The master password is stored in an outdated format, you should refresh it") +#define STR_REFRESH_PASSWORD NC_("STR_REFRESH_PASSWORD", "Refresh Password") + +// Translators: default Impress template names +#define STR_TEMPLATE_NAME1 NC_("STR_TEMPLATE_NAME1", "Grey Elegant") +#define STR_TEMPLATE_NAME2 NC_("STR_TEMPLATE_NAME2", "Beehive") +#define STR_TEMPLATE_NAME3 NC_("STR_TEMPLATE_NAME3", "Blue Curve") +#define STR_TEMPLATE_NAME4 NC_("STR_TEMPLATE_NAME4", "Blueprint Plans") +#define STR_TEMPLATE_NAME5 NC_("STR_TEMPLATE_NAME5", "Candy") +#define STR_TEMPLATE_NAME6 NC_("STR_TEMPLATE_NAME6", "Yellow Idea") +#define STR_TEMPLATE_NAME7 NC_("STR_TEMPLATE_NAME7", "DNA") +#define STR_TEMPLATE_NAME8 NC_("STR_TEMPLATE_NAME8", "Focus") +#define STR_TEMPLATE_NAME9 NC_("STR_TEMPLATE_NAME9", "Forestbird") +#define STR_TEMPLATE_NAME10 NC_("STR_TEMPLATE_NAME10", "Freshes") +#define STR_TEMPLATE_NAME11 NC_("STR_TEMPLATE_NAME11", "Inspiration") +#define STR_TEMPLATE_NAME12 NC_("STR_TEMPLATE_NAME12", "Lights") +#define STR_TEMPLATE_NAME13 NC_("STR_TEMPLATE_NAME13", "Growing Liberty") +#define STR_TEMPLATE_NAME14 NC_("STR_TEMPLATE_NAME14", "Metropolis") +#define STR_TEMPLATE_NAME15 NC_("STR_TEMPLATE_NAME15", "Midnightblue") +#define STR_TEMPLATE_NAME16 NC_("STR_TEMPLATE_NAME16", "Nature Illustration") +#define STR_TEMPLATE_NAME17 NC_("STR_TEMPLATE_NAME17", "Pencil") +#define STR_TEMPLATE_NAME18 NC_("STR_TEMPLATE_NAME18", "Piano") +#define STR_TEMPLATE_NAME19 NC_("STR_TEMPLATE_NAME19", "Portfolio") +#define STR_TEMPLATE_NAME20 NC_("STR_TEMPLATE_NAME20", "Progress") +#define STR_TEMPLATE_NAME21 NC_("STR_TEMPLATE_NAME21", "Sunset") +#define STR_TEMPLATE_NAME22 NC_("STR_TEMPLATE_NAME22", "Vintage") +#define STR_TEMPLATE_NAME23 NC_("STR_TEMPLATE_NAME23", "Vivid") +// Translators: default Writer template names +#define STR_TEMPLATE_NAME24 NC_("STR_TEMPLATE_NAME24", "CV") +#define STR_TEMPLATE_NAME25 NC_("STR_TEMPLATE_NAME25", "Resume") +#define STR_TEMPLATE_NAME26 NC_("STR_TEMPLATE_NAME26", "Default") +#define STR_TEMPLATE_NAME27 NC_("STR_TEMPLATE_NAME27", "Modern") +#define STR_TEMPLATE_NAME28 NC_("STR_TEMPLATE_NAME28", "Modern business letter sans-serif") +#define STR_TEMPLATE_NAME29 NC_("STR_TEMPLATE_NAME29", "Modern business letter serif") +#define STR_TEMPLATE_NAME30 NC_("STR_TEMPLATE_NAME30", "Businesscard with logo") +#define STR_TEMPLATE_NAME31 NC_("STR_TEMPLATE_NAME31", "Simple") +#define STR_TEMPLATE_NAME32 NC_("STR_TEMPLATE_NAME32", "BPMN") + +#define STR_CLEAR_CHAR NC_("STR_CLEAR_CHAR", "Remove") +#define STR_CLEAR_ALL_CHAR NC_("STR_CLEAR_ALL_CHAR", "Clear All") + +#define STR_PASSWORD_LEN NC_("STR_PASSWORD_LEN", "Password length") +#define STR_PASSWORD_WARNING NC_("STR_PASSWORD_WARNING", "The password you have entered causes interoperability issues. Please enter a password that is shorter than 52 bytes, or longer than 55 bytes.") + +#define STR_CTRLCLICKHYPERLINK NC_("STR_CTRLCLICKHYPERLINK", "%{key}-click to open hyperlink: %{link}") +#define STR_CLICKHYPERLINK NC_("STR_CLICKHYPERLINK", "Click to open hyperlink: %{link}") + +#define STR_STYLEUSEDBY NC_("STR_STYLEUSEDBY", "(used by: %STYLELIST)") + +#define STR_DOCUMENT NC_("STR_DOCUMENT", "Document") +#define STR_SPREADSHEET NC_("STR_SPREADSHEET", "Spreadsheet") +#define STR_PRESENTATION NC_("STR_PRESENTATION", "Presentation") +#define STR_DRAWING NC_("STR_DRAWING", "Drawing") +#define STR_RECENT NC_("STR_RECENT", "Recently used") +#define STR_NORECENT NC_("STR_NORECENT", "No recent characters") + +#define STR_ACTION_RESET_ALL_DEFAULT_TEMPLATES NC_("STR_ACTION_RESET_ALL_DEFAULT_TEMPLATES","Reset All De~fault Templates") +#define STR_ACTION_RESET_WRITER_TEMPLATE NC_("STR_ACTION_RESET_WRITER_TEMPLATE","Reset De~fault Text Document") +#define STR_ACTION_RESET_CALC_TEMPLATE NC_("STR_ACTION_RESET_CALC_TEMPLATE","Reset De~fault Spreadsheet") +#define STR_ACTION_RESET_IMPRESS_TEMPLATE NC_("STR_ACTION_RESET_IMPRESS_TEMPLATE","Reset De~fault Presentation") +#define STR_ACTION_RESET_DRAW_TEMPLATE NC_("STR_ACTION_RESET_DRAW_TEMPLATE","Reset De~fault Drawing") +#define STR_ACTION_IMPORT NC_("STR_ACTION_IMPORT","~Import") +#define STR_ACTION_EXTENSIONS NC_("STR_ACTION_EXTENSIONS","E~xtensions") +#define STR_WINDOW_TITLE_RENAME_TEMPLATE NC_("STR_WINDOW_TITLE_RENAME_TEMPLATE","Rename") +#define STR_WINDOW_TITLE_RENAME_CATEGORY NC_("STR_WINDOW_TITLE_RENAME_CATEGORY","Rename Category") +#define STR_WINDOW_TITLE_RENAME_NEW_CATEGORY NC_("STR_WINDOW_TITLE_RENAME_NEW_CATEGORY","New Category") +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/styfitem.hxx b/include/sfx2/styfitem.hxx new file mode 100644 index 000000000..dc2efd88c --- /dev/null +++ b/include/sfx2/styfitem.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_STYFITEM_HXX +#define INCLUDED_SFX2_STYFITEM_HXX + +#include +#include +#include +#include +#include +#include + +struct SFX2_DLLPUBLIC SfxFilterTuple +{ + OUString aName; + SfxStyleSearchBits nFlags; + SfxFilterTuple(const OUString& rName, SfxStyleSearchBits nArg) + : aName(rName) + , nFlags(nArg) + { + } +}; + +typedef std::vector SfxStyleFilter; + +class SFX2_DLLPUBLIC SfxStyleFamilyItem +{ + SfxStyleFamily nFamily; + OUString aText; + OUString aImage; + SfxStyleFilter aFilterList; + +public: + SfxStyleFamilyItem(SfxStyleFamily nFamily, const OUString &rName, const OUString& rImage, const std::pair* pStringArray, const std::locale& rLocale); + + const OUString& GetText() const { return aText; } + SfxStyleFamily GetFamily() const { return nFamily; } + const SfxStyleFilter& GetFilterList() const { return aFilterList; } + const OUString& GetImage() const { return aImage; } +}; + +using SfxStyleFamilies = std::vector; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/styledlg.hxx b/include/sfx2/styledlg.hxx new file mode 100644 index 000000000..6fd7afde1 --- /dev/null +++ b/include/sfx2/styledlg.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_STYLEDLG_HXX +#define INCLUDED_SFX2_STYLEDLG_HXX + +#include +#include +#include + +class SfxStyleSheetBase; +class SfxStyleSheetBasePool; +enum class SfxStyleFamily; + +class SFX2_DLLPUBLIC SfxStyleDialogController : public SfxTabDialogController +{ +private: + SfxStyleSheetBase& m_rStyle; + DECL_DLLPRIVATE_LINK(CancelHdl, weld::Button&, void); + +public: + SfxStyleDialogController(weld::Window* pParent, + const OUString& rUIXMLDescription, const OString& rID, SfxStyleSheetBase&); + + virtual ~SfxStyleDialogController() override; + + SfxStyleSheetBase& GetStyleSheet() { return m_rStyle; } + const SfxStyleSheetBase& GetStyleSheet() const { return m_rStyle; } + + virtual short Ok() override; + + static OUString GenerateUnusedName(SfxStyleSheetBasePool &rPool, SfxStyleFamily eFam); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/tabdlg.hxx b/include/sfx2/tabdlg.hxx new file mode 100644 index 000000000..4c519964e --- /dev/null +++ b/include/sfx2/tabdlg.hxx @@ -0,0 +1,269 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_TABDLG_HXX +#define INCLUDED_SFX2_TABDLG_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SfxTabPage; + +typedef std::unique_ptr (*CreateTabPage)(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet *rAttrSet); +typedef WhichRangesContainer (*GetTabPageRanges)(); // provides international Which-value +struct TabPageImpl; + +struct TabDlg_Impl; + +namespace com::sun::star::frame { class XFrame; } + +#define RET_USER 100 +#define RET_USER_CANCEL 101 + +class SFX2_DLLPUBLIC SfxTabDialogItem final : public SfxSetItem +{ +public: + SfxTabDialogItem( sal_uInt16 nId, const SfxItemSet& rItemSet ); + SfxTabDialogItem(const SfxTabDialogItem& rAttr, SfxItemPool* pItemPool); + virtual SfxTabDialogItem* Clone(SfxItemPool* pToPool = nullptr) const override; +}; + +class SFX2_DLLPUBLIC SfxTabDialogController : public SfxOkDialogController +{ +protected: + std::unique_ptr m_xTabCtrl; + + DECL_LINK(OkHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(ResetHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(BaseFmtHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(UserHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(CancelHdl, weld::Button&, void); +private: + std::unique_ptr m_xOKBtn; + std::unique_ptr m_xApplyBtn; + std::unique_ptr m_xUserBtn; + std::unique_ptr m_xCancelBtn; + std::unique_ptr m_xResetBtn; + std::unique_ptr m_xBaseFmtBtn; + std::unique_ptr m_xSizeGroup; + + std::unique_ptr m_pSet; + std::unique_ptr m_pOutSet; + std::unique_ptr m_pImpl; + WhichRangesContainer m_pRanges; + OString m_sAppPageId; + bool m_bStandardPushed; + std::unique_ptr m_xItemSet; + + DECL_DLLPRIVATE_LINK(ActivatePageHdl, const OString&, void); + DECL_DLLPRIVATE_LINK(DeactivatePageHdl, const OString&, bool); + SAL_DLLPRIVATE void Start_Impl(); + SAL_DLLPRIVATE void CreatePages(); + SAL_DLLPRIVATE void setPreviewsToSamePlace(); + +protected: + virtual short Ok(); + virtual void RefreshInputSet(); + virtual SfxItemSet* CreateInputItemSet(const OString& rName); + virtual void PageCreated(const OString &rName, SfxTabPage &rPage); + + std::unique_ptr m_xExampleSet; + SfxItemSet* GetInputSetImpl(); + SfxTabPage* GetTabPage(std::string_view rPageId) const; + + /** prepare to leave the current page. Calls the DeactivatePage method of the current page, (if necessary), + handles the item sets to copy. + @return sal_True if it is allowed to leave the current page, sal_False otherwise + */ + bool PrepareLeaveCurrentPage(); + + /** save the position of the TabDialog and which tab page is the currently active one + */ + void SavePosAndId(); +public: + SfxTabDialogController(weld::Widget* pParent, const OUString& rUIXMLDescription, const OString& rID, + const SfxItemSet * = nullptr, bool bEditFmt = false); + virtual ~SfxTabDialogController() override; + + void AddTabPage(const OString& rName, // Name of the label for the existing page in the notebook .ui + CreateTabPage pCreateFunc, // != 0 + GetTabPageRanges pRangesFunc); // can be 0 + + void AddTabPage(const OString& rName, // Name of the label for the existing page in the notebook .ui + sal_uInt16 nPageCreateId); // Identifier of the Factory Method to create the page + + void AddTabPage(const OString& rName, // Name of the label for the new page to create + const OUString& rLabel, // UI Label for the new page to create + CreateTabPage pCreateFunc); // != 0 + + void AddTabPage(const OString& rName, // Name of the label for the new page to create + const OUString& rLabel, // UI Label for the new page to create + sal_uInt16 nPageCreateId); // Identifier of the Factory Method to create the page + + void RemoveTabPage( const OString& rName ); // Name of the label for the page in the notebook .ui + + void SetCurPageId(const OString& rName); + void ShowPage(const OString& rName); // SetCurPageId + call Activate on it + OString GetCurPageId() const; + SfxTabPage* GetCurTabPage() const { return GetTabPage(GetCurPageId()); } + + // may provide local slots converted by Map + const WhichRangesContainer& GetInputRanges( const SfxItemPool& ); + void SetInputSet( const SfxItemSet* pInSet ); + const SfxItemSet* GetOutputItemSet() const { return m_pOutSet.get(); } + + virtual weld::Button& GetOKButton() const override { return *m_xOKBtn; } + weld::Button& GetCancelButton() const { return *m_xCancelBtn; } + weld::Button* GetUserButton() const { return m_xUserBtn.get(); } + weld::Button* GetStandardButton() const { return m_xBaseFmtBtn.get(); } + weld::Button* GetApplyButton() const { return m_xApplyBtn.get(); } + weld::Button* GetResetButton() const { return m_xResetBtn.get(); } + void RemoveResetButton(); + void RemoveStandardButton(); + + virtual short run() override; + static bool runAsync(const std::shared_ptr& rController, + const std::function&); + + virtual const SfxItemSet* GetExampleSet() const override { return m_xExampleSet.get(); } + + void SetApplyHandler(const Link& _rHdl); + + //calls Ok without closing dialog + bool Apply(); + void Applied() { m_xExampleSet->Put(*GetInputSetImpl()); } + + //screenshotting + std::vector getAllPageUIXMLDescriptions() const; + bool selectPageByUIXMLDescription(const OString& rUIXMLDescription); + BitmapEx createScreenshot() const; + OString GetScreenshotId() const; +}; + +enum class DeactivateRC { + KeepPage = 0x00, // Error handling; page does not change + // 2. Fill an itemset for update + // parent examples, this pointer can be NULL all the time! + LeavePage = 0x01, + // Set, refresh and update other Page + RefreshSet = 0x02 +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +class SFX2_DLLPUBLIC SfxTabPage : public BuilderPage +{ +friend class SfxTabDialog; +friend class SfxTabDialogController; + +private: + const SfxItemSet* pSet; + OUString aUserString; + bool bHasExchangeSupport; + std::unordered_map maAdditionalProperties; + + std::unique_ptr< TabPageImpl > pImpl; + +protected: + SfxTabPage(weld::Container* pPage, weld::DialogController* pController, const OUString& rUIXMLDescription, const OString& rID, const SfxItemSet *rAttrSet); + + sal_uInt16 GetWhich( sal_uInt16 nSlot, bool bDeep = true ) const + { return pSet->GetPool()->GetWhich( nSlot, bDeep ); } + template + TypedWhichId GetWhich( TypedWhichId nSlot, bool bDeep = true ) const + { + return TypedWhichId(GetWhich(sal_uInt16(nSlot), bDeep)); + } + + const SfxPoolItem* GetOldItem( const SfxItemSet& rSet, sal_uInt16 nSlot, bool bDeep = true ); + template const T* GetOldItem( const SfxItemSet& rSet, TypedWhichId nSlot, bool bDeep = true ) + { + return static_cast(GetOldItem(rSet, sal_uInt16(nSlot), bDeep)); + } + + SfxOkDialogController* GetDialogController() const; +public: + void SetDialogController(SfxOkDialogController* pDialog); +public: + virtual ~SfxTabPage() override; + + void set_visible(bool bVisible) + { + m_xContainer->set_visible(bVisible); + } + + const SfxItemSet& GetItemSet() const { return *pSet; } + + virtual bool FillItemSet( SfxItemSet* ); + virtual void Reset( const SfxItemSet* ); + // Allows to postpone some initialization to the first activation + virtual bool DeferResetToFirstActivation(); + + bool HasExchangeSupport() const + { return bHasExchangeSupport; } + void SetExchangeSupport() + { bHasExchangeSupport = true; } + + virtual void ActivatePage( const SfxItemSet& ); + virtual DeactivateRC DeactivatePage( SfxItemSet* pSet ); + void SetUserData(const OUString& rString) + { aUserString = rString; } + const OUString& GetUserData() const { return aUserString; } + virtual void FillUserData(); + virtual bool IsReadOnly() const; + virtual void PageCreated (const SfxAllItemSet& aSet); + virtual void ChangesApplied(); + static const SfxPoolItem* GetItem( const SfxItemSet& rSet, sal_uInt16 nSlot, bool bDeep = true ); + template static const T* GetItem( const SfxItemSet& rSet, TypedWhichId nSlot, bool bDeep = true ) + { + return static_cast(GetItem(rSet, sal_uInt16(nSlot), bDeep)); + } + + void SetFrame(const css::uno::Reference< css::frame::XFrame >& xFrame); + css::uno::Reference< css::frame::XFrame > GetFrame() const; + + const SfxItemSet* GetDialogExampleSet() const; + + OString GetHelpId() const; + OString GetConfigId() const { return GetHelpId(); } + bool IsVisible() const { return m_xContainer->get_visible(); } + + weld::Window* GetFrameWeld() const; + + std::unordered_map& getAdditionalProperties() + { + return maAdditionalProperties; + } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/tbxctrl.hxx b/include/sfx2/tbxctrl.hxx new file mode 100644 index 000000000..e3953c4e5 --- /dev/null +++ b/include/sfx2/tbxctrl.hxx @@ -0,0 +1,142 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_TBXCTRL_HXX +#define INCLUDED_SFX2_TBXCTRL_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::frame { class XDispatchProvider; } +namespace com::sun::star::frame { class XFrame; } +namespace vcl { class Window; } +namespace com::sun::star::frame { class XToolbarController; } + +class InterimItemWindow; +class SfxToolBoxControl; +class SfxModule; + +rtl::Reference SfxToolBoxControllerFactory( const css::uno::Reference< css::frame::XFrame >& rFrame, ToolBox* pToolbox, ToolBoxItemId nID, const OUString& aCommandURL ); + +typedef rtl::Reference (*SfxToolBoxControlCtor)( sal_uInt16 nSlotId, ToolBoxItemId nId, ToolBox& rBox ); + +struct SfxTbxCtrlFactory +{ + SfxToolBoxControlCtor pCtor; + const std::type_info& nTypeId; + sal_uInt16 nSlotId; + + SfxTbxCtrlFactory( SfxToolBoxControlCtor pTheCtor, + const std::type_info& nTheTypeId, sal_uInt16 nTheSlotId ): + pCtor(pTheCtor), + nTypeId(nTheTypeId), + nSlotId(nTheSlotId) + {} +}; + + +#define SFX_DECL_TOOLBOX_CONTROL() \ + static rtl::Reference CreateImpl( sal_uInt16 nSlotId, ToolBoxItemId nId, ToolBox &rTbx ); \ + static void RegisterControl(sal_uInt16 nSlotId = 0, SfxModule *pMod=nullptr) + +/* For special ToolBox controls, such as a font selection box or toolbox + tear-off floating windows, an appropriate Item-Subclass of SfxTooBoxControl + has to be implemented. + + This class has to be registered in SfxApplication:Init() with the static + control method RegisterControl(). The SFx then automatically creates these + controls in the toolbox, if the associated slots are of the specific type. + */ + +struct SfxToolBoxControl_Impl; +class SFX2_DLLPUBLIC SfxToolBoxControl: public svt::ToolboxController +{ +friend struct SfxTbxCtrlFactory; + + std::unique_ptr< SfxToolBoxControl_Impl> pImpl; + +protected: + // old SfxToolBoxControl methods + virtual void StateChangedAtToolBoxControl( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState ); + virtual void Select( sal_uInt16 nSelectModifier ); + + virtual void DoubleClick(); + virtual void Click(); + virtual void CreatePopupWindow(); + virtual VclPtr CreateItemWindow(vcl::Window *pParent); + +public: + // XComponent + virtual void SAL_CALL dispose() override; + + // new controller API + // XStatusListener + virtual void SAL_CALL statusChanged( const css::frame::FeatureStateEvent& Event ) override; + + // XToolbarController + virtual void SAL_CALL execute( sal_Int16 KeyModifier ) override; + virtual void SAL_CALL click() override; + virtual void SAL_CALL doubleClick() override; + virtual css::uno::Reference< css::awt::XWindow > SAL_CALL createPopupWindow() override; + virtual css::uno::Reference< css::awt::XWindow > SAL_CALL createItemWindow( const css::uno::Reference< css::awt::XWindow >& rParent ) override; + +public: + SFX_DECL_TOOLBOX_CONTROL(); + + SfxToolBoxControl( sal_uInt16 nSlotID, ToolBoxItemId nId, ToolBox& rBox, bool bShowStrings = false ); + virtual ~SfxToolBoxControl() override; + + ToolBox& GetToolBox() const; + ToolBoxItemId GetId() const; + unsigned short GetSlotId() const; + + void Dispatch( const OUString& aCommand, + css::uno::Sequence< css::beans::PropertyValue > const & aArgs ); + static void Dispatch( const css::uno::Reference< css::frame::XDispatchProvider >& rDispatchProvider, + const OUString& rCommand, + css::uno::Sequence< css::beans::PropertyValue > const & aArgs ); + + static SfxItemState GetItemState( const SfxPoolItem* pState ); + static rtl::Reference CreateControl( sal_uInt16 nSlotId, ToolBoxItemId nTbxId, ToolBox *pBox, SfxModule const *pMod ); + static void RegisterToolBoxControl( SfxModule*, const SfxTbxCtrlFactory&); +}; + +#define SFX_IMPL_TOOLBOX_CONTROL(Class, nItemClass) \ + rtl::Reference Class::CreateImpl( sal_uInt16 nSlotId, ToolBoxItemId nId, ToolBox &rTbx ) \ + { return new Class( nSlotId, nId, rTbx ); } \ + void Class::RegisterControl(sal_uInt16 nSlotId, SfxModule *pMod) \ + { SfxToolBoxControl::RegisterToolBoxControl( pMod, SfxTbxCtrlFactory( \ + Class::CreateImpl, typeid(nItemClass), nSlotId ) ); } + +#define SFX_IMPL_TOOLBOX_CONTROL_ARG(Class, nItemClass, Arg) \ + rtl::Reference Class::CreateImpl( sal_uInt16 nSlotId, ToolBoxItemId nId, ToolBox &rTbx ) \ + { return new Class( nSlotId, nId, rTbx, Arg); } \ + void Class::RegisterControl(sal_uInt16 nSlotId, SfxModule *pMod) \ + { SfxToolBoxControl::RegisterToolBoxControl( pMod, SfxTbxCtrlFactory( \ + Class::CreateImpl, typeid(nItemClass), nSlotId ) ); } + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/templatedlg.hxx b/include/sfx2/templatedlg.hxx new file mode 100644 index 000000000..10d3107fc --- /dev/null +++ b/include/sfx2/templatedlg.hxx @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_INC_TEMPLATEDLG_HXX +#define INCLUDED_SFX2_INC_TEMPLATEDLG_HXX + +#include +#include + +#include +#include + +#include +#include +#include + +#include + +class ThumbnailViewItem; + +namespace com +{ +namespace sun::star::frame +{ +class XDesktop2; +class XModel; +} +} + +class SFX2_DLLPUBLIC SfxTemplateManagerDlg : public weld::GenericDialogController +{ + typedef bool (*selection_cmp_fn)(const ThumbnailViewItem*, const ThumbnailViewItem*); + +public: + SfxTemplateManagerDlg(weld::Window* parent); + + virtual ~SfxTemplateManagerDlg() override; + virtual short run() override; + + void setDocumentModel(const css::uno::Reference& rModel); + void setTemplateViewMode(TemplateViewMode eViewMode); + TemplateViewMode getTemplateViewMode() const; + +protected: + void getApplicationSpecificSettings(); + + void readSettings(); + + void writeSettings(); + + void fillFolderComboBox(); + + DECL_DLLPRIVATE_LINK(SelectApplicationHdl, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(SelectRegionHdl, weld::ComboBox&, void); + + DECL_DLLPRIVATE_LINK(OkClickHdl, weld::Button&, void); + void ImportActionHdl(); + static void ExtensionsActionHdl(); + + DECL_DLLPRIVATE_LINK(TVItemStateHdl, const ThumbnailViewItem*, void); + + DECL_DLLPRIVATE_LINK(MenuSelectHdl, const OString&, void); + void DefaultTemplateMenuSelectHdl(std::string_view rIdent); + + DECL_DLLPRIVATE_LINK(OpenRegionHdl, void*, void); + DECL_DLLPRIVATE_LINK(CreateContextMenuHdl, ThumbnailViewItem*, void); + DECL_DLLPRIVATE_LINK(OpenTemplateHdl, ThumbnailViewItem*, void); + DECL_DLLPRIVATE_LINK(EditTemplateHdl, ThumbnailViewItem*, void); + DECL_DLLPRIVATE_LINK(DeleteTemplateHdl, void*, void); + DECL_DLLPRIVATE_LINK(DefaultTemplateHdl, ThumbnailViewItem*, void); + DECL_DLLPRIVATE_LINK(MoveTemplateHdl, void*, void); + DECL_DLLPRIVATE_LINK(ExportTemplateHdl, void*, void); + + void SearchUpdate(); + + DECL_DLLPRIVATE_LINK(SearchUpdateHdl, weld::Entry&, void); + DECL_DLLPRIVATE_LINK(GetFocusHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(LoseFocusHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(ImplUpdateDataHdl, Timer*, void); + DECL_DLLPRIVATE_LINK(KeyInputHdl, const KeyEvent&, bool); + + DECL_DLLPRIVATE_LINK(ListViewHdl, weld::Toggleable&, void); + DECL_DLLPRIVATE_LINK(ThumbnailViewHdl, weld::Toggleable&, void); + DECL_DLLPRIVATE_LINK(FocusRectLocalHdl, weld::Widget&, tools::Rectangle); + + void OnTemplateImportCategory(std::u16string_view sCategory); + // static void OnTemplateLink (); + void OnTemplateOpen(); + void OnTemplateExport(); + + void OnTemplateState(const ThumbnailViewItem* pItem); + + void OnCategoryNew(); + void OnCategoryRename(); + void OnCategoryDelete(); + + void updateMenuItems(); + + /** + * + * Move templates stored in the filesystem to another folder. + * + **/ + + void localMoveTo(sal_uInt16 nMenuId); + + /// Return filter according to the currently selected application filter. + FILTER_APPLICATION getCurrentApplicationFilter() const; + +protected: + std::set maSelTemplates; + css::uno::Reference m_xModel; + css::uno::Reference mxDesktop; + + Timer m_aUpdateDataTimer; + + std::unique_ptr mxSearchFilter; + std::unique_ptr mxCBApp; + std::unique_ptr mxCBFolder; + + std::unique_ptr mxOKButton; + std::unique_ptr mxCBXHideDlg; + std::unique_ptr mxActionBar; + std::unique_ptr mxLocalView; + std::unique_ptr mxTemplateDefaultMenu; + std::unique_ptr mxLocalViewWeld; + std::unique_ptr mxListViewButton; + std::unique_ptr mxThumbnailViewButton; + TemplateViewMode mViewMode; + bool bMakeSelItemVisible; +}; + +// class SfxTemplateCategoryDialog ------------------------------------------------------------------- + +class SfxTemplateCategoryDialog final : public weld::GenericDialogController +{ +private: + OUString msSelectedCategory; + bool mbIsNewCategory; + + std::unique_ptr mxLBCategory; + std::unique_ptr mxSelectLabel; + std::unique_ptr mxNewCategoryEdit; + std::unique_ptr mxCreateLabel; + std::unique_ptr mxOKButton; + +public: + DECL_LINK(NewCategoryEditHdl, weld::Entry&, void); + DECL_LINK(SelectCategoryHdl, weld::TreeView&, void); + + void SetCategoryLBEntries(std::vector names); + + const OUString& GetSelectedCategory() const { return msSelectedCategory; }; + + bool IsNewCategoryCreated() const { return mbIsNewCategory; } + +public: + explicit SfxTemplateCategoryDialog(weld::Window* pParent); + + virtual ~SfxTemplateCategoryDialog() override; +}; + +// class SfxTemplateSelectionDialog ------------------------------------------------------------------- + +class SFX2_DLLPUBLIC SfxTemplateSelectionDlg final : public SfxTemplateManagerDlg +{ +public: + SfxTemplateSelectionDlg(weld::Window* parent); + + virtual ~SfxTemplateSelectionDlg() override; + virtual short run() override; + + OUString const& getTemplatePath() const { return msTemplatePath; }; + bool IsStartWithTemplate() const { return mxCBXHideDlg->get_active(); }; + +private: + DECL_DLLPRIVATE_LINK(OpenTemplateHdl, ThumbnailViewItem*, void); + DECL_DLLPRIVATE_LINK(OkClickHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(TimeOut, Timer*, void); + + OUString msTemplatePath; + Idle maIdle; +}; + +#endif // INCLUDED_SFX2_INC_TEMPLATEDLG_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/templatedlglocalview.hxx b/include/sfx2/templatedlglocalview.hxx new file mode 100644 index 000000000..65b77ead1 --- /dev/null +++ b/include/sfx2/templatedlglocalview.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#pragma once + +#include +#include + +class TemplateDlgLocalView final : public TemplateLocalView, public ListView +{ +public: + TemplateDlgLocalView(std::unique_ptr xWindow, + std::unique_ptr xMenu, + std::unique_ptr xTreeView); + + void setTemplateViewMode(TemplateViewMode eMode); + + virtual void showAllTemplates() override; + + void showRegion(TemplateContainerItem const* pItem); + + void showRegion(std::u16string_view rName); + + void reload(); + + virtual bool KeyInput(const KeyEvent& rKEvt) override; + + void createContextMenu(const bool bIsDefault, const bool bIsBuiltIn, const bool bIsSingleSel, + const OUString& rDefaultImg); + + virtual void Show() override; + + virtual void Hide() override; + + bool IsVisible() const; + + void connect_focus_rect(const Link& rLink) + { + GetDrawingArea()->connect_focus_rect(rLink); + } + + void MakeItemVisible(sal_uInt16 nId) { ThumbnailView::MakeItemVisible(nId); } + + void insertItems(const std::vector& rTemplates, bool isRegionSelected, + bool bShowCategoryInTooltip); + +private: + void ContextMenuSelectHdl(std::string_view rIdent); + + void insertFilteredItems(); + + void syncCursor(); + + void updateSelection(); + + DECL_LINK(RowActivatedHdl, weld::TreeView&, bool); + + DECL_LINK(ListViewChangedHdl, weld::TreeView&, void); + + DECL_LINK(PopupMenuHdl, const CommandEvent&, bool); + + DECL_LINK(KeyPressHdl, const KeyEvent&, bool); + + TemplateViewMode mViewMode; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/templatelocalview.hxx b/include/sfx2/templatelocalview.hxx new file mode 100644 index 000000000..020ad2ba3 --- /dev/null +++ b/include/sfx2/templatelocalview.hxx @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_TEMPLATELOCALVIEW_HXX +#define INCLUDED_SFX2_TEMPLATELOCALVIEW_HXX + +#include +#include +#include +#include +#include + +//template thumbnail item defines +#define TEMPLATE_ITEM_MAX_WIDTH 160 +#define TEMPLATE_ITEM_MAX_HEIGHT 148 +#define TEMPLATE_ITEM_PADDING 5 +#define TEMPLATE_ITEM_MAX_TEXT_LENGTH 20 +#define TEMPLATE_ITEM_THUMBNAIL_MAX_HEIGHT 96 + +//template thumbnail height with a subtitle +#define TEMPLATE_ITEM_MAX_HEIGHT_SUB 160 + +//template thumbnail image defines +#define TEMPLATE_THUMBNAIL_MAX_HEIGHT TEMPLATE_ITEM_THUMBNAIL_MAX_HEIGHT - 2*TEMPLATE_ITEM_PADDING +#define TEMPLATE_THUMBNAIL_MAX_WIDTH TEMPLATE_ITEM_MAX_WIDTH - 2*TEMPLATE_ITEM_PADDING + +class SfxDocumentTemplates; +class TemplateContainerItem; +class TemplateViewItem; + +enum class FILTER_APPLICATION +{ + NONE, + WRITER, + CALC, + IMPRESS, + DRAW +}; + +// Display template items depending on the generator application +class ViewFilter_Application final +{ +public: + + ViewFilter_Application (FILTER_APPLICATION App) + : mApp(App) + {} + + bool operator () (const ThumbnailViewItem *pItem); + + static bool isFilteredExtension(FILTER_APPLICATION filter, std::u16string_view rExt); + bool isValid (std::u16string_view rPath) const; + +private: + + FILTER_APPLICATION mApp; +}; + +class TemplateLocalView : public ThumbnailView +{ + typedef bool (*selection_cmp_fn)(const ThumbnailViewItem*,const ThumbnailViewItem*); + +public: + + TemplateLocalView(std::unique_ptr xWindow, + std::unique_ptr xMenu); + + virtual ~TemplateLocalView () override; + + // Fill view with new item list + void insertItems (const std::vector &rTemplates, bool isRegionSelected = true, bool bShowCategoryInTooltip = false); + + // Fill view with template folders thumbnails + void Populate (); + + void reload (); + + virtual void showAllTemplates (); + + void showRegion (TemplateContainerItem const *pItem); + + void ContextMenuSelectHdl(std::string_view rIdent); + + TemplateContainerItem* getRegion(std::u16string_view sStr); + + sal_uInt16 getRegionId (size_t pos) const; + + sal_uInt16 getRegionId (std::u16string_view sRegionName) const; + + OUString getRegionName(const sal_uInt16 nRegionId) const; + + OUString getRegionItemName(const sal_uInt16 nItemId) const; + + std::vector getFolderNames (); + + std::vector + getFilteredItems (const std::function &rFunc) const; + + sal_uInt16 createRegion (const OUString &rName); + + bool renameRegion(std::u16string_view rTitle, const OUString &rNewTitle); + + bool removeRegion (const sal_uInt16 nItemId); + + bool removeTemplate (const sal_uInt16 nItemId, const sal_uInt16 nSrcItemId); + + void moveTemplates (const std::set &rItems, const sal_uInt16 nTargetItem); + + bool copyFrom(TemplateContainerItem *pItem, const OUString &rPath); + + bool exportTo (const sal_uInt16 nItemId, const sal_uInt16 nRegionItemId, std::u16string_view rName); + + virtual bool renameItem(ThumbnailViewItem* pItem, const OUString& sNewTitle) override; + + virtual bool MouseButtonDown( const MouseEvent& rMEvt ) override; + + virtual bool Command(const CommandEvent& rPos) override; + + virtual bool KeyInput( const KeyEvent& rKEvt ) override; + + sal_uInt16 getCurRegionId () const { return mnCurRegionId;} + + void setCurRegionId (sal_uInt16 nCurRegionId) { mnCurRegionId = nCurRegionId;} + + void setOpenRegionHdl(const Link &rLink); + + void setCreateContextMenuHdl(const Link &rLink); + + void setOpenTemplateHdl(const Link &rLink); + + void setEditTemplateHdl(const Link &rLink); + + void setDeleteTemplateHdl(const Link &rLink); + + void setDefaultTemplateHdl(const Link &rLink); + + void setMoveTemplateHdl(const Link &rLink); + + void setExportTemplateHdl(const Link &rLink); + + void updateThumbnailDimensions(tools::Long itemMaxSize); + + void RemoveDefaultTemplateIcon( std::u16string_view rPath); + + bool IsBuiltInRegion(const OUString& rRegionName); + + static BitmapEx scaleImg (const BitmapEx &rImg, tools::Long width, tools::Long height); + + static BitmapEx getDefaultThumbnail( std::u16string_view rPath ); + + static BitmapEx fetchThumbnail (const OUString &msURL, tools::Long width, tools::Long height); + + static bool IsDefaultTemplate(const OUString& rPath); + + static bool IsInternalTemplate(const OUString& rPath); + +protected: + virtual void OnItemDblClicked(ThumbnailViewItem *pItem) override; + + sal_uInt16 mnCurRegionId; + + TemplateViewItem *maSelectedItem; + + tools::Long mnThumbnailWidth; + tools::Long mnThumbnailHeight; + + Point maPosition; //store the point of click event + + Link maOpenRegionHdl; + Link maCreateContextMenuHdl; + Link maOpenTemplateHdl; + Link maEditTemplateHdl; + Link maDeleteTemplateHdl; + Link maDefaultTemplateHdl; + Link maMoveTemplateHdl; + Link maExportTemplateHdl; + + std::unique_ptr mpDocTemplates; + std::vector > maRegions; + std::vector maAllTemplates; +}; + + +#endif // INCLUDED_SFX2_TEMPLATELOCALVIEW_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/templateproperties.hxx b/include/sfx2/templateproperties.hxx new file mode 100644 index 000000000..2c1de0125 --- /dev/null +++ b/include/sfx2/templateproperties.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_TEMPLATEPROPERTIES_HXX +#define INCLUDED_SFX2_TEMPLATEPROPERTIES_HXX + +#include +#include + +struct TemplateItemProperties +{ + sal_uInt16 nId; ///< Index for ThumbnailView + sal_uInt16 nDocId; ///< Index based on SfxTemplateDocument + sal_uInt16 nRegionId; + OUString aName; + OUString aPath; + OUString aRegionName; + BitmapEx aThumbnail; +}; + +#endif // INCLUDED_SFX2_TEMPLATEPROPERTIES_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/templdlg.hxx b/include/sfx2/templdlg.hxx new file mode 100644 index 000000000..5dd5b8b6b --- /dev/null +++ b/include/sfx2/templdlg.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_TEMPLDLG_HXX +#define INCLUDED_SFX2_TEMPLDLG_HXX + +#include +#include +#include +#include +#include + +class SfxBindings; +class SfxTemplateDialog_Impl; + +class UNLESS_MERGELIBS(SFX2_DLLPUBLIC) SfxTemplatePanelControl final : public PanelLayout +{ +public: + SfxTemplatePanelControl(SfxBindings* pBindings, weld::Widget* pParent); + virtual ~SfxTemplatePanelControl() override; + + weld::Builder* get_builder() { return m_xBuilder.get(); } + weld::Container* get_container() { return m_xContainer.get(); } + +private: + std::unique_ptr pImpl; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/thumbnailview.hxx b/include/sfx2/thumbnailview.hxx new file mode 100644 index 000000000..453f3c9c5 --- /dev/null +++ b/include/sfx2/thumbnailview.hxx @@ -0,0 +1,331 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_THUMBNAILVIEW_HXX +#define INCLUDED_SFX2_THUMBNAILVIEW_HXX + +#include + +#include +#include +#include + +#include + +class BitmapEx; +class MouseEvent; +class KeyEvent; +class DataChangedEvent; +class ScrollBar; +class ThumbnailViewItem; +typedef ::std::vector< ThumbnailViewItem* > ThumbnailValueItemList; + + +struct ThumbnailItemAttributes; + +/************************************************************************* + + Description + ============ + + class ThumbnailView + + This class allows the selection of an item. In the process items are + drawn side by side. The selection of items can be more clear than in a + ListBox shape for example in case of colors or samples. + The amount of columns drawn by the control and whether the items + should be encircled can be specified. Optional a NoSelection or name + field could be shown. By default image and color items are supported. + Items could be drawn by oneself if InsertItem() is only called with + an ID. To achieve this the UserDraw handler needs to be overridden. The + description text could be specified afterwards in case of UserDraw + and any other items. + + Cross references + + class ListBox + + -------------------------------------------------------------------------- + + WinBits + + WB_VSCROLL A scrollbar will be always shown. The visible number of + lines have to be specified with SetLineCount() if this + flag is set. + WB_TABSTOP It is possible to jump into the ValueSet with the tab key. + WB_NOTABSTOP It is not possible to jump into the ValueSet with the + tab key. + -------------------------------------------------------------------------- + + The number of columns must be either set with SetColCount() or + SetItemWidth(). If the number of columns is specified by SetColCount() + the width of the items will be calculated by the visible range. + If the items should have a static width, it has to be specified + with SetItemWidth(). In this case the number of columns will be calculated + by the visible range. + + The number of rows is given by the number of items / number of columns. The + number of visible rows must either specified by SetLineCount() or + SetItemWidth(). If the number of visible rows is specified by SetLineCount(), + the height of the items will be calculated from the visible height. If the + items should have a fixed height it has to be specified with SetItemHeight(). + In this case the number of visible rows is then calculated from the visible + height. If the number of visible rows is neither specified by SetLineCount() + nor by SetItemHeight() all rows will be shown. The height of the items will + be calculated by the visible height. If the number of visible rows is + specified by SetLineCount() or SetItemHeight() ValueSet does scroll + automatically when more lines are available, as are visible. If scrolling + should be also possible with a ScrollBar WB_VSCROLL needs to be set. + + The distance between the items can be increased by SetExtraSpacing(). The + distance, which will be shown between two items (both in x and in y), is + measured in pixels. + + The exact window size for a specific item size can be calculated by + CalcWindowSizePixel(). To do this all relevant data (number of columns/...) + have to be specified and if no number of rows was set, all items need to + be inserted. If the window was created with WB_BORDER/Border=sal_True the + size has to be specified with SetOutputSizePixel(). In other cases different + size-methods can be used. With CalcItemSize() the inner and outer size of + an item could be calculated (for this the free space defined by + SetExtraSpacing() will not be included). + + The background color could be specified by SetColor(), with which the image + or UserDraw items will be underlaid. If no color is specified the color + of other windows (WindowColor) will be used for the background. + + -------------------------------------------------------------------------- + + At first all items should be inserted and only then Show() should be called + since the output area will be precomputed. If this is not done the first + Paint will appear a little bit slower. Therefore the Control, if it is loaded + from the resource and only supplied with items during runtime, should be + loaded with Hide = sal_True and then displayed with Show(). + + In case of a visible Control the creation of the new output area could be + activated before Paint by calling Format(). + + -------------------------------------------------------------------------- + + If Drag and Drop will be called from the ValueSet the Command-Handler has to + be overridden. From this StartDrag needs to be called. If this method returns + sal_True the drag-process could be initiated by ExecuteDrag(), otherwise no + processing will take place. This method makes sure that ValueSet stops its + processing and as appropriate selects the entry. Therefore the calling of + Select-Handler within this function must be expected. + + For dropping QueryDrop() and Drop() need to be overridden and ShowDropPos() + and HideDropPos() should be called within these methods. + To show the insertion point ShowDropPos() has to be called within the + QueryDrop-Handler. ShowDropPos() also scrolls the ValueSet if the passed + position is located at the window border. Furthermore ShowDropPos() returns + the position, at which the item should be inserted respectively which + insertion point was shown. If no insertion point was determined + VALUESET_ITEM_NOTFOUND will be returned. If the window was left during dragging + or the drag process is terminated HideDropPos() should be called in any case. + + -------------------------------------------------------------------------- + + This class is currently still in the SV-Tools. That's why the ValueSet needs + to be loaded as a Control out of the resource and the desired WinBits have + to be set (before Show) with SetStyle(). + +*************************************************************************/ + +/* ThumbnailView types */ + +#define THUMBNAILVIEW_ITEM_NOTFOUND (sal_uInt16(-1)) + +// Display all the available items in the thumbnail. +class ViewFilterAll +{ +public: + + bool operator () (const ThumbnailViewItem*) const + { + return true; + } +}; + +/** + * + * Class to display thumbnails with their names below their respective icons + * + **/ + +class SFX2_DLLPUBLIC ThumbnailView : public weld::CustomWidgetController +{ + friend class ThumbnailViewAcc; + friend class ThumbnailViewItemAcc; + +public: + ThumbnailView(std::unique_ptr xWindow, std::unique_ptr xMenu); + + virtual ~ThumbnailView() override; + + virtual bool MouseMove(const MouseEvent& rMEvt) override; + + /// Updates information in the view; used only in RecentDocsView ATM. + virtual void Reload() {} + + void AppendItem(std::unique_ptr pItem); + + void RemoveItem(sal_uInt16 nItemId); + + virtual void Clear(); + + // Change current thumbnail item list with new one (invalidates all pointers to a thumbnail item) + void updateItems(std::vector> items); + + size_t GetItemPos( sal_uInt16 nItemId ) const; + + sal_uInt16 GetItemId( size_t nPos ) const; + + sal_uInt16 GetItemId( const Point& rPos ) const; + + sal_uInt16 getNextItemId () const; + + virtual bool renameItem(ThumbnailViewItem* pItem, const OUString& sNewTitle); + + bool isDrawMnemonic() const { return mbDrawMnemonics; } + + void setItemMaxTextLength (sal_uInt32 nLength); + + void setItemDimensions (tools::Long ItemWidth, tools::Long ThumbnailHeight, + tools::Long DisplayHeight, int itemPadding); + + void SelectItem( sal_uInt16 nItemId ); + + bool IsItemSelected( sal_uInt16 nItemId ) const; + + /** + * + * @brief deselect all current selected items. + * + **/ + + void deselectItems (); + + void ShowTooltips( bool bShowTooltips ); + + void DrawMnemonics( bool bDrawMnemonics ); + + void filterItems (const std::function &func); + + void setItemStateHdl (const Link &aLink) { maItemStateHdl = aLink; } + + virtual void Resize() override; + + virtual void Show() override + { + mxScrolledWindow->show(); + CustomWidgetController::Show(); + } + + virtual void Hide() override + { + mxScrolledWindow->hide(); + CustomWidgetController::Hide(); + } + + virtual void SetDrawingArea(weld::DrawingArea* pDrawingArea) override; + + static BitmapEx readThumbnail(const OUString &msURL); + +protected: + + virtual bool KeyInput( const KeyEvent& rKEvt ) override; + + virtual bool MouseButtonDown( const MouseEvent& rMEvt ) override; + + virtual void Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect) override; + + virtual void GetFocus() override; + + virtual void LoseFocus() override; + + virtual OUString RequestHelp(tools::Rectangle& rRect) override; + + virtual css::uno::Reference< css::accessibility::XAccessible > CreateAccessible() override; + + const css::uno::Reference & getAccessible() const; + +protected: + + // Drawing item related functions, override them to make your own custom ones. + + void DrawItem (ThumbnailViewItem const *pItem); + + virtual void OnItemDblClicked (ThumbnailViewItem *pItem); + + // Set Item colors from the ThumbnailView colors + void UpdateColors(); + +protected: + + friend class ThumbnailViewAcc; + friend class ThumbnailViewItemAcc; + + void CalculateItemPositions (bool bScrollBarUsed = false); + void MakeItemVisible( sal_uInt16 nId ); + + void ImplInit(); + + void ImplDeleteItems(); + size_t ImplGetItem( const Point& rPoint ) const; + ThumbnailViewItem* ImplGetItem( size_t nPos ); + sal_uInt16 ImplGetVisibleItemCount() const; + ThumbnailViewItem* ImplGetVisibleItem(sal_uInt16 nVisiblePos); + void ImplFireAccessibleEvent( short nEventId, const css::uno::Any& rOldValue, const css::uno::Any& rNewValue ); + bool ImplHasAccessibleListeners() const; + DECL_DLLPRIVATE_LINK( ImplScrollHdl, weld::ScrolledWindow&, void ); + +protected: + + std::vector< std::unique_ptr > mItemList; + css::uno::Reference mxAccessible; + ThumbnailValueItemList mFilteredItemList; ///< Cache to store the filtered items + ThumbnailValueItemList::iterator mpStartSelRange; + tools::Long mnItemWidth; + tools::Long mnItemHeight; + tools::Long mnItemPadding; + tools::Long mnThumbnailHeight; // Maximum height of the thumbnail + tools::Long mnDisplayHeight; // Height of the data display box (name, etc) + tools::Long mnVItemSpace; // Vertical spacing between rows, -1 to use excess unused height split up between items + tools::Long mnVisLines; + tools::Long mnLines; + + sal_uInt16 mnCols; + sal_uInt16 mnFirstLine; + bool mbScroll : 1; // Whether we need to scroll + bool mbAllowVScrollBar : 1; // Whether to show a visible scrollbar + bool mbHasVisibleItems : 1; + bool mbShowTooltips : 1; + bool mbDrawMnemonics : 1; + bool mbSelectOnFocus : 1; + Color maFillColor; ///< Background color of the thumbnail view widget. + Color maTextColor; ///< Text color. + Color maHighlightColor; ///< Color of the highlight (background) of the hovered item. + Color maHighlightTextColor; ///< Color of the text for the highlighted item. + Color maSelectHighlightColor; ///< Color of the highlight (background) of the selected and hovered item. + Color maSelectHighlightTextColor; ///< Color of the text of the selected and hovered item. + double mfHighlightTransparence; ///< Transparence of the highlight. + + Link maItemStateHdl; + std::unique_ptr mpItemAttrs; + std::unique_ptr mxScrolledWindow; + std::unique_ptr mxContextMenu; + + std::function maFilterFunc; +}; + + +#endif // INCLUDED_SFX2_THUMBNAILVIEW_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/thumbnailviewitem.hxx b/include/sfx2/thumbnailviewitem.hxx new file mode 100644 index 000000000..d0da2edae --- /dev/null +++ b/include/sfx2/thumbnailviewitem.hxx @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace com::sun::star::accessibility { class XAccessible; } +namespace drawinglayer::primitive2d { class Primitive2DContainer; } + +#define THUMBNAILVIEW_ITEM_NONEITEM 0xFFFE + +const int THUMBNAILVIEW_ITEM_CORNER = 5; + +class ThumbnailView; +class MouseEvent; + +namespace basegfx { + class B2DPolygon; +} + +namespace drawinglayer { + namespace processor2d { + class BaseProcessor2D; + } + namespace primitive2d { + class PolygonHairlinePrimitive2D; + } +} + +struct ThumbnailItemAttributes +{ + sal_uInt32 nMaxTextLength; + basegfx::BColor aFillColor; + basegfx::BColor aTextColor; + basegfx::BColor aHighlightColor; + basegfx::BColor aHighlightTextColor; + basegfx::BColor aSelectHighlightColor; + basegfx::BColor aSelectHighlightTextColor; + double fHighlightTransparence; + basegfx::B2DVector aFontSize; + drawinglayer::attribute::FontAttribute aFontAttr; +}; + +class SFX2_DLLPUBLIC ThumbnailViewItem +{ +public: + + ThumbnailView& mrParent; + sal_uInt16 mnId; + bool mbVisible; + bool mbBorder; + bool mbSelected; + bool mbHover; + BitmapEx maPreview1; + OUString maTitle; + OUString maHelpText; + css::uno::Reference< css::accessibility::XAccessible > mxAcc; + + ThumbnailViewItem(ThumbnailView& rView, sal_uInt16 nId); + + virtual ~ThumbnailViewItem (); + + bool isVisible () const { return mbVisible; } + + void show (bool bVisible); + + bool isSelected () const { return mbSelected; } + + void setSelection (bool state); + + bool isHighlighted () const { return mbHover; } + + void setHighlight (bool state); + + /** Updates own highlight status based on the aPoint position. + + Returns rectangle that needs to be invalidated. + */ + virtual tools::Rectangle updateHighlight(bool bVisible, const Point& rPoint); + + /// Text to be used for the tooltip. + + void setHelpText (const OUString &sText) { maHelpText = sText; } + + virtual OUString getHelpText() const { return maHelpText; }; + OUString const & getTitle() const { return maTitle; }; + + void setTitle (const OUString& rTitle); + + css::uno::Reference< css::accessibility::XAccessible > const & + GetAccessible( bool bIsTransientChildrenDisabled ); + + void setDrawArea (const tools::Rectangle &area); + + const tools::Rectangle& getDrawArea () const { return maDrawArea; } + + virtual void calculateItemsPosition (const tools::Long nThumbnailHeight, + const tools::Long nPadding, sal_uInt32 nMaxTextLength, + const ThumbnailItemAttributes *pAttrs); + + virtual void Paint (drawinglayer::processor2d::BaseProcessor2D *pProcessor, + const ThumbnailItemAttributes *pAttrs); + void addTextPrimitives (const OUString& rText, const ThumbnailItemAttributes *pAttrs, Point aPos, drawinglayer::primitive2d::Primitive2DContainer& rSeq); + + static rtl::Reference + createBorderLine (const basegfx::B2DPolygon &rPolygon); + + virtual void MouseButtonUp(const MouseEvent&) {} + +protected: + + Point maTextPos; + Point maPrev1Pos; + tools::Rectangle maDrawArea; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/toolbarids.hxx b/include/sfx2/toolbarids.hxx new file mode 100644 index 000000000..1aedb4eda --- /dev/null +++ b/include/sfx2/toolbarids.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_TOOLBARIDS_HXX +#define INCLUDED_SFX2_TOOLBARIDS_HXX + +#include + +//these numbers end up in the configuration to identify toolbars +//so don't blindly change their numbers +enum class ToolbarId : sal_uInt32 +{ + None = 0, + FullScreenToolbox = 558, + EnvToolbox = 560, + Svx_Extrusion_Bar = 10986, + Svx_Fontwork_Bar = 10987, + Basicide_Objectbar = 14850, + SvxTbx_Form_Navigation = 18001, + SvxTbx_Form_Filter = 18002, + SvxTbx_Text_Control_Attributes = 18003, + SvxTbx_Controls = 18004, + SvxTbx_FormDesign = 18006, + Math_Toolbox = 20050, + Webtools_Toolbox = 20402, + Webtext_Toolbox = 20403, + Webframe_Toolbox = 20408, + Webgraphic_Toolbox = 20410, + Webole_Toolbox = 20411, + Draw_Toolbox_Sd = 23011, + Slide_Toolbox = 23012, + Draw_Obj_Toolbox = 23013, + Slide_Obj_Toolbox = 23014, + Bezier_Toolbox_Sd = 23015, + Draw_Text_Toolbox_Sd = 23016, + Outline_Toolbox = 23017, + Draw_Table_Toolbox = 23018, + Gluepoints_Toolbox = 23019, + Draw_Options_Toolbox = 23020, + Draw_CommonTask_Toolbox = 23021, + FormLayer_Toolbox = 23022, + Draw_Viewer_Toolbox = 23023, + Graphic_Obj_Toolbox = 23027, + Draw_Graf_Toolbox = 23030, + Draw_Media_Toolbox = 23031, + Text_Toolbox_Sw = 23265, + Table_Toolbox = 23266, + Frame_Toolbox = 23267, + Grafik_Toolbox = 23268, + Draw_Toolbox_Sw = 23269, + Draw_Text_Toolbox_Sw = 23270, + Num_Toolbox = 23271, + Ole_Toolbox = 23272, + Tools_Toolbox = 23273, + PView_Toolbox = 23281, + Bezier_Toolbox_Sw = 23283, + Module_Toolbox = 23310, + Media_Toolbox = 23311, + Objectbar_App = 25000, + Objectbar_Format = 25001, + Text_Toolbox_Sc = 25005, + Objectbar_Preview = 25006, + Objectbar_Tools = 25035, + Draw_Objectbar = 25053, + Graphic_Objectbar = 25054, + Media_Objectbar = 25060 +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/sfx2/tplpitem.hxx b/include/sfx2/tplpitem.hxx new file mode 100644 index 000000000..647e2b8e7 --- /dev/null +++ b/include/sfx2/tplpitem.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_TPLPITEM_HXX +#define INCLUDED_SFX2_TPLPITEM_HXX + +#include +#include +#include +#include +#include + +class SFX2_DLLPUBLIC SfxTemplateItem final : public SfxFlagItem +{ + OUString aStyle; + OUString aStyleIdentifier; +public: + static SfxPoolItem* CreateDefault(); + SfxTemplateItem(); + SfxTemplateItem( sal_uInt16 nWhich, + const OUString &rStyle, + const OUString &rStyleIdentifier = "" ); + + const OUString& GetStyleName() const { return aStyle; } + const OUString& GetStyleIdentifier() const { return aStyleIdentifier; } + + virtual SfxTemplateItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + virtual sal_uInt8 GetFlagCount() const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + SfxStyleSearchBits GetValue() const { return static_cast(SfxFlagItem::GetValue()); } + void SetValue(SfxStyleSearchBits n) { SfxFlagItem::SetValue(static_cast(n)); } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/userinputinterception.hxx b/include/sfx2/userinputinterception.hxx new file mode 100644 index 000000000..f94857978 --- /dev/null +++ b/include/sfx2/userinputinterception.hxx @@ -0,0 +1,82 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SFX2_USERINPUTINTERCEPTION_HXX +#define INCLUDED_SFX2_USERINPUTINTERCEPTION_HXX + +#include + +#include + +namespace com::sun::star::awt { class XKeyHandler; } +namespace com::sun::star::awt { class XMouseClickHandler; } +namespace com::sun::star::uno { template class Reference; } +namespace osl { class Mutex; } + +class NotifyEvent; + +namespace cppu { class OWeakObject; } + + +namespace sfx2 +{ + + + //= UserInputInterception + + struct UserInputInterception_Data; + /** helper class for implementing the XUserInputInterception interface + for a controller implementation + */ + class SFX2_DLLPUBLIC UserInputInterception + { + public: + UserInputInterception( ::cppu::OWeakObject& _rControllerImpl, ::osl::Mutex& _rMutex ); + ~UserInputInterception(); + UserInputInterception(const UserInputInterception&) = delete; + UserInputInterception& operator=( const UserInputInterception& ) = delete; + + // delegator functions for your XUserInputInterception implementation + /// @throws css::uno::RuntimeException + void addKeyHandler( const css::uno::Reference< css::awt::XKeyHandler >& xHandler ); + /// @throws css::uno::RuntimeException + void removeKeyHandler( const css::uno::Reference< css::awt::XKeyHandler >& xHandler ); + /// @throws css::uno::RuntimeException + void addMouseClickHandler( const css::uno::Reference< css::awt::XMouseClickHandler >& xHandler ); + /// @throws css::uno::RuntimeException + void removeMouseClickHandler( const css::uno::Reference< css::awt::XMouseClickHandler >& xHandler ); + + // state + bool hasKeyHandlers() const; + bool hasMouseClickListeners() const; + + // forwarding a NotifyEvent to the KeyListeners respectively MouseClickListeners + bool handleNotifyEvent( const NotifyEvent& _rEvent ); + + private: + ::std::unique_ptr< UserInputInterception_Data > m_pData; + }; + + +} // namespace sfx2 + + +#endif // INCLUDED_SFX2_USERINPUTINTERCEPTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/viewfac.hxx b/include/sfx2/viewfac.hxx new file mode 100644 index 000000000..efd511ea2 --- /dev/null +++ b/include/sfx2/viewfac.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_VIEWFAC_HXX +#define INCLUDED_SFX2_VIEWFAC_HXX + +#include +#include +#include +#include + +class SfxViewFrame; +class SfxViewShell; + +typedef SfxViewShell* (*SfxViewCtor)(SfxViewFrame*, SfxViewShell*); + +// CLASS ----------------------------------------------------------------- +class SFX2_DLLPUBLIC SfxViewFactory +{ +public: + SfxViewFactory( SfxViewCtor fnC, + SfxInterfaceId nOrdinal, const char* asciiViewName ); + + SfxViewShell* CreateInstance(SfxViewFrame *pViewFrame, SfxViewShell *pOldSh); + SfxInterfaceId GetOrdinal() const { return nOrd; } + + /// returns a legacy view name. This is "view" with an appended ordinal/ID. + OUString GetLegacyViewName() const; + + /** returns an API-compatible view name. + + For details on which view names are specified, see the XModel2.getAvailableViewControllerNames + documentation. + */ + OUString GetAPIViewName() const; + +private: + SfxViewCtor fnCreate; + SfxInterfaceId nOrd; + const OUString m_sViewName; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/viewfrm.hxx b/include/sfx2/viewfrm.hxx new file mode 100644 index 000000000..24d1c35db --- /dev/null +++ b/include/sfx2/viewfrm.hxx @@ -0,0 +1,277 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_VIEWFRM_HXX +#define INCLUDED_SFX2_VIEWFRM_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace weld { + class Button; + class Window; +} +class SvBorder; +class SfxDispatcher; +class SfxBindings; +class SfxProgress; +class SfxViewShell; +class Point; +class Size; +class SfxChildWindow; +class SfxInfoBarWindow; +enum class InfobarType; +class CommandPopupHandler; + +class SFX2_DLLPUBLIC SfxViewFrame final : public SfxShell, public SfxListener +{ + std::unique_ptr m_pImpl; + + SfxObjectShellRef m_xObjSh; + std::unique_ptr m_pDispatcher; + SfxBindings* m_pBindings; + ImplSVHelpData* m_pHelpData; + ImplSVWinData* m_pWinData; + sal_uInt16 m_nAdjustPosPixelLock; + + std::unique_ptr m_pCommandPopupHandler; + + SAL_DLLPRIVATE void Construct_Impl( SfxObjectShell *pObjSh ); + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; + DECL_DLLPRIVATE_LINK(GetInvolvedHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(DonationHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(WhatsNewHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(SwitchReadOnlyHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(SignDocumentHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(HiddenTrackChangesHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(HyphenationMissingHandler, weld::Button&, void); + DECL_DLLPRIVATE_LINK(RefreshMasterPasswordHdl, weld::Button&, void); + SAL_DLLPRIVATE void KillDispatcher_Impl(); + + virtual ~SfxViewFrame() override; + +public: + SfxViewFrame( SfxFrame& rFrame, SfxObjectShell *pDoc ); + + SFX_DECL_INTERFACE(SFX_INTERFACE_SFXVIEWFRM) + +private: + /// SfxInterface initializer. + static void InitInterface_Impl(); + +public: + + static void SetViewFrame( SfxViewFrame* ); + + static SfxViewFrame* LoadHiddenDocument( SfxObjectShell const & i_rDoc, SfxInterfaceId i_nViewId ); + static SfxViewFrame* LoadDocument( SfxObjectShell const & i_rDoc, SfxInterfaceId i_nViewId ); + static SfxViewFrame* LoadDocumentIntoFrame( SfxObjectShell const & i_rDoc, const SfxFrameItem* i_pFrameItem, SfxInterfaceId i_nViewId ); + static SfxViewFrame* LoadDocumentIntoFrame( SfxObjectShell const & i_rDoc, const css::uno::Reference< css::frame::XFrame >& i_rFrameItem ); + static SfxViewFrame* DisplayNewDocument( SfxObjectShell const & i_rDoc, const SfxRequest& i_rCreateDocRequest ); + + static SfxViewFrame* Current(); + static SfxViewFrame* GetFirst( const SfxObjectShell* pDoc = nullptr, bool bOnlyVisible = true ); + static SfxViewFrame* GetNext( const SfxViewFrame& rPrev, const SfxObjectShell* pDoc = nullptr, bool bOnlyVisible = true ); + + static SfxViewFrame* Get( const css::uno::Reference< css::frame::XController>& i_rController, const SfxObjectShell* i_pDoc ); + + void DoActivate(bool bMDI); + void DoDeactivate(bool bMDI, SfxViewFrame const *pOld); + + using SfxShell::GetDispatcher; + SfxDispatcher* GetDispatcher() { return m_pDispatcher.get(); } + SfxBindings& GetBindings() { return *m_pBindings; } + const SfxBindings& GetBindings() const { return *m_pBindings; } + vcl::Window& GetWindow() const; + weld::Window* GetFrameWeld() const; + + SfxProgress* GetProgress() const; + + void LockAdjustPosSizePixel() + { m_nAdjustPosPixelLock++; } + void UnlockAdjustPosSizePixel() + { m_nAdjustPosPixelLock--; } + void DoAdjustPosSizePixel( SfxViewShell * pSh, + const Point &rPos, const Size &rSize, + bool inplaceEditModeChange ); + void Show(); + bool IsVisible() const; + void ToTop(); + void Enable( bool bEnable ); + void Close(); + virtual void Activate( bool bUI ) override; + virtual void Deactivate( bool bUI ) override; + + void UpdateTitle(); + + // interne Handler + SAL_DLLPRIVATE void SetBorderPixelImpl( const SfxViewShell *pSh, const SvBorder &rBorder ); + SAL_DLLPRIVATE const SvBorder& GetBorderPixelImpl() const; + SAL_DLLPRIVATE void InvalidateBorderImpl( const SfxViewShell *pSh ); + + virtual SfxObjectShell* GetObjectShell() override; + SfxInterfaceId GetCurViewId() const; + SfxFrame& GetFrame() const; + SfxViewFrame* GetTopViewFrame() const; + + bool DoClose(); + static void GetTargetList( TargetList& rList ) + { SfxFrame::GetDefaultTargetList( rList ); } + + void SetModalMode( bool ); + bool IsInModalMode() const; + void Resize(bool bForce=false); + + void SetChildWindow(sal_uInt16 nId, bool bVisible, bool bSetFocus=true); + void ToggleChildWindow(sal_uInt16); + bool HasChildWindow(sal_uInt16); + bool KnowsChildWindow(sal_uInt16); + void ShowChildWindow(sal_uInt16,bool bVisible=true); + SfxChildWindow* GetChildWindow(sal_uInt16); + void ChildWindowExecute(SfxRequest&); + void ChildWindowState(SfxItemSet&); + + /** Append a new InfoBar (see https://wiki.documentfoundation.org/Design/Whiteboards/Infobar). + + The buttons will be added from Right to Left at the right of the info bar. The parent, size + and position of each button will be changed: only the width will remain unchanged. + */ + VclPtr AppendInfoBar(const OUString& sId, + const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, + InfobarType aInfobarType, + bool bShowCloseButton=true); + void RemoveInfoBar(std::u16string_view sId); + void UpdateInfoBar(std::u16string_view sId, const OUString& sPrimaryMessage, + const OUString& sSecondaryMessage, + InfobarType eType); + bool HasInfoBarWithID(std::u16string_view sId); + void AppendReadOnlyInfobar(); + + SAL_DLLPRIVATE void GetDocNumber_Impl(); + SAL_DLLPRIVATE void SetViewShell_Impl( SfxViewShell *pVSh ); + SAL_DLLPRIVATE void ReleaseObjectShell_Impl(); + + SAL_DLLPRIVATE void GetState_Impl( SfxItemSet &rSet ); + void ExecReload_Impl(SfxRequest& rReq); + SAL_DLLPRIVATE void StateReload_Impl( SfxItemSet &rSet ); + SAL_DLLPRIVATE void ExecView_Impl( SfxRequest &rReq ); + SAL_DLLPRIVATE void StateView_Impl( SfxItemSet &rSet ); + SAL_DLLPRIVATE void ExecHistory_Impl( SfxRequest &rReq ); + SAL_DLLPRIVATE void StateHistory_Impl( SfxItemSet &rSet ); + SAL_DLLPRIVATE void ForceOuterResize_Impl(); + SAL_DLLPRIVATE void UpdateDocument_Impl(); + + SAL_DLLPRIVATE void LockObjectShell_Impl(); + + SAL_DLLPRIVATE void MakeActive_Impl( bool bActivate ); + SAL_DLLPRIVATE const Size& GetMargin_Impl() const; + SAL_DLLPRIVATE OUString GetActualPresentationURL_Impl() const; + SAL_DLLPRIVATE void MiscExec_Impl(SfxRequest &); + SAL_DLLPRIVATE void MiscState_Impl(SfxItemSet &); + SAL_DLLPRIVATE SfxWorkWindow* GetWorkWindow_Impl(); + SAL_DLLPRIVATE void AddDispatchMacroToBasic_Impl(const OUString& sMacro); + + SAL_DLLPRIVATE void Exec_Impl(SfxRequest &); + SAL_DLLPRIVATE void INetExecute_Impl(SfxRequest &); + SAL_DLLPRIVATE void INetState_Impl(SfxItemSet &); + + SAL_DLLPRIVATE void SetCurViewId_Impl( const SfxInterfaceId i_nID ); + +private: + SAL_DLLPRIVATE bool SwitchToViewShell_Impl( sal_uInt16 nNo, bool bIsIndex = false ); + SAL_DLLPRIVATE void PopShellAndSubShells_Impl( SfxViewShell& i_rViewShell ); + SAL_DLLPRIVATE void SaveCurrentViewData_Impl( const SfxInterfaceId i_nNewViewId ); + + /** loads the given existing document into the given frame + + This is done using the XComponentLoader interface of the frame, so the SFX document loader is invoked. + + @param i_rDoc + the document to load + @param i_rFrame + the frame to load the document into + @param i_rLoadArgs + the arguments to pass to the component loader. If this sequence is empty, then the current arguments of the + model will be obtained, and passed to the loader. This ensures that any arguments in the model will be preserved, + instead of being reset. + @param i_nViewId + the ID of the view to create + @throws Exception + if something goes wrong. The caller is responsible for handling this. + */ + SAL_DLLPRIVATE static SfxViewShell* LoadViewIntoFrame_Impl( + const SfxObjectShell& i_rDoc, + const css::uno::Reference< css::frame::XFrame >& i_rFrame, + const css::uno::Sequence< css::beans::PropertyValue >& i_rLoadArgs, + const SfxInterfaceId i_nViewId, + const bool i_bHidden + ); + + /** loads the given existing document into the given frame + + This is done using the XComponentLoader interface of the frame, so the SFX document loader is invoked. + + If no frame is given, a blank top level frame is created. + + If anything fails during the process, as much as possible is cleaned up. + + @param i_rDoc + the document to load + @param i_rFrame + the frame to load the document into. Might be , in which case a new frame is created. + @param i_nViewId + the ID of the view to create + */ + SAL_DLLPRIVATE static SfxViewFrame* LoadViewIntoFrame_Impl_NoThrow( + const SfxObjectShell& i_rDoc, + const css::uno::Reference< css::frame::XFrame >& i_rFrame, + const SfxInterfaceId i_nViewId, + const bool i_bHidden + ); +}; + + +class SFX2_DLLPUBLIC SfxViewFrameItem final : public SfxPoolItem +{ + SfxViewFrame* pFrame; + +public: + SfxViewFrameItem( SfxViewFrame *pViewFrame ): + SfxPoolItem( 0 ), + pFrame( pViewFrame) + {} + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxViewFrameItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + SfxViewFrame* GetFrame() const + { return pFrame; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/viewsh.hxx b/include/sfx2/viewsh.hxx new file mode 100644 index 000000000..31fac39ee --- /dev/null +++ b/include/sfx2/viewsh.hxx @@ -0,0 +1,435 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_VIEWSH_HXX +#define INCLUDED_SFX2_VIEWSH_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SfxTabPage; +class SfxBaseController; +class Size; +class Point; +class Fraction; +namespace weld { + class Container; + class DialogController; + class Window; +} +class KeyEvent; +class SvBorder; +class SdrView; +class SfxModule; +class SfxViewFrame; +class Printer; +class SfxPrinter; +class NotifyEvent; +class SfxInPlaceClient; +class SfxLokCallbackInterface; +namespace vcl { class PrinterController; } + +namespace com::sun::star::awt{ class XPopupMenu; } +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::datatransfer::clipboard { class XClipboardListener; } +namespace com::sun::star::datatransfer::clipboard { class XClipboardNotifier; } +namespace com::sun::star::embed { class XEmbeddedObject; } +namespace com::sun::star::frame { class XController; } +namespace com::sun::star::frame { class XModel; } +namespace com::sun::star::ui { class XContextMenuInterceptor; } +namespace com::sun::star::ui { struct ContextMenuExecuteEvent; } +namespace com::sun::star::view { class XRenderable; } + + +enum class SfxPrinterChangeFlags +{ + NONE = 0, + PRINTER = 1, // without JOB SETUP => Temporary + JOBSETUP = 2, + OPTIONS = 4, + CHG_ORIENTATION = 8, + CHG_SIZE = 16 +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} +#define SFX_PRINTER_ALL (SfxPrinterChangeFlags::PRINTER | SfxPrinterChangeFlags::JOBSETUP | SfxPrinterChangeFlags::OPTIONS | SfxPrinterChangeFlags::CHG_ORIENTATION | SfxPrinterChangeFlags::CHG_SIZE) + +#define SFX_PRINTERROR_BUSY 1 + +// "Verified" using www.apple.com and Netscape 3.01 +#define DEFAULT_MARGIN_WIDTH 8 +#define DEFAULT_MARGIN_HEIGHT 12 + + +// @[SfxViewShell-Flags] + +enum class SfxViewShellFlags +{ + NONE = 0x0000, + HAS_PRINTOPTIONS = 0x0010, /* Options-Button and Options-Dialog in PrintDialog */ + NO_NEWWINDOW = 0x0100, /* Allow N View */ +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +/* [Description] + + The SfxViewShell flags control the behavior of SfxViewShell for the + duration of its lifetime. They are defined in the constructor of + . +*/ + +enum class LOKDeviceFormFactor +{ + UNKNOWN = 0, + DESKTOP = 1, + TABLET = 2, + MOBILE = 3 +}; + +class SfxViewFactory; +#define SFX_DECL_VIEWFACTORY(Class) \ +private: \ + static SfxViewFactory *s_pFactory; \ +public: \ + static SfxViewShell *CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldView); \ + static void RegisterFactory( SfxInterfaceId nPrio ); \ + static SfxViewFactory*Factory() { return s_pFactory; } \ + static void InitFactory() + +#define SFX_IMPL_NAMED_VIEWFACTORY(Class, AsciiViewName) \ + SfxViewFactory* Class::s_pFactory; \ + SfxViewShell* Class::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldView) \ + { return new Class(pFrame, pOldView); } \ + void Class::RegisterFactory( SfxInterfaceId nPrio ) \ + { \ + s_pFactory = new SfxViewFactory(&CreateInstance,nPrio,AsciiViewName);\ + InitFactory(); \ + } \ + void Class::InitFactory() + +#define SFX_VIEW_REGISTRATION(DocClass) \ + DocClass::Factory().RegisterViewFactory( *Factory() ) + +template bool checkSfxViewShell(const SfxViewShell* pShell) +{ + return dynamic_cast(pShell) != nullptr; +} + +/** + * One SfxViewShell more or less represents one edit window for a document, there can be multiple + * ones for a single opened document (SfxObjectShell). + */ +class SFX2_DLLPUBLIC SfxViewShell: public SfxShell, public SfxListener, public OutlinerViewShell, public vcl::ILibreOfficeKitNotifier +{ +friend class SfxViewFrame; +friend class SfxBaseController; +friend class SfxPrinterController; + + std::unique_ptr pImpl; + SfxViewFrame* pFrame; + VclPtr pWindow; + bool bNoNewWindow; + bool mbPrinterSettingsModified; + LanguageTag maLOKLanguageTag; + LanguageTag maLOKLocale; + LOKDeviceFormFactor maLOKDeviceFormFactor; + std::unordered_set mvLOKBlockedCommandList; + + /// Used to set the DocId at construction time. See SetCurrentDocId. + static ViewShellDocId mnCurrentDocId; + +protected: + virtual void Activate(bool IsMDIActivate) override; + virtual void Deactivate(bool IsMDIActivate) override; + + virtual void InnerResizePixel( const Point &rOfs, const Size &rSize, bool inplaceEditModeChange ); + virtual void OuterResizePixel( const Point &rOfs, const Size &rSize ); + virtual void SetZoomFactor( const Fraction &rZoomX, const Fraction &rZoomY ); + + virtual void Move(); + + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; + +public: + // Iteration + static SfxViewShell* GetFirst( bool bOnlyVisible = true, const std::function& isViewShell = nullptr ); + static SfxViewShell* GetNext( const SfxViewShell& rPrev, + bool bOnlyVisible = true, + const std::function& isViewShell = nullptr ); + static SfxViewShell* Current(); + + static SfxViewShell* Get( const css::uno::Reference< css::frame::XController>& i_rController ); + + // Initialize Constructors/Destructors + SFX_DECL_INTERFACE(SFX_INTERFACE_SFXVIEWSH) + +private: + /// SfxInterface initializer. + static void InitInterface_Impl(); + +public: + + SfxViewShell( SfxViewFrame *pFrame, SfxViewShellFlags nFlags ); + virtual ~SfxViewShell() override; + + SfxInPlaceClient* GetIPClient() const; + SfxInPlaceClient* GetUIActiveClient() const; + SfxInPlaceClient* FindIPClient( const css::uno::Reference < css::embed::XEmbeddedObject >& xObj, vcl::Window *pObjParentWin ) const; + + virtual ErrCode DoVerb(sal_Int32 nVerb); + + void OutplaceActivated( bool bActive ); + virtual void UIActivating( SfxInPlaceClient* pClient ); + virtual void UIDeactivated( SfxInPlaceClient* pClient ); + + void JumpToMark( const OUString& rMark ); + void VisAreaChanged(); + + // Misc + + /** + * Initialize is called after the frame has been loaded and the controller + * has been set. By the time this is called the document has been fully + * imported. + * @param bOnlyASample used by some dialogs to avoid constructing monster strings e.g. in calc + */ + virtual bool PrepareClose( bool bUI = true ); + virtual OUString GetSelectionText( bool bCompleteWords = false, bool bOnlyASample = false ); + virtual bool HasSelection( bool bText = true ) const; + virtual SdrView* GetDrawView() const; + + void AddSubShell( SfxShell& rShell ); + void RemoveSubShell( SfxShell *pShell=nullptr ); + SfxShell* GetSubShell( sal_uInt16 ); + + virtual SfxShell* GetFormShell() { return nullptr; }; + virtual const SfxShell* GetFormShell() const { return nullptr; }; + + // ILibreOfficeKitNotifier + virtual void notifyWindow(vcl::LOKWindowId nLOKWindowId, const OUString& rAction, const std::vector& rPayload = std::vector()) const override; + + // Focus, KeyInput, Cursor + virtual void ShowCursor( bool bOn = true ); + virtual bool KeyInput( const KeyEvent &rKeyEvent ); + bool Escape(); + + // Viewing Interface + vcl::Window* GetWindow() const { return pWindow; } + weld::Window* GetFrameWeld() const; + void SetWindow( vcl::Window *pViewPort ); + const SvBorder& GetBorderPixel() const; + void SetBorderPixel( const SvBorder &rBorder ); + void InvalidateBorder(); + inline SfxViewFrame* GetViewFrame() const; + + // Printing Interface + virtual SfxPrinter* GetPrinter( bool bCreate = false ); + virtual sal_uInt16 SetPrinter( SfxPrinter *pNewPrinter, SfxPrinterChangeFlags nDiffFlags = SFX_PRINTER_ALL ); + virtual bool HasPrintOptionsPage() const; + virtual std::unique_ptr CreatePrintOptionsPage(weld::Container* pPage, weld::DialogController* pController, const SfxItemSet &rOptions); + Printer* GetActivePrinter() const; + + // Working set + virtual void WriteUserData( OUString&, bool bBrowse = false ); + virtual void ReadUserData( const OUString&, bool bBrowse = false ); + virtual void WriteUserDataSequence ( css::uno::Sequence < css::beans::PropertyValue >& ); + virtual void ReadUserDataSequence ( const css::uno::Sequence < css::beans::PropertyValue >& ); + virtual void QueryObjAreaPixel( tools::Rectangle& rRect ) const; + + virtual SfxObjectShell* GetObjectShell() override; + + /** retrieves the document which shall be considered the "current document" when the frame is active + + The default implementation simply returns the XModel of the associated SfxObjectShell. You will rarely + need to overwrite this behavior. + */ + virtual css::uno::Reference< css::frame::XModel > + GetCurrentDocument() const; + + /** forwards the current document, as returned by ->GetCurrentDocument, to SfxObjectShell::SetWorkingDocument + */ + void SetCurrentDocument() const; + + /** get an XRenderable instance that can render this document + */ + virtual css::uno::Reference< css::view::XRenderable > GetRenderable(); + + + virtual void MarginChanged(); + const Size& GetMargin() const; + void SetMargin( const Size& ); + void DisconnectAllClients(); + bool NewWindowAllowed() const { return !bNoNewWindow; } + void SetNewWindowAllowed( bool bSet ) { bNoNewWindow = !bSet; } + + void SetController( SfxBaseController* pController ); + css::uno::Reference GetController() const; + + bool TryContextMenuInterception(const css::uno::Reference& rIn, + const OUString& rMenuIdentifier, + css::uno::Reference& rOut, + css::ui::ContextMenuExecuteEvent aEvent); + bool TryContextMenuInterception(const css::uno::Reference&, + const OUString& rMenuIdentifier, + css::ui::ContextMenuExecuteEvent aEvent); + + void ExecPrint( const css::uno::Sequence < css::beans::PropertyValue >&, bool, bool ); + // Like ExecPrint(), but only sets up for printing. Use Printer::ExecutePrintJob() and Printer::FinishPrintJob() afterwards. + void StartPrint( const css::uno::Sequence < css::beans::PropertyValue >&, bool, bool ); + const std::shared_ptr< vcl::PrinterController >& GetPrinterController() const; + + void AddRemoveClipboardListener( const css::uno::Reference < css::datatransfer::clipboard::XClipboardListener>&, bool ); + css::uno::Reference< css::datatransfer::clipboard::XClipboardNotifier > GetClipboardNotifier() const; + + SAL_DLLPRIVATE SfxInPlaceClient* GetUIActiveIPClient_Impl() const; + SAL_DLLPRIVATE void AddContextMenuInterceptor_Impl( const css::uno::Reference < css::ui::XContextMenuInterceptor >& xInterceptor ); + SAL_DLLPRIVATE void RemoveContextMenuInterceptor_Impl( const css::uno::Reference < css::ui::XContextMenuInterceptor >& xInterceptor ); + SAL_DLLPRIVATE bool GlobalKeyInput_Impl( const KeyEvent &rKeyEvent ); + + SAL_DLLPRIVATE void NewIPClient_Impl( SfxInPlaceClient *pIPClient ); + SAL_DLLPRIVATE void IPClientGone_Impl( SfxInPlaceClient const *pIPClient ); + SAL_DLLPRIVATE void ResetAllClients_Impl( SfxInPlaceClient const *pIP ); + + SAL_DLLPRIVATE void SetPrinter_Impl( VclPtr& pNewPrinter ); + + SAL_DLLPRIVATE bool HandleNotifyEvent_Impl( NotifyEvent const & rEvent ); + SAL_DLLPRIVATE bool HasKeyListeners_Impl() const; + SAL_DLLPRIVATE bool HasMouseClickListeners_Impl() const; + + SAL_DLLPRIVATE SfxBaseController* GetBaseController_Impl() const; + + // Shell Interface + SAL_DLLPRIVATE void ExecPrint_Impl(SfxRequest &); + SAL_DLLPRIVATE void ExecMisc_Impl(SfxRequest &); + SAL_DLLPRIVATE void GetState_Impl(SfxItemSet&); + SAL_DLLPRIVATE void CheckIPClient_Impl(SfxInPlaceClient const *, const tools::Rectangle&); + SAL_DLLPRIVATE void PushSubShells_Impl( bool bPush=true ); + SAL_DLLPRIVATE void PopSubShells_Impl() { PushSubShells_Impl( false ); } + SAL_DLLPRIVATE bool ExecKey_Impl(const KeyEvent& aKey); + + /// Set up a more efficient internal callback instead of LibreOfficeKitCallback. + void setLibreOfficeKitViewCallback(SfxLokCallbackInterface* pCallback); + /// Invokes the registered callback, if there are any. + virtual void libreOfficeKitViewCallback(int nType, const char* pPayload) const override; + virtual void libreOfficeKitViewCallbackWithViewId(int nType, const char* pPayload, int nViewId) const override; + virtual void libreOfficeKitViewInvalidateTilesCallback(const tools::Rectangle* pRect, int nPart) const override; + // Performs any pending calls to libreOfficeKitViewInvalidateTilesCallback() as necessary. + virtual void flushPendingLOKInvalidateTiles(); + virtual void libreOfficeKitViewUpdatedCallback(int nType) const override; + virtual void libreOfficeKitViewUpdatedCallbackPerViewId(int nType, int nViewId, int nSourceViewId) const override; + // Returns current payload for nType, after libreOfficeKitViewUpdatedCallback() or + // libreOfficeKitViewUpdatedCallbackPerViewId() were called. If no payload should + // be generated, the ignore flag should be set. + virtual OString getLOKPayload(int nType, int nViewId, bool* ignore) const; + + /// Set if we are doing tiled searching. + void setTiledSearching(bool bTiledSearching); + /// See lok::Document::getPart(). + virtual int getPart() const; + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const; + /// See OutlinerViewShell::GetViewShellId(). + ViewShellId GetViewShellId() const override; + + /// Set the current DocId, which is used by Mobile LOKit to + /// load multiple documents and yet identify the views of each. + /// There are events that are fired while creating a new view, + /// and if we don't have a DocId, we can't know which other views + /// within the same document (if any) should get those events. + /// By setting this static value, we are able to set the DocId + /// of each SfxViewShell at construction time. + static void SetCurrentDocId(ViewShellDocId nId); + /// Get the DocId used by Mobile LOKit to load multiple documents. + ViewShellDocId GetDocId() const override; + + /// See OutlinerViewShell::NotifyOtherViews(). + void NotifyOtherViews(int nType, const OString& rKey, const OString& rPayload) override; + /// See OutlinerViewShell::NotifyOtherView(). + void NotifyOtherView(OutlinerViewShell* pOtherShell, int nType, const OString& rKey, const OString& rPayload) override; + /// Ask this view to send its cursor position to pViewShell. + virtual void NotifyCursor(SfxViewShell* /*pViewShell*/) const; + /// Where a new view can perform some update/initialization soon after the callback has been registered. + virtual void afterCallbackRegistered(); + /// See OutlinerViewShell::GetEditWindowForActiveOLEObj(). + virtual vcl::Window* GetEditWindowForActiveOLEObj() const override; + + /// Set the LibreOfficeKit language of this view. + void SetLOKLanguageTag(const OUString& rBcp47LanguageTag); + /// Get the LibreOfficeKit language of this view. + const LanguageTag& GetLOKLanguageTag() const { return maLOKLanguageTag; } + + /// Set the LibreOfficeKit locale of this view. + void SetLOKLocale(const OUString& rBcp47LanguageTag); + /// Get the LibreOfficeKit locale of this view. + const LanguageTag& GetLOKLocale() const { return maLOKLocale; } + /// Get the form factor of the device where the lok client is running. + LOKDeviceFormFactor GetLOKDeviceFormFactor() const { return maLOKDeviceFormFactor; } + /// Check if the lok client is running on a desktop machine. + bool isLOKDesktop() const { return maLOKDeviceFormFactor == LOKDeviceFormFactor::DESKTOP; } + /// Check if the lok client is running on a tablet. + bool isLOKTablet() const { return maLOKDeviceFormFactor == LOKDeviceFormFactor::TABLET; } + /// Check if the lok client is running on a mobile device. + bool isLOKMobilePhone() const { return maLOKDeviceFormFactor == LOKDeviceFormFactor::MOBILE; } + + virtual tools::Rectangle getLOKVisibleArea() const { return tools::Rectangle(); } + + // Blocked Command view settings + void setBlockedCommandList(const char* blockedCommandList); + bool isBlockedCommand(OUString command); +}; + + +inline SfxViewFrame* SfxViewShell::GetViewFrame() const + +/* [Description] + + This method returns a pointer to the Instance in which + this SfxViewShell is displayed. This is the instance that was passed + on in the constructor. It is guaranteed that the returned pointer + points on the valid SfxViewFrame instance. + + [Cross-reference] + + +*/ + +{ + return pFrame; +} + +#endif // INCLUDED_SFX2_VIEWSH_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/watermarkitem.hxx b/include/sfx2/watermarkitem.hxx new file mode 100644 index 000000000..c298894bb --- /dev/null +++ b/include/sfx2/watermarkitem.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_SFX2_WATERMARKITEM_HXX +#define INCLUDED_SFX2_WATERMARKITEM_HXX + +#include +#include +#include + +class SFX2_DLLPUBLIC SfxWatermarkItem final : public SfxPoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + SfxWatermarkItem(); + virtual SfxWatermarkItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + OUString const & GetText() const { return m_aText; } + void SetText(const OUString& aText) { m_aText = aText; } + OUString const & GetFont() const { return m_aFont; } + void SetFont(const OUString& aFont) { m_aFont = aFont; } + sal_Int16 GetAngle() const { return m_nAngle; } + void SetAngle(const sal_Int16 nAngle) { m_nAngle = nAngle; } + sal_Int16 GetTransparency() const { return m_nTransparency; } + void SetTransparency(const sal_Int16 nTransparency) { m_nTransparency = nTransparency; } + Color GetColor() const { return m_nColor; } + void SetColor(Color nColor) { m_nColor = nColor; } + +private: + OUString m_aText; + OUString m_aFont; + sal_Int16 m_nAngle; + sal_Int16 m_nTransparency; + Color m_nColor; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/sfx2/weldutils.hxx b/include/sfx2/weldutils.hxx new file mode 100644 index 000000000..8f230cee5 --- /dev/null +++ b/include/sfx2/weldutils.hxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SFX2_WELDUTILS_HXX +#define INCLUDED_SFX2_WELDUTILS_HXX + +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace weld +{ +class Builder; +class Toolbar; +} + +class SFX2_DLLPUBLIC ToolbarUnoDispatcher +{ +private: + css::uno::Reference m_xFrame; + SvtMiscOptions m_aToolbarOptions; + weld::Toolbar* m_pToolbar; + weld::Builder* m_pBuilder; + bool m_bSideBar; + + DECL_DLLPRIVATE_LINK(SelectHdl, const OString&, void); + DECL_DLLPRIVATE_LINK(ToggleMenuHdl, const OString&, void); + DECL_DLLPRIVATE_LINK(ChangedIconSizeHandler, LinkParamNone*, void); + + void CreateController(const OUString& rCommand); + static vcl::ImageType GetIconSize(); + + typedef std::map> + ControllerContainer; + ControllerContainer maControllers; + +public: + // fill in the label and icons for actions and dispatch the action on item click + ToolbarUnoDispatcher(weld::Toolbar& rToolbar, weld::Builder& rBuilder, + const css::uno::Reference& rFrame, + bool bSideBar = true); + + css::uno::Reference + GetControllerForCommand(const OUString& rCommand) const; + + const css::uno::Reference& GetFrame() const { return m_xFrame; } + + void dispose(); + ~ToolbarUnoDispatcher(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/xmldump.hxx b/include/sfx2/xmldump.hxx new file mode 100644 index 000000000..245a07b22 --- /dev/null +++ b/include/sfx2/xmldump.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +typedef struct _xmlTextWriter* xmlTextWriterPtr; + +namespace sfx2 +{ +/// Implemented by objects that can be dumped to xml for debugging purposes. +class SAL_NO_VTABLE SAL_DLLPUBLIC_RTTI XmlDump +{ +public: + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const = 0; + +protected: + ~XmlDump() noexcept = default; +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sfx2/zoomitem.hxx b/include/sfx2/zoomitem.hxx new file mode 100644 index 000000000..4e7703dfd --- /dev/null +++ b/include/sfx2/zoomitem.hxx @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SFX2_ZOOMITEM_HXX +#define INCLUDED_SFX2_ZOOMITEM_HXX + +#include +#include +#include +#include + + +enum class SvxZoomType +{ + PERCENT, // GetValue() is no special percentage value + OPTIMAL, // GetValue() corresponds to the optimal size + WHOLEPAGE, // GetValue() corresponds to the whole page + PAGEWIDTH, // GetValue() corresponds to the page width + PAGEWIDTH_NOBORDER // GetValue() pagewidth without border +}; + +enum class SvxZoomEnableFlags +{ + NONE = 0x0000, + N50 = 0x0001, + N75 = 0x0002, + N100 = 0x0004, + N150 = 0x0008, + N200 = 0x0010, + OPTIMAL = 0x1000, + WHOLEPAGE = 0x2000, + PAGEWIDTH = 0x4000, + ALL = 0x701F +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +class SFX2_DLLPUBLIC SvxZoomItem final : public SfxUInt16Item +{ + SvxZoomEnableFlags nValueSet; // allowed values (see #defines below) + SvxZoomType eType; + +public: + static SfxPoolItem* CreateDefault(); + + SvxZoomItem( SvxZoomType eZoomType = SvxZoomType::PERCENT, + sal_uInt16 nVal = 0, sal_uInt16 nWhich = SID_ATTR_ZOOM ); + + void SetValueSet( SvxZoomEnableFlags nValues ) { nValueSet = nValues; } + SvxZoomEnableFlags GetValueSet() const { return nValueSet; } + + SvxZoomType GetType() const { return eType; } + void SetType( SvxZoomType eNewType ) { eType = eNewType; } + + virtual SvxZoomItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/exchange.hxx b/include/sot/exchange.hxx new file mode 100644 index 000000000..c7fed6d3b --- /dev/null +++ b/include/sot/exchange.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_EXCHANGE_HXX +#define INCLUDED_SOT_EXCHANGE_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::datatransfer { + class XTransferable; +} + +namespace com::sun::star::uno { template class Reference; } + +struct DataFlavorEx : public css::datatransfer::DataFlavor +{ + SotClipboardFormatId mnSotId; +}; + +typedef ::std::vector DataFlavorExVector; + + +SOT_DLLPUBLIC bool IsFormatSupported( const DataFlavorExVector& rDataFlavorExVector, + SotClipboardFormatId nId ); + +// actions +#define EXCHG_INOUT_ACTION_NONE (sal_uInt8(css::datatransfer::dnd::DNDConstants::ACTION_NONE)) +#define EXCHG_IN_ACTION_DEFAULT EXCHG_INOUT_ACTION_NONE +#define EXCHG_IN_ACTION_MOVE (sal_uInt8(css::datatransfer::dnd::DNDConstants::ACTION_MOVE)) +#define EXCHG_IN_ACTION_COPY (sal_uInt8(css::datatransfer::dnd::DNDConstants::ACTION_COPY)) +#define EXCHG_IN_ACTION_LINK (sal_uInt8(css::datatransfer::dnd::DNDConstants::ACTION_LINK)) +#define EXCHG_OUT_ACTION_INSERT_FILE (sal_uInt8(20)) +#define EXCHG_OUT_ACTION_INSERT_IMAGEMAP (sal_uInt8(22)) +#define EXCHG_OUT_ACTION_INSERT_OLE (sal_uInt8(23)) +#define EXCHG_OUT_ACTION_INSERT_INTERACTIVE (sal_uInt8(24)) +#define EXCHG_OUT_ACTION_REPLACE_IMAGEMAP (sal_uInt8(29)) +#define EXCHG_OUT_ACTION_GET_ATTRIBUTES (sal_uInt8(30)) +#define EXCHG_OUT_ACTION_INSERT_PRIVATE (sal_uInt8(35)) +#define EXCHG_OUT_ACTION_INSERT_HTML (sal_uInt8(36)) +#define EXCHG_OUT_ACTION_MOVE_PRIVATE (sal_uInt8(37)) +#define EXCHG_OUT_ACTION_INSERT_STRING (sal_uInt8(38)) +#define EXCHG_OUT_ACTION_INSERT_DRAWOBJ (sal_uInt8(39)) +#define EXCHG_OUT_ACTION_INSERT_SVXB (sal_uInt8(40)) +#define EXCHG_OUT_ACTION_INSERT_GDIMETAFILE (sal_uInt8(41)) +#define EXCHG_OUT_ACTION_INSERT_BITMAP (sal_uInt8(42)) +#define EXCHG_OUT_ACTION_INSERT_DDE (sal_uInt8(43)) +#define EXCHG_OUT_ACTION_INSERT_HYPERLINK (sal_uInt8(44)) +#define EXCHG_OUT_ACTION_REPLACE_DRAWOBJ (sal_uInt8(45)) +#define EXCHG_OUT_ACTION_REPLACE_SVXB (sal_uInt8(46)) +#define EXCHG_OUT_ACTION_REPLACE_GDIMETAFILE (sal_uInt8(47)) +#define EXCHG_OUT_ACTION_REPLACE_BITMAP (sal_uInt8(48)) +#define EXCHG_OUT_ACTION_REPLACE_GRAPH (sal_uInt8(49)) +#define EXCHG_OUT_ACTION_INSERT_GRAPH (sal_uInt8(50)) + +enum class SotExchangeActionFlags { + NONE = 0x0000, + InsertImageMap = 0x0400, + ReplaceImageMap = 0x0800, + InsertTargetUrl = 0x2000, +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +// destinations +enum class SotExchangeDest +{ + NONE = 0, + DOC_OLEOBJ = 1, + CHARTDOC_OLEOBJ = 2, + DOC_TEXTFRAME = 3, + DOC_GRAPHOBJ = 4, + DOC_LNKD_GRAPHOBJ = 5, + DOC_GRAPH_W_IMAP = 6, + DOC_LNKD_GRAPH_W_IMAP = 7, + DOC_IMAPREGION = 8, + DOC_DRAWOBJ = 9, + DOC_URLBUTTON = 10, + DOC_URLFIELD = 11, + DOC_GROUPOBJ = 12, + SWDOC_FREE_AREA = 13, + SCDOC_FREE_AREA = 14, + SDDOC_FREE_AREA = 15, + DOC_TEXTFRAME_WEB = 16, + SWDOC_FREE_AREA_WEB = 17, +}; + +class SvGlobalName; + +class SOT_DLLPUBLIC SotExchange +{ +public: + static SotClipboardFormatId RegisterFormat( const css::datatransfer::DataFlavor& rFlavor ); + static SotClipboardFormatId RegisterFormatName( const OUString& rName ); + static SotClipboardFormatId RegisterFormatMimeType( const OUString& rMimeType ); + + static SotClipboardFormatId GetFormat( const css::datatransfer::DataFlavor& rFlavor ); + static OUString GetFormatName( SotClipboardFormatId nFormat ); + static bool GetFormatDataFlavor( SotClipboardFormatId nFormat, css::datatransfer::DataFlavor& rFlavor ); + static OUString GetFormatMimeType( SotClipboardFormatId nFormat ); + static bool IsInternal( const SvGlobalName& ); + static SotClipboardFormatId GetFormatIdFromMimeType( const OUString& rMimeType ); + + // same for XTransferable interface + static sal_uInt8 GetExchangeAction( + // XTransferable + const DataFlavorExVector& rDataFlavorExVector, + // destination of an action + SotExchangeDest nDestination, + // action for a source + sal_uInt16 nSourceOptions, + // user action (EXCHG_IN_*, EXCHG_INOUT_*) + sal_uInt8 nUserAction, + // In:- Out: format to use + SotClipboardFormatId& rFormat, + // In:- Out: default action (EXCHG_IN_*, EXCHG_INOUT_*) + sal_uInt8& rDefaultAction, + // In:- optional - check only for this specific format + SotClipboardFormatId nOnlyTestFormat = SotClipboardFormatId::NONE, + // In:- optional - check the contents of Xtransferable + const css::uno::Reference< css::datatransfer::XTransferable >* pxTransferable = nullptr, + // Out: optional: - default action flags + SotExchangeActionFlags* pActionFlags = nullptr); + + static sal_uInt16 IsChart( const SvGlobalName& rName ); + static sal_uInt16 IsMath( const SvGlobalName& rName ); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/filelist.hxx b/include/sot/filelist.hxx new file mode 100644 index 000000000..e95ea38cc --- /dev/null +++ b/include/sot/filelist.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_FILELIST_HXX +#define INCLUDED_SOT_FILELIST_HXX + +#include +#include + +#include + +class SvStream; + +class SOT_DLLPUBLIC FileList +{ + std::vector aStrList; + +private: + void clear() { aStrList.clear(); } + +public: + // import / export + SOT_DLLPUBLIC friend SvStream& ReadFileList(SvStream& rIStm, FileList& rFileList); + + // fill in / interrogate list + void AppendFile(const OUString& rStr); + OUString GetFile(size_t nIndex) const; + size_t Count() const; +}; + +#endif // INCLUDED_SOT_FILELIST_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/formats.hxx b/include/sot/formats.hxx new file mode 100644 index 000000000..12727ffb3 --- /dev/null +++ b/include/sot/formats.hxx @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_FORMATS_HXX +#define INCLUDED_SOT_FORMATS_HXX + +#include + +// - predefined formats - +// Do NOT change the order of these values as the implementation depends on them! +enum class SotClipboardFormatId : sal_uInt32 +{ +// standard formats for that Copy/Paste methods exist + STRING = 1, + BITMAP = 2, + GDIMETAFILE = 3, + PRIVATE = 4, + SIMPLE_FILE = 5, + FILE_LIST = 6, +// further formats (only via CopyData/PasteData) + RTF = 10, + + NONE = 0, + ONLY_USED_IN_SW = 8, // the SW module essentially creates its own ID's and this is one of them + DRAWING = 11, + SVXB = 12, + SVIM = 13, + XFA = 14, + EDITENGINE_ODF_TEXT_FLAT = 15, + INTERNALLINK_STATE = 16, + SOLK = 17, + NETSCAPE_BOOKMARK = 18, + TREELISTBOX = 19, + NATIVE = 20, + OWNERLINK = 21, + STARSERVER = 22, + STAROBJECT = 23, + APPLETOBJECT = 24, + PLUGIN_OBJECT = 25, + STARWRITER_30 = 26, + STARWRITER_40 = 27, + STARWRITER_50 = 28, + STARWRITERWEB_40 = 29, + STARWRITERWEB_50 = 30, + STARWRITERGLOB_40 = 31, + STARWRITERGLOB_50 = 32, + STARDRAW = 33, + STARDRAW_40 = 34, + STARIMPRESS_50 = 35, + STARDRAW_50 = 36, + STARCALC = 37, + STARCALC_40 = 38, + STARCALC_50 = 39, + STARCHART = 40, + STARCHART_40 = 41, + STARCHART_50 = 42, + STARIMAGE = 43, + STARIMAGE_40 = 44, + STARIMAGE_50 = 45, + STARMATH = 46, + STARMATH_40 = 47, + STARMATH_50 = 48, + STAROBJECT_PAINTDOC = 49, + FILLED_AREA = 50, + HTML = 51, + HTML_SIMPLE = 52, + CHAOS = 53, + CNT_MSGATTACHFILE = 54, + BIFF_5 = 55, + BIFF__5 = 56, + SYLK = 57, + SYLK_BIGCAPS = 58, + LINK = 59, + DIF = 60, + STARDRAW_TABBAR = 61, + SONLK = 62, + MSWORD_DOC = 63, + STAR_FRAMESET_DOC = 64, + OFFICE_DOC = 65, + NOTES_DOCINFO = 66, + NOTES_HNOTE = 67, + NOTES_NATIVE = 68, + SFX_DOC = 69, + EVDF = 70, + ESDF = 71, + IDF = 72, + EFTP = 73, + EFD = 74, + SVX_FORMFIELDEXCH = 75, + EXTENDED_TABBAR = 76, + SBA_DATAEXCHANGE = 77, + SBA_FIELDDATAEXCHANGE = 78, + SBA_PRIVATE_URL = 79, + SBA_TABED = 80, + SBA_TABID = 81, + SBA_JOIN = 82, + OBJECTDESCRIPTOR = 83, + LINKSRCDESCRIPTOR = 84, + EMBED_SOURCE = 85, + LINK_SOURCE = 86, + EMBEDDED_OBJ = 87, + FILECONTENT = 88, + FILEGRPDESCRIPTOR = 89, + FILENAME = 90, + SD_OLE = 91, + EMBEDDED_OBJ_OLE = 92, + EMBED_SOURCE_OLE = 93, + OBJECTDESCRIPTOR_OLE = 94, + LINKSRCDESCRIPTOR_OLE = 95, + LINK_SOURCE_OLE = 96, + SBA_CTRLDATAEXCHANGE = 97, + OUTPLACE_OBJ = 98, + CNT_OWN_CLIP = 99, + INET_IMAGE = 100, + NETSCAPE_IMAGE = 101, + SBA_FORMEXCHANGE = 102, + SBA_REPORTEXCHANGE = 103, + UNIFORMRESOURCELOCATOR = 104, + STARCHARTDOCUMENT_50 = 105, + GRAPHOBJ = 106, + STARWRITER_60 = 107, + STARWRITERWEB_60 = 108, + STARWRITERGLOB_60 = 109, + STARDRAW_60 = 110, + STARIMPRESS_60 = 111, + STARCALC_60 = 112, + STARCHART_60 = 113, + STARMATH_60 = 114, + WMF = 115, + DBACCESS_QUERY = 116, + DBACCESS_TABLE = 117, + DBACCESS_COMMAND = 118, + DIALOG_60 = 119, + EMF = 120, + BIFF_8 = 121, + BMP = 122, + HTML_NO_COMMENT = 123, + STARWRITER_8 = 124, + STARWRITERWEB_8 = 125, + STARWRITERGLOB_8 = 126, + STARDRAW_8 = 127, + STARIMPRESS_8 = 128, + STARCALC_8 = 129, + STARCHART_8 = 130, + STARMATH_8 = 131, + XFORMS = 132, + STARWRITER_8_TEMPLATE = 133, + STARDRAW_8_TEMPLATE = 134, + STARIMPRESS_8_TEMPLATE = 135, + STARCALC_8_TEMPLATE = 136, + STARCHART_8_TEMPLATE = 137, + STARMATH_8_TEMPLATE = 138, + STARBASE_8 = 139, + HC_GDIMETAFILE = 140, + PNG = 141, + STARWRITERGLOB_8_TEMPLATE = 142, + MATHML = 143, + JPEG = 144, + RICHTEXT = 145, + STRING_TSVC = 146, + PDF = 147, + // the point at which we start allocating "runtime" format IDs + USER_END = PDF +}; + +/** Make it easier to iterate over format IDs */ +inline SotClipboardFormatId& operator++(SotClipboardFormatId& eFormat) +{ + eFormat = static_cast(static_cast(eFormat) + 1); + return eFormat; +} + +#define SOT_FORMAT_SYSTEM_START SotClipboardFormatId::NONE + +#endif // INCLUDED_SOT_FORMATS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/object.hxx b/include/sot/object.hxx new file mode 100644 index 000000000..1657986c8 --- /dev/null +++ b/include/sot/object.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_OBJECT_HXX +#define INCLUDED_SOT_OBJECT_HXX + +#include + +#include +#include + +class SOT_DLLPUBLIC SotObject : virtual public SvRefBase +{ + sal_uInt16 nOwnerLockCount; + bool bInClose; // TRUE, in DoClose + +protected: + virtual ~SotObject() override; + virtual bool Close(); + +public: + SotObject(); + + sal_uInt16 GetOwnerLockCount() const { return nOwnerLockCount; } + + void OwnerLock(bool bLock); + bool DoClose(); + bool IsInClose() const { return bInClose; } + +private: + SotObject& operator=(const SotObject&) = delete; + SotObject(const SotObject&) = delete; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/sotdllapi.h b/include/sot/sotdllapi.h new file mode 100644 index 000000000..c01d6ed3a --- /dev/null +++ b/include/sot/sotdllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_SOTDLLAPI_H +#define INCLUDED_SOT_SOTDLLAPI_H + +#include + +#if defined(SOT_DLLIMPLEMENTATION) +#define SOT_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define SOT_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define SOT_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_SOT_SOTDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/stg.hxx b/include/sot/stg.hxx new file mode 100644 index 000000000..72003f08f --- /dev/null +++ b/include/sot/stg.hxx @@ -0,0 +1,317 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_STG_HXX +#define INCLUDED_SOT_STG_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star::ucb { class XProgressHandler; } +namespace com::sun::star::uno { class Any; } +namespace com::sun::star::uno { template class Reference; } + +class StgIo; +class StgDirEntry; +typedef struct SvGUID ClsId; + +class StorageBase : public SvRefBase +{ +protected: + mutable ErrCode m_nError; // error code + StreamMode m_nMode; // open mode + bool m_bAutoCommit; + StorageBase(); + virtual ~StorageBase() override; +public: + virtual bool Validate( bool=false ) const = 0; + virtual bool ValidateMode( StreamMode ) const = 0; + void ResetError() const; + void SetError( ErrCode ) const; + ErrCode GetError() const; + bool Good() const { return m_nError == ERRCODE_NONE; } + StreamMode GetMode() const { return m_nMode; } + void SetAutoCommit( bool bSet ) + { m_bAutoCommit = bSet; } +}; + +class BaseStorageStream : public StorageBase +{ +public: + virtual sal_Int32 Read( void * pData, sal_Int32 nSize ) = 0; + virtual sal_Int32 Write( const void* pData, sal_Int32 nSize ) = 0; + virtual sal_uInt64 Seek( sal_uInt64 nPos ) = 0; + virtual sal_uInt64 Tell() = 0; + virtual void Flush() = 0; + virtual bool SetSize( sal_uInt64 nNewSize ) = 0; + virtual sal_uInt64 GetSize() const = 0; + virtual void CopyTo( BaseStorageStream * pDestStm ) = 0; + virtual bool Commit() = 0; + virtual bool Equals( const BaseStorageStream& rStream ) const = 0; +}; + +enum class SotClipboardFormatId : sal_uInt32; + +class SAL_DLLPUBLIC_RTTI BaseStorage : public StorageBase +{ +public: + virtual const OUString& GetName() const = 0; + virtual bool IsRoot() const = 0; + virtual void SetClassId( const ClsId& ) = 0; + virtual const ClsId& GetClassId() const = 0; + virtual void SetDirty() = 0; + virtual void SetClass( const SvGlobalName & rClass, + SotClipboardFormatId nOriginalClipFormat, + const OUString & rUserTypeName ) = 0; + virtual SvGlobalName GetClassName() = 0; + virtual SotClipboardFormatId GetFormat() = 0; + virtual OUString GetUserName() = 0; + virtual void FillInfoList( SvStorageInfoList* ) const = 0; + virtual bool CopyTo( BaseStorage* pDestStg ) const = 0; + virtual bool Commit() = 0; + virtual bool Revert() = 0; + virtual BaseStorageStream* OpenStream( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = true ) = 0; + virtual BaseStorage* OpenStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) = 0; + virtual BaseStorage* OpenUCBStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) = 0; + virtual BaseStorage* OpenOLEStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) = 0; + virtual bool IsStream( const OUString& rEleName ) const = 0; + virtual bool IsStorage( const OUString& rEleName ) const = 0; + virtual bool IsContained( const OUString& rEleName ) const = 0; + virtual void Remove( const OUString & rEleName ) = 0; + virtual bool CopyTo( const OUString & rEleName, BaseStorage * pDest, const OUString & rNewName ) = 0; + virtual bool ValidateFAT() = 0; + virtual bool Equals( const BaseStorage& rStream ) const = 0; +}; + +class OLEStorageBase +{ +protected: + StreamMode& nStreamMode; // open mode + StgIo* pIo; // I/O subsystem + StgDirEntry* pEntry; // the dir entry + OLEStorageBase( StgIo*, StgDirEntry*, StreamMode& ); + ~OLEStorageBase(); + bool Validate_Impl( bool ) const; + static bool ValidateMode_Impl( StreamMode, StgDirEntry const * p = nullptr ); +}; + +class StorageStream final : public BaseStorageStream, public OLEStorageBase +{ +//friend class Storage; + sal_uInt64 nPos; // current position + + virtual ~StorageStream() override; +public: + StorageStream( StgIo*, StgDirEntry*, StreamMode ); + virtual sal_Int32 Read( void * pData, sal_Int32 nSize ) override; + virtual sal_Int32 Write( const void* pData, sal_Int32 nSize ) override; + virtual sal_uInt64 Seek( sal_uInt64 nPos ) override; + virtual sal_uInt64 Tell() override { return nPos; } + virtual void Flush() override; + virtual bool SetSize( sal_uInt64 nNewSize ) override; + virtual sal_uInt64 GetSize() const override; + virtual void CopyTo( BaseStorageStream * pDestStm ) override; + virtual bool Commit() final override; + virtual bool Validate( bool=false ) const override; + virtual bool ValidateMode( StreamMode ) const override; + virtual bool Equals( const BaseStorageStream& rStream ) const override; +}; + +class UCBStorageStream; + +class UNLESS_MERGELIBS(SOT_DLLPUBLIC) Storage final : public BaseStorage, public OLEStorageBase +{ + OUString aName; + bool bIsRoot; + void Init( bool bCreate ); + Storage( StgIo*, StgDirEntry*, StreamMode ); + virtual ~Storage() override; +public: + Storage( OUString, StreamMode, bool bDirect ); + Storage( SvStream& rStrm, bool bDirect ); + Storage( UCBStorageStream& rStrm, bool bDirect ); + + static bool IsStorageFile( const OUString & rFileName ); + static bool IsStorageFile( SvStream* ); + + virtual const OUString& GetName() const final override; + virtual bool IsRoot() const override { return bIsRoot; } + virtual void SetClassId( const ClsId& ) override; + virtual const ClsId& GetClassId() const override; + virtual void SetDirty() override; + virtual void SetClass( const SvGlobalName & rClass, + SotClipboardFormatId nOriginalClipFormat, + const OUString & rUserTypeName ) override; + virtual SvGlobalName GetClassName() override; + virtual SotClipboardFormatId GetFormat() override; + virtual OUString GetUserName() override; + virtual void FillInfoList( SvStorageInfoList* ) const override; + virtual bool CopyTo( BaseStorage* pDestStg ) const override; + virtual bool Commit() final override; + virtual bool Revert() override; + virtual BaseStorageStream* OpenStream( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = true ) override; + virtual BaseStorage* OpenStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) override; + virtual BaseStorage* OpenUCBStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) override; + virtual BaseStorage* OpenOLEStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) override; + virtual bool IsStream( const OUString& rEleName ) const override; + virtual bool IsStorage( const OUString& rEleName ) const override; + virtual bool IsContained( const OUString& rEleName ) const override; + virtual void Remove( const OUString & rEleName ) override; + virtual bool CopyTo( const OUString & rEleName, BaseStorage * pDest, const OUString & rNewName ) override; + virtual bool ValidateFAT() override; + virtual bool Validate( bool=false ) const override; + virtual bool ValidateMode( StreamMode ) const override; + bool ValidateMode( StreamMode, StgDirEntry const * p ) const; + virtual bool Equals( const BaseStorage& rStream ) const override; +}; + +class UCBStorageStream_Impl; +class UCBStorageStream final : public BaseStorageStream +{ +friend class UCBStorage; + + UCBStorageStream_Impl* + pImp; + virtual ~UCBStorageStream() override; +public: + UCBStorageStream( const OUString& rName, StreamMode nMode, bool bDirect, bool bRepair, css::uno::Reference< css::ucb::XProgressHandler > const & xProgress ); + UCBStorageStream( UCBStorageStream_Impl* ); + + virtual sal_Int32 Read( void * pData, sal_Int32 nSize ) override; + virtual sal_Int32 Write( const void* pData, sal_Int32 nSize ) override; + virtual sal_uInt64 Seek( sal_uInt64 nPos ) override; + virtual sal_uInt64 Tell() override; + virtual void Flush() override; + virtual bool SetSize( sal_uInt64 nNewSize ) override; + virtual sal_uInt64 GetSize() const override; + virtual void CopyTo( BaseStorageStream * pDestStm ) override; + virtual bool Commit() override; + virtual bool Validate( bool=false ) const override; + virtual bool ValidateMode( StreamMode ) const override; + virtual bool Equals( const BaseStorageStream& rStream ) const override; + bool SetProperty( const OUString& rName, const css::uno::Any& rValue ); + + SvStream* GetModifySvStream(); +}; + +namespace ucbhelper +{ + class Content; +} + +class UCBStorage_Impl; +struct UCBStorageElement_Impl; +class SOT_DLLPUBLIC UCBStorage final : public BaseStorage +{ + UCBStorage_Impl* pImp; + + virtual ~UCBStorage() override; +public: + static bool IsStorageFile( SvStream* ); + + UCBStorage( const ::ucbhelper::Content& rContent, + const OUString& rName, + StreamMode nMode, + bool bDirect, + bool bIsRoot ); + + UCBStorage( const OUString& rName, + StreamMode nMode, + bool bDirect, + bool bIsRoot ); + + UCBStorage( const OUString& rName, + StreamMode nMode, + bool bDirect, + bool bIsRoot, + bool bIsRepair, + css::uno::Reference< css::ucb::XProgressHandler > const & + xProgressHandler ); + + UCBStorage( UCBStorage_Impl* ); + + UCBStorage( SvStream& rStrm, bool bDirect ); + + virtual const OUString& GetName() const override; + virtual bool IsRoot() const override; + virtual void SetClassId( const ClsId& ) override; + virtual const ClsId& GetClassId() const override; + virtual void SetDirty() override; + virtual void SetClass( const SvGlobalName & rClass, + SotClipboardFormatId nOriginalClipFormat, + const OUString & rUserTypeName ) override; + virtual SvGlobalName GetClassName() override; + virtual SotClipboardFormatId GetFormat() override; + virtual OUString GetUserName() override; + virtual void FillInfoList( SvStorageInfoList* ) const override; + virtual bool CopyTo( BaseStorage* pDestStg ) const override; + virtual bool Commit() final override; + virtual bool Revert() override; + virtual BaseStorageStream* OpenStream( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = true ) override; + virtual BaseStorage* OpenStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) override; + virtual BaseStorage* OpenUCBStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) override; + virtual BaseStorage* OpenOLEStorage( const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool bDirect = false ) override; + virtual bool IsStream( const OUString& rEleName ) const override; + virtual bool IsStorage( const OUString& rEleName ) const override; + virtual bool IsContained( const OUString& rEleName ) const override; + virtual void Remove( const OUString & rEleName ) override; + virtual bool CopyTo( const OUString & rEleName, BaseStorage * pDest, const OUString & rNewName ) override; + virtual bool ValidateFAT() override; + virtual bool Validate( bool=false ) const override; + virtual bool ValidateMode( StreamMode ) const override; + virtual bool Equals( const BaseStorage& rStream ) const override; + + UCBStorageElement_Impl* FindElement_Impl( std::u16string_view rName ) const; + bool CopyStorageElement_Impl( UCBStorageElement_Impl const & rElement, + BaseStorage* pDest, const OUString& rNew ) const; + BaseStorage* OpenStorage_Impl( const OUString & rEleName, + StreamMode, bool bDirect, bool bForceUCBStorage ); + +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/storage.hxx b/include/sot/storage.hxx new file mode 100644 index 000000000..dd44b0206 --- /dev/null +++ b/include/sot/storage.hxx @@ -0,0 +1,172 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_STORAGE_HXX +#define INCLUDED_SOT_STORAGE_HXX + +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::embed { class XStorage; } +namespace com::sun::star::uno { class Any; } +namespace com::sun::star::uno { template class Reference; } + +enum class SotClipboardFormatId : sal_uInt32; + +class BaseStorageStream; + +class SOT_DLLPUBLIC SotTempStream final : virtual public SvRefBase, public SvStream +{ +friend class SotStorage; + + virtual ~SotTempStream() override; +public: + SotTempStream(OUString const & rString, StreamMode = StreamMode::STD_READWRITE); + + void CopyTo(SotTempStream * pDestStm); +}; + +class SOT_DLLPUBLIC SotStorageStream final : virtual public SotObject, public SvStream +{ +friend class SotStorage; + BaseStorageStream * pOwnStm; // pointer to the own stream + + virtual std::size_t GetData(void* pData, std::size_t nSize) override; + virtual std::size_t PutData(const void* pData, std::size_t nSize) override; + virtual sal_uInt64 SeekPos(sal_uInt64 nPos) override; + virtual void FlushData() override; + + virtual ~SotStorageStream() override; +public: + SotStorageStream(BaseStorageStream *pBaseStream); + + virtual void ResetError() override; + + virtual void SetSize(sal_uInt64 nNewSize) override; + sal_uInt32 GetSize() const; + void Commit(); + bool SetProperty(OUString const & rName, css::uno::Any const & rValue); + virtual sal_uInt64 TellEnd() override; +}; + +class BaseStorage; +class SOT_DLLPUBLIC SotStorage final : virtual public SotObject +{ +friend class SotStorageStream; + + BaseStorage* m_pOwnStg; // target storage + SvStream* m_pStorStm; // only for SDSTORAGES + ErrCode m_nError; + OUString m_aName;// name of the storage + bool m_bIsRoot; // e.g.: File Storage + bool m_bDelStm; + OString m_aKey; // aKey.Len != 0 -> encryption + sal_Int32 m_nVersion; + + virtual ~SotStorage() override; + void CreateStorage(bool bUCBStorage, StreamMode); +public: + SotStorage(OUString const & rString, StreamMode eMode = StreamMode::STD_READWRITE); + SotStorage(bool bUCBStorage, const OUString & rString, + StreamMode = StreamMode::STD_READWRITE); + SotStorage(BaseStorage * pStorage); + SotStorage(SvStream & rStream); + SotStorage(bool bUCBStorage, SvStream & rStream); + SotStorage(SvStream * rStream, bool bDelete); + + std::unique_ptr CreateMemoryStream(); + + static bool IsStorageFile(OUString const & rFileName); + static bool IsStorageFile(SvStream* pStream); + + const OUString& GetName() const; + + bool Validate(); + + const OString& GetKey() const { return m_aKey;} + + void SetVersion(sal_Int32 nVersion) + { + m_nVersion = nVersion; + } + sal_Int32 GetVersion() const + { + return m_nVersion; + } + + ErrCode GetError() const + { + return m_nError.IgnoreWarning(); + } + void SetError(ErrCode nErrorCode) + { + if (m_nError == ERRCODE_NONE) + m_nError = nErrorCode; + } + + void SignAsRoot(bool bRoot) { m_bIsRoot = bRoot; } + + // own data sector + void SetClass(const SvGlobalName & rClass, + SotClipboardFormatId bOriginalClipFormat, + const OUString & rUserTypeName); + + SvGlobalName GetClassName(); // type of data in the storage + SotClipboardFormatId GetFormat(); + OUString GetUserName(); + + // list of all elements + void FillInfoList(SvStorageInfoList *) const; + bool CopyTo(SotStorage * pDestStg); + bool Commit(); + + // create stream with connection to Storage, + // more or less a Parent-Child relationship + tools::SvRef OpenSotStream(const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE); + SotStorage* OpenSotStorage(const OUString & rEleName, + StreamMode = StreamMode::STD_READWRITE, + bool transacted = true); + + // query whether Storage or Stream + bool IsStream( const OUString & rEleName ) const; + bool IsStorage( const OUString & rEleName ) const; + bool IsContained( const OUString & rEleName ) const; + // remove element + bool Remove(const OUString & rEleName); + bool CopyTo(const OUString & rEleName, SotStorage* pDest, + const OUString & rNewName); + + bool IsOLEStorage() const; + static bool IsOLEStorage(const OUString & rFileName); + static bool IsOLEStorage(SvStream* pStream); + + static SotStorage* OpenOLEStorage(css::uno::Reference const & xStorage, + OUString const & rEleName, StreamMode = StreamMode::STD_READWRITE); + static SotClipboardFormatId GetFormatID(css::uno::Reference const & xStorage); + static sal_Int32 GetVersion(css::uno::Reference const & xStorage); +}; + +#endif // INCLUDED_SOT_STORAGE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/sot/storinfo.hxx b/include/sot/storinfo.hxx new file mode 100644 index 000000000..c1283cffe --- /dev/null +++ b/include/sot/storinfo.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SOT_STORINFO_HXX +#define INCLUDED_SOT_STORINFO_HXX + +#include +#include +#include +#include +#include + +class StgDirEntry; +class SvStream; + +class SvStorageInfo +{ + friend class SotStorage; + OUString aName; + sal_uInt64 nSize; + bool bStream; + bool bStorage; + +public: + SvStorageInfo(const StgDirEntry&); + SvStorageInfo(OUString _aName, sal_uInt64 nSz, bool bIsStorage) + : aName(std::move(_aName)) + , nSize(nSz) + , bStream(!bIsStorage) + , bStorage(bIsStorage) + { + } + + const OUString& GetName() const { return aName; } + bool IsStream() const { return bStream; } + bool IsStorage() const { return bStorage; } + sal_uInt64 GetSize() const { return nSize; } +}; + +typedef std::vector SvStorageInfoList; + +SotClipboardFormatId ReadClipboardFormat(SvStream& rStm); +SOT_DLLPUBLIC void WriteClipboardFormat(SvStream& rStm, SotClipboardFormatId nFormat); + +#endif // _STORINFO_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/store/store.h b/include/store/store.h new file mode 100644 index 000000000..2fdfa4a30 --- /dev/null +++ b/include/store/store.h @@ -0,0 +1,217 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** Handle opaque type. + */ +typedef void* storeHandle; + +/** Acquire a Handle. + @param Handle [in] the Handle. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_acquireHandle ( + storeHandle Handle +) SAL_THROW_EXTERN_C(); + +/** Release a Handle. + @param Handle [in] the Handle. + @return store_E_None upon success, + store_E_InvalidHandle otherwise. + */ +STORE_DLLPUBLIC storeError store_releaseHandle ( + storeHandle Handle +) SAL_THROW_EXTERN_C(); + +/** File Handle opaque type. + */ +typedef void* storeFileHandle; + +/** Open a temporary file in memory. + @param nPageSize [in] the creation page size, + integer multiple of minimum page size. + @param phFile [out] the File Handle. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_createMemoryFile ( + sal_uInt16 nPageSize, + storeFileHandle *phFile +) SAL_THROW_EXTERN_C(); + +/** Open a file. + @param pFilename [in] the filename as URL or system path. + @param eAccessMode [in] the access mode. + storeAccessMode::Create truncate existing and create, + store_AccessReadCreate create not existing, + storeAccessMode::ReadWrite write existing, + storeAccessMode::ReadOnly never modifies. + @param nPageSize [in] the creation page size, + integer multiple of minimum page size. + @param phFile [out] the File Handle. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_openFile ( + rtl_uString *pFilename, + storeAccessMode eAccessMode, + sal_uInt16 nPageSize, + storeFileHandle *phFile +) SAL_THROW_EXTERN_C(); + +/** Close a file. + @param hFile [in] the File Handle. + @return store_E_None upon success, + store_E_InvalidHandle otherwise. + */ +STORE_DLLPUBLIC storeError store_closeFile ( + storeFileHandle hFile +) SAL_THROW_EXTERN_C(); + +/** Flush a file. + @param hFile [in] the File Handle. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_flushFile ( + storeFileHandle hFile +) SAL_THROW_EXTERN_C(); + +/** Directory Handle opaque type. + */ +typedef void* storeDirectoryHandle; + +/** Open a directory. + @see store_openFile() + + @param hFile [in] the File Handle. + @param pPath [in] the directory path. + @param pName [in] the directory name. + @param eAccessMode [in] the access mode. + @param phDirectory [out] the Directory Handle. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_openDirectory ( + storeFileHandle hFile, + rtl_uString const *pPath, + rtl_uString const *pName, + storeAccessMode eAccessMode, + storeDirectoryHandle *phDirectory +) SAL_THROW_EXTERN_C(); + +/** Find first directory entry. + @param hDirectory [in] the Directory Handle. + @param pFindData [out] the Find Data structure. + @return store_E_None upon success, + store_E_NoMoreFile upon end of iteration. + */ +STORE_DLLPUBLIC storeError store_findFirst ( + storeDirectoryHandle hDirectory, + storeFindData *pFindData +) SAL_THROW_EXTERN_C(); + +/** Find next directory entry. + @param hDirectory [in] the Directory Handle. + @param pFindData [out] the Find Data structure. + @return store_E_None upon success, + store_E_NoMoreFile upon end of iteration. + */ +STORE_DLLPUBLIC storeError store_findNext ( + storeDirectoryHandle hDirectory, + storeFindData *pFindData +) SAL_THROW_EXTERN_C(); + +/** Stream Handle opaque type. + */ +typedef void* storeStreamHandle; + +/** Open a stream. + @see store_openFile() + + @param hFile [in] the File Handle. + @param pPath [in] the stream path. + @param pName [in] the stream name. + @param eMode [in] the access mode. + @param phStrm [out] the Stream Handle. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_openStream ( + storeFileHandle hFile, + rtl_uString const *pPath, + rtl_uString const *pName, + storeAccessMode eMode, + storeStreamHandle *phStrm +) SAL_THROW_EXTERN_C(); + +/** Read from a stream. + @param hStrm [in] the Stream Handle. + @param nOffset [in] the offset of the first byte to read. + @param pBuffer [out] the buffer. + @param nBytes [in] the number of bytes to read. + @param pnDone [out] the number of bytes actually read. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_readStream ( + storeStreamHandle hStrm, + sal_uInt32 nOffset, + void *pBuffer, + sal_uInt32 nBytes, + sal_uInt32 *pnDone +) SAL_THROW_EXTERN_C(); + +/** Write to a stream. + @param hStrm [in] the Stream Handle. + @param nOffset [in] the offset of the first byte to write. + @param pBuffer [in] the buffer. + @param nBytes [in] the number of bytes to write. + @param pnDone [out] the number of bytes actually written. + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_writeStream ( + storeStreamHandle hStrm, + sal_uInt32 nOffset, + const void *pBuffer, + sal_uInt32 nBytes, + sal_uInt32 *pnDone +) SAL_THROW_EXTERN_C(); + +/** Remove a file entry. + @param hFile [in] the File Handle + @param pPath [in] the entry path + @param pName [in] the entry name + @return store_E_None upon success + */ +STORE_DLLPUBLIC storeError store_remove ( + storeFileHandle hFile, + rtl_uString const *pPath, + rtl_uString const *pName +) SAL_THROW_EXTERN_C(); + +#ifdef __cplusplus +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/store/store.hxx b/include/store/store.hxx new file mode 100644 index 000000000..d32ceefbe --- /dev/null +++ b/include/store/store.hxx @@ -0,0 +1,353 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace store +{ + +class OStoreStream +{ +public: + /** Construction. + */ + OStoreStream() + : m_hImpl (nullptr) + {} + + /** Destruction. + */ + ~OStoreStream() + { + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + } + + /** Copy construction. + */ + OStoreStream (OStoreStream const & rhs) + : m_hImpl (rhs.m_hImpl) + { + if (m_hImpl) + (void) store_acquireHandle (m_hImpl); + } + + /** Assignment. + */ + OStoreStream & operator= (OStoreStream const & rhs) + { + if (rhs.m_hImpl) + (void) store_acquireHandle (rhs.m_hImpl); + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + m_hImpl = rhs.m_hImpl; + return *this; + } + + /** Open the stream. + @see store_openStream() + */ + storeError create ( + storeFileHandle hFile, + OUString const & rPath, + OUString const & rName, + storeAccessMode eMode) + { + if (m_hImpl) + { + (void) store_releaseHandle (m_hImpl); + m_hImpl = nullptr; + } + return store_openStream (hFile, rPath.pData, rName.pData, eMode, &m_hImpl); + } + + /** Read from the stream. + @see store_readStream() + */ + storeError readAt ( + sal_uInt32 nOffset, + void * pBuffer, + sal_uInt32 nBytes, + sal_uInt32 & rnDone) + { + if (!m_hImpl) + return store_E_InvalidHandle; + + return store_readStream (m_hImpl, nOffset, pBuffer, nBytes, &rnDone); + } + + /** Write to the stream. + @see store_writeStream() + */ + storeError writeAt ( + sal_uInt32 nOffset, + void const * pBuffer, + sal_uInt32 nBytes, + sal_uInt32 & rnDone) + { + if (!m_hImpl) + return store_E_InvalidHandle; + + return store_writeStream (m_hImpl, nOffset, pBuffer, nBytes, &rnDone); + } + +private: + /** Representation. + */ + storeStreamHandle m_hImpl; +}; + +class OStoreDirectory +{ +public: + /** Construction. + */ + OStoreDirectory() + : m_hImpl (nullptr) + {} + + /** Destruction. + */ + ~OStoreDirectory() + { + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + } + + /** Copy construction. + */ + OStoreDirectory (OStoreDirectory const & rhs) + : m_hImpl (rhs.m_hImpl) + { + if (m_hImpl) + (void) store_acquireHandle (m_hImpl); + } + + /** Move construction. + */ + OStoreDirectory (OStoreDirectory && rhs) noexcept + : m_hImpl (rhs.m_hImpl) + { + rhs.m_hImpl = nullptr; + } + + /** Assignment. + */ + OStoreDirectory & operator= (OStoreDirectory const & rhs) + { + if (rhs.m_hImpl) + (void) store_acquireHandle (rhs.m_hImpl); + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + m_hImpl = rhs.m_hImpl; + return *this; + } + + /** Move assignment. + */ + OStoreDirectory & operator= (OStoreDirectory && rhs) noexcept + { + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + m_hImpl = rhs.m_hImpl; + rhs.m_hImpl = nullptr; + return *this; + } + + /** Open the directory. + @see store_openDirectory() + */ + storeError create ( + storeFileHandle hFile, + OUString const & rPath, + OUString const & rName, + storeAccessMode eMode) + { + if (m_hImpl) + { + (void) store_releaseHandle (m_hImpl); + m_hImpl = nullptr; + } + return store_openDirectory (hFile, rPath.pData, rName.pData, eMode, &m_hImpl); + } + + /** Directory iterator type. + @see first() + @see next() + */ + typedef storeFindData iterator; + + /** Find first directory entry. + @see store_findFirst() + */ + storeError first (iterator& it) + { + if (!m_hImpl) + return store_E_InvalidHandle; + + return store_findFirst (m_hImpl, &it); + } + + /** Find next directory entry. + @see store_findNext() + */ + storeError next (iterator& it) + { + if (!m_hImpl) + return store_E_InvalidHandle; + + return store_findNext (m_hImpl, &it); + } + +private: + /** Representation. + */ + storeDirectoryHandle m_hImpl; +}; + +class OStoreFile +{ +public: + /** Construction. + */ + OStoreFile() + : m_hImpl (nullptr) + {} + + /** Destruction. + */ + ~OStoreFile() + { + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + } + + /** Copy construction. + */ + OStoreFile (OStoreFile const & rhs) + : m_hImpl (rhs.m_hImpl) + { + if (m_hImpl) + (void) store_acquireHandle (m_hImpl); + } + + /** Assignment. + */ + OStoreFile & operator= (OStoreFile const & rhs) + { + if (rhs.m_hImpl) + (void) store_acquireHandle (rhs.m_hImpl); + if (m_hImpl) + (void) store_releaseHandle (m_hImpl); + m_hImpl = rhs.m_hImpl; + return *this; + } + + /** Conversion into File Handle. + */ + operator storeFileHandle() const + { + return m_hImpl; + } + + /** Check for a valid File Handle. + @return sal_True if valid, sal_False otherwise. + */ + bool isValid() const + { + return (m_hImpl != nullptr); + } + + /** Open the file. + @see store_openFile() + */ + storeError create( + OUString const & rFilename, + storeAccessMode eAccessMode ) + { + if (m_hImpl) + { + (void) store_releaseHandle (m_hImpl); + m_hImpl = nullptr; + } + return store_openFile (rFilename.pData, eAccessMode, STORE_DEFAULT_PAGESIZE, &m_hImpl); + } + + /** Open the temporary file in memory. + @see store_createMemoryFile() + */ + storeError createInMemory () + { + if (m_hImpl) + { + (void) store_releaseHandle (m_hImpl); + m_hImpl = nullptr; + } + return store_createMemoryFile (STORE_DEFAULT_PAGESIZE, &m_hImpl); + } + + /** Close the file. + @see store_closeFile() + */ + void close() + { + if (m_hImpl) + { + (void) store_closeFile (m_hImpl); + m_hImpl = nullptr; + } + } + + /** Flush the file. + @see store_flushFile() + */ + storeError flush() const + { + if (!m_hImpl) + return store_E_InvalidHandle; + + return store_flushFile (m_hImpl); + } + + /** Remove a file entry. + @see store_remove() + */ + storeError remove ( + OUString const & rPath, OUString const & rName) + { + if (!m_hImpl) + return store_E_InvalidHandle; + + return store_remove (m_hImpl, rPath.pData, rName.pData); + } + +private: + /** Representation. + */ + storeFileHandle m_hImpl; +}; + +} // namespace store + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/store/storedllapi.h b/include/store/storedllapi.h new file mode 100644 index 000000000..14a0d2feb --- /dev/null +++ b/include/store/storedllapi.h @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#if defined(STORE_DLLIMPLEMENTATION) +#define STORE_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define STORE_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/store/types.h b/include/store/types.h new file mode 100644 index 000000000..7abf012ea --- /dev/null +++ b/include/store/types.h @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** PageSize (recommended) default. + @see store_openFile() + */ +constexpr sal_uInt16 STORE_DEFAULT_PAGESIZE = 0x0400; + + +/** PageSize (enforced) limits. + @see store_openFile() + */ +constexpr sal_uInt16 STORE_MINIMUM_PAGESIZE = 0x0200; +constexpr sal_uInt16 STORE_MAXIMUM_PAGESIZE = 0x8000; + + +/** NameSize (enforced) limit. + @see any param pName + @see store_E_NameTooLong + */ +constexpr auto STORE_MAXIMUM_NAMESIZE = 256; + + +/** Attributes (predefined). + @see store_attrib() + */ +constexpr sal_uInt32 STORE_ATTRIB_ISLINK = 0x10000000; +constexpr sal_uInt32 STORE_ATTRIB_ISDIR = 0x20000000; +constexpr sal_uInt32 STORE_ATTRIB_ISFILE = 0x40000000; + + +/** Access Mode enumeration. + @see store_openFile() + @see store_openDirectory() + @see store_openStream() + */ +enum class storeAccessMode +{ + Create, + ReadWrite, + ReadOnly, + FORCE_EQUAL_SIZE = SAL_MAX_ENUM +}; + + +/** Error Code enumeration. + */ +typedef enum +{ + store_E_None = 0, + store_E_AccessViolation, + store_E_LockingViolation, + store_E_CantSeek, + store_E_CantRead, + store_E_CantWrite, + store_E_InvalidAccess, + store_E_InvalidHandle, + store_E_InvalidParameter, + store_E_InvalidChecksum, + store_E_AlreadyExists, + store_E_NotExists, + store_E_NotDirectory, + store_E_NotFile, + store_E_NoMoreFiles, + store_E_NameTooLong, + store_E_OutOfMemory, + store_E_OutOfSpace, + store_E_Pending, + store_E_WrongFormat, + store_E_WrongVersion, + store_E_Unknown, + store_E_FORCE_EQUAL_SIZE = SAL_MAX_ENUM +} storeError; + + +/** Find Data structure. + @see store_findFirst() + @see store_findNext() + */ +typedef struct +{ + /** Name. + @see m_nLength + */ + sal_Unicode m_pszName[STORE_MAXIMUM_NAMESIZE]; + + /** Name Length. + @see m_pszName + */ + sal_Int32 m_nLength; + + /** Attributes. + @see store_attrib() + */ + sal_uInt32 m_nAttrib; + + /** Reserved for internal use. + */ + sal_uInt32 m_nReserved; +} storeFindData; + +#ifdef __cplusplus +} +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/IndexedStyleSheets.hxx b/include/svl/IndexedStyleSheets.hxx new file mode 100644 index 000000000..910acd9e2 --- /dev/null +++ b/include/svl/IndexedStyleSheets.hxx @@ -0,0 +1,182 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_INDEXEDSTYLESHEETS_HXX +#define INCLUDED_SVL_INDEXEDSTYLESHEETS_HXX + +#include +#include +#include + +#include + +#include +#include + +namespace svl +{ +/** Function object to check whether a style sheet a fulfills specific criteria. + * Derive from this class and override the Check() method. + */ +struct StyleSheetPredicate +{ + virtual bool Check(const SfxStyleSheetBase& styleSheet) = 0; + virtual ~StyleSheetPredicate() {} +}; + +/** Function object for cleanup-Strategy for IndexedSfxStyleSheets::Clear(). + * Derive from it and do what is necessary to dispose of a style sheet in Dispose(). + */ +struct StyleSheetDisposer +{ + virtual void Dispose(rtl::Reference styleSheet) = 0; + virtual ~StyleSheetDisposer() {} +}; + +/** Function object to apply a method on all style sheets. + * Derive from it and do whatever you want to with the style sheet in the DoIt() method. + */ +struct StyleSheetCallback +{ + virtual void DoIt(const SfxStyleSheetBase& styleSheet) = 0; + virtual ~StyleSheetCallback() {} +}; + +/** This class holds SfxStyleSheets and allows for access via an id and a name. + * + * @warning + * The identification of style sheets happens by their name. If the name of a sheet changes, + * it will not be found again! Please call Reindex() after changing a style sheet's name. + * + * @internal + * This class was implemented to mitigate solve #fdo 30770. + * The issue describes an Excel file which takes several hours to open. + * An analysis revealed that the time is spent searching for style sheets with linear scans in an array. + * This class implements access to the style sheets via their name in (usually) constant time. + * + * The return type for most methods is a vector of unsigned integers which denote the position + * of the style sheets in the vector, and not of pointers to style sheets. + * You will need a non-const StyleSheetPool to obtain the actual style sheets. + * + * + * Index-based access is required in several code portions. Hence we have to store the style sheets + * in a vector as well as in a map. + */ +class SVL_DLLPUBLIC IndexedStyleSheets final +{ +public: + IndexedStyleSheets(); + + /** Destructor. + * + * @internal + * Is explicit because it has to know how to dispose of SfxStyleSheetBase objects. + */ + ~IndexedStyleSheets(); + + /** Adds a style sheet. + * + * If the style sheet is already contained, this call has no effect. + */ + void AddStyleSheet(const rtl::Reference& style); + + /** Removes a style sheet. */ + bool RemoveStyleSheet(const rtl::Reference& style); + + /** Check whether a specified style sheet is stored. */ + bool HasStyleSheet(const rtl::Reference& style) const; + + /** Obtain the number of style sheets which are held */ + sal_Int32 GetNumberOfStyleSheets() const; + + /** Obtain the number of style sheets for which a certain condition holds */ + sal_Int32 GetNumberOfStyleSheetsWithPredicate(StyleSheetPredicate& predicate) const; + + /** Return the stylesheet by its position. + * You can obtain the position by, e.g., FindStyleSheetPosition() + * @internal + * Method is not const because the returned style sheet is not const + */ + SfxStyleSheetBase* GetStyleSheetByPosition(sal_Int32 pos); + + /** Find the position of a provided style. + * + * @throws std::runtime_error if the style has not been found. + */ + sal_Int32 FindStyleSheetPosition(const SfxStyleSheetBase& style) const; + + /** Obtain the positions of all styles which have a given name + */ + std::vector FindPositionsByName(const OUString& name) const; + + enum class SearchBehavior + { + ReturnAll, + ReturnFirst + }; + /** Obtain the positions of all styles which have a certain name and fulfill a certain condition. + * + * This method is fast because it can use the name-based index + */ + std::vector + FindPositionsByNameAndPredicate(const OUString& name, StyleSheetPredicate& predicate, + SearchBehavior behavior = SearchBehavior::ReturnAll) const; + + /** Obtain the positions of all styles which fulfill a certain condition. + * + * This method is slow because it cannot use the name-based index + */ + std::vector FindPositionsByPredicate(StyleSheetPredicate& predicate) const; + + /** Execute a callback on all style sheets */ + void ApplyToAllStyleSheets(StyleSheetCallback& callback) const; + + /** Clear the contents of the index. + * The StyleSheetDisposer::Dispose() method is called on each style sheet, e.g., if you want to broadcast + * changes. + */ + void Clear(StyleSheetDisposer& cleanup); + + void Reindex(); + + /** Warning: counting for n starts at 0, i.e., the 0th style sheet is the first that is found. */ + SfxStyleSheetBase* GetNthStyleSheetThatMatchesPredicate(sal_Int32 n, + StyleSheetPredicate& predicate, + sal_Int32 startAt = 0); + + /** Get the positions of the style sheets which belong to a certain family. + */ + const std::vector& GetStyleSheetPositionsByFamily(SfxStyleFamily) const; + +private: + /** Register the position of a styleName in the index */ + void Register(const SfxStyleSheetBase& style, sal_Int32 pos); + + typedef std::vector> VectorType; + /** Vector with the stylesheets to allow for index-based access. + */ + VectorType mStyleSheets; + + /** The map type that is used to store the mapping from strings to ids in mStyleSheets + * + * @internal + * Must be an unordered map. A regular map is too slow for some files. */ + typedef std::unordered_multimap MapType; + + /** A map which stores the positions of style sheets by their name */ + MapType mPositionsByName; + + std::vector> mStyleSheetPositionsByFamily; +}; + +} /* namespace svl */ + +#endif // INCLUDED_SVL_INDEXEDSTYLESHEETS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/PasswordHelper.hxx b/include/svl/PasswordHelper.hxx new file mode 100644 index 000000000..aa7e55867 --- /dev/null +++ b/include/svl/PasswordHelper.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_PASSWORDHELPER_HXX +#define INCLUDED_SVL_PASSWORDHELPER_HXX + +#include + +#include + +#include +#include +#include + +class SvPasswordHelper +{ + static void GetHashPasswordLittleEndian(css::uno::Sequence& rPassHash, std::u16string_view sPass); + static void GetHashPasswordBigEndian(css::uno::Sequence& rPassHash, std::u16string_view sPass); + +public: + SVL_DLLPUBLIC static void GetHashPassword(css::uno::Sequence & rPassHash, const char* pPass, sal_uInt32 nLen); + + SVL_DLLPUBLIC static void GetHashPassword(css::uno::Sequence& rPassHash, std::u16string_view sPass); + SVL_DLLPUBLIC static void GetHashPasswordSHA1UTF8(css::uno::Sequence& rPassHash, std::u16string_view sPass); + SVL_DLLPUBLIC static void GetHashPasswordSHA256(css::uno::Sequence& rPassHash, std::u16string_view sPass); + /** + Use this method to compare a given string with another given Hash value. + This is necessary, because in older versions exists different hashes of the same string. They were endian dependent. + We need this to handle old files. This method will compare against big and + little endian UTF-16. + tdf#115483: also check 2 different new ways of hashing that were added in + ODF 1.2, requiring UTF-8 encoding. + */ + SVL_DLLPUBLIC static bool CompareHashPassword(const css::uno::Sequence& rOldPassHash, std::u16string_view sNewPass); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/SfxBroadcaster.hxx b/include/svl/SfxBroadcaster.hxx new file mode 100644 index 000000000..2c05a6abf --- /dev/null +++ b/include/svl/SfxBroadcaster.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_BRDCST_HXX +#define INCLUDED_SVL_BRDCST_HXX + +#include +#include + +class SfxListener; +class SfxHint; +class SfxBroadcasterTest; + +class SVL_DLLPUBLIC SfxBroadcaster +{ + /** Contains the positions of removed listeners. */ + std::vector m_RemovedPositions; + std::vector m_Listeners; + +private: + void AddListener( SfxListener& rListener ); + void RemoveListener( SfxListener& rListener ); + const SfxBroadcaster& operator=(const SfxBroadcaster &) = delete; + +protected: + void Forward(SfxBroadcaster& rBC, const SfxHint& rHint); + +public: + + SfxBroadcaster() {} + SfxBroadcaster( const SfxBroadcaster &rBC ); + virtual ~SfxBroadcaster() COVERITY_NOEXCEPT_FALSE; + + void Broadcast( const SfxHint &rHint ); + bool HasListeners() const; + + /** Get the number of listeners which are registered at this broadcaster */ + size_t GetListenerCount() const; + + /** Get the size of the internally stored vector. + * Use it to iterate over all listeners. + */ + size_t GetSizeOfVector() const; + + /** Get a listener by its position in the internally stored vector. + * Note that this method may return NULL + */ + SfxListener* GetListener( size_t nNo ) const; + + friend class SfxListener; + friend class ::SfxBroadcasterTest; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/adrparse.hxx b/include/svl/adrparse.hxx new file mode 100644 index 000000000..f19fc7ef0 --- /dev/null +++ b/include/svl/adrparse.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_ADRPARSE_HXX +#define INCLUDED_SVL_ADRPARSE_HXX + +#include +#include +#include + + +class SVL_DLLPUBLIC SvAddressParser +{ + friend class SvAddressParser_Impl; + + ::std::vector< OUString > + m_vAddresses; + +public: + SvAddressParser(const OUString& rInput); + + ~SvAddressParser(); + + sal_Int32 Count() const { return m_vAddresses.size(); } + + const OUString& GetEmailAddress(sal_Int32 nIndex) const + { + return m_vAddresses[nIndex]; + } +}; + +#endif // INCLUDED_SVL_ADRPARSE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/aeitem.hxx b/include/svl/aeitem.hxx new file mode 100644 index 000000000..447e6d710 --- /dev/null +++ b/include/svl/aeitem.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_AEITEM_HXX +#define INCLUDED_SVL_AEITEM_HXX + +#include +#include +#include + +#include + +class UNLESS_MERGELIBS(SVL_DLLPUBLIC) SfxAllEnumItem final : public SfxPoolItem +{ + std::vector m_Values; + +public: + explicit SfxAllEnumItem( sal_uInt16 nWhich); + SfxAllEnumItem( const SfxAllEnumItem & ); + virtual ~SfxAllEnumItem() override; + + void SetTextByPos( sal_uInt16 nPos, const OUString &rText ); + OUString const & GetTextByPos( sal_uInt16 nPos ) const; + sal_Int32 GetTextCount() const; + virtual SfxAllEnumItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool operator==( SfxPoolItem const & ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/asiancfg.hxx b/include/svl/asiancfg.hxx new file mode 100644 index 000000000..6ee88fe35 --- /dev/null +++ b/include/svl/asiancfg.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_ASIANCFG_HXX +#define INCLUDED_SVL_ASIANCFG_HXX + +#include + +#include +#include +#include + +namespace com::sun::star::lang { + struct Locale; +} + +/// These constants define character compression in Asian text. +/// Must match the values in com::sun::star::text::CharacterCompressionType. +/// For bonus points, also appears to be directly stored in the ww8 file format. +enum class CharCompressType { + NONE, /// No Compression + PunctuationOnly, /// Only punctuation is compressed + PunctuationAndKana, /// Punctuation and Japanese Kana are compressed. + Invalid = 0xff /// only used in SC +}; + +class SVL_DLLPUBLIC SvxAsianConfig { +public: + SvxAsianConfig(); + ~SvxAsianConfig(); + SvxAsianConfig(const SvxAsianConfig&) = delete; + SvxAsianConfig& operator=( const SvxAsianConfig& ) = delete; + + void Commit(); + + bool IsKerningWesternTextOnly() const; + + void SetKerningWesternTextOnly(bool value); + + CharCompressType GetCharDistanceCompression() const; + + void SetCharDistanceCompression(CharCompressType value); + + css::uno::Sequence< css::lang::Locale > GetStartEndCharLocales() const; + + bool GetStartEndChars( + css::lang::Locale const & locale, OUString & startChars, + OUString & endChars) const; + + void SetStartEndChars( + css::lang::Locale const & locale, + OUString const * startChars, OUString const * endChars); + +private: + struct Impl; + + std::unique_ptr< Impl > impl_; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/broadcast.hxx b/include/svl/broadcast.hxx new file mode 100644 index 000000000..30592d22c --- /dev/null +++ b/include/svl/broadcast.hxx @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_BROADCAST_HXX +#define INCLUDED_SVL_BROADCAST_HXX + +#include + +#include + +class SvtListener; +class SfxHint; + +class SVL_DLLPUBLIC SvtBroadcaster +{ +public: + friend class SvtListener; + + typedef std::vector ListenersType; + +private: + const SvtBroadcaster& operator=(const SvtBroadcaster &) = delete; + + /** + * Ensure that the container doesn't contain any duplicated listener + * entries. As a side effect, the listeners get sorted by pointer values + * after this call. + */ + void Normalize() const; + + void Add( SvtListener* p ); + void Remove( SvtListener* p ); + +protected: + virtual void ListenersGone(); + +public: + SvtBroadcaster() + : mnEmptySlots(0), mnListenersFirstUnsorted(0), mbAboutToDie(false) + , mbDisposing(false), mbDestNormalized(true) {} + SvtBroadcaster( const SvtBroadcaster &rBC ); + virtual ~SvtBroadcaster(); + + void Broadcast( const SfxHint &rHint ); + + ListenersType& GetAllListeners(); + const ListenersType& GetAllListeners() const; + + bool HasListeners() const { return (maListeners.size() - mnEmptySlots) > 0; } + + /** + * Listeners and broadcasters are M:N relationship. If you want to + * destruct them, you easily end up in O(M*N) situation; where for every + * listener, you iterate all broadcasters, to remove that one listener. + * + * To avoid that, use this call to announce to the broadcaster it is going + * to die, and the listeners do not have to bother with removing + * themselves from the broadcaster - the broadcaster will not broadcast + * anything after the PrepareForDestruction() call anyway. + */ + void PrepareForDestruction(); + +private: + /// contains only one of each listener, which is enforced by SvtListener + mutable ListenersType maListeners; + + /// When the broadcaster is about to die, collect listeners that asked for removal. + mutable ListenersType maDestructedListeners; + + /** + Note that this class is very performance sensitive, so the following fields have been + carefully sized and packed so we can access them quickly, while also taking as little CPU cache + space as possible (because e.g. calc can have a LOT of them) + */ + mutable sal_Int32 mnEmptySlots; + // The first item in maListeners that is not sorted. The container can become large, so this optimizes sorting. + mutable sal_Int32 mnListenersFirstUnsorted; + /// Indicate that this broadcaster will be destructed (we indicate this on all ScColumn's broadcasters during the ScTable destruction, eg.) + bool mbAboutToDie:1; + bool mbDisposing:1; + // Whether maDestructedListeners is sorted or not. + mutable bool mbDestNormalized:1; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/cenumitm.hxx b/include/svl/cenumitm.hxx new file mode 100644 index 000000000..9428e095c --- /dev/null +++ b/include/svl/cenumitm.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_CENUMITM_HXX +#define INCLUDED_SVL_CENUMITM_HXX + +#include +#include + +class SVL_DLLPUBLIC SfxEnumItemInterface: public SfxPoolItem +{ +protected: + explicit SfxEnumItemInterface(sal_uInt16 which): SfxPoolItem(which) {} + + SfxEnumItemInterface(const SfxEnumItemInterface &) = default; + +public: + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) const override; + + virtual bool QueryValue(css::uno::Any & rVal, sal_uInt8 = 0) const override; + + virtual bool PutValue(const css::uno::Any & rVal, sal_uInt8 ) override; + + virtual sal_uInt16 GetValueCount() const = 0; + + virtual sal_uInt16 GetEnumValue() const = 0; + + virtual void SetEnumValue(sal_uInt16 nValue) = 0; + + virtual bool HasBoolValue() const; + + virtual bool GetBoolValue() const; + + virtual void SetBoolValue(bool bValue); +}; + +#endif // INCLUDED_SVL_CENUMITM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/cintitem.hxx b/include/svl/cintitem.hxx new file mode 100644 index 000000000..bde59c399 --- /dev/null +++ b/include/svl/cintitem.hxx @@ -0,0 +1,176 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_CINTITEM_HXX +#define INCLUDED_SVL_CINTITEM_HXX + +#include +#include +#include + +class SVL_DLLPUBLIC CntByteItem: public SfxPoolItem +{ + sal_uInt8 m_nValue; + +public: + + CntByteItem(sal_uInt16 which, sal_uInt8 nTheValue): + SfxPoolItem(which), m_nValue(nTheValue) {} + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual bool QueryValue(css::uno::Any& rVal, + sal_uInt8 nMemberId = 0) const override; + + virtual bool PutValue(const css::uno::Any& rVal, + sal_uInt8 nMemberId) override; + + virtual CntByteItem* Clone(SfxItemPool * = nullptr) const override; + + sal_uInt8 GetValue() const { return m_nValue; } + + inline void SetValue(sal_uInt8 nTheValue); +}; + +inline void CntByteItem::SetValue(sal_uInt8 nTheValue) +{ + DBG_ASSERT(GetRefCount() == 0, "CntByteItem::SetValue(): Pooled item"); + m_nValue = nTheValue; +} + +class SVL_DLLPUBLIC CntUInt16Item: public SfxPoolItem +{ + sal_uInt16 m_nValue; + +public: + + CntUInt16Item(sal_uInt16 which, sal_uInt16 nTheValue): + SfxPoolItem(which), m_nValue(nTheValue) + {} + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual bool QueryValue(css::uno::Any& rVal, + sal_uInt8 nMemberId = 0) const override; + + virtual bool PutValue(const css::uno::Any& rVal, + sal_uInt8 nMemberId) override; + + virtual CntUInt16Item* Clone(SfxItemPool * = nullptr) const override; + + sal_uInt16 GetValue() const { return m_nValue; } + + inline void SetValue(sal_uInt16 nTheValue); +}; + +inline void CntUInt16Item::SetValue(sal_uInt16 nTheValue) +{ + DBG_ASSERT(GetRefCount() == 0, "CntUInt16Item::SetValue(): Pooled item"); + m_nValue = nTheValue; +} + +class SVL_DLLPUBLIC CntInt32Item: public SfxPoolItem +{ + sal_Int32 m_nValue; + +public: + + CntInt32Item(sal_uInt16 which, sal_Int32 nTheValue): + SfxPoolItem(which), m_nValue(nTheValue) + {} + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual bool QueryValue(css::uno::Any& rVal, + sal_uInt8 nMemberId = 0) const override; + + virtual bool PutValue(const css::uno::Any& rVal, + sal_uInt8 nMemberId) override; + + virtual CntInt32Item* Clone(SfxItemPool * = nullptr) const override; + + sal_Int32 GetValue() const { return m_nValue; } + + inline void SetValue(sal_Int32 nTheValue); +}; + +inline void CntInt32Item::SetValue(sal_Int32 nTheValue) +{ + DBG_ASSERT(GetRefCount() == 0, "CntInt32Item::SetValue(): Pooled item"); + m_nValue = nTheValue; +} + +class SVL_DLLPUBLIC CntUInt32Item: public SfxPoolItem +{ + sal_uInt32 m_nValue; + +public: + + CntUInt32Item(sal_uInt16 which, sal_uInt32 nTheValue): + SfxPoolItem(which), m_nValue(nTheValue) + {} + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual bool QueryValue(css::uno::Any& rVal, + sal_uInt8 nMemberId = 0) const override; + + virtual bool PutValue(const css::uno::Any& rVal, + sal_uInt8 nMemberId) override; + + virtual CntUInt32Item* Clone(SfxItemPool * = nullptr) const override; + + sal_uInt32 GetValue() const { return m_nValue; } + + inline void SetValue(sal_uInt32 nTheValue); +}; + +inline void CntUInt32Item::SetValue(sal_uInt32 nTheValue) +{ + DBG_ASSERT(GetRefCount() == 0, "CntUInt32Item::SetValue(): Pooled item"); + m_nValue = nTheValue; +} + +#endif // INCLUDED_SVL_CINTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/cjkoptions.hxx b/include/svl/cjkoptions.hxx new file mode 100644 index 000000000..9ac227541 --- /dev/null +++ b/include/svl/cjkoptions.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +namespace SvtCJKOptions +{ +enum EOption +{ + E_CJKFONT, + E_VERTICALTEXT, + E_ASIANTYPOGRAPHY, + E_JAPANESEFIND, + E_RUBY, + E_CHANGECASEMAP, + E_DOUBLELINES, + E_ALL // special one for IsAnyEnabled()/SetAll() functionality +}; + +SVL_DLLPUBLIC bool IsCJKFontEnabled(); +SVL_DLLPUBLIC bool IsVerticalTextEnabled(); +SVL_DLLPUBLIC bool IsAsianTypographyEnabled(); +SVL_DLLPUBLIC bool IsJapaneseFindEnabled(); +SVL_DLLPUBLIC bool IsRubyEnabled(); +SVL_DLLPUBLIC bool IsChangeCaseMapEnabled(); +SVL_DLLPUBLIC bool IsDoubleLinesEnabled(); + +SVL_DLLPUBLIC void SetAll(bool bSet); +SVL_DLLPUBLIC bool IsAnyEnabled(); +SVL_DLLPUBLIC bool IsReadOnly(EOption eOption); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/converter.hxx b/include/svl/converter.hxx new file mode 100644 index 000000000..7b2000c88 --- /dev/null +++ b/include/svl/converter.hxx @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_CONVERTER_HXX +#define INCLUDED_SVL_CONVERTER_HXX + +#include + +class SvDbaseConverter +{ +public: + SVL_DLLPUBLIC static sal_Int32 ConvertPrecisionToDbase(sal_Int32 _nLen, sal_Int32 _nScale); + SVL_DLLPUBLIC static sal_Int32 ConvertPrecisionToOdbc(sal_Int32 _nLen, sal_Int32 _nScale); +}; + +#endif //_CONVERTER_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/cryptosign.hxx b/include/svl/cryptosign.hxx new file mode 100644 index 000000000..3bb682916 --- /dev/null +++ b/include/svl/cryptosign.hxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include + +#include +#include + +#include +#include + +#include + +#include + +// Is this length truly the maximum possible, or just a number that +// seemed large enough when the author tested this (with some type of +// certificates)? I suspect the latter. + +// Used to be 0x4000 = 16384, but a sample signed PDF (produced by +// some other software) provided by the customer has a signature +// content that is 30000 bytes. The SampleSignedPDFDocument.pdf from +// Adobe has one that is 21942 bytes. So let's be careful. Pity this +// can't be dynamic, at least not without restructuring the code. Also +// note that the checks in the code for this being too small +// apparently are broken, if this overflows you end up with an invalid +// PDF. Need to fix that. + +#define MAX_SIGNATURE_CONTENT_LENGTH 50000 + +namespace com::sun::star::security { class XCertificate; } +class SvStream; +struct SignatureInformation; + +namespace svl::crypto { + +/// Converts a hex-encoded string into a byte array. +SVL_DLLPUBLIC std::vector DecodeHexString(std::string_view rHex); + +/// Helper to cryptographically sign and verify +/// arbitrary data blocks. +class SVL_DLLPUBLIC Signing +{ +public: + + Signing(css::uno::Reference xCertificate) : + m_xCertificate(std::move(xCertificate)) + { + } + + /// Add a range to sign. + /// Note: for efficiency this takes a naked pointer, which must remain valid + /// until this object is discarded. + void AddDataRange(const void* pData, sal_Int32 size) + { + m_dataBlocks.emplace_back(pData, size); + } + + void SetSignTSA(const OUString& tsa) { m_aSignTSA = tsa; } + void SetSignPassword(const OUString& password) { m_aSignPassword = password; } + + /// Signs one or more data blocks (as a single, contiguous, array). + /// Returns the signature (in PKCS#7 format) as string (hex). + bool Sign(OStringBuffer& rCMSHexBuffer); + + /// Verify and get Signature Information given a byte array. + static bool Verify(const std::vector& aData, + const bool bNonDetached, + const std::vector& aSignature, + SignatureInformation& rInformation); + + /// Verify and get Signature Information given a signature and stream. + static bool Verify(SvStream& rStream, + const std::vector>& aByteRanges, + const bool bNonDetached, + const std::vector& aSignature, + SignatureInformation& rInformation); + +private: + /// The certificate to use for signing. + const css::uno::Reference m_xCertificate; + + /// Data blocks (pointer-size pairs). + std::vector> m_dataBlocks; + OUString m_aSignTSA; + OUString m_aSignPassword; +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ + diff --git a/include/svl/ctloptions.hxx b/include/svl/ctloptions.hxx new file mode 100644 index 000000000..5140907dd --- /dev/null +++ b/include/svl/ctloptions.hxx @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_CTLOPTIONS_HXX +#define INCLUDED_SVL_CTLOPTIONS_HXX + +#include +#include +#include + +class SvtCTLOptions_Impl; + +// class SvtCTLOptions -------------------------------------------------------- + +class SVL_DLLPUBLIC SvtCTLOptions final : public utl::detail::Options +{ +private: + std::shared_ptr m_pImpl; + +public: + + // bDontLoad is for referencing purposes only + SvtCTLOptions( bool bDontLoad = false ); + virtual ~SvtCTLOptions() override; + + void SetCTLFontEnabled( bool _bEnabled ); + bool IsCTLFontEnabled() const; + + void SetCTLSequenceChecking( bool _bEnabled ); + bool IsCTLSequenceChecking() const; + + void SetCTLSequenceCheckingRestricted( bool _bEnable ); + bool IsCTLSequenceCheckingRestricted() const; + + void SetCTLSequenceCheckingTypeAndReplace( bool _bEnable ); + bool IsCTLSequenceCheckingTypeAndReplace() const; + + enum CursorMovement + { + MOVEMENT_LOGICAL = 0, + MOVEMENT_VISUAL + }; + void SetCTLCursorMovement( CursorMovement _eMovement ); + CursorMovement GetCTLCursorMovement() const; + + enum TextNumerals + { + NUMERALS_ARABIC = 0, + NUMERALS_HINDI, + NUMERALS_SYSTEM, + NUMERALS_CONTEXT + }; + void SetCTLTextNumerals( TextNumerals _eNumerals ); + TextNumerals GetCTLTextNumerals() const; + + enum EOption + { + E_CTLFONT, + E_CTLSEQUENCECHECKING, + E_CTLCURSORMOVEMENT, + E_CTLTEXTNUMERALS, + E_CTLSEQUENCECHECKINGRESTRICTED, + E_CTLSEQUENCECHECKINGTYPEANDREPLACE + }; + bool IsReadOnly(EOption eOption) const; +}; + +#endif // INCLUDED_SVL_CTLOPTIONS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/currencytable.hxx b/include/svl/currencytable.hxx new file mode 100644 index 000000000..a990ba4e0 --- /dev/null +++ b/include/svl/currencytable.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* +* This file is part of the LibreOffice project. +* +* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef INCLUDED_SVL_CURRENCYTABLE_HXX +#define INCLUDED_SVL_CURRENCYTABLE_HXX + +#include +#include + +#include + +class SVL_DLLPUBLIC NfCurrencyTable +{ + typedef std::vector DataType; + DataType maData; + + NfCurrencyTable(NfCurrencyTable const&) = delete; + void operator=(NfCurrencyTable const&) = delete; + +public: + NfCurrencyTable() {} + typedef DataType::iterator iterator; + typedef DataType::const_iterator const_iterator; + + iterator begin(); + + NfCurrencyEntry& operator[](size_t i); + const NfCurrencyEntry& operator[](size_t i) const; + + size_t size() const; + + void insert(const iterator& it, NfCurrencyEntry p); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/custritm.hxx b/include/svl/custritm.hxx new file mode 100644 index 000000000..90215aff4 --- /dev/null +++ b/include/svl/custritm.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_CUSTRITM_HXX +#define INCLUDED_SVL_CUSTRITM_HXX + +#include +#include +#include +#include + +class SVL_DLLPUBLIC CntUnencodedStringItem: public SfxPoolItem +{ + OUString m_aValue; + +public: + + CntUnencodedStringItem(sal_uInt16 which): SfxPoolItem(which) + {} + + CntUnencodedStringItem(sal_uInt16 which, OUString aTheValue): + SfxPoolItem(which), m_aValue(std::move(aTheValue)) + {} + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + virtual bool operator <(const SfxPoolItem & rItem) const override; + virtual bool IsSortable() const override { return true; } + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) const override; + + virtual bool QueryValue(css::uno::Any& rVal, + sal_uInt8 nMemberId = 0) const override; + + virtual bool PutValue(const css::uno::Any& rVal, sal_uInt8 nMemberId) override; + + virtual CntUnencodedStringItem* Clone(SfxItemPool * = nullptr) const override; + + const OUString & GetValue() const { return m_aValue; } + + inline void SetValue(const OUString & rTheValue); +}; + +inline void CntUnencodedStringItem::SetValue(const OUString & rTheValue) +{ + assert(GetRefCount() == 0 && "cannot modify name of pooled item"); + m_aValue = rTheValue; +} + +#endif // INCLUDED_SVL_CUSTRITM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/documentlockfile.hxx b/include/svl/documentlockfile.hxx new file mode 100644 index 000000000..b4f731db7 --- /dev/null +++ b/include/svl/documentlockfile.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_DOCUMENTLOCKFILE_HXX +#define INCLUDED_SVL_DOCUMENTLOCKFILE_HXX + +#include + +#include + +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::io { class XOutputStream; } + +namespace svt { + +/// Generalized class for LO and MSO lockfile handling. +class SVL_DLLPUBLIC GenDocumentLockFile : public LockFileCommon +{ +public: + GenDocumentLockFile(const OUString& aLockFileURL); + virtual ~GenDocumentLockFile() override; + + bool CreateOwnLockFile(); + bool OverwriteOwnLockFile(); + /// Delete the Lockfile, if current user is the owner + virtual void RemoveFile(); + /// Only delete lockfile, disregarding ownership + void RemoveFileDirectly(); + + virtual LockFileEntry GetLockData() = 0; + +protected: + virtual void WriteEntryToStream( const LockFileEntry& aEntry, const css::uno::Reference< css::io::XOutputStream >& xStream ) = 0; + virtual css::uno::Reference< css::io::XInputStream > OpenStream(); +}; + +/// Class implementing reading and writing LO lockfiles. +class SVL_DLLPUBLIC DocumentLockFile final : public GenDocumentLockFile +{ + virtual void WriteEntryToStream( const LockFileEntry& aEntry, const css::uno::Reference< css::io::XOutputStream >& xStream ) override; + +public: + DocumentLockFile( std::u16string_view aOrigURL ); + virtual ~DocumentLockFile() override; + + virtual LockFileEntry GetLockData() override; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/eitem.hxx b/include/svl/eitem.hxx new file mode 100644 index 000000000..114e451c0 --- /dev/null +++ b/include/svl/eitem.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_EITEM_HXX +#define INCLUDED_SVL_EITEM_HXX + +#include +#include + + +template +class SAL_DLLPUBLIC_RTTI SfxEnumItem : public SfxEnumItemInterface +{ + EnumT m_nValue; + +protected: + explicit SfxEnumItem(sal_uInt16 const nWhich, EnumT const nValue) + : SfxEnumItemInterface(nWhich) + , m_nValue(nValue) + { } + + SfxEnumItem(const SfxEnumItem &) = default; + +public: + + EnumT GetValue() const { return m_nValue; } + + void SetValue(EnumT nTheValue) + { + assert(GetRefCount() == 0 && "SfxEnumItem::SetValue(): Pooled item"); + m_nValue = nTheValue; + } + + virtual sal_uInt16 GetEnumValue() const override + { + return static_cast(GetValue()); + } + + virtual void SetEnumValue(sal_uInt16 nTheValue) override + { + SetValue(static_cast(nTheValue)); + } + + virtual bool operator==(SfxPoolItem const & other) const override + { + return SfxEnumItemInterface::operator==(other) && + m_nValue == static_cast &>(other).m_nValue; + } +}; + +class SVL_DLLPUBLIC SfxBoolItem + : public SfxPoolItem +{ + bool m_bValue; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SfxBoolItem(sal_uInt16 const nWhich = 0, bool const bValue = false) + : SfxPoolItem(nWhich) + , m_bValue(bValue) + { } + + bool GetValue() const { return m_bValue; } + + void SetValue(bool const bTheValue) { m_bValue = bTheValue; } + + // SfxPoolItem + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const override; + + virtual bool QueryValue(css::uno::Any& rVal, sal_uInt8 = 0) const override; + + virtual bool PutValue(const css::uno::Any& rVal, sal_uInt8) override; + + + virtual SfxBoolItem* Clone(SfxItemPool * = nullptr) const override; + + virtual OUString GetValueTextByVal(bool bTheValue) const; +}; + +#endif // INCLUDED_SVL_EITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/filenotation.hxx b/include/svl/filenotation.hxx new file mode 100644 index 000000000..d33e442b9 --- /dev/null +++ b/include/svl/filenotation.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_FILENOTATION_HXX +#define INCLUDED_SVL_FILENOTATION_HXX + +#include +#include + + +namespace svt +{ + + + //= OFileNotation + + class SVL_DLLPUBLIC OFileNotation final + { + public: + enum NOTATION + { + N_SYSTEM, + N_URL + }; + + OFileNotation( const OUString& _rUrlOrPath ); + OFileNotation( const OUString& _rUrlOrPath, NOTATION _eInputNotation ); + + OUString get(NOTATION _eOutputNotation) const; + + private: + SVL_DLLPRIVATE void construct( const OUString& _rUrlOrPath ); + SVL_DLLPRIVATE bool implInitWithSystemNotation( const OUString& _rSystemPath ); + SVL_DLLPRIVATE void implInitWithURLNotation( const OUString& _rURL ); + + OUString m_sSystem; + OUString m_sFileURL; + }; + + +} // namespace svt + + +#endif // INCLUDED_SVL_FILENOTATION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/flagitem.hxx b/include/svl/flagitem.hxx new file mode 100644 index 000000000..70b968f2c --- /dev/null +++ b/include/svl/flagitem.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_FLAGITEM_HXX +#define INCLUDED_SVL_FLAGITEM_HXX + +#include +#include +#include + +class SvStream; + +class SVL_DLLPUBLIC SfxFlagItem: public SfxPoolItem +{ + sal_uInt16 nVal; + +public: + + explicit SfxFlagItem( sal_uInt16 nWhich = 0, sal_uInt16 nValue = 0 ); + + virtual sal_uInt8 GetFlagCount() const; + + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual SfxFlagItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString & rText, + const IntlWrapper& ) const override; + sal_uInt16 GetValue() const { return nVal; } + void SetValue( sal_uInt16 nNewVal ) { + DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" ); + nVal = nNewVal; + } + bool GetFlag( sal_uInt8 nFlag ) const { return (nVal & ( 1< +#include + +class Date; +namespace tools { class Time; } + +namespace FStatHelper { + +/** Return the modified time and date stamp for this URL. + + @param URL the asking URL + + @param pDate if unequal 0, the function set the date stamp + + @param pTime if unequal 0, the function set the time stamp + + @return it was be able to get the date/time stamp +*/ +SVL_DLLPUBLIC bool GetModifiedDateTimeOfFile( const OUString& rURL, + Date* pDate, tools::Time* pTime ); + +/** Return if under the URL a document exist. This is only a wrapper for the + UCB.IsContent. +*/ +SVL_DLLPUBLIC bool IsDocument( const OUString& rURL ); + +/** Return if under the URL a folder exist. This is only a wrapper for the + UCB.isFolder. +*/ +SVL_DLLPUBLIC bool IsFolder( const OUString& rURL ); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/globalnameitem.hxx b/include/svl/globalnameitem.hxx new file mode 100644 index 000000000..edbb56273 --- /dev/null +++ b/include/svl/globalnameitem.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_GLOBALNAMEITEM_HXX +#define INCLUDED_SVL_GLOBALNAMEITEM_HXX + +#include +#include +#include + +class SVL_DLLPUBLIC SfxGlobalNameItem final : public SfxPoolItem +{ + SvGlobalName m_aName; + +public: + static SfxPoolItem* CreateDefault(); + + SfxGlobalNameItem(); + SfxGlobalNameItem( sal_uInt16 nWhich, const SvGlobalName& ); + virtual ~SfxGlobalNameItem() override; + + SfxGlobalNameItem(SfxGlobalNameItem const &) = default; + SfxGlobalNameItem(SfxGlobalNameItem &&) = default; + SfxGlobalNameItem & operator =(SfxGlobalNameItem const &) = delete; // due to SfxPoolItem + SfxGlobalNameItem & operator =(SfxGlobalNameItem &&) = delete; // due to SfxPoolItem + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxGlobalNameItem* Clone( SfxItemPool *pPool = nullptr ) const override; + const SvGlobalName& GetValue() const { return m_aName; } + + virtual bool PutValue ( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/grabbagitem.hxx b/include/svl/grabbagitem.hxx new file mode 100644 index 000000000..77a619aec --- /dev/null +++ b/include/svl/grabbagitem.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_SVL_GRABBAGITEM_HXX +#define INCLUDED_SVL_GRABBAGITEM_HXX + +#include + +#include +#include +#include + +/// Grab bag item provides a string-any map for keys with untyped values. +class SVL_DLLPUBLIC SfxGrabBagItem final : public SfxPoolItem +{ +private: + std::map m_aMap; + +public: + SfxGrabBagItem(); + SfxGrabBagItem(sal_uInt16 nWhich); + ~SfxGrabBagItem() override; + + SfxGrabBagItem(SfxGrabBagItem const&) = default; + SfxGrabBagItem(SfxGrabBagItem&&) = default; + SfxGrabBagItem& operator=(SfxGrabBagItem const&) = delete; // due to SfxPoolItem + SfxGrabBagItem& operator=(SfxGrabBagItem&&) = delete; // due to SfxPoolItem + + const std::map& GetGrabBag() const { return m_aMap; } + + std::map& GetGrabBag() { return m_aMap; } + + bool operator==(const SfxPoolItem& rItem) const override; + SfxGrabBagItem* Clone(SfxItemPool* pPool = nullptr) const override; + + bool PutValue(const css::uno::Any& rVal, sal_uInt8 nMemberId) override; + bool QueryValue(css::uno::Any& rVal, sal_uInt8 nMemberId = 0) const override; +}; +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/gridprinter.hxx b/include/svl/gridprinter.hxx new file mode 100644 index 000000000..e69d9f50c --- /dev/null +++ b/include/svl/gridprinter.hxx @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_GRIDPRINTER_HXX +#define INCLUDED_SVL_GRIDPRINTER_HXX + +#include +#include +#include + +namespace svl +{ +/** + * Print 2-dimensional data in a nice and pleasant fashion. Useful when + * debugging grid layout data. + */ +class SVL_DLLPUBLIC GridPrinter +{ + struct Impl; + std::unique_ptr mpImpl; + +public: + GridPrinter(size_t nRows, size_t nCols, bool bPrint); + ~GridPrinter(); + void set(size_t nRow, size_t nCol, const OUString& rStr); + void print(const char* pHeader) const; +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/hint.hxx b/include/svl/hint.hxx new file mode 100644 index 000000000..ba26bf7e0 --- /dev/null +++ b/include/svl/hint.hxx @@ -0,0 +1,225 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_HINT_HXX +#define INCLUDED_SVL_HINT_HXX + +#include +#include + +#include + +enum class SfxHintId { + NONE, + Dying, + NameChanged, + TitleChanged, + DataChanged, + DocChanged, + UpdateDone, + Deinitializing, + ModeChanged, + ColorsChanged, + LanguageChanged, + RedlineChanged, + DocumentRepair, + +// VCL text hints + TextParaInserted, + TextParaRemoved, + TextParaContentChanged, + TextHeightChanged, + TextFormatPara, + TextFormatted, + TextModified, + TextProcessNotifications, + TextViewScrolled, + TextViewSelectionChanged, + TextViewCaretChanged, + +// BASIC hints + BasicDataWanted, + BasicDataChanged, + BasicInfoWanted, + BasicStart, + BasicStop, + +// SVX edit source + EditSourceParasMoved, + EditSourceSelectionChanged, + +// SC hints + ScDataChanged, + ScTableOpDirty, + ScCalcAll, + ScReference, + ScDrawLayerNew, + ScDbAreasChanged, + ScAreasChanged, + ScTablesChanged, + ScDrawChanged, + ScDocNameChanged, + ScAreaLinksChanged, + ScShowRangeFinder, + ScDocSaved, + ScForceSetTab, + ScNavigatorUpdateAll, + ScAnyDataChanged, + ScPrintOptions, + ScRefModeChanged, + ScKillEditView, + ScKillEditViewNoPaint, + ScHiddenRowsChanged, + ScSelectionChanged, + ScClearCache, + +// SC accessibility hints + ScAccTableChanged, + ScAccCursorChanged, + ScAccVisAreaChanged, + ScAccEnterEditMode, + ScAccLeaveEditMode, + ScAccMakeDrawLayer, + ScAccWindowResized, + + +// SFX stylesheet + StyleSheetCreated, // new + StyleSheetModified, // changed + StyleSheetChanged, // erased and re-created (replaced) + StyleSheetErased, // erased + StyleSheetInDestruction, // in the process of being destructed + +// STARMATH + MathFormatChanged, + +// Sw + SwDrawViewsCreated, + SwSplitNodeOperation, + SwSectionFrameMoveAndDelete, + SwNavigatorUpdateTracking, + SwNavigatorSelectOutlinesWithSelections, + SwLegacyModify, + + ThisIsAnSdrHint // used to avoid dynamic_cast +}; + +template< typename charT, typename traits > +inline std::basic_ostream & operator <<( + std::basic_ostream & stream, const SfxHintId& id ) +{ + switch(id) + { + case SfxHintId::NONE: return stream << "NONE"; + case SfxHintId::Dying: return stream << "Dying"; + case SfxHintId::NameChanged: return stream << "NameChanged"; + case SfxHintId::TitleChanged: return stream << "TitleChanged"; + case SfxHintId::DataChanged: return stream << "DataChanged"; + case SfxHintId::DocChanged: return stream << "DocChanged"; + case SfxHintId::UpdateDone: return stream << "UpdateDone"; + case SfxHintId::Deinitializing: return stream << "Deinitializing"; + case SfxHintId::ModeChanged: return stream << "ModeChanged"; + case SfxHintId::ColorsChanged: return stream << "ColorsChanged"; + case SfxHintId::LanguageChanged: return stream << "LanguageChanged"; + case SfxHintId::RedlineChanged: return stream << "RedlineChanged"; + case SfxHintId::DocumentRepair: return stream << "DocumentRepair"; + case SfxHintId::TextParaInserted: return stream << "TextParaInserted"; + case SfxHintId::TextParaRemoved: return stream << "TextParaRemoved"; + case SfxHintId::TextParaContentChanged: return stream << "TextParaContentChanged"; + case SfxHintId::TextHeightChanged: return stream << "TextHeightChanged"; + case SfxHintId::TextFormatPara: return stream << "TextFormatPara"; + case SfxHintId::TextFormatted: return stream << "TextFormatted"; + case SfxHintId::TextModified: return stream << "TextModified"; + case SfxHintId::TextProcessNotifications: return stream << "TextProcessNotifications"; + case SfxHintId::TextViewScrolled: return stream << "TextViewScrolled"; + case SfxHintId::TextViewSelectionChanged: return stream << "TextViewSelectionChanged"; + case SfxHintId::TextViewCaretChanged: return stream << "TextViewCaretChanged"; + case SfxHintId::BasicDataWanted: return stream << "BasicDataWanted"; + case SfxHintId::BasicDataChanged: return stream << "BasicDataChanged"; + case SfxHintId::BasicInfoWanted: return stream << "BasicInfoWanted"; + case SfxHintId::BasicStart: return stream << "BasicStart"; + case SfxHintId::BasicStop: return stream << "BasicStop"; + case SfxHintId::EditSourceParasMoved: return stream << "EditSourceParasMoved"; + case SfxHintId::EditSourceSelectionChanged: return stream << "EditSourceSelectionChanged"; + case SfxHintId::ScDataChanged: return stream << "ScDataChanged"; + case SfxHintId::ScTableOpDirty: return stream << "ScTableOpDirty"; + case SfxHintId::ScCalcAll: return stream << "ScCalcAll"; + case SfxHintId::ScReference: return stream << "ScReference"; + case SfxHintId::ScDrawLayerNew: return stream << "ScDrawLayerNew"; + case SfxHintId::ScDbAreasChanged: return stream << "ScDbAreasChanged"; + case SfxHintId::ScAreasChanged: return stream << "ScAreasChanged"; + case SfxHintId::ScTablesChanged: return stream << "ScTablesChanged"; + case SfxHintId::ScDrawChanged: return stream << "ScDrawChanged"; + case SfxHintId::ScDocNameChanged: return stream << "ScDocNameChanged"; + case SfxHintId::ScAreaLinksChanged: return stream << "ScAreaLinksChanged"; + case SfxHintId::ScShowRangeFinder: return stream << "ScShowRangeFinder"; + case SfxHintId::ScDocSaved: return stream << "ScDocSaved"; + case SfxHintId::ScForceSetTab: return stream << "ScForceSetTab"; + case SfxHintId::ScNavigatorUpdateAll: return stream << "ScNavigatorUpdateAll"; + case SfxHintId::ScAnyDataChanged: return stream << "ScAnyDataChanged"; + case SfxHintId::ScPrintOptions: return stream << "ScPrintOptions"; + case SfxHintId::ScRefModeChanged: return stream << "ScRefModeChanged"; + case SfxHintId::ScKillEditView: return stream << "ScKillEditView"; + case SfxHintId::ScKillEditViewNoPaint: return stream << "ScKillEditViewNoPaint"; + case SfxHintId::ScHiddenRowsChanged: return stream << "ScHiddenRowsChanged"; + case SfxHintId::ScSelectionChanged: return stream << "ScSelectionChanged"; + case SfxHintId::ScClearCache: return stream << "ScClearCache"; + case SfxHintId::ScAccTableChanged: return stream << "ScAccTableChanged"; + case SfxHintId::ScAccCursorChanged: return stream << "ScAccCursorChanged"; + case SfxHintId::ScAccVisAreaChanged: return stream << "ScAccVisAreaChanged"; + case SfxHintId::ScAccEnterEditMode: return stream << "ScAccEnterEditMode"; + case SfxHintId::ScAccLeaveEditMode: return stream << "ScAccLeaveEditMode"; + case SfxHintId::ScAccMakeDrawLayer: return stream << "ScAccMakeDrawLayer"; + case SfxHintId::ScAccWindowResized: return stream << "ScAccWindowResized"; + case SfxHintId::StyleSheetCreated: return stream << "StyleSheetCreated"; + case SfxHintId::StyleSheetModified: return stream << "StyleSheetModified"; + case SfxHintId::StyleSheetChanged: return stream << "StyleSheetChanged"; + case SfxHintId::StyleSheetErased: return stream << "StyleSheetErased"; + case SfxHintId::StyleSheetInDestruction: return stream << "StyleSheetInDestruction"; + case SfxHintId::MathFormatChanged: return stream << "MathFormatChanged"; + case SfxHintId::SwDrawViewsCreated: return stream << "SwDrawViewsCreated"; + case SfxHintId::SwSplitNodeOperation: return stream << "SwSplitNodeOperation"; + case SfxHintId::SwSectionFrameMoveAndDelete: return stream << "SwSectionFrameMoveAndDelete"; + case SfxHintId::SwNavigatorUpdateTracking: return stream << "SwNavigatorUpdateTracking"; + case SfxHintId::SwNavigatorSelectOutlinesWithSelections: + return stream << "SwNavigatorSelectOutlinesWithSelections"; + case SfxHintId::ThisIsAnSdrHint: return stream << "SdrHint"; + default: return stream << "unk(" << std::to_string(int(id)) << ")"; + } +} + +class SVL_DLLPUBLIC SfxHint +{ +private: + SfxHintId mnId; +public: + SfxHint() : mnId(SfxHintId::NONE) {} + explicit SfxHint( SfxHintId nId ) : mnId(nId) {} + virtual ~SfxHint() {}; + + SfxHint(SfxHint const &) = default; + SfxHint(SfxHint &&) = default; + SfxHint & operator =(SfxHint const &) = default; + SfxHint & operator =(SfxHint &&) = default; + + SfxHintId GetId() const { return mnId; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/ilstitem.hxx b/include/svl/ilstitem.hxx new file mode 100644 index 000000000..bb49d18c9 --- /dev/null +++ b/include/svl/ilstitem.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_ILSTITEM_HXX +#define INCLUDED_SVL_ILSTITEM_HXX + +#include +#include +#include + +namespace com::sun::star::uno { template class Sequence; } + +class SVL_DLLPUBLIC SfxIntegerListItem final : public SfxPoolItem +{ + std::vector < sal_Int32 > m_aList; + +public: + static SfxPoolItem* CreateDefault(); + SfxIntegerListItem(); + SfxIntegerListItem( sal_uInt16 nWhich, std::vector < sal_Int32 >&& rList ); + SfxIntegerListItem( sal_uInt16 nWhich, const css::uno::Sequence < sal_Int32 >& rList ); + virtual ~SfxIntegerListItem() override; + + SfxIntegerListItem(SfxIntegerListItem const &) = default; + SfxIntegerListItem(SfxIntegerListItem &&) = default; + SfxIntegerListItem & operator =(SfxIntegerListItem const &) = delete; // due to SfxPoolItem + SfxIntegerListItem & operator =(SfxIntegerListItem &&) = delete; // due to SfxPoolItem + + const std::vector< sal_Int32 >& GetList() const { return m_aList; } + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxIntegerListItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool PutValue ( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; +}; + +#endif // INCLUDED_SVL_ILSTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/imageitm.hxx b/include/svl/imageitm.hxx new file mode 100644 index 000000000..f06eb7fd6 --- /dev/null +++ b/include/svl/imageitm.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_IMAGEITM_HXX +#define INCLUDED_SVL_IMAGEITM_HXX + +#include +#include +#include + +struct SfxImageItem_Impl; +class SVL_DLLPUBLIC SfxImageItem final : public SfxInt16Item +{ +public: + static SfxPoolItem* CreateDefault(); + SfxImageItem( sal_uInt16 nWhich = 0 ); + SfxImageItem( const SfxImageItem& ); + virtual ~SfxImageItem() override; + + virtual SfxImageItem* Clone( SfxItemPool* pPool = nullptr ) const override; + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + void SetRotation( Degree10 nValue ) { mnAngle = nValue; } + Degree10 GetRotation() const { return mnAngle; } + void SetMirrored( bool bSet ) { mbMirrored = bSet; } + bool IsMirrored() const { return mbMirrored; } + +private: + OUString maURL; + Degree10 mnAngle; + bool mbMirrored; +}; + +#endif // _SFX_IMAGEITM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/inethist.hxx b/include/svl/inethist.hxx new file mode 100644 index 000000000..9f88fd84b --- /dev/null +++ b/include/svl/inethist.hxx @@ -0,0 +1,99 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_INETHIST_HXX +#define INCLUDED_SVL_INETHIST_HXX + +#include +#include +#include +#include +#include + +class INetURLHistory_Impl; +class SVL_DLLPUBLIC INetURLHistory final : public SfxBroadcaster +{ + /** Representation. + */ + std::unique_ptr m_pImpl; + + /** Construction/Destruction. + */ + SAL_DLLPRIVATE INetURLHistory(); + SAL_DLLPRIVATE virtual ~INetURLHistory() override; + + /** Implementation. + */ + SAL_DLLPRIVATE static void NormalizeUrl_Impl (INetURLObject &rUrl); + + void PutUrl_Impl (const INetURLObject &rUrl); + bool QueryUrl_Impl (INetURLObject rUrl) const; + + /** Not implemented. + */ + INetURLHistory (const INetURLHistory&) = delete; + INetURLHistory& operator= (const INetURLHistory&) = delete; + +public: + /** GetOrCreate. + */ + static INetURLHistory* GetOrCreate(); + + /** QueryProtocol. + */ + bool QueryProtocol (INetProtocol eProto) const + { + return ((eProto == INetProtocol::File ) || + (eProto == INetProtocol::Ftp ) || + (eProto == INetProtocol::Http ) || + (eProto == INetProtocol::Https) ); + } + + /** QueryUrl. + */ + bool QueryUrl (const INetURLObject &rUrl) const + { + if (QueryProtocol (rUrl.GetProtocol())) + return QueryUrl_Impl (rUrl); + else + return false; + } + + bool QueryUrl (std::u16string_view rUrl) const; + + /** PutUrl. + */ + void PutUrl (const INetURLObject &rUrl) + { + if (QueryProtocol (rUrl.GetProtocol())) + PutUrl_Impl (rUrl); + } +}; + +// broadcasted from PutUrl(). +class SVL_DLLPUBLIC INetURLHistoryHint final : public SfxHint +{ + const INetURLObject* pObj; +public: + explicit INetURLHistoryHint( const INetURLObject* Object ) : pObj(Object) {} + const INetURLObject* GetObject() const { return pObj; } +}; + +#endif // INCLUDED_SVL_INETHIST_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/inettype.hxx b/include/svl/inettype.hxx new file mode 100644 index 000000000..ea955437e --- /dev/null +++ b/include/svl/inettype.hxx @@ -0,0 +1,263 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_INETTYPE_HXX +#define INCLUDED_SVL_INETTYPE_HXX + +#include +#include + +/** Definitions for frequently used media type names. + */ +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_OCTSTREAM = u"application/octet-stream"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_PDF = u"application/pdf"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_RTF = u"application/rtf"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_CALC + = u"application/vnd.stardivision.calc"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_CHART + = u"application/vnd.stardivision.chart"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_DRAW + = u"application/vnd.stardivision.draw"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_IMAGE + = u"application/vnd.stardivision.image"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_IMPRESSPACKED + = u"application/vnd.stardivision.impress-packed"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_IMPRESS + = u"application/vnd.stardivision.impress"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_MAIL + = u"application/vnd.stardivision.mail"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_MATH + = u"application/vnd.stardivision.math"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_NEWS + = u"application/vnd.stardivision.news"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_OUTTRAY + = u"application/vnd.stardivision.outtray"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_TEMPLATE + = u"application/vnd.stardivision.template"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_WRITER_GLOBAL + = u"application/vnd.stardivision.writer-global"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_WRITER_WEB + = u"application/vnd.stardivision.writer-web"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_WRITER + = u"application/vnd.stardivision.writer"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_FRAMESET = u"application/x-frameset"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_GALLERY_THEME + = u"application/x-gallery-theme"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_GALLERY = u"application/x-gallery"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_JAR = u"application/x-jar"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MACRO = u"application/x-macro"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MSEXCEL_TEMPL + = u"application/x-msexcel-template"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MSEXCEL = u"application/x-msexcel"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MSPPOINT_TEMPL + = u"application/x-mspowerpoint-template"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MSPPOINT = u"application/x-mspowerpoint"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MSWORD_TEMPL + = u"application/x-msword-template"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_MSWORD = u"application/x-msword"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARCALC = u"application/x-starcalc"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARCHART = u"application/x-starchart;"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARDRAW = u"application/x-stardraw"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARHELP = u"application/x-starhelp"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARIMAGE = u"application/x-starimage"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARIMPRESS = u"application/x-starimpress"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARMAIL_SDM = u"application/x-starmail-sdm"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARMAIL_SMD = u"application/x-starmail-smd"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARMATH = u"application/x-starmath"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARWRITER_GLOB + = u"application/x-starwriter-global"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_STARWRITER = u"application/x-starwriter"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_CDE_CALENDAR_APP + = u"application/x-sun-ae-file"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_ZIP = u"application/x-zip-compressed"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_AUDIO_AIFF = u"audio/aiff"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_AUDIO_BASIC = u"audio/basic"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_AUDIO_MIDI = u"audio/midi"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_AUDIO_VORBIS = u"audio/vorbis"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_AUDIO_WAV = u"audio/wav"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_AUDIO_WEBM = u"audio/webm"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_X_CNT_FSYSBOX = u".chaos/fsys-box"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_X_CNT_FSYSFOLDER = u".chaos/fsys-folder"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_X_CNT_FSYSSPECIALFOLDER + = u".chaos/fsys-special-folder"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_GENERIC = u"image/generic"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_GIF = u"image/gif"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_JPEG = u"image/jpeg"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_PCX = u"image/pcx"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_PNG = u"image/png"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_TIFF = u"image/tiff"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_BMP = u"image/x-MS-bmp"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_IMAGE_WEBP = u"image/webp"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_INET_MSG_RFC822 = u"message/rfc822"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_INET_MULTI_ALTERNATIVE = u"multipart/alternative"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_INET_MULTI_DIGEST = u"multipart/digest"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_INET_MULTI_MIXED = u"multipart/mixed"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_INET_MULTI_PARALLEL = u"multipart/parallel"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_INET_MULTI_RELATED = u"multipart/related"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_ICALENDAR = u"text/calendar"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_HTML = u"text/html"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_PLAIN = u"text/plain"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_XMLICALENDAR = u"text/x-icalxml"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_URL = u"text/x-url"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_VCALENDAR = u"text/x-vCalendar"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_TEXT_VCARD = u"text/x-vCard"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_VIDEO_MSVIDEO = u"video/x-msvideo"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_VIDEO_THEORA = u"video/theora"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_VIDEO_VDO = u"video/vdo"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_VIDEO_WEBM = u"audio/webm"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_X_STARMAIL = u"x-starmail"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_X_VRML = u"x-world/x-vrml"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_WRITER + = u"application/vnd.sun.xml.writer"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_CALC + = u"application/vnd.sun.xml.calc"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_IMPRESS + = u"application/vnd.sun.xml.impress"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_DRAW + = u"application/vnd.sun.xml.draw"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_CHART + = u"application/vnd.sun.xml.chart"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_MATH + = u"application/vnd.sun.xml.math"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_WRITER_GLOBAL + = u"application/vnd.sun.xml.writer-global"; +inline constexpr OUStringLiteral CONTENT_TYPE_STR_APP_VND_SUN_XML_IMPRESSPACKED + = u"application/vnd.sun.xml.impress-packed"; + +/** Definitions for matching parts of URIs. + */ +#define INETTYPE_URL_PROT_DATA "data" +#define INETTYPE_URL_PROT_FILE "file" +#define INETTYPE_URL_PROT_HTTP "http" +#define INETTYPE_URL_PROT_HTTPS "https" +#define INETTYPE_URL_PROT_MACRO "macro" +#define INETTYPE_URL_PROT_MAILTO "mailto" +#define INETTYPE_URL_PROT_PRIVATE "private" + +enum INetContentType +{ + CONTENT_TYPE_UNKNOWN, + CONTENT_TYPE_APP_OCTSTREAM, + CONTENT_TYPE_APP_PDF, + CONTENT_TYPE_APP_RTF, + CONTENT_TYPE_APP_MSWORD, + CONTENT_TYPE_APP_MSWORD_TEMPL, + CONTENT_TYPE_APP_STARCALC, + CONTENT_TYPE_APP_STARCHART, + CONTENT_TYPE_APP_STARDRAW, + CONTENT_TYPE_APP_STARHELP, + CONTENT_TYPE_APP_STARIMAGE, + CONTENT_TYPE_APP_STARIMPRESS, + CONTENT_TYPE_APP_STARMATH, + CONTENT_TYPE_APP_STARWRITER, + CONTENT_TYPE_APP_ZIP, + CONTENT_TYPE_AUDIO_AIFF, + CONTENT_TYPE_AUDIO_BASIC, + CONTENT_TYPE_AUDIO_MIDI, + CONTENT_TYPE_AUDIO_VORBIS, + CONTENT_TYPE_AUDIO_WAV, + CONTENT_TYPE_AUDIO_WEBM, + CONTENT_TYPE_IMAGE_GIF, + CONTENT_TYPE_IMAGE_JPEG, + CONTENT_TYPE_IMAGE_PCX, + CONTENT_TYPE_IMAGE_PNG, + CONTENT_TYPE_IMAGE_TIFF, + CONTENT_TYPE_IMAGE_BMP, + CONTENT_TYPE_IMAGE_WEBP, + CONTENT_TYPE_TEXT_HTML, + CONTENT_TYPE_TEXT_PLAIN, + CONTENT_TYPE_TEXT_URL, + CONTENT_TYPE_TEXT_VCARD, + CONTENT_TYPE_VIDEO_MSVIDEO, + CONTENT_TYPE_VIDEO_THEORA, + CONTENT_TYPE_VIDEO_VDO, + CONTENT_TYPE_VIDEO_WEBM, + CONTENT_TYPE_X_CNT_FSYSBOX, + CONTENT_TYPE_X_CNT_FSYSFOLDER, + CONTENT_TYPE_X_STARMAIL, + CONTENT_TYPE_X_VRML, + CONTENT_TYPE_APP_GALLERY, + CONTENT_TYPE_APP_GALLERY_THEME, + CONTENT_TYPE_APP_STARWRITER_GLOB, + CONTENT_TYPE_APP_STARMAIL_SDM, + CONTENT_TYPE_APP_STARMAIL_SMD, + CONTENT_TYPE_APP_VND_CALC, + CONTENT_TYPE_APP_VND_CHART, + CONTENT_TYPE_APP_VND_DRAW, + CONTENT_TYPE_APP_VND_IMAGE, + CONTENT_TYPE_APP_VND_IMPRESS, + CONTENT_TYPE_APP_VND_MAIL, + CONTENT_TYPE_APP_VND_MATH, + CONTENT_TYPE_APP_VND_WRITER, + CONTENT_TYPE_APP_VND_WRITER_GLOBAL, + CONTENT_TYPE_APP_VND_WRITER_WEB, + CONTENT_TYPE_APP_FRAMESET, + CONTENT_TYPE_APP_MACRO, + CONTENT_TYPE_X_CNT_FSYSSPECIALFOLDER, + CONTENT_TYPE_APP_VND_TEMPLATE, + CONTENT_TYPE_IMAGE_GENERIC, + CONTENT_TYPE_APP_VND_NEWS, + CONTENT_TYPE_APP_VND_OUTTRAY, + CONTENT_TYPE_APP_MSEXCEL, + CONTENT_TYPE_APP_MSEXCEL_TEMPL, + CONTENT_TYPE_APP_MSPPOINT, + CONTENT_TYPE_APP_MSPPOINT_TEMPL, + CONTENT_TYPE_TEXT_VCALENDAR, + CONTENT_TYPE_TEXT_ICALENDAR, + CONTENT_TYPE_TEXT_XMLICALENDAR, + CONTENT_TYPE_APP_CDE_CALENDAR_APP, + CONTENT_TYPE_INET_MESSAGE_RFC822, + CONTENT_TYPE_INET_MULTIPART_ALTERNATIVE, + CONTENT_TYPE_INET_MULTIPART_DIGEST, + CONTENT_TYPE_INET_MULTIPART_PARALLEL, + CONTENT_TYPE_INET_MULTIPART_RELATED, + CONTENT_TYPE_INET_MULTIPART_MIXED, + CONTENT_TYPE_APP_VND_IMPRESSPACKED, + CONTENT_TYPE_APP_JAR, + CONTENT_TYPE_APP_VND_SUN_XML_WRITER, + CONTENT_TYPE_APP_VND_SUN_XML_CALC, + CONTENT_TYPE_APP_VND_SUN_XML_IMPRESS, + CONTENT_TYPE_APP_VND_SUN_XML_DRAW, + CONTENT_TYPE_APP_VND_SUN_XML_CHART, + CONTENT_TYPE_APP_VND_SUN_XML_MATH, + CONTENT_TYPE_APP_VND_SUN_XML_WRITER_GLOBAL, + CONTENT_TYPE_APP_VND_SUN_XML_IMPRESSPACKED, + CONTENT_TYPE_LAST = CONTENT_TYPE_APP_VND_SUN_XML_IMPRESSPACKED +}; + +class SVL_DLLPUBLIC INetContentTypes +{ +public: + static INetContentType GetContentType(OUString const& rTypeName); + + static OUString GetContentType(INetContentType eTypeID); + + static INetContentType GetContentType4Extension(OUString const& rExtension); + + static INetContentType GetContentTypeFromURL(OUString const& rURL); + + static bool GetExtensionFromURL(std::u16string_view rURL, OUString& rExtension); + + static bool parse(OUString const& rMediaType, OUString& rType, OUString& rSubType, + INetContentTypeParameterList* pParameters = nullptr); +}; + +#endif // INCLUDED_SVL_INETTYPE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/instrm.hxx b/include/svl/instrm.hxx new file mode 100644 index 000000000..66f30a107 --- /dev/null +++ b/include/svl/instrm.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_INSTRM_HXX +#define INCLUDED_SVL_INSTRM_HXX + +#include +#include +#include +#include + +namespace com::sun::star::io { + class XInputStream; + class XSeekable; +} + +class SvDataPipe_Impl; + + +class SVL_DLLPUBLIC SvInputStream final : public SvStream +{ + css::uno::Reference< css::io::XInputStream > m_xStream; + css::uno::Reference< css::io::XSeekable > m_xSeekable; + std::unique_ptr m_pPipe; + sal_uInt64 m_nSeekedFrom; + + SVL_DLLPRIVATE bool open(); + + SVL_DLLPRIVATE virtual std::size_t GetData(void * pData, std::size_t nSize) override; + + SVL_DLLPRIVATE virtual std::size_t PutData(void const *, std::size_t) override; + + SVL_DLLPRIVATE virtual sal_uInt64 SeekPos(sal_uInt64 nPos) override; + + SVL_DLLPRIVATE virtual void FlushData() override; + + SVL_DLLPRIVATE virtual void SetSize(sal_uInt64) override; + +public: + SvInputStream( css::uno::Reference< css::io::XInputStream > xTheStream ); + + virtual ~SvInputStream() override; +}; + +#endif // INCLUDED_SVL_INSTRM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/int64item.hxx b/include/svl/int64item.hxx new file mode 100644 index 000000000..70a502c64 --- /dev/null +++ b/include/svl/int64item.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_INT64ITEM_HXX +#define INCLUDED_SVL_INT64ITEM_HXX + +#include +#include + +class SVL_DLLPUBLIC SfxInt64Item final : public SfxPoolItem +{ + sal_Int64 mnValue; + +public: + SfxInt64Item( sal_uInt16 nWhich, sal_Int64 nVal ); + + virtual ~SfxInt64Item() override; + + SfxInt64Item(SfxInt64Item const &) = default; + SfxInt64Item(SfxInt64Item &&) = default; + SfxInt64Item & operator =(SfxInt64Item const &) = delete; // due to SfxPoolItem; + SfxInt64Item & operator =(SfxInt64Item &&) = delete; // due to SfxPoolItem + + virtual bool operator== ( const SfxPoolItem& rItem ) const override; + + virtual bool GetPresentation( + SfxItemPresentation, MapUnit, MapUnit, + OUString& rText, const IntlWrapper& rIntlWrapper ) const override; + + virtual bool QueryValue( + css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + + virtual bool PutValue( + const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + + virtual SfxInt64Item* Clone( SfxItemPool* pOther = nullptr ) const override; + + sal_Int64 GetValue() const { return mnValue;} + +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/intitem.hxx b/include/svl/intitem.hxx new file mode 100644 index 000000000..92999568b --- /dev/null +++ b/include/svl/intitem.hxx @@ -0,0 +1,130 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_INTITEM_HXX +#define INCLUDED_SVL_INTITEM_HXX + +#include +#include +#include + + +class SVL_DLLPUBLIC SfxByteItem: public CntByteItem +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SfxByteItem(sal_uInt16 which = 0, sal_uInt8 nValue = 0): + CntByteItem(which, nValue) {} + + virtual SfxByteItem* Clone(SfxItemPool * = nullptr) const override + { return new SfxByteItem(*this); } +}; + +class SVL_DLLPUBLIC SfxInt16Item: public SfxPoolItem +{ + sal_Int16 m_nValue; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SfxInt16Item(sal_uInt16 which = 0, sal_Int16 nTheValue = 0): + SfxPoolItem(which), m_nValue(nTheValue) + {} + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, + MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual boost::property_tree::ptree dumpAsJSON() const override; + + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; + + virtual bool PutValue( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; + + virtual SfxInt16Item* Clone(SfxItemPool * = nullptr) const override; + + sal_Int16 GetValue() const { return m_nValue; } + + inline void SetValue(sal_Int16 nTheValue); +}; + +inline void SfxInt16Item::SetValue(sal_Int16 nTheValue) +{ + DBG_ASSERT(GetRefCount() == 0, "SfxInt16Item::SetValue(); Pooled item"); + m_nValue = nTheValue; +} + + +class SVL_DLLPUBLIC SfxUInt16Item: public CntUInt16Item +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SfxUInt16Item(sal_uInt16 which = 0, sal_uInt16 nValue = 0): + CntUInt16Item(which, nValue) {} + + virtual SfxUInt16Item* Clone(SfxItemPool * = nullptr) const override + { return new SfxUInt16Item(*this); } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + virtual boost::property_tree::ptree dumpAsJSON() const override; +}; + + +class SVL_DLLPUBLIC SfxInt32Item: public CntInt32Item +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SfxInt32Item(sal_uInt16 which = 0, sal_Int32 nValue = 0): + CntInt32Item(which, nValue) {} + + virtual SfxInt32Item* Clone(SfxItemPool * = nullptr) const override + { return new SfxInt32Item(*this); } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + virtual boost::property_tree::ptree dumpAsJSON() const override; +}; + + +class SVL_DLLPUBLIC SfxUInt32Item: public CntUInt32Item +{ +public: + static SfxPoolItem* CreateDefault(); + + explicit SfxUInt32Item(sal_uInt16 which = 0, sal_uInt32 nValue = 0): + CntUInt32Item(which, nValue) {} + + virtual SfxUInt32Item* Clone(SfxItemPool * = nullptr) const override + { return new SfxUInt32Item(*this); } + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + virtual boost::property_tree::ptree dumpAsJSON() const override; +}; + +#endif // INCLUDED_SVL_INTITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/isethint.hxx b/include/svl/isethint.hxx new file mode 100644 index 000000000..89dbc3b71 --- /dev/null +++ b/include/svl/isethint.hxx @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_ISETHINT_HXX +#define INCLUDED_SVL_ISETHINT_HXX + +#include +#include +#include + + +class SVL_DLLPUBLIC SfxItemSetHint final : public SfxHint +{ + SfxItemSet maItemSet; + +public: + SfxItemSetHint( const SfxItemSet &rItemSet ); + virtual ~SfxItemSetHint() override; + + const SfxItemSet& GetItemSet() const { return maItemSet; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/itemiter.hxx b/include/svl/itemiter.hxx new file mode 100644 index 000000000..13cf14b61 --- /dev/null +++ b/include/svl/itemiter.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_ITEMITER_HXX +#define INCLUDED_SVL_ITEMITER_HXX + +#include +#include + +class SfxPoolItem; + +class SVL_DLLPUBLIC SfxItemIter +{ + const SfxItemSet& m_rSet; + sal_uInt16 m_nStart; + sal_uInt16 m_nEnd; + sal_uInt16 m_nCurrent; + +public: + SfxItemIter(const SfxItemSet& rSet); + + /// get item, or null if no items + const SfxPoolItem* GetCurItem() const + { + return m_rSet.m_nCount ? *(m_rSet.m_ppItems + m_nCurrent) : nullptr; + } + const SfxPoolItem* NextItem() { return (m_nCurrent < m_nEnd) ? ImplNextItem() : nullptr; } + + bool IsAtEnd() const { return m_nCurrent == m_nEnd; } + + sal_uInt16 GetCurPos() const { return m_nCurrent; } + sal_uInt16 GetFirstPos() const { return m_nStart; } + sal_uInt16 GetLastPos() const { return m_nEnd; } + + SfxItemState GetItemState(bool bSrchInParent = true, + const SfxPoolItem** ppItem = nullptr) const; + void ClearItem(); + +private: + const SfxPoolItem* ImplNextItem(); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/itempool.hxx b/include/svl/itempool.hxx new file mode 100644 index 000000000..e85451ecb --- /dev/null +++ b/include/svl/itempool.hxx @@ -0,0 +1,228 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SfxBroadcaster; +struct SfxItemPool_Impl; + +struct SfxItemInfo +{ + sal_uInt16 _nSID; + bool _bPoolable; +}; + +class SfxItemPool; + +/** Base class for providers of defaults of SfxPoolItems. + * + * The derived classes hold the concrete (const) instances which are referenced in several places + * (usually within a single document). + * This helps to lower the amount of calls to lifecycle methods, speeds up comparisons within a document + * and facilitates loading and saving of attributes. + */ +class SVL_DLLPUBLIC SfxItemPool : public salhelper::SimpleReferenceObject +{ + friend struct SfxItemPool_Impl; + friend class SfxItemSet; + friend class SfxAllItemSet; + + const SfxItemInfo* pItemInfos; + std::unique_ptr pImpl; + +private: + sal_uInt16 GetIndex_Impl(sal_uInt16 nWhich) const; + sal_uInt16 GetSize_Impl() const; + + SVL_DLLPRIVATE bool IsItemPoolable_Impl( sal_uInt16 nWhich ) const; + +public: + // for default SfxItemSet::CTOR, set default WhichRanges + void FillItemIdRanges_Impl( WhichRangesContainer& pWhichRanges ) const; + const WhichRangesContainer & GetFrozenIdRanges() const; + +protected: + static inline void ClearRefCount(SfxPoolItem& rItem); + static inline void AddRef(const SfxPoolItem& rItem); + static inline sal_uInt32 ReleaseRef(const SfxPoolItem& rItem, sal_uInt32 n = 1); + +public: + SfxItemPool( const SfxItemPool &rPool, + bool bCloneStaticDefaults = false ); + SfxItemPool( const OUString &rName, + sal_uInt16 nStart, sal_uInt16 nEnd, + const SfxItemInfo *pItemInfos, + std::vector *pDefaults = nullptr ); + +public: + virtual ~SfxItemPool(); + + SfxBroadcaster& BC(); + + void SetPoolDefaultItem( const SfxPoolItem& ); + + const SfxPoolItem* GetPoolDefaultItem( sal_uInt16 nWhich ) const; + template const T* GetPoolDefaultItem( TypedWhichId nWhich ) const + { return static_cast(GetPoolDefaultItem(sal_uInt16(nWhich))); } + + void ResetPoolDefaultItem( sal_uInt16 nWhich ); + + void SetDefaults(std::vector* pDefaults); + void ClearDefaults(); + void ReleaseDefaults( bool bDelete = false ); + static void ReleaseDefaults( std::vector *pDefaults, bool bDelete = false ); + + virtual MapUnit GetMetric( sal_uInt16 nWhich ) const; + void SetDefaultMetric( MapUnit eNewMetric ); + MapUnit GetDefaultMetric() const; + + /** Request string representation of pool items. + + This virtual function produces a string representation + from the respective SfxItemPool subclass' known SfxPoolItems. + + Subclasses, please override this method, and handle + SfxPoolItems that don't return useful/complete information on + SfxPoolItem::GetPresentation() + + This baseclass yields the unmodified string representation of + rItem. + + @param[in] rItem + SfxPoolItem to query the string representation of + + @param[in] ePresent + requested kind of representation - see SfxItemPresentation + + @param[in] eMetric + requested unit of measure of the representation + + @param[out] rText + string representation of 'rItem' + + @return true if it has a valid string representation + */ + virtual bool GetPresentation( const SfxPoolItem& rItem, + MapUnit ePresentationMetric, + OUString& rText, + const IntlWrapper& rIntlWrapper ) const; + virtual rtl::Reference Clone() const; + const OUString& GetName() const; + + template const T& Put( std::unique_ptr xItem, sal_uInt16 nWhich = 0 ) + { return static_cast(PutImpl( *xItem.release(), nWhich, /*bPassingOwnership*/true)); } + template const T& Put( const T& rItem, sal_uInt16 nWhich = 0 ) + { return static_cast(PutImpl( rItem, nWhich, /*bPassingOwnership*/false)); } + void Remove( const SfxPoolItem& ); + + const SfxPoolItem& GetDefaultItem( sal_uInt16 nWhich ) const; + template const T& GetDefaultItem( TypedWhichId nWhich ) const + { return static_cast(GetDefaultItem(sal_uInt16(nWhich))); } + + bool CheckItemInPool(const SfxPoolItem *) const; + + struct Item2Range + { + o3tl::sorted_vector::const_iterator m_begin; + o3tl::sorted_vector::const_iterator m_end; + o3tl::sorted_vector::const_iterator const & begin() const { return m_begin; } + o3tl::sorted_vector::const_iterator const & end() const { return m_end; } + }; + const SfxPoolItem * GetItem2Default(sal_uInt16 nWhich) const; + template const T* GetItem2Default( TypedWhichId nWhich ) const + { return static_cast(GetItem2Default(sal_uInt16(nWhich))); } + + sal_uInt32 GetItemCount2(sal_uInt16 nWhich) const; + Item2Range GetItemSurrogates(sal_uInt16 nWhich) const; + /* + This is only valid for SfxPoolItem that override IsSortable and operator<. + Returns a range of items defined by using operator<. + @param rNeedle must be the same type or a supertype of the pool items for nWhich. + */ + std::vector FindItemSurrogate(sal_uInt16 nWhich, SfxPoolItem const & rNeedle) const; + + sal_uInt16 GetFirstWhich() const; + sal_uInt16 GetLastWhich() const; + bool IsInRange( sal_uInt16 nWhich ) const; + void SetSecondaryPool( SfxItemPool *pPool ); + SfxItemPool* GetSecondaryPool() const; + /* get the last pool by following the GetSecondaryPool chain */ + SfxItemPool* GetLastPoolInChain(); + SfxItemPool* GetMasterPool() const; + void FreezeIdRanges(); + + void Delete(); + + bool IsItemPoolable( sal_uInt16 nWhich ) const; + bool IsItemPoolable( const SfxPoolItem &rItem ) const + { return IsItemPoolable( rItem.Which() ); } + void SetItemInfos( const SfxItemInfo *pInfos ); + sal_uInt16 GetWhich( sal_uInt16 nSlot, bool bDeep = true ) const; + template + TypedWhichId GetWhich( TypedWhichId nSlot, bool bDeep = true ) const + { return TypedWhichId(GetWhich(sal_uInt16(nSlot), bDeep)); } + sal_uInt16 GetSlotId( sal_uInt16 nWhich ) const; + sal_uInt16 GetTrueWhich( sal_uInt16 nSlot, bool bDeep = true ) const; + sal_uInt16 GetTrueSlotId( sal_uInt16 nWhich ) const; + + static bool IsWhich(sal_uInt16 nId) { + return nId && nId <= SFX_WHICH_MAX; } + static bool IsSlot(sal_uInt16 nId) { + return nId && nId > SFX_WHICH_MAX; } + + void dumpAsXml(xmlTextWriterPtr pWriter) const; + +protected: + virtual const SfxPoolItem& PutImpl( const SfxPoolItem&, sal_uInt16 nWhich = 0, bool bPassingOwnership = false ); +private: + const SfxItemPool& operator=(const SfxItemPool &) = delete; + + //IDs below or equal are Which IDs, IDs above slot IDs + static const sal_uInt16 SFX_WHICH_MAX = 4999; +}; + +// only the pool may manipulate the reference counts +inline void SfxItemPool::ClearRefCount(SfxPoolItem& rItem) +{ + rItem.SetRefCount(0); +} + +// only the pool may manipulate the reference counts +inline void SfxItemPool::AddRef(const SfxPoolItem& rItem) +{ + rItem.AddRef(); +} + +// only the pool may manipulate the reference counts +inline sal_uInt32 SfxItemPool::ReleaseRef(const SfxPoolItem& rItem, sal_uInt32 n) +{ + return rItem.ReleaseRef(n); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/itemprop.hxx b/include/svl/itemprop.hxx new file mode 100644 index 000000000..08207f1b1 --- /dev/null +++ b/include/svl/itemprop.hxx @@ -0,0 +1,203 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_ITEMPROP_HXX +#define INCLUDED_SVL_ITEMPROP_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// values from com/sun/star/beans/PropertyAttribute +#define PROPERTY_NONE 0 + +/// map a property between beans::XPropertySet and SfxPoolItem +struct SfxItemPropertyMapEntry +{ + OUString aName; ///< name of property + css::uno::Type aType; ///< UNO type of property + sal_uInt16 nWID; ///< WhichId of SfxPoolItem + /// flag bitmap, @see css::beans::PropertyAttribute + sal_Int16 nFlags; + /// "member ID" to tell QueryValue/PutValue which property it is + /// (when multiple properties map to the same nWID) + sal_uInt8 nMemberId; + PropertyMoreFlags nMoreFlags; + + SfxItemPropertyMapEntry(OUString _aName, sal_uInt16 _nWID, css::uno::Type const & _rType, + sal_Int16 _nFlags, sal_uInt8 const _nMemberId, PropertyMoreFlags _nMoreFlags = PropertyMoreFlags::NONE) + : aName(std::move( _aName )) + , aType( _rType ) + , nWID( _nWID ) + , nFlags( _nFlags ) + , nMemberId( _nMemberId ) + , nMoreFlags( _nMoreFlags ) + { + assert(_nFlags <= 0x1ff ); + assert( (_nMemberId & 0x40) == 0 ); + // Verify that if METRIC_ITEM is set, we are one of the types supported by + // SvxUnoConvertToMM. + assert(!(_nMoreFlags & PropertyMoreFlags::METRIC_ITEM) || + ( (aType.getTypeClass() == css::uno::TypeClass_BYTE) + || (aType.getTypeClass() == css::uno::TypeClass_SHORT) + || (aType.getTypeClass() == css::uno::TypeClass_UNSIGNED_SHORT) + || (aType.getTypeClass() == css::uno::TypeClass_LONG) + || (aType.getTypeClass() == css::uno::TypeClass_UNSIGNED_LONG) + ) ); + } +}; + +struct SfxItemPropertyMapCompare +{ + bool operator() ( const SfxItemPropertyMapEntry * lhs, const SfxItemPropertyMapEntry * rhs ) const + { + return lhs->aName < rhs->aName; + } +}; +class SVL_DLLPUBLIC SfxItemPropertyMap +{ + o3tl::sorted_vector< const SfxItemPropertyMapEntry*, SfxItemPropertyMapCompare > m_aMap; + mutable css::uno::Sequence< css::beans::Property > m_aPropSeq; +public: + SfxItemPropertyMap( const SfxItemPropertyMapEntry* pEntries ); + SfxItemPropertyMap( const SfxItemPropertyMap& rSource ); + ~SfxItemPropertyMap(); + + const SfxItemPropertyMapEntry* getByName( std::u16string_view rName ) const; + css::uno::Sequence< css::beans::Property > const & getProperties() const; + /// @throws css::beans::UnknownPropertyException + css::beans::Property getPropertyByName( const OUString & rName ) const; + bool hasPropertyByName( std::u16string_view rName ) const; + + const o3tl::sorted_vector< const SfxItemPropertyMapEntry*, SfxItemPropertyMapCompare >& getPropertyEntries() const { return m_aMap; } +}; + +class SVL_DLLPUBLIC SfxItemPropertySet final +{ + SfxItemPropertyMap m_aMap; + mutable css::uno::Reference m_xInfo; + +public: + SfxItemPropertySet( const SfxItemPropertyMapEntry *pMap ) : + m_aMap(pMap) {} + ~SfxItemPropertySet(); + + /// @throws css::uno::RuntimeException + void getPropertyValue( const SfxItemPropertyMapEntry& rEntry, + const SfxItemSet& rSet, + css::uno::Any& rAny) const; + /// @throws css::uno::RuntimeException + /// @throws css::beans::UnknownPropertyException + void getPropertyValue( const OUString &rName, + const SfxItemSet& rSet, + css::uno::Any& rAny) const; + /// @throws css::uno::RuntimeException + /// @throws css::beans::UnknownPropertyException + css::uno::Any + getPropertyValue( const OUString &rName, + const SfxItemSet& rSet ) const; + /// @throws css::uno::RuntimeException + /// @throws css::lang::IllegalArgumentException + void setPropertyValue( const SfxItemPropertyMapEntry& rEntry, + const css::uno::Any& aVal, + SfxItemSet& rSet ) const; + /// @throws css::uno::RuntimeException + /// @throws css::lang::IllegalArgumentException + /// @throws css::beans::UnknownPropertyException + void setPropertyValue( const OUString& rPropertyName, + const css::uno::Any& aVal, + SfxItemSet& rSet ) const; + + /// @throws css::beans::UnknownPropertyException + css::beans::PropertyState + getPropertyState(const OUString& rName, const SfxItemSet& rSet)const; + css::beans::PropertyState + getPropertyState(const SfxItemPropertyMapEntry& rEntry, const SfxItemSet& rSet) const + noexcept; + + css::uno::Reference const & + getPropertySetInfo() const; + const SfxItemPropertyMap& getPropertyMap() const {return m_aMap;} +}; + +// workaround for incremental linking bugs in MSVC2015 +class SAL_DLLPUBLIC_TEMPLATE SfxItemPropertySetInfo_Base : public cppu::WeakImplHelper< css::beans::XPropertySetInfo > {}; + +class SVL_DLLPUBLIC SfxItemPropertySetInfo final : public SfxItemPropertySetInfo_Base +{ + SfxItemPropertyMap m_aOwnMap; + +public: + SfxItemPropertySetInfo(const SfxItemPropertyMap &rMap ); + SfxItemPropertySetInfo(const SfxItemPropertyMapEntry *pEntries ); + virtual ~SfxItemPropertySetInfo() override; + + virtual css::uno::Sequence< css::beans::Property > SAL_CALL + getProperties( ) override; + + virtual css::beans::Property SAL_CALL + getPropertyByName( const OUString& aName ) override; + + virtual sal_Bool SAL_CALL + hasPropertyByName( const OUString& Name ) override; + +}; + +struct SfxItemPropertyMapCompare2 +{ + bool operator() ( const SfxItemPropertyMapEntry & lhs, const SfxItemPropertyMapEntry & rhs ) const + { + return lhs.aName < rhs.aName; + } +}; + +// workaround for incremental linking bugs in MSVC2015 +class SAL_DLLPUBLIC_TEMPLATE SfxExtItemPropertySetInfo_Base : public cppu::WeakImplHelper< css::beans::XPropertySetInfo > {}; + +class SVL_DLLPUBLIC SfxExtItemPropertySetInfo final : public SfxExtItemPropertySetInfo_Base +{ +public: + SfxExtItemPropertySetInfo( + const SfxItemPropertyMapEntry *pMap, + const css::uno::Sequence& rPropSeq ); + virtual ~SfxExtItemPropertySetInfo() override; + + virtual css::uno::Sequence< css::beans::Property > SAL_CALL + getProperties( ) override; + + virtual css::beans::Property SAL_CALL + getPropertyByName( const OUString& aName ) override; + + virtual sal_Bool SAL_CALL + hasPropertyByName( const OUString& Name ) override; + +private: + const SfxItemPropertyMapEntry* getByName( std::u16string_view rName ) const; + o3tl::sorted_vector< SfxItemPropertyMapEntry, SfxItemPropertyMapCompare2 > maMap; + mutable css::uno::Sequence< css::beans::Property > m_aPropSeq; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/itemset.hxx b/include/svl/itemset.hxx new file mode 100644 index 000000000..b6404b6cc --- /dev/null +++ b/include/svl/itemset.hxx @@ -0,0 +1,287 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +class SfxItemPool; + +class SAL_WARN_UNUSED SVL_DLLPUBLIC SfxItemSet +{ + friend class SfxItemIter; + friend class SfxWhichIter; + + SfxItemPool* m_pPool; ///< pool that stores the items + const SfxItemSet* m_pParent; ///< derivation + SfxPoolItem const** m_ppItems; ///< pointer to array of items, we allocate and free this unless m_bItemsFixed==true + WhichRangesContainer m_pWhichRanges; ///< array of Which Ranges + sal_uInt16 m_nCount; ///< number of items + bool m_bItemsFixed; ///< true if this is a SfxItemSetFixed object + +friend class SfxItemPoolCache; +friend class SfxAllItemSet; + +private: + SVL_DLLPRIVATE void RecreateRanges_Impl(const WhichRangesContainer& pNewRanges); + + SfxItemSet( SfxItemPool & pool, const WhichRangesContainer& wids, std::size_t items ); + +public: + SfxPoolItem const** GetItems_Impl() const { return m_ppItems; } + +private: + const SfxItemSet& operator=(const SfxItemSet &) = delete; + +protected: + // Notification-Callback + virtual void Changed( const SfxPoolItem& rOld, const SfxPoolItem& rNew ); + + void PutDirect(const SfxPoolItem &rItem); + + virtual const SfxPoolItem* PutImpl( const SfxPoolItem&, sal_uInt16 nWhich, bool bPassingOwnership ); + + /** special constructor for SfxAllItemSet */ + enum class SfxAllItemSetFlag { Flag }; + SfxItemSet( SfxItemPool&, SfxAllItemSetFlag ); + /** special constructor for SfxItemSetFixed */ + SfxItemSet( SfxItemPool&, WhichRangesContainer&& ranges, SfxPoolItem const ** ppItems ); + +public: + SfxItemSet( const SfxItemSet& ); + SfxItemSet( SfxItemSet&& ) noexcept; + SfxItemSet( SfxItemPool& ); + SfxItemSet( SfxItemPool&, const WhichRangesContainer& ranges ); + SfxItemSet( SfxItemPool&, WhichRangesContainer&& ranges ); + + SfxItemSet( SfxItemPool& rPool, sal_uInt16 nWhichStart, sal_uInt16 nWhichEnd ) + : SfxItemSet(rPool, WhichRangesContainer(nWhichStart, nWhichEnd)) {} + + template + SfxItemSet(SfxItemPool& pool, svl::Items_t wids) + : SfxItemSet(pool, WhichRangesContainer(wids)) {} + + virtual ~SfxItemSet(); + + virtual std::unique_ptr Clone(bool bItems = true, SfxItemPool *pToPool = nullptr) const; + /** note that this only works if you know for sure that you are dealing with an SfxItemSet + and not one of it's subclasses. */ + SfxItemSet CloneAsValue(bool bItems = true, SfxItemPool *pToPool = nullptr) const; + + // Get number of items + sal_uInt16 Count() const { return m_nCount; } + sal_uInt16 TotalCount() const; + + const SfxPoolItem& Get( sal_uInt16 nWhich, bool bSrchInParent = true ) const; + template + const T& Get( TypedWhichId nWhich, bool bSrchInParent = true ) const + { + return static_cast(Get(sal_uInt16(nWhich), bSrchInParent)); + } + + /** This method eases accessing single Items in the SfxItemSet. + + @param nId SlotId or the Item's WhichId + @param bSearchInParent also search in parent ItemSets + @returns 0 if the ItemSet does not contain an Item with the Id 'nWhich' + */ + const SfxPoolItem* GetItem(sal_uInt16 nWhich, bool bSearchInParent = true) const; + + /// Templatized version of GetItem() to directly return the correct type. + template const T* GetItem(sal_uInt16 nWhich, bool bSearchInParent = true) const + { + const SfxPoolItem* pItem = GetItem(nWhich, bSearchInParent); + const T* pCastedItem = dynamic_cast(pItem); + + assert(!pItem || pCastedItem); // if it exists, must have the correct type + return pCastedItem; + } + template const T* GetItem( TypedWhichId nWhich, bool bSearchInParent = true ) const + { + return GetItem(sal_uInt16(nWhich), bSearchInParent); + } + + + /// Templatized static version of GetItem() to directly return the correct type if the SfxItemSet is available. + template static const T* GetItem(const SfxItemSet* pItemSet, sal_uInt16 nWhich, bool bSearchInParent) + { + if (pItemSet) + return pItemSet->GetItem(nWhich, bSearchInParent); + + return nullptr; + } + template + static const T* GetItem(const SfxItemSet* pItemSet, TypedWhichId nWhich, + bool bSearchInParent) + { + return GetItem(pItemSet, static_cast(nWhich), bSearchInParent); + } + + sal_uInt16 GetWhichByPos(sal_uInt16 nPos) const; + + SfxItemState GetItemState( sal_uInt16 nWhich, + bool bSrchInParent = true, + const SfxPoolItem **ppItem = nullptr ) const; + + template + SfxItemState GetItemState( TypedWhichId nWhich, + bool bSrchInParent = true, + const T **ppItem = nullptr ) const + { return GetItemState(sal_uInt16(nWhich), bSrchInParent, reinterpret_cast(ppItem)); } + + /// Templatized version of GetItemState() to directly return the correct type. + template + const T * GetItemIfSet( TypedWhichId nWhich, + bool bSrchInParent = true ) const + { + const SfxPoolItem * pItem = nullptr; + if( SfxItemState::SET == GetItemState(sal_uInt16(nWhich), bSrchInParent, &pItem) ) + return static_cast(pItem); + return nullptr; + } + + bool HasItem(sal_uInt16 nWhich, const SfxPoolItem** ppItem = nullptr) const; + template + bool HasItem(TypedWhichId nWhich, const T** ppItem = nullptr) const + { return HasItem(sal_uInt16(nWhich), reinterpret_cast(ppItem)); } + + void DisableItem(sal_uInt16 nWhich); + void InvalidateItem( sal_uInt16 nWhich ); + sal_uInt16 ClearItem( sal_uInt16 nWhich = 0); + void ClearInvalidItems(); + void InvalidateAllItems(); // HACK(via nWhich = 0) ??? + + inline void SetParent( const SfxItemSet* pNew ); + + // add, delete items, work on items +public: + const SfxPoolItem* Put( const SfxPoolItem& rItem, sal_uInt16 nWhich ) + { return PutImpl(rItem, nWhich, /*bPassingOwnership*/false); } + const SfxPoolItem* Put( std::unique_ptr xItem, sal_uInt16 nWhich ) + { return PutImpl(*xItem.release(), nWhich, /*bPassingOwnership*/true); } + const SfxPoolItem* Put( const SfxPoolItem& rItem ) + { return Put(rItem, rItem.Which()); } + const SfxPoolItem* Put( std::unique_ptr xItem ) + { auto nWhich = xItem->Which(); return Put(std::move(xItem), nWhich); } + bool Put( const SfxItemSet&, + bool bInvalidAsDefault = true ); + void PutExtended( const SfxItemSet&, + SfxItemState eDontCareAs, + SfxItemState eDefaultAs ); + + bool Set( const SfxItemSet&, bool bDeep = true ); + + void Intersect( const SfxItemSet& rSet ); + void MergeValues( const SfxItemSet& rSet ); + void Differentiate( const SfxItemSet& rSet ); + void MergeValue( const SfxPoolItem& rItem, bool bOverwriteDefaults = false ); + + SfxItemPool* GetPool() const { return m_pPool; } + const WhichRangesContainer & GetRanges() const { return m_pWhichRanges; } + void SetRanges( const WhichRangesContainer& ); + void SetRanges( WhichRangesContainer&& ); + void MergeRange( sal_uInt16 nFrom, sal_uInt16 nTo ); + const SfxItemSet* GetParent() const { return m_pParent; } + + bool operator==(const SfxItemSet &) const; + + /** Compare possibly ignoring SfxItemPool pointer. + + This can be used to compare the content of two SfxItemSet even if they + don't share the same pool. EditTextObject::Equals(...,false) uses this + which is needed in ScGlobal::EETextObjEqual() for + ScPageHFItem::operator==() + + @param bComparePool + if ignore SfxItemPool pointer, + if compare also SfxItemPool pointer (identical to operator==()) + */ + bool Equals(const SfxItemSet &, bool bComparePool) const; + + void dumpAsXml(xmlTextWriterPtr pWriter) const; + +private: + sal_uInt16 ClearSingleItemImpl( sal_uInt16 nWhich, std::optional oItemOffsetHint ); + sal_uInt16 ClearAllItemsImpl(); + SfxItemState GetItemStateImpl( sal_uInt16 nWhich, + bool bSrchInParent, + const SfxPoolItem **ppItem, + std::optional oItemsOffsetHint) const; +}; + +inline void SfxItemSet::SetParent( const SfxItemSet* pNew ) +{ + m_pParent = pNew; +} + +class SVL_DLLPUBLIC SfxAllItemSet final : public SfxItemSet + +// Handles all Ranges. Ranges are automatically modified by putting items. + +{ +public: + SfxAllItemSet( SfxItemPool &rPool ); + SfxAllItemSet( const SfxItemSet & ); + SfxAllItemSet( const SfxAllItemSet & ); + + virtual std::unique_ptr Clone( bool bItems = true, SfxItemPool *pToPool = nullptr ) const override; +private: + virtual const SfxPoolItem* PutImpl( const SfxPoolItem&, sal_uInt16 nWhich, bool bPassingOwnership ) override; +}; + + +namespace svl::detail +{ +/** + * Determines the number of sal_uInt16s in a container of pairs of + * sal_uInt16s, each representing a range of sal_uInt16s, and total capacity of the ranges. + */ +template +static constexpr sal_uInt16 CountRanges1() +{ + sal_uInt16 nCapacity = rangeSize(WID1, WID2); + if constexpr (sizeof...(Rest) > 0) + nCapacity += CountRanges1(); + return nCapacity; +}} + +// Allocate the items array inside the object, to reduce allocation cost. +// +template +class SfxItemSetFixed : public SfxItemSet +{ +public: + SfxItemSetFixed( SfxItemPool& rPool) + : SfxItemSet(rPool, WhichRangesContainer(svl::Items_t{}), m_aItems) {} +private: + static constexpr sal_uInt16 NITEMS = svl::detail::CountRanges1(); + const SfxPoolItem* m_aItems[NITEMS] = {}; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/languageoptions.hxx b/include/svl/languageoptions.hxx new file mode 100644 index 000000000..e780ed475 --- /dev/null +++ b/include/svl/languageoptions.hxx @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_LANGUAGEOPTIONS_HXX +#define INCLUDED_SVL_LANGUAGEOPTIONS_HXX + +#include +#include +#include +#include + +// class SvtLanguageOptions ---------------------------------------------------- + +// these defines can be ORed +// note these values DO NOT match the values in css::i18n::ScriptType +enum class SvtScriptType : sal_uInt8 +{ + NONE = 0x00, + LATIN = 0x01, + ASIAN = 0x02, + COMPLEX = 0x04, + UNKNOWN = 0x08 // (only used in SC) if type has not been determined yet +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace SvtLanguageOptions +{ + // CJK options +// SVL_DLLPUBLIC bool IsCJKFontEnabled() { m_pCJKOptions->IsCJKFontEnabled(); } +// SVL_DLLPUBLIC bool IsVerticalTextEnabled() m_pCJKOptions->IsVerticalTextEnabled(); +// SVL_DLLPUBLIC bool IsAsianTypographyEnabled() m_pCJKOptions->IsAsianTypographyEnabled(); +// SVL_DLLPUBLIC bool IsJapaneseFindEnabled() m_pCJKOptions->IsJapaneseFindEnabled(); +// SVL_DLLPUBLIC void SetAll( bool _bSet ) m_pCJKOptions->SetAll( _bSet ); +// SVL_DLLPUBLIC bool IsAnyEnabled() m_pCJKOptions->IsAnyEnabled(); + + // CTL options + //SVL_DLLPUBLIC void SetCTLFontEnabled( bool _bEnabled ) m_pCTLOptions->SetCTLFontEnabled( _bEnabled ); +// SVL_DLLPUBLIC bool IsCTLFontEnabled() m_pCTLOptions->IsCTLFontEnabled(); + +// SVL_DLLPUBLIC void SetCTLSequenceChecking( bool _bEnabled ) m_pCTLOptions->SetCTLSequenceChecking( _bEnabled ); + + //SVL_DLLPUBLIC void SetCTLSequenceCheckingRestricted( bool _bEnable ) m_pCTLOptions->SetCTLSequenceCheckingRestricted( _bEnable ); + +// SVL_DLLPUBLIC void SetCTLSequenceCheckingTypeAndReplace( bool _bEnable ) m_pCTLOptions->SetCTLSequenceCheckingTypeAndReplace( _bEnable ); + + // returns for a language the scripttype + SVL_DLLPUBLIC SvtScriptType GetScriptTypeOfLanguage( LanguageType nLang ); + + // convert from css::i18n::ScriptType constants to SvtScriptType + SVL_DLLPUBLIC SvtScriptType FromI18NToSvtScriptType( sal_Int16 nI18NType ); + + SVL_DLLPUBLIC sal_Int16 FromSvtScriptTypeToI18N( SvtScriptType nI18NType ); + + SVL_DLLPUBLIC sal_Int16 GetI18NScriptTypeOfLanguage( LanguageType nLang ); + +}; + +/** #i42730# Gives access to the Windows 16bit system locale + */ +namespace SvtSystemLanguageOptions +{ + bool isCJKKeyboardLayoutInstalled(); +}; + +#endif // INCLUDED_SVL_LANGUAGEOPTIONS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/lckbitem.hxx b/include/svl/lckbitem.hxx new file mode 100644 index 000000000..5625a7aac --- /dev/null +++ b/include/svl/lckbitem.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_LCKBITEM_HXX +#define INCLUDED_SVL_LCKBITEM_HXX + +#include +#include +#include + +class SVL_DLLPUBLIC SfxLockBytesItem final : public SfxPoolItem +{ + SvLockBytesRef _xVal; + +public: + static SfxPoolItem* CreateDefault(); + SfxLockBytesItem(); + virtual ~SfxLockBytesItem() override; + + SfxLockBytesItem(SfxLockBytesItem const &) = default; + SfxLockBytesItem(SfxLockBytesItem &&) = default; + SfxLockBytesItem & operator =(SfxLockBytesItem const &) = delete; // due to SfxPoolItem + SfxLockBytesItem & operator =(SfxLockBytesItem &&) = delete; // due to SfxPoolItem + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxLockBytesItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + SvLockBytes* GetValue() const { return _xVal.get(); } + + virtual bool PutValue ( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/legacyitem.hxx b/include/svl/legacyitem.hxx new file mode 100644 index 000000000..b2035aeca --- /dev/null +++ b/include/svl/legacyitem.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_LEGACYITEM_HXX +#define INCLUDED_SVL_LEGACYITEM_HXX + +#include + +////////////////////////////////////////////////////////////////////////////// +// // svl +// SfxBoolItem aLinebreak; +// SfxInt32Item aRotateAngle; -> CntInt32Item +////////////////////////////////////////////////////////////////////////////// + +class SvStream; +class SfxBoolItem; +class CntInt32Item; + +namespace legacy +{ + namespace SfxBool + { + sal_uInt16 SVL_DLLPUBLIC GetVersion(sal_uInt16 nFileFormatVersion); + void SVL_DLLPUBLIC Create(SfxBoolItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + SVL_DLLPUBLIC SvStream& Store(const SfxBoolItem& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } + namespace CntInt32 + { + sal_uInt16 SVL_DLLPUBLIC GetVersion(sal_uInt16 nFileFormatVersion); + void SVL_DLLPUBLIC Create(CntInt32Item& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + SVL_DLLPUBLIC SvStream& Store(const CntInt32Item& rItem, SvStream& rStrm, sal_uInt16 nItemVersion); + } +} + +#endif // INCLUDED_SVL_LEGACYITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/listener.hxx b/include/svl/listener.hxx new file mode 100644 index 000000000..e7c589625 --- /dev/null +++ b/include/svl/listener.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_LISTENER_HXX +#define INCLUDED_SVL_LISTENER_HXX + +#include + +#include + +class SvtBroadcaster; +class SfxHint; + +class SVL_DLLPUBLIC SvtListener +{ + friend class SvtBroadcaster; + typedef o3tl::sorted_vector BroadcastersType; + BroadcastersType maBroadcasters; + + const SvtListener& operator=(const SvtListener &) = delete; + // called from the SvtBroadcaster destructor + void BroadcasterDying( SvtBroadcaster& rBroadcaster ); + +public: + class SVL_DLLPUBLIC QueryBase + { + sal_uInt16 mnId; + public: + QueryBase( sal_uInt16 nId ) : mnId(nId) {} + virtual ~QueryBase() {}; + + sal_uInt16 getId() const { return mnId; } + }; + + SvtListener() = default; + SvtListener( const SvtListener &r ) = default; + virtual ~SvtListener() COVERITY_NOEXCEPT_FALSE; + + bool StartListening( SvtBroadcaster& rBroadcaster ); + void EndListening( SvtBroadcaster& rBroadcaster ); + void EndListeningAll(); + + /// Overwrites existing broadcasters with the ones from the specified listener + void CopyAllBroadcasters( const SvtListener& r ); + bool HasBroadcaster() const { return !maBroadcasters.empty(); } + + virtual void Notify( const SfxHint& rHint ); + virtual void Query( QueryBase& rQuery ) const; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/lngmisc.hxx b/include/svl/lngmisc.hxx new file mode 100644 index 000000000..eb7b7cbbe --- /dev/null +++ b/include/svl/lngmisc.hxx @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_LNGMISC_HXX +#define INCLUDED_SVL_LNGMISC_HXX + +#include + +#include + +#define SVT_SOFT_HYPHEN u'\x00AD' +#define SVT_HARD_HYPHEN u'\x2011' + +// the non-breaking space +#define SVT_HARD_SPACE u'\x00A0' + +namespace linguistic +{ + inline bool IsHyphen(sal_Unicode cChar) + { + return cChar == SVT_SOFT_HYPHEN || cChar == SVT_HARD_HYPHEN; + } + + inline bool IsControlChar(sal_Unicode cChar) + { + // TODO: why doesn't this include 0x7F DEL? + return cChar < u' '; + } + + sal_Int32 GetNumControlChars( std::u16string_view rTxt ); + + SVL_DLLPUBLIC bool RemoveHyphens(OUString &rTxt); + SVL_DLLPUBLIC bool RemoveControlChars(OUString &rTxt); + SVL_DLLPUBLIC bool ReplaceControlChars(OUString &rTxt); + SVL_DLLPUBLIC OUString GetThesaurusReplaceText(const OUString &rText); +} // namespace linguistic + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/lockfilecommon.hxx b/include/svl/lockfilecommon.hxx new file mode 100644 index 000000000..d71cb8262 --- /dev/null +++ b/include/svl/lockfilecommon.hxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_LOCKFILECOMMON_HXX +#define INCLUDED_SVL_LOCKFILECOMMON_HXX + +#include + +#include + +#include +#include +#include + +#include +#include + +enum class LockFileComponent +{ + OOOUSERNAME, SYSUSERNAME, LOCALHOST, EDITTIME, USERURL, LAST=USERURL +}; + +typedef o3tl::enumarray LockFileEntry; + +namespace svt { + +/// This is a general implementation that is used in document lock file implementation and in sharing control file implementation +class SVL_DLLPUBLIC LockFileCommon +{ +private: + OUString m_aURL; + +protected: + ::osl::Mutex m_aMutex; + + /// This method generates the URL of the lock file based on the document URL and the specified prefix. + static OUString GenerateOwnLockFileURL(std::u16string_view aOrigURL, std::u16string_view aPrefix); + +public: + LockFileCommon(OUString aLockFileURL); + virtual ~LockFileCommon(); + + const OUString& GetURL() const; + void SetURL(const OUString& aURL); + + static void ParseList( const css::uno::Sequence< sal_Int8 >& aBuffer, std::vector< LockFileEntry > &rOutput ); + static LockFileEntry ParseEntry( const css::uno::Sequence< sal_Int8 >& aBuffer, sal_Int32& o_nCurPos ); + static OUString ParseName( const css::uno::Sequence< sal_Int8 >& aBuffer, sal_Int32& o_nCurPos ); + static OUString EscapeCharacters( const OUString& aSource ); + static OUString GetOOOUserName(); + static OUString GetCurrentLocalTime(); + static LockFileEntry GenerateOwnEntry(); + + static INetURLObject ResolveLinks( const INetURLObject& aDocURL ); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/lstner.hxx b/include/svl/lstner.hxx new file mode 100644 index 000000000..1b0e88063 --- /dev/null +++ b/include/svl/lstner.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_LSTNER_HXX +#define INCLUDED_SVL_LSTNER_HXX + +#include +#include +#include +#include +#ifdef DBG_UTIL +#include +#endif + +class SfxBroadcaster; +class SfxHint; + +//StartListening duplicate handling options +//Prevent only adds the listener if it's not already added +//Allow allows duplicate listeners +//Unexpected, the default, is for the usual case where the +//listener should only be added once and duplicates are +//unexpected. In dbgutil mode this tracks where the original +//listener was added from and reports the duplicate addition +//as an error +enum class DuplicateHandling { Unexpected, Prevent, Allow }; + +class SVL_DLLPUBLIC SfxListener +{ + std::vector maBCs; +#ifdef DBG_UTIL + std::map> + maCallStacks; +#endif + +private: + const SfxListener& operator=(const SfxListener &) = delete; + +public: + + SfxListener() {} + SfxListener( const SfxListener &rCopy ); + virtual ~SfxListener() COVERITY_NOEXCEPT_FALSE; + + void StartListening(SfxBroadcaster& rBroadcaster, DuplicateHandling eDuplicateHanding = DuplicateHandling::Unexpected); + void EndListening( SfxBroadcaster& rBroadcaster, bool bRemoveAllDuplicates = false ); + void EndListeningAll(); + bool IsListening( SfxBroadcaster& rBroadcaster ) const; + + sal_uInt16 GetBroadcasterCount() const; + SfxBroadcaster* GetBroadcasterJOE( sal_uInt16 nNo ) const; + + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); + + void RemoveBroadcaster_Impl( SfxBroadcaster& rBC ); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/macitem.hxx b/include/svl/macitem.hxx new file mode 100644 index 000000000..e58871101 --- /dev/null +++ b/include/svl/macitem.hxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_MACITEM_HXX +#define INCLUDED_SVL_MACITEM_HXX + +// class SvxMacroItem ---------------------------------------------------- + +#include +#include +#include +#include +#include + +class SvStream; +enum class SvMacroItemId : sal_uInt16; + +inline constexpr OUStringLiteral SVX_MACRO_LANGUAGE_JAVASCRIPT = u"JavaScript"; +inline constexpr OUStringLiteral SVX_MACRO_LANGUAGE_STARBASIC = u"StarBasic"; +inline constexpr OUStringLiteral SVX_MACRO_LANGUAGE_SF = u"Script"; + +enum ScriptType +{ + STARBASIC, + JAVASCRIPT, + EXTENDED_STYPE +}; + +class SVL_DLLPUBLIC SvxMacro +{ + OUString aMacName; + OUString aLibName; + ScriptType eType; + +public: + + SvxMacro( OUString aMacName, const OUString &rLanguage); + + SvxMacro( OUString aMacName, OUString aLibName, + ScriptType eType); // = STARBASIC removes + + const OUString &GetLibName() const { return aLibName; } + const OUString &GetMacName() const { return aMacName; } + OUString GetLanguage()const; + + ScriptType GetScriptType() const { return eType; } + + bool HasMacro() const { return !aMacName.isEmpty(); } +}; + +inline SvxMacro::SvxMacro( OUString _aMacName, OUString _aLibName, + ScriptType eTyp ) + : aMacName(std::move( _aMacName )), aLibName(std::move( _aLibName )), eType( eTyp ) +{} + +// Macro Table, destroys the pointers in the DTor! +typedef std::map SvxMacroTable; + +#define SVX_MACROTBL_VERSION31 0 +#define SVX_MACROTBL_VERSION40 1 + +class SVL_DLLPUBLIC SvxMacroTableDtor +{ +private: + SvxMacroTable aSvxMacroTable; +public: + SvxMacroTableDtor() {} + SvxMacroTableDtor( const SvxMacroTableDtor &rCpy ) : aSvxMacroTable(rCpy.aSvxMacroTable) { } + + SvxMacroTableDtor& operator=( const SvxMacroTableDtor &rCpy ); + bool operator==( const SvxMacroTableDtor& rOther ) const; + + void Read( SvStream & ); + SvStream& Write( SvStream & ) const; + + bool empty() const { return aSvxMacroTable.empty(); } + + // returns NULL if no entry exists, or a pointer to the internal value + const SvxMacro* Get(SvMacroItemId nEvent) const; + // returns NULL if no entry exists, or a pointer to the internal value + SvxMacro* Get(SvMacroItemId nEvent); + // return true if the key exists + bool IsKeyValid(SvMacroItemId nEvent) const; + // This stores a copy of the rMacro parameter + SvxMacro& Insert(SvMacroItemId nEvent, const SvxMacro& rMacro); + // If the entry exists, remove it from the map and release it's storage + void Erase(SvMacroItemId nEvent); +}; + + +/* +This item describes a Macro table. +*/ + +class SVL_DLLPUBLIC SvxMacroItem final : public SfxPoolItem +{ +public: + explicit inline SvxMacroItem ( const sal_uInt16 nId ); + + // "pure virtual methods" of SfxPoolItem + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + virtual SvxMacroItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + const SvxMacroTableDtor& GetMacroTable() const { return aMacroTable;} + void SetMacroTable( const SvxMacroTableDtor& rTbl ) { aMacroTable = rTbl; } + + inline const SvxMacro& GetMacro( SvMacroItemId nEvent ) const; + inline bool HasMacro( SvMacroItemId nEvent ) const; + void SetMacro( SvMacroItemId nEvent, const SvxMacro& ); + +private: + SvxMacroTableDtor aMacroTable; + + SvxMacroItem( const SvxMacroItem& ) = default; +}; + +inline SvxMacroItem::SvxMacroItem( const sal_uInt16 nId ) + : SfxPoolItem( nId ) +{} + +inline bool SvxMacroItem::HasMacro( SvMacroItemId nEvent ) const +{ + return aMacroTable.IsKeyValid( nEvent ); +} +inline const SvxMacro& SvxMacroItem::GetMacro( SvMacroItemId nEvent ) const +{ + return *(aMacroTable.Get(nEvent)); +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/memberid.h b/include/svl/memberid.h new file mode 100644 index 000000000..afe106d41 --- /dev/null +++ b/include/svl/memberid.h @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_MEMBERID_H +#define INCLUDED_SVL_MEMBERID_H + +#define MID_X 1 +#define MID_Y 2 +#define MID_RECT_LEFT 3 +#define MID_RECT_TOP 4 +#define MID_WIDTH 5 +#define MID_HEIGHT 6 +#define MID_RECT_RIGHT 7 + +// SvxSizeItem +#define MID_SIZE_SIZE 0 +#define MID_SIZE_WIDTH 1 +#define MID_SIZE_HEIGHT 2 + +// SvxSearchItem +// XXX When changing the MID count here, also increment the corresponding +// SvxSearchItem SFX_DECL_TYPE(n) value in include/sfx2/msg.hxx to match, and +// add a member to struct SvxSearch in sfx2/sdi/sfxitems.sdi so that dependent +// slot items get generated. +#define MID_SEARCH_STYLEFAMILY 1 +#define MID_SEARCH_CELLTYPE 2 +#define MID_SEARCH_ROWDIRECTION 3 +#define MID_SEARCH_ALLTABLES 4 +#define MID_SEARCH_SEARCHFILTERED 5 +#define MID_SEARCH_BACKWARD 6 +#define MID_SEARCH_PATTERN 7 +#define MID_SEARCH_CONTENT 8 +#define MID_SEARCH_ASIANOPTIONS 9 +#define MID_SEARCH_ALGORITHMTYPE 10 +#define MID_SEARCH_FLAGS 11 +#define MID_SEARCH_SEARCHSTRING 12 +#define MID_SEARCH_REPLACESTRING 13 +#define MID_SEARCH_LOCALE 14 +#define MID_SEARCH_CHANGEDCHARS 15 +#define MID_SEARCH_DELETEDCHARS 16 +#define MID_SEARCH_INSERTEDCHARS 17 +#define MID_SEARCH_TRANSLITERATEFLAGS 18 +#define MID_SEARCH_COMMAND 19 +#define MID_SEARCH_STARTPOINTX 20 +#define MID_SEARCH_STARTPOINTY 21 +#define MID_SEARCH_SEARCHFORMATTED 22 +#define MID_SEARCH_ALGORITHMTYPE2 23 + +// SfxDocumentInfoItem +#define MID_DOCINFO_DESCRIPTION 0x13 +#define MID_DOCINFO_KEYWORDS 0x17 +#define MID_DOCINFO_SUBJECT 0x1b +#define MID_DOCINFO_TITLE 0x1d +#define MID_DOCINFO_AUTOLOADENABLED 0x2d +#define MID_DOCINFO_AUTOLOADURL 0x2e +#define MID_DOCINFO_AUTOLOADSECS 0x2f +#define MID_DOCINFO_DEFAULTTARGET 0x30 +#define MID_DOCINFO_USEUSERDATA 0x31 +#define MID_DOCINFO_DELETEUSERDATA 0x32 +#define MID_DOCINFO_USETHUMBNAILSAVE 0x33 + +// only for FastPropertySet +#define MID_TYPE 0x38 +#define MID_VALUE 0x39 +#define MID_VALUESET 0x40 + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/metitem.hxx b/include/svl/metitem.hxx new file mode 100644 index 000000000..30cf75b7f --- /dev/null +++ b/include/svl/metitem.hxx @@ -0,0 +1,37 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_METITEM_HXX +#define INCLUDED_SVL_METITEM_HXX + +#include +#include + +class SVL_DLLPUBLIC SfxMetricItem: public SfxInt32Item +{ +public: + explicit SfxMetricItem( sal_uInt16 nWhich, sal_Int32 nValue ); + + virtual void ScaleMetrics( tools::Long lMult, tools::Long lDiv ) override; + virtual bool HasMetrics() const override; + +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/msodocumentlockfile.hxx b/include/svl/msodocumentlockfile.hxx new file mode 100644 index 000000000..f91c7ccff --- /dev/null +++ b/include/svl/msodocumentlockfile.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_MSODOCUMENTLOCKFILE_HXX +#define INCLUDED_SVL_MSODOCUMENTLOCKFILE_HXX + +#include +#include + +#define MSO_WORD_LOCKFILE_SIZE 162 +#define MSO_EXCEL_AND_POWERPOINT_LOCKFILE_SIZE 165 +#define MSO_USERNAME_MAX_LENGTH 52 + +namespace svt +{ +/// Class implementing reading and writing MSO lockfiles. +class SVL_DLLPUBLIC MSODocumentLockFile final : public GenDocumentLockFile +{ +private: + enum class AppType + { + Word, + Excel, + PowerPoint + }; + static AppType getAppType(std::u16string_view sOrigURL); + AppType m_eAppType; + + virtual void + WriteEntryToStream(const LockFileEntry& aEntry, + const css::uno::Reference& xStream) override; + + virtual css::uno::Reference OpenStream() override; + +public: + MSODocumentLockFile(std::u16string_view aOrigURL); + virtual ~MSODocumentLockFile() override; + + virtual LockFileEntry GetLockData() override; + + virtual void RemoveFile() override; + + static bool IsMSOSupportedFileFormat(std::u16string_view aURL); +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/svl/nfkeytab.hxx b/include/svl/nfkeytab.hxx new file mode 100644 index 000000000..3ab012f39 --- /dev/null +++ b/include/svl/nfkeytab.hxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_NFKEYTAB_HXX +#define INCLUDED_SVL_NFKEYTAB_HXX + +#include +#include + +//! For ImpSvNumberformatScan: first the short symbols, then the long symbols! +//! e.g. first YY then YYYY +//! The internal order is essential for the format code string scanner. +// +// This table is externally only to be used with method +// OUString SvNumberformat::GetMappedFormatstring( const NfKeywordTable&, const LocaleDataWrapper& ); +// and method +// void SvNumberFormatter::FillKeywordTable( NfKeywordTable&, LanguageType ); +enum NfKeywordIndex +{ + NF_KEY_NONE = 0, + NF_KEY_E, // exponential symbol + NF_KEY_AMPM, // AM/PM + NF_KEY_AP, // a/p + NF_KEY_MI, // minute (!) + NF_KEY_MMI, // minute 02 (!) + NF_KEY_M, // month (!) + NF_KEY_MM, // month 02 (!) + NF_KEY_MMM, // month short name + NF_KEY_MMMM, // month long name + NF_KEY_MMMMM, // month narrow name, first letter + NF_KEY_H, // hour + NF_KEY_HH, // hour 02 + NF_KEY_S, // second + NF_KEY_SS, // second 02 + NF_KEY_Q, // quarter + NF_KEY_QQ, // quarter 02 + NF_KEY_D, // day of month + NF_KEY_DD, // day of month 02 + NF_KEY_DDD, // day of week short + NF_KEY_DDDD, // day of week long + NF_KEY_YY, // year two digits + NF_KEY_YYYY, // year four digits + NF_KEY_NN, // day of week short + NF_KEY_NNN, // day of week long without separator, as of version 6, 10.10.97 + NF_KEY_NNNN, // day of week long with separator + NF_KEY_AAA, // abbreviated day name from Japanese Xcl, same as DDD or NN English + NF_KEY_AAAA, // full day name from Japanese Xcl, same as DDDD or NNN English + NF_KEY_EC, // E non-gregorian calendar year without preceding 0 + NF_KEY_EEC, // EE non-gregorian calendar year with preceding 0 (two digit) + NF_KEY_G, // abbreviated era name, latin characters M T S or H for Gengou calendar + NF_KEY_GG, // abbreviated era name + NF_KEY_GGG, // full era name + NF_KEY_R, // acts as EE (Xcl) => GR==GEE, GGR==GGEE, GGGR==GGGEE + NF_KEY_RR, // acts as GGGEE (Xcl) + NF_KEY_WW, // week of year, as of version 8, 19.06.98 + NF_KEY_THAI_T, // Thai T modifier, speciality of Thai Excel, only used with Thai locale and converted to [NatNum1] + NF_KEY_CCC, // currency bank symbol (old version) + NF_KEY_BOOLEAN, // boolean + NF_KEY_GENERAL, // General / Standard + NF_KEY_LASTKEYWORD = NF_KEY_GENERAL, + + // Reserved words translated and color names follow: + NF_KEY_TRUE, // boolean true + NF_KEY_FALSE, // boolean false + NF_KEY_COLOR, // color + NF_KEY_FIRSTCOLOR, + NF_KEY_BLACK = NF_KEY_FIRSTCOLOR, // you do know colors, don't you? + NF_KEY_BLUE, + NF_KEY_GREEN, + NF_KEY_CYAN, + NF_KEY_RED, + NF_KEY_MAGENTA, + NF_KEY_BROWN, + NF_KEY_GREY, + NF_KEY_YELLOW, + NF_KEY_WHITE, + NF_KEY_LASTCOLOR = NF_KEY_WHITE, + + NF_KEYWORD_ENTRIES_COUNT +}; + +typedef ::std::array NfKeywordTable; + +#endif // INCLUDED_SVL_NFKEYTAB_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/nfsymbol.hxx b/include/svl/nfsymbol.hxx new file mode 100644 index 000000000..8a659857e --- /dev/null +++ b/include/svl/nfsymbol.hxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_NFSYMBOL_HXX +#define INCLUDED_SVL_NFSYMBOL_HXX + +/* ATTENTION! If new types arrive that had its content previously handled as + * SYMBOLTYPE_STRING, they have to be added at several places in zforscan.cxx + * and/or zformat.cxx, and in xmloff/source/style/xmlnumfe.cxx. Mostly these + * are places where already NF_SYMBOLTYPE_STRING together with + * NF_SYMBOLTYPE_CURRENCY or NF_SYMBOLTYPE_DATESEP are used in the same case of + * a switch respectively an if-condition. + */ + +namespace svt { + +/// Number formatter's symbol types of a token, if not key words, which are >0 +enum NfSymbolType +{ + NF_SYMBOLTYPE_STRING = -1, // literal string in output + NF_SYMBOLTYPE_DEL = -2, // special character + NF_SYMBOLTYPE_BLANK = -3, // blank for '_' + NF_SYMBOLTYPE_STAR = -4, // *-character + NF_SYMBOLTYPE_DIGIT = -5, // digit place holder + NF_SYMBOLTYPE_DECSEP = -6, // decimal separator + NF_SYMBOLTYPE_THSEP = -7, // group AKA thousand separator + NF_SYMBOLTYPE_EXP = -8, // exponent E + NF_SYMBOLTYPE_FRAC = -9, // fraction / + NF_SYMBOLTYPE_EMPTY = -10, // deleted symbols + NF_SYMBOLTYPE_FRACBLANK = -11, // delimiter between integer and fraction + NF_SYMBOLTYPE_CURRENCY = -12, // currency symbol + NF_SYMBOLTYPE_CURRDEL = -13, // currency symbol delimiter [$] + NF_SYMBOLTYPE_CURREXT = -14, // currency symbol extension -xxx + NF_SYMBOLTYPE_CALENDAR = -15, // calendar ID + NF_SYMBOLTYPE_CALDEL = -16, // calendar delimiter [~] + NF_SYMBOLTYPE_DATESEP = -17, // date separator + NF_SYMBOLTYPE_TIMESEP = -18, // time separator + NF_SYMBOLTYPE_TIME100SECSEP = -19, // time 100th seconds separator + NF_SYMBOLTYPE_PERCENT = -20, // percent % + NF_SYMBOLTYPE_FRAC_FDIV = -21 // forced divisors +}; + +} // namespace svt + +#endif // INCLUDED_SVL_NFSYMBOL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/numformat.hxx b/include/svl/numformat.hxx new file mode 100644 index 000000000..dc1c704d3 --- /dev/null +++ b/include/svl/numformat.hxx @@ -0,0 +1,750 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +class Color; +class ImpSvNumberformatScan; +class ImpSvNumberInputScan; +class SvNumberFormatterRegistry_Impl; +class NfCurrencyTable; + +class SVL_DLLPUBLIC SvNumberFormatter +{ + friend class SvNumberFormatterRegistry_Impl; + +public: + /** + * We can't technically have an "infinite" value, so we use an arbitrary + * upper precision threshold to represent the "unlimited" precision. + */ + static const sal_uInt16 UNLIMITED_PRECISION; + + /** + * Precision suitable for numbers displayed in input bar, for instance + * Calc's formula input bar. + */ + static const sal_uInt16 INPUTSTRING_PRECISION; + + /// Preferred ctor with service manager and language/country enum + SvNumberFormatter(const css::uno::Reference& rxContext, + LanguageType eLang); + + ~SvNumberFormatter(); + + /// Set CallBack to ColorTable + void SetColorLink(const Link& rColorTableCallBack); + /// Do the CallBack to ColorTable + Color* GetUserDefColor(sal_uInt16 nIndex); + + /// Change language/country, also input and format scanner + void ChangeIntl(LanguageType eLnge); + /// Change the reference null date + void ChangeNullDate(sal_uInt16 nDay, sal_uInt16 nMonth, sal_Int16 nYear); + /// Change standard precision + void ChangeStandardPrec(short nPrec); + /// Set zero value suppression + void SetNoZero(bool bNZ); + + /** The language with which the formatter was initialized (system setting), + NOT the current language after a ChangeIntl() */ + LanguageType GetLanguage() const; + + // Determine whether two format types are input compatible or not + static bool IsCompatible(SvNumFormatType eOldType, SvNumFormatType eNewType); + + /** Get table of formats of a specific type of a locale. A format FIndex is + tested whether it has the type and locale requested, if it doesn't + match FIndex returns the default format for the type/locale. If no + specific format is to be selected FIndex may be initialized to 0. */ + SvNumberFormatTable& GetEntryTable(SvNumFormatType eType, sal_uInt32& FIndex, + LanguageType eLnge); + + /** Get table of formats of a specific type of a language/country. + FIndex returns the default format of that type. + If the language/country was never touched before new entries are generated */ + SvNumberFormatTable& ChangeCL(SvNumFormatType eType, sal_uInt32& FIndex, LanguageType eLnge); + + /** Get table of formats of the same type as FIndex; eType and rLnge are + set accordingly. An unknown format is set to Standard/General */ + SvNumberFormatTable& GetFirstEntryTable(SvNumFormatType& eType, sal_uInt32& FIndex, + LanguageType& rLnge); + + /// Delete an entry including the format it is referring to + void DeleteEntry(sal_uInt32 nKey); + + /** Create new entry of a format code string for language/country. + @return + if string new and ok and inserted. + if string already exists or an unresolvable parse error + occurred, in which case nCheckPos is the error position within rString. + If the error occurs at position 0 or rString is empty nCheckPos + will be 1, so an error in the string is always indicated by + nCheckPos not being zero. + The content of the rString variable can be changed and corrected + by the method. + nType contains the type of the format. + nKey contains the index key of the format. + */ + bool PutEntry(OUString& rString, sal_Int32& nCheckPos, SvNumFormatType& nType, sal_uInt32& nKey, + LanguageType eLnge = LANGUAGE_DONTKNOW, bool bReplaceBooleanEquivalent = true); + + /** Same as PutEntry but the format code string is + considered to be of language/country eLnge and is converted to + language/country eNewLnge */ + bool PutandConvertEntry(OUString& rString, sal_Int32& nCheckPos, SvNumFormatType& nType, + sal_uInt32& nKey, LanguageType eLnge, LanguageType eNewLnge, + bool bConvertDateOrder, bool bReplaceBooleanEquivalent = true); + + /** Same as PutandConvertEntry but the format code string + is considered to be of the System language/country eLnge and is + converted to another System language/country eNewLnge. In this case + the automatic currency is converted too. */ + bool PutandConvertEntrySystem(OUString& rString, sal_Int32& nCheckPos, SvNumFormatType& nType, + sal_uInt32& nKey, LanguageType eLnge, LanguageType eNewLnge); + + /** Similar to PutEntry and + PutandConvertEntry or + PutandConvertEntrySystem, the format code string + passed is considered to be of language/country eLnge. If + eLnge==LANGUAGE_SYSTEM the format code has to match eSysLnge, and if + eSysLnge is not the current application locale the format code is + converted to the current locale. Additionally, if the format code + represents an old "automatic" currency format, it is converted to the + new default currency format of the eLnge locale. The rString format + code passed as an argument may get adapted in case eLnge was used (or + is LANGUAGE_SYSTEM and eSysLnge is identical); in case it wasn't the + method works on a copy instead, otherwise the resulting string would + not match eSysLnge anymore. + +

    This method was introduced to handle the legacy currency formats of + the "autotbl.fmt" file used by Calc and Writer and convert them to + fixed currency codes of the actual currency. Note that in the case of + legacy currency formats no special attribution is converted, only the + default currency format of the locale is chosen, and that new fixed + currency codes are of course not converted to other currencies. The + method may also be used as a general method taking, converting and + inserting almost arbitrary format codes. To insert or use, for example, + the default currency format code matching the current locale, the + method could be called with
    + + + GetIndexPuttingAndConverting( "0 $", LANGUAGE_SYSTEM, LANGUAGE_ENGLISH_US, ...); + + + @return + The index key of the resulting number format. If the format code + was empty, could not be converted or has errors, the eLnge locale's + standard number format is chosen instead. The index key is + guaranteed to represent some valid number format. If + rNewInserted==false and rCheckPos>0 the format code has errors + and/or could not be converted. + */ + sal_uInt32 GetIndexPuttingAndConverting(OUString& rString, LanguageType eLnge, + LanguageType eSysLnge, SvNumFormatType& rType, + bool& rNewInserted, sal_Int32& rCheckPos); + + /** Create a format code string using format nIndex as a template and + applying other settings (passed from the dialog) */ + OUString GenerateFormat(sal_uInt32 nIndex, LanguageType eLnge = LANGUAGE_DONTKNOW, + bool bThousand = false, bool IsRed = false, sal_uInt16 nPrecision = 0, + sal_uInt16 nLeadingCnt = 1); + + /** Analyze an input string + @return + if input is a number or is matching a format F_Index + F_Index is set to a matching format if number, the value is + returned in fOutNumber + if input is not a number + */ + bool IsNumberFormat(const OUString& sString, sal_uInt32& F_Index, double& fOutNumber, + SvNumInputOptions eInputOptions = SvNumInputOptions::NONE); + + /// Format a number according to a format index, return string and color + void GetOutputString(const double& fOutNumber, sal_uInt32 nFIndex, OUString& sOutString, + const Color** ppColor, bool bUseStarFormat = false); + + /** Format a string according to a format index, return string and color. + Formats only if the format code is of type text or the 4th subcode + of a format code is specified, otherwise sOutString will be == "" */ + void GetOutputString(const OUString& sString, sal_uInt32 nFIndex, OUString& sOutString, + const Color** ppColor, bool bUseStarFormat = false); + + /** Format a number according to the standard default format matching + the given format index. rOutString will be the real cell string (e.g. + a number rounded by the cell format, which rounded value is used + in the filtering condition now), instead of the EditFormat string + (e.g a not rounded value, which is visible during editing).*/ + void GetInputLineString(const double& fOutNumber, sal_uInt32 nFIndex, OUString& rOutString, + bool bFiltering = false, bool bForceSystemLocale = false); + + /** Format a number according to a format code string to be scanned. + @return + if format code contains an error + else, in which case the string and color are returned. + */ + bool GetPreviewString(const OUString& sFormatString, double fPreviewNumber, + OUString& sOutString, const Color** ppColor, LanguageType eLnge, + bool bUseStarFormat = false); + + /** Same as GetPreviewString but the format code string + may be either language/country eLnge or en_US english US */ + bool GetPreviewStringGuess(const OUString& sFormatString, double fPreviewNumber, + OUString& sOutString, const Color** ppColor, + LanguageType eLnge = LANGUAGE_DONTKNOW); + + /** Format a string according to a format code string to be scanned. + @return + if format code contains an error + else, in which case the string and color are returned. + */ + bool GetPreviewString(const OUString& sFormatString, const OUString& sPreviewString, + OUString& sOutString, const Color** ppColor, + LanguageType eLnge = LANGUAGE_DONTKNOW); + + /** Test whether the format code string is already present in container + @return + NUMBERFORMAT_ENTRY_NOT_FOUND if not found, else the format index. + */ + sal_uInt32 TestNewString(const OUString& sFormatString, LanguageType eLnge = LANGUAGE_DONTKNOW); + + /// Whether format index nFIndex is of type text or not + bool IsTextFormat(sal_uInt32 nFIndex) const; + + /// Get additional info of a format index, e.g. for dialog box + void GetFormatSpecialInfo(sal_uInt32 nFormat, bool& bThousand, bool& IsRed, + sal_uInt16& nPrecision, sal_uInt16& nLeadingCnt); + + /// Count of decimals + sal_uInt16 GetFormatPrecision(sal_uInt32 nFormat) const; + + /// Count of integer digits + sal_uInt16 GetFormatIntegerDigits(sal_uInt32 nFormat) const; + + /** Get additional info of a format code string, e.g. for dialog box. + Uses a temporary parse, if possible use only if format code is not + present in container yet, otherwise ineffective. + @return + 0 if format code string parsed without errors, otherwise error + position (like nCheckPos on PutEntry) + */ + sal_uInt32 GetFormatSpecialInfo(const OUString&, bool& bThousand, bool& IsRed, + sal_uInt16& nPrecision, sal_uInt16& nLeadingCnt, + LanguageType eLnge = LANGUAGE_DONTKNOW); + + /// Get return string for Calc CELL() function, "G", "D1", ... + OUString GetCalcCellReturn(sal_uInt32 nFormat) const; + + bool IsUserDefined(sal_uInt32 F_Index) const; + + /// Check if format code string may be deleted by user + bool IsUserDefined(std::u16string_view sStr, LanguageType eLnge = LANGUAGE_DONTKNOW); + + /** Return the format index of the format code string for language/country, + or NUMBERFORMAT_ENTRY_NOT_FOUND */ + sal_uInt32 GetEntryKey(std::u16string_view sStr, LanguageType eLnge = LANGUAGE_DONTKNOW); + + /// Return the format for a format index + const SvNumberformat* GetEntry(sal_uInt32 nKey) const; + + /// Obtain substituted GetFormatEntry(), i.e. system formats. + const SvNumberformat* GetSubstitutedEntry(sal_uInt32 nKey, sal_uInt32& o_rNewKey) const; + + /// Return the format index of the standard default number format for language/country + sal_uInt32 GetStandardIndex(LanguageType eLnge = LANGUAGE_DONTKNOW); + + /// Return the format index of the default format of a type for language/country + sal_uInt32 GetStandardFormat(SvNumFormatType eType, LanguageType eLnge = LANGUAGE_DONTKNOW); + + /** Return the format index of the default format of a type for language/country. + Maybe not the default format but a special builtin format, e.g. for + NF_TIME_HH_MMSS00, if that format is passed in nFIndex. */ + sal_uInt32 GetStandardFormat(sal_uInt32 nFIndex, SvNumFormatType eType, LanguageType eLnge); + + /** Return the format index of the default format of a type for language/country. + Maybe not the default format but a special builtin format, e.g. for + NF_TIME_HH_MMSS00, or NF_TIME_HH_MMSS if fNumber >= 1.0 */ + sal_uInt32 GetStandardFormat(double fNumber, sal_uInt32 nFIndex, SvNumFormatType eType, + LanguageType eLnge); + + /// Whether nFIndex is a special builtin format + bool IsSpecialStandardFormat(sal_uInt32 nFIndex, LanguageType eLnge); + + /** Return a time format that best matches fNumber. */ + sal_uInt32 GetTimeFormat(double fNumber, LanguageType eLnge, bool bForceDuration); + + /** Return a format and type that best matches the value of fNumber if + fNumber is assumed to be a date, time or datetime value, but unknown + which. Originally introduced for Chart databrowser editor, probably + should not be used otherwise. */ + sal_uInt32 GuessDateTimeFormat(SvNumFormatType& rType, double fNumber, LanguageType eLnge); + + /** Return the corresponding edit format of a format. + + nFIndex, eType and pFormat (if not nullptr) are assumed to match each + other / be of one format. The locale to use is obtained from pFormat, + if nullptr then LANGUAGE_SYSTEM is used. This can be overridden by + specifying eForLocale other than LANGUAGE_DONTKNOW. + */ + sal_uInt32 GetEditFormat(double fNumber, sal_uInt32 nFIndex, SvNumFormatType eType, + SvNumberformat const* pFormat, + LanguageType eForLocale = LANGUAGE_DONTKNOW); + + /// Return the reference date + const Date& GetNullDate() const; + /// Return the standard decimal precision + sal_uInt16 GetStandardPrec() const; + /// Return whether zero suppression is switched on + bool GetNoZero() const; + /** Get the type of a format (or css::util::NumberFormat::UNDEFINED if no entry), + but with css::util::NumberFormat::DEFINED masked out */ + SvNumFormatType GetType(sal_uInt32 nFIndex) const; + + /// As the name says + void ClearMergeTable(); + /// Merge in all new entries from rNewTable and return a table of resulting new format indices + SvNumberFormatterIndexTable* MergeFormatter(SvNumberFormatter& rNewTable); + + /// Whether a merge table is present or not + bool HasMergeFormatTable() const; + /// Return the new format index for an old format index, if a merge table exists + sal_uInt32 GetMergeFormatIndex(sal_uInt32 nOldFmt) const; + + /** Convert the ugly old tools' Table type bloated with new'ed sal_uInt32 + entries merge table to ::std::map with old index key and new index key. + @ATTENTION! Also clears the old table using ClearMergeTable() */ + SvNumberFormatterMergeMap ConvertMergeTableToMap(); + + /** Return the format index of a builtin format for a specific language/country. + If nFormat is not a builtin format nFormat is returned. */ + sal_uInt32 GetFormatForLanguageIfBuiltIn(sal_uInt32 nFormat, + LanguageType eLnge = LANGUAGE_DONTKNOW); + + /** Return the format index for a builtin format of a specific language + @see NfIndexTableOffset + */ + sal_uInt32 GetFormatIndex(NfIndexTableOffset, LanguageType eLnge = LANGUAGE_DONTKNOW); + + /** Return enum index of a format index of a builtin format, + NF_INDEX_TABLE_ENTRIES if it's not a builtin format. + @see NfIndexTableOffset + */ + NfIndexTableOffset GetIndexTableOffset(sal_uInt32 nFormat) const; + + /** Set evaluation type and order of input date strings + @see NfEvalDateFormat + */ + void SetEvalDateFormat(NfEvalDateFormat eEDF); + NfEvalDateFormat GetEvalDateFormat() const; + + /** Set TwoDigitYearStart, how the input string scanner handles a two digit year. + Default from VCL: 1930, 30-99 19xx, 00-29 20xx + +

    Historically (prior to src513e) it was a two digit number determining + until which number the string scanner recognizes a year to be 20xx, + default <= 29 is used by SFX/OfaMiscCfg. + The name Year2000 is kept although the actual functionality is now a + TwoDigitYearStart which might be in any century. + */ + void SetYear2000(sal_uInt16 nVal); + sal_uInt16 GetYear2000() const; + static sal_uInt16 GetYear2000Default(); + + sal_uInt16 ExpandTwoDigitYear(sal_uInt16 nYear) const; + static sal_uInt16 ExpandTwoDigitYear(sal_uInt16 nYear, sal_uInt16 nTwoDigitYearStart); + + /// Return the decimal separator matching the locale of the given format + OUString GetFormatDecimalSep(sal_uInt32 nFormat) const; + + /// Return the decimal separator matching the given locale / LanguageType. + OUString GetLangDecimalSep(LanguageType nLang) const; + + static void resetTheCurrencyTable(); + + /// Return a NfCurrencyTable with pointers to NfCurrencyEntry entries + static const NfCurrencyTable& GetTheCurrencyTable(); + + /** Searches, according to the default locale currency, an entry of the + CurrencyTable which is not the first (LANGUAGE_SYSTEM) entry. + @return + if not found + else pointer to NfCurrencyEntry + */ + static const NfCurrencyEntry* MatchSystemCurrency(); + + /** Return a NfCurrencyEntry matching a language/country. + If language/country is LANGUAGE_SYSTEM a MatchSystemCurrency + call is tried to get an entry. If that fails or the corresponding + language/country is not present the entry for LANGUAGE_SYSTEM is returned. + */ + static const NfCurrencyEntry& GetCurrencyEntry(LanguageType); + + /** Return a NfCurrencyEntry pointer matching a language/country + and currency abbreviation (AKA banking symbol). + This method is meant for the configuration of the default currency. + @return + if not found + else pointer to NfCurrencyEntry + */ + static const NfCurrencyEntry* GetCurrencyEntry(std::u16string_view rAbbrev, LanguageType eLang); + + /** Return a NfCurrencyEntry pointer matching the symbol + combination of a LegacyOnly currency. Note that this means only that + the currency matching both symbols was once used in the Office, but is + not offered in dialogs anymore. It doesn't even mean that the currency + symbol combination is valid, since the reason for removing it may have + been just that. #i61657# + @return + A matching entry, or else . + */ + static const NfCurrencyEntry* GetLegacyOnlyCurrencyEntry(std::u16string_view rSymbol, + std::u16string_view rAbbrev); + + /** Set the default system currency. The combination of abbreviation and + language must match an existent element of theCurrencyTable. If not, + the SYSTEM (current locale) entry becomes the default. + This method is meant for the configuration of the default currency. + */ + static void SetDefaultSystemCurrency(std::u16string_view rAbbrev, LanguageType eLang); + + /** Get all standard formats for a specific currency, formats are + appended to the NfWSStringsDtor list. + @param bBank + : generate only format strings with currency abbreviation + : mixed format strings + @return + position of default format + */ + sal_uInt16 GetCurrencyFormatStrings(NfWSStringsDtor&, const NfCurrencyEntry&, bool bBank) const; + + /** Whether nFormat is of type css::util::NumberFormat::CURRENCY and the format code + contains a new SYMBOLTYPE_CURRENCY and if so which one [$xxx-nnn]. + If ppEntry is not NULL and exactly one entry is found, a [$xxx-nnn] is + returned, even if the format code only contains [$xxx] ! + */ + bool GetNewCurrencySymbolString(sal_uInt32 nFormat, OUString& rSymbol, + const NfCurrencyEntry** ppEntry, bool* pBank = nullptr) const; + + /** Look up the corresponding NfCurrencyEntry matching + rSymbol (may be CurrencySymbol or CurrencyAbbreviation) and possibly + a rExtension (being yyy of [$xxx-yyy]) or a given language/country + value. Tries to match a rSymbol with rExtension first, then with + eFormatLanguage, then rSymbol only. This is because a currency entry + might have been constructed using I18N locale data where a used locale + of a currency format code must not necessarily match the locale of + the locale data itself, e.g. [$HK$-40C] (being "zh_HK" locale) in + zh_CN locale data. Here the rExtension would have the value 0x40c but + eFormatLanguage of the number format would have the value of zh_CN + locale, the value with which the corresponding CurrencyEntry is + constructed. + + @param bFoundBank + Only used for output. + If the return value is not this value is set to if + the matching entry was found by comparing rSymbol against the + CurrencyAbbreviation (AKA BankSymbol). + If the return value is the value of bFoundBank is undefined. + @param rSymbol + Currency symbol, preferably obtained of a format by a call to + SvNumberformat::GetNewCurrencySymbol() + @param rExtension + Currency extension, preferably obtained of a format by a call to + SvNumberformat::GetNewCurrencySymbol() + @param eFormatLanguage + The language/country value of the format of which rSymbol and + rExtension are obtained (SvNumberformat::GetLanguage()). + @param bOnlyStringLanguage + If only entries with language/country of rExtension are + checked, no match on eFormatLanguage. If rExtension is empty all + entries are checked. + @return + The matching entry if unique (in which case bFoundBank is set), + else . + */ + static const NfCurrencyEntry* GetCurrencyEntry(bool& bFoundBank, std::u16string_view rSymbol, + const OUString& rExtension, + LanguageType eFormatLanguage, + bool bOnlyStringLanguage = false); + + /// Get compatibility ("automatic" old style) currency from I18N locale data + void GetCompatibilityCurrency(OUString& rSymbol, OUString& rAbbrev) const; + + /// Fill rList with the language/country codes that have been allocated + void GetUsedLanguages(std::vector& rList); + + /// Fill a NfKeywordIndex table with keywords of a language/country + void FillKeywordTable(NfKeywordTable& rKeywords, LanguageType eLang); + + /** Fill a NfKeywordIndex table with keywords usable in Excel export with + GetFormatStringForExcel() or SvNumberformat::GetMappedFormatstring() */ + void FillKeywordTableForExcel(NfKeywordTable& rKeywords); + + /** Return a format code string suitable for Excel export. + + @param rTempFormatter + SvNumberFormatter to use if a non-en-US format code needs to be + converted and put, should not be the same formatter to not + pollute the entries of this one here. + */ + OUString GetFormatStringForExcel(sal_uInt32 nKey, const NfKeywordTable& rKeywords, + SvNumberFormatter& rTempFormatter) const; + + /** Return a keyword for a language/country and NfKeywordIndex + for XML import, to generate number format strings. */ + OUString GetKeyword(LanguageType eLnge, sal_uInt16 nIndex); + + /** Return the GENERAL keyword in proper case ("General") for a + language/country, used in XML import */ + OUString GetStandardName(LanguageType eLnge); + + /** Check if a specific locale has supported locale data. */ + static bool IsLocaleInstalled(LanguageType eLang); + + /** Obtain NfKeywordTable used with a format, possibly localized. + + XXX NOTE: the content (actual keywords) is only valid as long as the + locale context of the associated ImpSvNumberformatScan instance does + not change to a locale with different keywords, which may happen + anytime with a call (implicit or explicit) to + SvNumberFormatter::ChangeIntl(). If needed longer, copy-create another + NfKeywordTable instance or copy individual elements. + + If the format specified with nKey does not exist, the content of the + NfKeywordTable matches the locale with which the SvNumberFormatter + instance was created and initialized. + + This function preliminary exists for unit tests and otherwise is + pretty much useless. + */ + const NfKeywordTable& GetKeywords(sal_uInt32 nKey); + + /** Access for unit tests. */ + const NfKeywordTable& GetEnglishKeywords() const; + + /** Access for unit tests. */ + const std::vector& GetStandardColors() const; + + /** Access for unit tests. */ + size_t GetMaxDefaultColors() const; + + struct InputScannerPrivateAccess + { + friend class ImpSvNumberInputScan; + + private: + InputScannerPrivateAccess() {} + }; + /** Access for input scanner to temporarily (!) switch locales. */ + OnDemandLocaleDataWrapper& GetOnDemandLocaleDataWrapper(const InputScannerPrivateAccess&) + { + return xLocaleData; + } + +private: + mutable ::osl::Mutex m_aMutex; + css::uno::Reference m_xContext; + LanguageTag maLanguageTag; + std::map> + aFTable; // Table of format keys to format entries + typedef std::map DefaultFormatKeysMap; + DefaultFormatKeysMap aDefaultFormatKeys; // Table of default standard to format keys + std::unique_ptr pFormatTable; // For the UI dialog + std::unique_ptr + pMergeTable; // List of indices for merging two formatters + OnDemandCharClass xCharClass; // CharacterClassification + OnDemandLocaleDataWrapper xLocaleData; // LocaleData switched between SYSTEM, ENGLISH and other + OnDemandTransliterationWrapper xTransliteration; // Transliteration loaded on demand + OnDemandCalendarWrapper xCalendar; // Calendar loaded on demand + OnDemandNativeNumberWrapper xNatNum; // Native number service loaded on demand + std::unique_ptr pStringScanner; // Input string scanner + std::unique_ptr pFormatScanner; // Format code string scanner + Link aColorLink; // User defined color table CallBack + sal_uInt32 MaxCLOffset; // Max language/country offset used + sal_uInt32 nDefaultSystemCurrencyFormat; // NewCurrency matching SYSTEM locale + LanguageType IniLnge; // Initialized setting language/country + LanguageType ActLnge; // Current setting language/country + NfEvalDateFormat eEvalDateFormat; // DateFormat evaluation + bool bNoZero; // Zero value suppression + + // cached locale data items needed almost any time + OUString aDecimalSep; + OUString aDecimalSepAlt; + OUString aThousandSep; + OUString aDateSep; + + SVL_DLLPRIVATE static volatile bool bCurrencyTableInitialized; + SVL_DLLPRIVATE static sal_uInt16 nSystemCurrencyPosition; + SVL_DLLPRIVATE static SvNumberFormatterRegistry_Impl* pFormatterRegistry; + + // get the registry, create one if none exists + SVL_DLLPRIVATE static SvNumberFormatterRegistry_Impl& GetFormatterRegistry(); + + // called by ctors + SVL_DLLPRIVATE void ImpConstruct(LanguageType eLang); + + // Generate builtin formats provided by i18n behind CLOffset, + // if bNoAdditionalFormats==false also generate additional i18n formats. + SVL_DLLPRIVATE void ImpGenerateFormats(sal_uInt32 CLOffset, bool bNoAdditionalFormats); + + // Generate additional formats provided by i18n + SVL_DLLPRIVATE void ImpGenerateAdditionalFormats( + sal_uInt32 CLOffset, + css::uno::Reference const& rNumberFormatCode, + bool bAfterChangingSystemCL); + + SVL_DLLPRIVATE SvNumberformat* ImpInsertFormat(const css::i18n::NumberFormatCode& rCode, + sal_uInt32 nPos, + bool bAfterChangingSystemCL = false, + sal_Int16 nOrgIndex = 0); + + // Return CLOffset or (MaxCLOffset + SV_COUNTRY_LANGUAGE_OFFSET) if new language/country + SVL_DLLPRIVATE sal_uInt32 ImpGetCLOffset(LanguageType eLnge) const; + + // Test whether format code already exists, then return index key, + // otherwise NUMBERFORMAT_ENTRY_NOT_FOUND + SVL_DLLPRIVATE sal_uInt32 ImpIsEntry(std::u16string_view rString, sal_uInt32 CLOffset, + LanguageType eLnge); + + // Create builtin formats for language/country if necessary, return CLOffset + SVL_DLLPRIVATE sal_uInt32 ImpGenerateCL(LanguageType eLnge); + + // Create theCurrencyTable with all NfCurrencyEntry + SVL_DLLPRIVATE static void ImpInitCurrencyTable(); + + // Return the format index of the currency format of the system locale. + // Format is created if not already present. + SVL_DLLPRIVATE sal_uInt32 ImpGetDefaultSystemCurrencyFormat(); + + // Return the format index of the currency format of the current locale. + // Format is created if not already present. + SVL_DLLPRIVATE sal_uInt32 ImpGetDefaultCurrencyFormat(); + + // Return the default format for a given type and current locale. + // May ONLY be called from within GetStandardFormat(). + SVL_DLLPRIVATE sal_uInt32 ImpGetDefaultFormat(SvNumFormatType nType); + + // Return the index in a sequence of format codes matching an enum of + // NfIndexTableOffset. If not found 0 is returned. If the sequence doesn't + // contain any format code elements a default element is created and inserted. + SVL_DLLPRIVATE sal_Int32 ImpGetFormatCodeIndex( + css::uno::Sequence& rSeq, const NfIndexTableOffset nTabOff); + + // Adjust a sequence of format codes to contain only one (THE) default + // instead of multiple defaults for short/medium/long types. + // If there is no medium but a short and a long default the long is taken. + // Non-PRODUCT version may check locale data for matching defaults in one + // FormatElement group. + SVL_DLLPRIVATE void ImpAdjustFormatCodeDefault(css::i18n::NumberFormatCode* pFormatArr, + sal_Int32 nCount); + + // Obtain the format entry for a given key index. + SVL_DLLPRIVATE SvNumberformat* GetFormatEntry(sal_uInt32 nKey); + SVL_DLLPRIVATE const SvNumberformat* GetFormatEntry(sal_uInt32 nKey) const; + + // used as a loop body inside of GetNewCurrencySymbolString() and GetCurrencyEntry() + static bool ImpLookupCurrencyEntryLoopBody(const NfCurrencyEntry*& pFoundEntry, + bool& bFoundBank, const NfCurrencyEntry* pData, + sal_uInt16 nPos, std::u16string_view rSymbol); + + // link to be set at SvtSysLocaleOptions::SetCurrencyChangeLink() + DECL_DLLPRIVATE_STATIC_LINK(SvNumberFormatter, CurrencyChangeLink, LinkParamNone*, void); + + // return position of a special character + sal_Int32 ImpPosToken(const OUStringBuffer& sFormat, sal_Unicode token, + sal_Int32 nStartPos = 0) const; + + // Substitute a format during GetFormatEntry(), i.e. system formats. + SvNumberformat* ImpSubstituteEntry(SvNumberformat* pFormat, sal_uInt32* o_pRealKey = nullptr); + + // own mutex, may also be used by internal class SvNumberFormatterRegistry_Impl + static ::osl::Mutex& GetGlobalMutex(); + ::osl::Mutex& GetInstanceMutex() const { return m_aMutex; } + +public: + // called by SvNumberFormatterRegistry_Impl::Notify if the default system currency changes + void ResetDefaultSystemCurrency(); + + // Called by SvNumberFormatterRegistry_Impl::Notify if the system locale's + // date acceptance patterns change. + void InvalidateDateAcceptancePatterns(); + + // Replace the SYSTEM language/country format codes. Called upon change of + // the user configurable locale. + // Old compatibility codes are replaced, user defined are converted, and + // new format codes are appended. + void ReplaceSystemCL(LanguageType eOldLanguage); + + const css::uno::Reference& GetComponentContext() const; + + //! The following method is not to be used from outside but must be + //! public for the InputScanner. + // return the current FormatScanner + const ImpSvNumberformatScan* GetFormatScanner() const; + + //! The following methods are not to be used from outside but must be + //! public for the InputScanner and FormatScanner. + + // return current (!) Locale + const LanguageTag& GetLanguageTag() const; + + // return corresponding Transliteration wrapper + const ::utl::TransliterationWrapper* GetTransliteration() const; + + // return the corresponding CharacterClassification wrapper + const CharClass* GetCharClass() const; + + // return the corresponding LocaleData wrapper + const LocaleDataWrapper* GetLocaleData() const; + + // return the corresponding Calendar wrapper + CalendarWrapper* GetCalendar() const; + + // return the corresponding NativeNumberSupplier wrapper + const NativeNumberWrapper* GetNatNum() const; + + // cached locale data items + + // return the corresponding decimal separator + const OUString& GetNumDecimalSep() const; + + // return the corresponding decimal separator alternative + const OUString& GetNumDecimalSepAlt() const; + + // return the corresponding group (AKA thousand) separator + const OUString& GetNumThousandSep() const; + + // return the corresponding date separator + const OUString& GetDateSep() const; + + // checks for decimal separator and optional alternative + bool IsDecimalSep(std::u16string_view rStr) const; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/numuno.hxx b/include/svl/numuno.hxx new file mode 100644 index 000000000..a439b9559 --- /dev/null +++ b/include/svl/numuno.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_NUMUNO_HXX +#define INCLUDED_SVL_NUMUNO_HXX + +#include +#include +#include +#include +#include +#include + +class SvNumberFormatter; +class SvNumFmtSuppl_Impl; + +namespace comphelper +{ + class SharedMutex; +} + + +// SvNumberFormatsSupplierObj: aggregate to document, +// construct with SvNumberFormatter + +class SVL_DLLPUBLIC SvNumberFormatsSupplierObj : public cppu::WeakAggImplHelper2< + css::util::XNumberFormatsSupplier, + css::lang::XUnoTunnel> +{ +private: + std::unique_ptr pImpl; + +public: + SvNumberFormatsSupplierObj(); + SvNumberFormatsSupplierObj(SvNumberFormatter* pForm); + virtual ~SvNumberFormatsSupplierObj() override; + + void SetNumberFormatter(SvNumberFormatter* pNew); + SvNumberFormatter* GetNumberFormatter() const; + + // XNumberFormatsSupplier + virtual css::uno::Reference< css::beans::XPropertySet > SAL_CALL + getNumberFormatSettings() override; + virtual css::uno::Reference< css::util::XNumberFormats > SAL_CALL + getNumberFormats() override; + + // XUnoTunnel + UNO3_GETIMPLEMENTATION_DECL(SvNumberFormatsSupplierObj) + + ::comphelper::SharedMutex& getSharedMutex() const; +}; + +#endif // INCLUDED_SVL_NUMUNO_HXX + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/ondemand.hxx b/include/svl/ondemand.hxx new file mode 100644 index 000000000..4a0a91b18 --- /dev/null +++ b/include/svl/ondemand.hxx @@ -0,0 +1,349 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + On demand instantiation and initialization of several i18n wrappers, + helping the number formatter to not perform worse than it already does. + */ + +/** @short + Switch between LANGUAGE_SYSTEM and LANGUAGE_ENGLISH_US and any other + LocaleDataWrapper. + SvNumberformatter uses it upon switching locales. + + @descr + Avoids reloading and analysing of locale data again and again. + + @ATTENTION + If the default ctor is used the init() method MUST be called before + accessing any locale data. The passed parameters Locale and LanguageType + must match each other. + */ + +class OnDemandLocaleDataWrapper +{ + css::uno::Reference m_xContext; + SvtSysLocale aSysLocale; + LanguageType eCurrentLanguage; + LanguageType eLastAnyLanguage; + std::optional moEnglish; + std::optional moAny; + int nCurrent; // 0 == system, 1 == english, 2 == any + bool bInitialized; + +public: + OnDemandLocaleDataWrapper() + : eLastAnyLanguage(LANGUAGE_DONTKNOW) + , nCurrent(0) + , bInitialized(false) + { + eCurrentLanguage = LANGUAGE_SYSTEM; + } + + bool isInitialized() const { return bInitialized; } + + void init(const css::uno::Reference& rxContext, + const LanguageTag& rLanguageTag) + { + m_xContext = rxContext; + changeLocale(rLanguageTag); + bInitialized = true; + } + + void changeLocale(const LanguageTag& rLanguageTag) + { + LanguageType eLang = rLanguageTag.getLanguageType(false); + if (eLang == LANGUAGE_SYSTEM) + nCurrent = 0; + else if (eLang == LANGUAGE_ENGLISH_US) + { + if (!moEnglish) + moEnglish.emplace(m_xContext, rLanguageTag); + nCurrent = 1; + } + else + { + if (!moAny) + { + moAny.emplace(m_xContext, rLanguageTag); + eLastAnyLanguage = eLang; + } + else if (eLastAnyLanguage != eLang) + { + moAny.emplace(m_xContext, rLanguageTag); + eLastAnyLanguage = eLang; + } + nCurrent = 2; + } + eCurrentLanguage = eLang; + } + + LanguageType getCurrentLanguage() const { return eCurrentLanguage; } + + const LocaleDataWrapper* get() const + { + switch (nCurrent) + { + case 0: + return &aSysLocale.GetLocaleData(); + case 1: + return &*moEnglish; + case 2: + return &*moAny; + default: + assert(false); + return nullptr; + } + } + const LocaleDataWrapper* operator->() const { return get(); } + const LocaleDataWrapper& operator*() const { return *get(); } +}; + +/** Load a calendar only if it's needed. Keep calendar for "en-US" locale + separately, as there can be alternation between locale dependent and + locale independent formats. + SvNumberformatter uses it upon switching locales. + + @ATTENTION If the default ctor is used the init() method MUST be called + before accessing the calendar. + */ +class OnDemandCalendarWrapper +{ + css::uno::Reference m_xContext; + css::lang::Locale aEnglishLocale; + css::lang::Locale aLocale; + mutable css::lang::Locale aLastAnyLocale; + mutable std::optional moEnglish; + mutable std::optional moAny; + +public: + OnDemandCalendarWrapper() + { + LanguageTag aEnglishLanguageTag(LANGUAGE_ENGLISH_US); + aEnglishLocale = aEnglishLanguageTag.getLocale(); + aLastAnyLocale = aEnglishLocale; + } + + void init(const css::uno::Reference& rxContext, + const css::lang::Locale& rLocale) + { + m_xContext = rxContext; + changeLocale(rLocale); + moEnglish.reset(); + moAny.reset(); + } + + void changeLocale(const css::lang::Locale& rLocale) { aLocale = rLocale; } + + CalendarWrapper* get() const + { + CalendarWrapper* pPtr; + if (aLocale == aEnglishLocale) + { + if (!moEnglish) + { + moEnglish.emplace(m_xContext); + moEnglish->loadDefaultCalendar(aEnglishLocale); + } + pPtr = &*moEnglish; + } + else + { + if (!moAny) + { + moAny.emplace(m_xContext); + moAny->loadDefaultCalendar(aLocale); + aLastAnyLocale = aLocale; + } + else if (aLocale != aLastAnyLocale) + { + moAny->loadDefaultCalendar(aLocale); + aLastAnyLocale = aLocale; + } + pPtr = &*moAny; + } + return pPtr; + } +}; + +/** Load a transliteration only if it's needed. + SvNumberformatter uses it upon switching locales. + @ATTENTION If the default ctor is used the init() method MUST be called + before accessing the transliteration. + */ +class OnDemandTransliterationWrapper +{ + css::uno::Reference m_xContext; + LanguageType eLanguage; + TransliterationFlags nType; + mutable std::optional<::utl::TransliterationWrapper> moTransliterate; + mutable bool bValid; + bool bInitialized; + +public: + OnDemandTransliterationWrapper() + : eLanguage(LANGUAGE_SYSTEM) + , nType(TransliterationFlags::NONE) + , bValid(false) + , bInitialized(false) + { + } + + bool isInitialized() const { return bInitialized; } + + void init(const css::uno::Reference& rxContext, LanguageType eLang) + { + m_xContext = rxContext; + nType = TransliterationFlags::IGNORE_CASE; + changeLocale(eLang); + moTransliterate.reset(); + bInitialized = true; + } + + void changeLocale(LanguageType eLang) + { + bValid = false; + eLanguage = eLang; + } + + const ::utl::TransliterationWrapper* get() const + { + if (!bValid) + { + if (!moTransliterate) + moTransliterate.emplace(m_xContext, nType); + moTransliterate->loadModuleIfNeeded(eLanguage); + bValid = true; + } + return &*moTransliterate; + } + + const ::utl::TransliterationWrapper* operator->() const { return get(); } +}; + +/** Load a native number service wrapper only if it's needed. + SvNumberformatter uses it. + + @ATTENTION + If the default ctor is used the init() method MUST be called + before accessing the native number supplier. + */ +class OnDemandNativeNumberWrapper +{ + css::uno::Reference m_xContext; + mutable std::optional moNativeNumber; + +public: + OnDemandNativeNumberWrapper() {} + + void init(const css::uno::Reference& rxContext) + { + m_xContext = rxContext; + moNativeNumber.reset(); + } + + NativeNumberWrapper* get() const + { + if (!moNativeNumber) + moNativeNumber.emplace(m_xContext); + return &*moNativeNumber; + } +}; + +/** @short + SvNumberformatter uses it upon switching locales. + + @descr + Avoids reloading and analysing of locale data again and again. + + @ATTENTION + If the default ctor is used the init() method MUST be called before + accessing any locale data. + */ + +class OnDemandCharClass +{ + std::optional moCharClass1; + std::optional moCharClass2; + int nCurrent; // -1 == uninitialised, 0 == class1, 1 == class2 + +public: + OnDemandCharClass() + : nCurrent(-1) + { + } + + void changeLocale(const css::uno::Reference& xContext, + const LanguageTag& rLanguageTag) + { + // check for existing match + if (moCharClass1 && moCharClass1->getLanguageTag() == rLanguageTag) + { + nCurrent = 0; + return; + } + if (moCharClass2 && moCharClass2->getLanguageTag() == rLanguageTag) + { + nCurrent = 1; + return; + } + // no match - update one the current entries + if (nCurrent == -1 || nCurrent == 1) + { + moCharClass1.emplace(xContext, rLanguageTag); + nCurrent = 0; + } + else + { + moCharClass2.emplace(xContext, rLanguageTag); + nCurrent = 1; + } + } + + const CharClass* get() const + { + switch (nCurrent) + { + case 0: + return &*moCharClass1; + case 1: + return &*moCharClass2; + default: + assert(false); + return nullptr; + } + } + const CharClass* operator->() const { return get(); } + const CharClass& operator*() const { return *get(); } +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/outstrm.hxx b/include/svl/outstrm.hxx new file mode 100644 index 000000000..f85b26515 --- /dev/null +++ b/include/svl/outstrm.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_OUTSTRM_HXX +#define INCLUDED_SVL_OUTSTRM_HXX + +#include +#include +#include + +namespace com::sun::star::io +{ +class XOutputStream; +} + +class SVL_DLLPUBLIC SvOutputStream final : public SvStream +{ + css::uno::Reference m_xStream; + + SVL_DLLPRIVATE virtual std::size_t GetData(void*, std::size_t) override; + + SVL_DLLPRIVATE virtual std::size_t PutData(void const* pData, std::size_t nSize) override; + + SVL_DLLPRIVATE virtual sal_uInt64 SeekPos(sal_uInt64) override; + + SVL_DLLPRIVATE virtual void FlushData() override; + + SVL_DLLPRIVATE virtual void SetSize(sal_uInt64) override; + +public: + SvOutputStream(css::uno::Reference xTheStream); + + virtual ~SvOutputStream() override; +}; + +#endif // INCLUDED_SVL_OUTSTRM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/ownlist.hxx b/include/svl/ownlist.hxx new file mode 100644 index 000000000..cd93e6436 --- /dev/null +++ b/include/svl/ownlist.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_OWNLIST_HXX +#define INCLUDED_SVL_OWNLIST_HXX + +#include +#include +#include + +namespace com::sun::star::beans { struct PropertyValue; } +namespace com::sun::star::uno { template class Sequence; } + +class SvCommand +/* + Contains a string that defines the command and another string for the + command arguments. If such a command were given in the command line, + it would look like this: command = argument +*/ +{ + OUString aCommand; + OUString aArgument; +public: + SvCommand( const OUString & rCommand, const OUString & rArg ) + { + aCommand = rCommand; + aArgument = rArg; + } + const OUString & GetCommand() const { return aCommand; } + const OUString & GetArgument() const { return aArgument; } +}; + +class SVL_DLLPUBLIC SvCommandList +/* + The list contains objects of type SvCommand. + If an object is inserted, it is copied and inserted at the end + of the list. + */ +{ +private: + ::std::vector< SvCommand > aCommandList; + +public: + void Append( const OUString & rCommand, const OUString & rArg ); + + void FillFromSequence( const css::uno::Sequence < css::beans::PropertyValue >& ); + void FillSequence( css::uno::Sequence < css::beans::PropertyValue >& ) const; + + size_t size() const { return aCommandList.size(); } + + SvCommand const & operator[]( size_t i) { + return aCommandList[ i ]; + } + +}; + +#endif // INCLUDED_SVL_OWNLIST_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/pickerhistoryaccess.hxx b/include/svl/pickerhistoryaccess.hxx new file mode 100644 index 000000000..7e855f17a --- /dev/null +++ b/include/svl/pickerhistoryaccess.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_PICKERHISTORYACCESS_HXX +#define INCLUDED_SVL_PICKERHISTORYACCESS_HXX + +#include + +#include + + +namespace svt +{ + + + SVL_DLLPUBLIC void addFolderPicker( + const css::uno::Reference< css::uno::XInterface >& _rxPicker ); + + SVL_DLLPUBLIC void addFilePicker( + const css::uno::Reference< css::uno::XInterface >& _rxPicker ); + + +} // namespace svt + + +#endif // INCLUDED_SVL_PICKERHISTORYACCESS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/poolcach.hxx b/include/svl/poolcach.hxx new file mode 100644 index 000000000..fe06ce416 --- /dev/null +++ b/include/svl/poolcach.hxx @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_POOLCACH_HXX +#define INCLUDED_SVL_POOLCACH_HXX + +#include +#include + +class SfxItemPool; +class SfxItemSet; +class SfxPoolItem; +class SfxSetItem; + +class SVL_DLLPUBLIC SfxItemPoolCache +{ + struct SfxItemModifyImpl + { + const SfxSetItem *pOrigItem; + SfxSetItem *pPoolItem; + }; + + SfxItemPool *pPool; + std::vector + m_aCache; + const SfxItemSet *pSetToPut; + const SfxPoolItem *pItemToPut; + +public: + SfxItemPoolCache( SfxItemPool *pPool, + const SfxPoolItem *pPutItem ); + SfxItemPoolCache( SfxItemPool *pPool, + const SfxItemSet *pPutSet ); + ~SfxItemPoolCache(); + + const SfxSetItem& ApplyTo( const SfxSetItem& rSetItem ); +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/poolitem.hxx b/include/svl/poolitem.hxx new file mode 100644 index 000000000..10a7901b4 --- /dev/null +++ b/include/svl/poolitem.hxx @@ -0,0 +1,333 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_POOLITEM_HXX +#define INCLUDED_SVL_POOLITEM_HXX + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +class IntlWrapper; + +enum class SfxItemKind : sal_Int8 +{ + NONE, + DeleteOnIdle, + StaticDefault, + PoolDefault +}; + +#define SFX_ITEMS_OLD_MAXREF 0xffef +#define SFX_ITEMS_MAXREF 0xfffffffe +#define SFX_ITEMS_SPECIAL 0xffffffff + +#define CONVERT_TWIPS 0x80 // Uno conversion for measurement (for MemberId) + +// warning, if there is no boolean inside the any this will always return the value false +inline bool Any2Bool( const css::uno::Any&rValue ) +{ + bool bValue = false; + if( !(rValue >>= bValue) ) + { + sal_Int32 nNum = 0; + if( rValue >>= nNum ) + bValue = nNum != 0; + } + + return bValue; +} + +/* + * The values of this enum describe the degree of textual + * representation of an item after calling the virtual + * method . + */ +enum class SfxItemPresentation +{ + Nameless, + Complete +}; + +/** + * These values have to match the values in the + * css::frame::status::ItemState IDL + * to be found at offapi/com/sun/star/frame/status/ItemState.idl +*/ +enum class SfxItemState { + + /** Specifies an unknown state. */ + UNKNOWN = 0, + + /** Specifies that the property is currently disabled. */ + DISABLED = 0x0001, + + /** Specifies that the property is currently in a don't care state. + *
    + * This is normally used if a selection provides more than one state + * for a property at the same time. + */ + DONTCARE = 0x0010, + + /** Specifies that the property is currently in a default state. */ + DEFAULT = 0x0020, + + /** The property has been explicitly set to a given value hence we know + * we are not taking the default value. + *
    + * For example, you may want to get the font color and it might either + * be the default one or one that has been explicitly set. + */ + SET = 0x0040 +}; + +#define INVALID_POOL_ITEM reinterpret_cast(-1) + +class SfxItemPool; +class SfxItemSet; +typedef struct _xmlTextWriter* xmlTextWriterPtr; + +class SVL_DLLPUBLIC SfxPoolItem +{ +friend class SfxItemPool; +friend class SfxItemDisruptor_Impl; +friend class SfxItemPoolCache; +friend class SfxItemSet; +friend class SfxVoidItem; + + mutable sal_uInt32 m_nRefCount; + sal_uInt16 m_nWhich; + SfxItemKind m_nKind; + +private: + inline void SetRefCount(sal_uInt32 n); + inline void SetKind( SfxItemKind n ); +public: + inline void AddRef(sal_uInt32 n = 1) const; +private: + inline sal_uInt32 ReleaseRef(sal_uInt32 n = 1) const; + +protected: + explicit SfxPoolItem( sal_uInt16 nWhich = 0 ); + SfxPoolItem( const SfxPoolItem& rCopy) + : SfxPoolItem(rCopy.m_nWhich) {} + +public: + virtual ~SfxPoolItem(); + + void SetWhich( sal_uInt16 nId ) + { + // can only change the Which before we are in a set + assert(m_nRefCount==0); + m_nWhich = nId; + } + sal_uInt16 Which() const { return m_nWhich; } + // StaticWhichCast asserts if the TypedWhichId is not matching its type, otherwise it returns a reference. + // You can use StaticWhichCast when you are sure about the type at compile time -- like a static_cast. + template T& StaticWhichCast(TypedWhichId nId) + { + (void)nId; + assert(nId == m_nWhich); + assert(dynamic_cast(this)); + return *static_cast(this); + } + template const T& StaticWhichCast(TypedWhichId nId) const + { + (void)nId; + assert(nId == m_nWhich); + assert(dynamic_cast(this)); + return *static_cast(this); + } + // DynamicWhichCast returns nullptr if the TypedWhichId is not matching its type, otherwise it returns a typed pointer. + // it asserts if the TypedWhichId matches its Which, but not the RTTI type. + // You can use DynamicWhichCast when you are not sure about the type at compile time -- like a dynamic_cast. + template T* DynamicWhichCast(TypedWhichId nId) + { + if(m_nWhich != nId) + return nullptr; + assert(dynamic_cast(this)); + return static_cast(this); + } + template const T* DynamicWhichCast(TypedWhichId nId) const + { + if(m_nWhich != nId) + return nullptr; + assert(dynamic_cast(this)); + return static_cast(this); + } + virtual bool operator==( const SfxPoolItem& ) const = 0; + bool operator!=( const SfxPoolItem& rItem ) const + { return !(*this == rItem); } + + // Sorting is only used for faster searching in a pool which contains large quantities + // of a single kind of pool item. + virtual bool operator<( const SfxPoolItem& ) const { assert(false); return false; } + virtual bool IsSortable() const { return false; } + + // Some item types cannot be IsSortable() (such as because they are modified while stored + // in a pool, which would change the ordering position, see e.g. 585e0ac43b9bd8a2f714903034). + // To improve performance in such cases it is possible to reimplement Lookup() to do a linear + // lookup optimized for the specific class (avoiding virtual functions may allow the compiler + // to generate better code and class-specific optimizations such as hashing or caching may + // be used.) + // If reimplemented, the Lookup() function should search [begin,end) for an item matching + // this object and return an iterator pointing to the item or the end iterator. + virtual bool HasLookup() const { return false; } + typedef std::vector::const_iterator lookup_iterator; + virtual lookup_iterator Lookup(lookup_iterator /*begin*/, lookup_iterator end ) const + { assert( false ); return end; } + + /** @return true if it has a valid string representation */ + virtual bool GetPresentation( SfxItemPresentation ePresentation, + MapUnit eCoreMetric, + MapUnit ePresentationMetric, + OUString &rText, + const IntlWrapper& rIntlWrapper ) const; + + virtual void ScaleMetrics( tools::Long lMult, tools::Long lDiv ); + virtual bool HasMetrics() const; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ); + + virtual SfxPoolItem* Clone( SfxItemPool *pPool = nullptr ) const = 0; + // clone and call SetWhich + std::unique_ptr CloneSetWhich( sal_uInt16 nNewWhich ) const; + template std::unique_ptr CloneSetWhich( TypedWhichId nId ) const + { + return std::unique_ptr(static_cast(CloneSetWhich(sal_uInt16(nId)).release())); + } + + sal_uInt32 GetRefCount() const { return m_nRefCount; } + SfxItemKind GetKind() const { return m_nKind; } + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const; + virtual boost::property_tree::ptree dumpAsJSON() const; + + /** Only SfxVoidItem shall and must return true for this. + + This avoids costly calls to dynamic_cast() + specifically in SfxItemSet::GetItemState() + */ + virtual bool IsVoidItem() const; + +private: + SfxPoolItem& operator=( const SfxPoolItem& ) = delete; +}; + +inline void SfxPoolItem::SetRefCount(sal_uInt32 n) +{ + m_nRefCount = n; + m_nKind = SfxItemKind::NONE; +} + +inline void SfxPoolItem::SetKind( SfxItemKind n ) +{ + m_nRefCount = SFX_ITEMS_SPECIAL; + m_nKind = n; +} + +inline void SfxPoolItem::AddRef(sal_uInt32 n) const +{ + assert(m_nRefCount <= SFX_ITEMS_MAXREF && "AddRef with non-Pool-Item"); + assert(n <= SFX_ITEMS_MAXREF - m_nRefCount && "AddRef: refcount overflow"); + m_nRefCount += n; +} + +inline sal_uInt32 SfxPoolItem::ReleaseRef(sal_uInt32 n) const +{ + assert(m_nRefCount <= SFX_ITEMS_MAXREF && "ReleaseRef with non-Pool-Item"); + assert(n <= m_nRefCount); + m_nRefCount -= n; + return m_nRefCount; +} + +inline bool IsPoolDefaultItem(const SfxPoolItem *pItem ) +{ + return pItem && pItem->GetKind() == SfxItemKind::PoolDefault; +} + +inline bool IsStaticDefaultItem(const SfxPoolItem *pItem ) +{ + return pItem && pItem->GetKind() == SfxItemKind::StaticDefault; +} + +inline bool IsDefaultItem( const SfxPoolItem *pItem ) +{ + return pItem && (pItem->GetKind() == SfxItemKind::StaticDefault || pItem->GetKind() == SfxItemKind::PoolDefault); +} + +inline bool IsPooledItem( const SfxPoolItem *pItem ) +{ + return pItem && pItem->GetRefCount() > 0 && pItem->GetRefCount() <= SFX_ITEMS_MAXREF; +} + +inline bool IsInvalidItem(const SfxPoolItem *pItem) +{ + return pItem == INVALID_POOL_ITEM; +} + +class SVL_DLLPUBLIC SfxVoidItem final: public SfxPoolItem +{ +public: + static SfxPoolItem* CreateDefault(); + explicit SfxVoidItem( sal_uInt16 nWhich ); + virtual ~SfxVoidItem() override; + + SfxVoidItem(SfxVoidItem const &) = default; + SfxVoidItem(SfxVoidItem &&) = default; + SfxVoidItem & operator =(SfxVoidItem const &) = delete; // due to SfxPoolItem + SfxVoidItem & operator =(SfxVoidItem &&) = delete; // due to SfxPoolItem + + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const override; + + // create a copy of itself + virtual SfxVoidItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + /** Always returns true as this is an SfxVoidItem. */ + virtual bool IsVoidItem() const override; +}; + + +class SVL_DLLPUBLIC SfxPoolItemHint final : public SfxHint +{ + SfxPoolItem* pObj; +public: + explicit SfxPoolItemHint( SfxPoolItem* Object ) : pObj(Object) {} + SfxPoolItem* GetObject() const { return pObj; } +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/ptitem.hxx b/include/svl/ptitem.hxx new file mode 100644 index 000000000..2ceb39410 --- /dev/null +++ b/include/svl/ptitem.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_PTITEM_HXX +#define INCLUDED_SVL_PTITEM_HXX + +#include +#include +#include +#include + +class SvStream; + +class SVL_DLLPUBLIC SfxPointItem final : public SfxPoolItem +{ + Point aVal; + +public: + static SfxPoolItem* CreateDefault(); + SfxPointItem(); + SfxPointItem( sal_uInt16 nWhich, const Point& rVal ); + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool operator==( const SfxPoolItem& ) const override; + + virtual SfxPointItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + const Point& GetValue() const { return aVal; } + void SetValue( const Point& rNewVal ) { + DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" ); + aVal = rNewVal; + } + + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/rectitem.hxx b/include/svl/rectitem.hxx new file mode 100644 index 000000000..94465bad4 --- /dev/null +++ b/include/svl/rectitem.hxx @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_RECTITEM_HXX +#define INCLUDED_SVL_RECTITEM_HXX + +#include +#include +#include + +class SvStream; + +class SVL_DLLPUBLIC SfxRectangleItem final : public SfxPoolItem +{ + tools::Rectangle aVal; + +public: + static SfxPoolItem* CreateDefault(); + SfxRectangleItem(); + SfxRectangleItem( sal_uInt16 nWhich, const tools::Rectangle& rVal ); + + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual SfxRectangleItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + const tools::Rectangle& GetValue() const { return aVal; } + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/rngitem.hxx b/include/svl/rngitem.hxx new file mode 100644 index 000000000..7e8caf937 --- /dev/null +++ b/include/svl/rngitem.hxx @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_RNGITEM_HXX +#define INCLUDED_SVL_RNGITEM_HXX + +#include +#include + +class SvStream; + + +class SVL_DLLPUBLIC SfxRangeItem final : public SfxPoolItem +{ +private: + sal_uInt16 nFrom; + sal_uInt16 nTo; +public: + SfxRangeItem( sal_uInt16 nWID, sal_uInt16 nFrom, sal_uInt16 nTo ); + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + virtual SfxRangeItem* Clone( SfxItemPool *pPool = nullptr ) const override; +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/setitem.hxx b/include/svl/setitem.hxx new file mode 100644 index 000000000..69ebea4b1 --- /dev/null +++ b/include/svl/setitem.hxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +class SVL_DLLPUBLIC SfxSetItem : public SfxPoolItem +{ + SfxItemSet maSet; + + SfxSetItem& operator=(const SfxSetItem&) = delete; + +public: + SfxSetItem(sal_uInt16 nWhich, SfxItemSet&& pSet); + SfxSetItem(sal_uInt16 nWhich, const SfxItemSet& rSet); + SfxSetItem(const SfxSetItem&, SfxItemPool* pPool = nullptr); + + virtual bool operator==(const SfxPoolItem&) const override; + + virtual bool GetPresentation(SfxItemPresentation ePres, MapUnit eCoreMetric, + MapUnit ePresMetric, OUString& rText, + const IntlWrapper&) const override; + + // create a copy of itself + virtual SfxSetItem* Clone(SfxItemPool* pPool = nullptr) const override = 0; + + const SfxItemSet& GetItemSet() const { return maSet; } + SfxItemSet& GetItemSet() { return maSet; } +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/sharecontrolfile.hxx b/include/svl/sharecontrolfile.hxx new file mode 100644 index 000000000..fe7171312 --- /dev/null +++ b/include/svl/sharecontrolfile.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_SHARECONTROLFILE_HXX +#define INCLUDED_SVL_SHARECONTROLFILE_HXX + +#include + +#include +#include + +namespace com::sun::star::io { class XInputStream; } +namespace com::sun::star::io { class XOutputStream; } +namespace com::sun::star::io { class XSeekable; } +namespace com::sun::star::io { class XStream; } +namespace com::sun::star::io { class XTruncate; } + +namespace svt { + +class SVL_DLLPUBLIC ShareControlFile final : public LockFileCommon +{ + css::uno::Reference< css::io::XStream > m_xStream; + css::uno::Reference< css::io::XInputStream > m_xInputStream; + css::uno::Reference< css::io::XOutputStream > m_xOutputStream; + css::uno::Reference< css::io::XSeekable > m_xSeekable; + css::uno::Reference< css::io::XTruncate > m_xTruncate; + + std::vector< LockFileEntry > m_aUsersData; + + void Close(); + bool IsValid() const + { + return ( m_xStream.is() && m_xInputStream.is() && m_xOutputStream.is() && m_xSeekable.is() && m_xTruncate.is() ); + } + +public: + + // The constructor will throw exception in case the stream can not be opened + ShareControlFile( std::u16string_view aOrigURL ); + virtual ~ShareControlFile() override; + + std::vector< LockFileEntry > GetUsersData(); + void SetUsersDataAndStore( std::vector< LockFileEntry >&& aUserNames ); + LockFileEntry InsertOwnEntry(); + bool HasOwnEntry(); + void RemoveEntry( const LockFileEntry& aOptionalSpecification ); + void RemoveEntry(); + void RemoveFile(); +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/sharedstring.hxx b/include/svl/sharedstring.hxx new file mode 100644 index 000000000..5b5c35b95 --- /dev/null +++ b/include/svl/sharedstring.hxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_SHAREDSTRING_HXX +#define INCLUDED_SVL_SHAREDSTRING_HXX + +#include +#include + +namespace svl { + +class SVL_DLLPUBLIC SharedString +{ + rtl_uString* mpData; + rtl_uString* mpDataIgnoreCase; +public: + + static const SharedString & getEmptyString(); + + SharedString(); + SharedString( rtl_uString* pData, rtl_uString* pDataIgnoreCase ); + explicit SharedString( const OUString& rStr ); + SharedString( const SharedString& r ); + SharedString(SharedString&& r) noexcept; + ~SharedString(); + + SharedString& operator= ( const SharedString& r ); + SharedString& operator=(SharedString&& r) noexcept; + + bool operator== ( const SharedString& r ) const; + bool operator!= ( const SharedString& r ) const; + + OUString getString() const; + + rtl_uString* getData(); + const rtl_uString* getData() const; + + rtl_uString* getDataIgnoreCase(); + const rtl_uString* getDataIgnoreCase() const; + + bool isValid() const; + bool isEmpty() const; + + sal_Int32 getLength() const; +}; + +inline SharedString::SharedString() : mpData(nullptr), mpDataIgnoreCase(nullptr) {} + +inline SharedString::SharedString( rtl_uString* pData, rtl_uString* pDataIgnoreCase ) : + mpData(pData), mpDataIgnoreCase(pDataIgnoreCase) +{ + if (mpData) + rtl_uString_acquire(mpData); + if (mpDataIgnoreCase) + rtl_uString_acquire(mpDataIgnoreCase); +} + +inline SharedString::SharedString( const OUString& rStr ) : mpData(rStr.pData), mpDataIgnoreCase(nullptr) +{ + rtl_uString_acquire(mpData); +} + +inline SharedString::SharedString( const SharedString& r ) : mpData(r.mpData), mpDataIgnoreCase(r.mpDataIgnoreCase) +{ + if (mpData) + rtl_uString_acquire(mpData); + if (mpDataIgnoreCase) + rtl_uString_acquire(mpDataIgnoreCase); +} + +inline SharedString::SharedString(SharedString&& r) noexcept : mpData(r.mpData), mpDataIgnoreCase(r.mpDataIgnoreCase) +{ + r.mpData = nullptr; + r.mpDataIgnoreCase = nullptr; +} + +inline SharedString::~SharedString() +{ + if (mpData) + rtl_uString_release(mpData); + if (mpDataIgnoreCase) + rtl_uString_release(mpDataIgnoreCase); +} + +inline SharedString& SharedString::operator=(SharedString&& r) noexcept +{ + // Having this inline helps Calc's mdds::multi_type_vector to do some operations + // much faster. + if (mpData) + rtl_uString_release(mpData); + if (mpDataIgnoreCase) + rtl_uString_release(mpDataIgnoreCase); + + mpData = r.mpData; + mpDataIgnoreCase = r.mpDataIgnoreCase; + + r.mpData = nullptr; + r.mpDataIgnoreCase = nullptr; + + return *this; +} + +inline bool SharedString::operator!= ( const SharedString& r ) const +{ + return !operator== (r); +} + +inline OUString SharedString::getString() const +{ + return mpData ? OUString(mpData) : OUString(); +} + +inline rtl_uString* SharedString::getData() +{ + return mpData; +} + +inline const rtl_uString* SharedString::getData() const +{ + return mpData; +} + +inline rtl_uString* SharedString::getDataIgnoreCase() +{ + return mpDataIgnoreCase; +} + +inline const rtl_uString* SharedString::getDataIgnoreCase() const +{ + return mpDataIgnoreCase; +} + +inline bool SharedString::isValid() const +{ + return mpData != nullptr; +} + +inline bool SharedString::isEmpty() const +{ + return mpData == nullptr || mpData->length == 0; +} + +inline sal_Int32 SharedString::getLength() const +{ + return mpData ? mpData->length : 0; +} + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/sharedstringpool.hxx b/include/svl/sharedstringpool.hxx new file mode 100644 index 000000000..6880fec2a --- /dev/null +++ b/include/svl/sharedstringpool.hxx @@ -0,0 +1,65 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_SHAREDSTRINGPOOL_HXX +#define INCLUDED_SVL_SHAREDSTRINGPOOL_HXX + +#include +#include +#include + +class CharClass; + +namespace svl +{ +class SharedString; + +/** + * Storage for pool of shared strings. It also provides mapping from + * original-cased strings to upper-cased strings for case insensitive + * operations. + */ +class SVL_DLLPUBLIC SharedStringPool +{ + struct Impl; + std::unique_ptr mpImpl; + + SharedStringPool(const SharedStringPool&) = delete; + SharedStringPool& operator=(const SharedStringPool&) = delete; + +public: + SharedStringPool(const CharClass& rCharClass); + ~SharedStringPool(); + + /** + * Intern a string object into the shared string pool. + * + * @param rStr string object to intern. + * + * @return a pointer to the string object stored inside the pool, or NULL + * if the insertion fails. + */ + SharedString intern(const OUString& rStr); + + /** + * Go through all string objects in the pool, and clear those that are no + * longer used outside of the pool. + */ + void purge(); + + // For unit tests. Note that an "empty" pool may contain some internal items, + // such as SharedString::getEmptyString(). + size_t getCount() const; + size_t getCountIgnoreCase() const; +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/sigstruct.hxx b/include/svl/sigstruct.hxx new file mode 100644 index 000000000..20cb0ebd2 --- /dev/null +++ b/include/svl/sigstruct.hxx @@ -0,0 +1,177 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_XMLSECURITY_INC_SIGSTRUCT_HXX +#define INCLUDED_XMLSECURITY_INC_SIGSTRUCT_HXX + +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::graphic { class XGraphic; } + +/* + * type of reference + */ +enum class SignatureReferenceType +{ + SAMEDOCUMENT = 1, + BINARYSTREAM = 2, + XMLSTREAM = 3 +}; + +struct SignatureReferenceInformation +{ + SignatureReferenceType nType; + OUString ouURI; + // For ODF: XAdES digests (SHA256) or the old SHA1, from css::xml::crypto::DigestID + sal_Int32 nDigestID; + OUString ouDigestValue; + /// Type of the reference: a URI (newer idSignedProperties references) or empty. + OUString ouType; + + SignatureReferenceInformation() : + nType(SignatureReferenceType::SAMEDOCUMENT), + ouURI(""), + nDigestID(css::xml::crypto::DigestID::SHA1), + ouDigestValue("") + { + } + + SignatureReferenceInformation( SignatureReferenceType type, sal_Int32 digestID, const OUString& uri, const OUString& rType ) : + SignatureReferenceInformation() + { + nType = type; + nDigestID = digestID; + ouURI = uri; + ouType = rType; + } +}; + +typedef ::std::vector< SignatureReferenceInformation > SignatureReferenceInformations; + +namespace svl::crypto +{ +/// Specifies the algorithm used for signature generation and validation. +enum class SignatureMethodAlgorithm +{ + RSA, + ECDSA +}; +} + + +struct SignatureInformation +{ + sal_Int32 nSecurityId; + css::xml::crypto::SecurityOperationStatus nStatus; + SignatureReferenceInformations vSignatureReferenceInfors; + struct X509CertInfo + { + OUString X509IssuerName; + OUString X509SerialNumber; + OUString X509Certificate; + /// OOXML certificate SHA-256 digest, empty for ODF except when doing XAdES signature. + OUString CertDigest; + /// The certificate owner (aka subject). + OUString X509Subject; + }; + typedef std::vector X509Data; + // note: at parse time, it's unknown which one is the signing certificate; + // ImplVerifySignatures() figures it out and puts it at the back + std::vector X509Datas; + + X509CertInfo const* GetSigningCertificate() const + { + if (X509Datas.empty()) + { + return nullptr; + } + assert(!X509Datas.back().empty()); + return & X509Datas.back().back(); + } + + OUString ouGpgKeyID; + OUString ouGpgCertificate; + OUString ouGpgOwner; + + OUString ouSignatureValue; + css::util::DateTime stDateTime; + + // XAdES EncapsulatedX509Certificate values + std::set maEncapsulatedX509Certificates; + + OUString ouSignatureId; + // signature may contain multiple time stamps - check they're consistent + bool hasInconsistentSigningTime = false; + //We also keep the date and time as string. This is done when this + //structure is created as a result of a XML signature being read. + //When then a signature is added or another removed, then the original + //XML signatures are written again (unless they have been removed). + //If the date time string is converted into the DateTime structure + //then information can be lost because it only holds a fractional + //of a second with an accuracy of one hundredth of second. + //If the string contains + //milliseconds (because the document was created by an application other than OOo) + //and the converted time is written back, then the string looks different + //and the signature is broken. + OUString ouDateTime; + /// The Id attribute of the element that contains the . + OUString ouDateTimePropertyId; + /// Characters of the element inside the signature. + OUString ouDescription; + /// The Id attribute of the element that contains the . + OUString ouDescriptionPropertyId; + /// Valid and invalid signature line images + css::uno::Reference aValidSignatureImage; + css::uno::Reference aInvalidSignatureImage; + /// Signature Line Id, used to map signatures to their respective signature line images. + OUString ouSignatureLineId; + /// A full OOXML signature for unchanged roundtrip, empty for ODF. + css::uno::Sequence aSignatureBytes; + /// For PDF: digest format, from css::xml::crypto::DigestID + sal_Int32 nDigestID; + /// For PDF: has id-aa-signingCertificateV2 as a signed attribute. + bool bHasSigningCertificate; + /// For PDF: the byte range doesn't cover the whole document. + bool bPartialDocumentSignature; + + svl::crypto::SignatureMethodAlgorithm eAlgorithmID; + + SignatureInformation( sal_Int32 nId ) + { + nSecurityId = nId; + nStatus = css::xml::crypto::SecurityOperationStatus_UNKNOWN; + nDigestID = 0; + bHasSigningCertificate = false; + bPartialDocumentSignature = false; + eAlgorithmID = svl::crypto::SignatureMethodAlgorithm::RSA; + } +}; + +typedef ::std::vector< SignatureInformation > SignatureInformations; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/slstitm.hxx b/include/svl/slstitm.hxx new file mode 100644 index 000000000..48e558149 --- /dev/null +++ b/include/svl/slstitm.hxx @@ -0,0 +1,72 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_SLSTITM_HXX +#define INCLUDED_SVL_SLSTITM_HXX + +#include + +#include +#include +#include + +namespace com::sun::star::uno { template class Sequence; } + +class SVL_DLLPUBLIC SfxStringListItem final : public SfxPoolItem +{ + std::shared_ptr> mpList; + +public: + static SfxPoolItem* CreateDefault(); + + SfxStringListItem(); + SfxStringListItem( sal_uInt16 nWhich, const std::vector *pList=nullptr ); + virtual ~SfxStringListItem() override; + + SfxStringListItem(SfxStringListItem const &) = default; + SfxStringListItem(SfxStringListItem &&) = default; + SfxStringListItem & operator =(SfxStringListItem const &) = delete; // due to SfxPoolItem + SfxStringListItem & operator =(SfxStringListItem &&) = delete; // due to SfxPoolItem + + std::vector& GetList(); + + const std::vector& GetList() const; + + // String-Separator: \n + void SetString( const OUString& ); + OUString GetString(); + + void SetStringList( const css::uno::Sequence< OUString >& rList ); + void GetStringList( css::uno::Sequence< OUString >& rList ) const; + + virtual bool operator==( const SfxPoolItem& ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, + const IntlWrapper& ) const override; + virtual SfxStringListItem* Clone( SfxItemPool *pPool = nullptr ) const override; + + virtual bool PutValue ( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; +}; +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/solar.hrc b/include/svl/solar.hrc new file mode 100644 index 000000000..5caeb64f4 --- /dev/null +++ b/include/svl/solar.hrc @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_SOLAR_HRC +#define INCLUDED_SVL_SOLAR_HRC + +// defines ------------------------------------------------------------------ + +#define OWN_ATTR_VALUE_START 3900 +#define OWN_ATTR_VALUE_END 4007 + +#define RID_LIB_START 10000 +#define RID_LIB_END 19999 + +#define RID_SVX_START (RID_LIB_START) +// RID_SVX_END (RID_LIB_START+499) + +#define RID_OFA_START (RID_LIB_START+6900) +// RID_OFA_END (RID_LIB_START+7399) + +// do *NOT* add more ranges here, RID_LIB_END is (RID_LIB_START + 10000) + +#define RID_APP_START 20000 +// RID_APP_END 31999 + +#define RID_SW_START (20000) +// RID_SW_END (25999) + +// free: 26000-28199 + +// Help-Ids -------------------------------------------------------------- + +#define HID_START 32768 + +#define HID_SC_START (HID_START+25000) +// HID_SC_END (HID_START+26999) + +#define HID_SD_START (HID_START+27000) +// HID_SD_END (HID_START+27999) + +// Slot Ids + +#define SID_SFX_START 5000 +// SID_SFX_END 8999 +#define SID_DOCKWIN_START 9800 +// SID_DOCKWIN_END 9999 + +#define SID_LIB_START 10000 +// SID_LIB_END 19999 +// free: 20000-29999 +#define SID_OBJ_START 30000 + +#define SID_SW_START 20000 +// SID_SW_END 25999 +#define SID_SC_START 26000 +// SID_SC_END 26999 +#define SID_SD_START 27000 +// SID_SD_END 27999 + +#define SID_SMA_START (SID_OBJ_START + 256) +// SID_SMA_END (SID_OBJ_START + 511) +#define SID_BASICIDE_START (SID_OBJ_START + 768) +// SID_BASICIDE_END (SID_BASICIDE_START + 255) + +#define SID_SVX_START SID_LIB_START // 10000 +#define SID_SVX_END (SID_SVX_START + 1499) +#define SID_EDIT_START (SID_SVX_END + 1) // 11500 +#define SID_EDIT_END (SID_EDIT_START + 499) +#define SID_OPTIONS_START (SID_EDIT_END + 1) // 12000 +#define SID_OPTIONS_END (SID_OPTIONS_START + 100) +#define SID_SBA_START (SID_OPTIONS_END + 1) // 12101 +#define SID_SBA_END (SID_SBA_START + 149) +#define SID_DBACCESS_START (SID_SBA_END + 1) // 12251 +#define SID_DBACCESS_END (SID_DBACCESS_START + 200) +#define SID_RPTUI_START (SID_DBACCESS_END + 1) // 12452 +// SID_RPTUI_END (SID_RPTUI_START + 199) + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/srchdefs.hxx b/include/svl/srchdefs.hxx new file mode 100644 index 000000000..d77341c36 --- /dev/null +++ b/include/svl/srchdefs.hxx @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF, under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License",; you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_SRCHDEFS_HXX +#define INCLUDED_SVL_SRCHDEFS_HXX + +#include + +enum class SearchOptionFlags +{ + NONE = 0x0000, + SEARCH = 0x0001, + SEARCHALL = 0x0002, // named to this way to avoid conflict with macro on Windows. + REPLACE = 0x0004, + REPLACE_ALL = 0x0008, + WHOLE_WORDS = 0x0010, + BACKWARDS = 0x0020, + REG_EXP = 0x0040, + EXACT = 0x0080, + SELECTION = 0x0100, + FAMILIES = 0x0200, + FORMAT = 0x0400, + SIMILARITY = 0x0800, + WILDCARD = 0x1000, + ALL = 0x1fff +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/srchitem.hxx b/include/svl/srchitem.hxx new file mode 100644 index 000000000..7aa403211 --- /dev/null +++ b/include/svl/srchitem.hxx @@ -0,0 +1,326 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_SRCHITEM_HXX +#define INCLUDED_SVL_SRCHITEM_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// defines --------------------------------------------------------------- + +// commands +enum class SvxSearchCmd +{ + FIND = 0, + FIND_ALL = 1, + REPLACE = 2, + REPLACE_ALL = 3, +}; + +// search flags +enum class SvxSearchCellType +{ + FORMULA = 0, + VALUE = 1, + NOTE = 2, +}; + +enum class SvxSearchApp +{ + WRITER = 0, + CALC = 1, + DRAW = 2, +}; + +// class SvxSearchItem --------------------------------------------------- + +class SVL_DLLPUBLIC SvxSearchItem final : + public SfxPoolItem, + public utl::ConfigItem +{ + i18nutil::SearchOptions2 m_aSearchOpt; + + SfxStyleFamily m_eFamily; // style family + + SvxSearchCmd m_nCommand; // command (Search, Search all, Replace, Replace all) + + // Calc-specific + SvxSearchCellType m_nCellType; // Search in Formulas/Values/Notes + SvxSearchApp m_nAppFlag; // application which the dialog is for + bool m_bRowDirection; // search direction: row-wise/column-wise + bool m_bAllTables; // search in all sheets + bool m_bSearchFiltered; // search filtered cells. + bool m_bSearchFormatted; // search formatted display strings + + // Writer-specific + bool m_bNotes; + + bool m_bBackward; // search backwards + bool m_bPattern; // search for styles + bool m_bContent; // search in content + bool m_bAsianOptions; // use asian options? + + // Start search at this point (absolute twips). + sal_Int32 m_nStartPointX; + sal_Int32 m_nStartPointY; + + virtual void ImplCommit() override; + +public: + static SfxPoolItem* CreateDefault(); + + explicit SvxSearchItem( const sal_uInt16 nId ); + SvxSearchItem( const SvxSearchItem& rItem ); + virtual ~SvxSearchItem() override; + + virtual bool QueryValue( css::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const override; + virtual bool PutValue( const css::uno::Any& rVal, sal_uInt8 nMemberId ) override; + virtual bool operator == ( const SfxPoolItem& ) const override; + virtual SvxSearchItem* Clone( SfxItemPool *pPool = nullptr ) const override; + virtual bool GetPresentation( SfxItemPresentation ePres, + MapUnit eCoreMetric, + MapUnit ePresMetric, + OUString &rText, const IntlWrapper& ) const override; + + // ConfigItem + virtual void Notify( const css::uno::Sequence< OUString > &rPropertyNames ) override; + + bool equalsIgnoring(const SvxSearchItem& rSItem, bool bIgnoreReplace, + bool bIgnoreCommand) const; + + SvxSearchCmd GetCommand() const { return m_nCommand; } + void SetCommand(SvxSearchCmd nNewCommand) { m_nCommand = nNewCommand; } + + inline const OUString& GetSearchString() const; + inline void SetSearchString(const OUString& rNewString); + + inline const OUString& GetReplaceString() const; + inline void SetReplaceString(const OUString& rNewString); + + inline bool GetWordOnly() const; + void SetWordOnly(bool bNewWordOnly); + + inline bool GetExact() const; + void SetExact(bool bNewExact); + + bool GetBackward() const { return m_bBackward; } + void SetBackward(bool bNewBackward) { m_bBackward = bNewBackward; } + + inline bool GetSelection() const; + void SetSelection(bool bNewSelection); + + inline bool GetRegExp() const; + void SetRegExp( bool bVal ); + + inline bool GetWildcard() const; + void SetWildcard( bool bVal ); + + bool GetPattern() const { return m_bPattern; } + void SetPattern(bool bNewPattern) { m_bPattern = bNewPattern; } + + SfxStyleFamily GetFamily() const { return m_eFamily; } + void SetFamily( SfxStyleFamily eNewFamily ) + { m_eFamily = eNewFamily; } + + bool GetRowDirection() const { return m_bRowDirection; } + void SetRowDirection(bool bNewRowDirection) { m_bRowDirection = bNewRowDirection; } + + bool IsAllTables() const { return m_bAllTables; } + void SetAllTables(bool bNew) { m_bAllTables = bNew; } + + bool IsSearchFiltered() const { return m_bSearchFiltered; } + void SetSearchFiltered(bool b) { m_bSearchFiltered = b; } + + bool IsSearchFormatted() const { return m_bSearchFormatted; } + void SetSearchFormatted(bool b) { m_bSearchFormatted = b; } + + SvxSearchCellType GetCellType() const { return m_nCellType; } + void SetCellType(SvxSearchCellType nNewCellType) { m_nCellType = nNewCellType; } + + bool GetNotes() const { return m_bNotes; } + void SetNotes(bool bNew) { m_bNotes = bNew; } + + SvxSearchApp GetAppFlag() const { return m_nAppFlag; } + void SetAppFlag(SvxSearchApp nNewAppFlag) { m_nAppFlag = nNewAppFlag; } + + inline bool IsLevenshtein() const; + void SetLevenshtein( bool bVal ); + + inline bool IsLEVRelaxed() const; + void SetLEVRelaxed(bool bSet); + + inline sal_uInt16 GetLEVOther() const; + inline void SetLEVOther(sal_uInt16 nSet); + + inline sal_uInt16 GetLEVShorter() const; + inline void SetLEVShorter(sal_uInt16 nSet); + + inline sal_uInt16 GetLEVLonger() const; + inline void SetLEVLonger(sal_uInt16 nSet); + + inline const i18nutil::SearchOptions2 & + GetSearchOptions() const; + inline void SetSearchOptions( const i18nutil::SearchOptions2 &rOpt ); + + inline TransliterationFlags + GetTransliterationFlags() const; + void SetTransliterationFlags( TransliterationFlags nFlags ); + + inline bool IsMatchFullHalfWidthForms() const; + void SetMatchFullHalfWidthForms( bool bVal ); + + bool IsUseAsianOptions() const { return m_bAsianOptions; } + void SetUseAsianOptions( bool bVal ) { m_bAsianOptions = bVal; } + + sal_Int32 GetStartPointX() const; + sal_Int32 GetStartPointY() const; + /// Either x or y start point is set. + bool HasStartPoint() const; +}; + +const OUString& SvxSearchItem::GetSearchString() const +{ + return m_aSearchOpt.searchString; +} + +void SvxSearchItem::SetSearchString(const OUString& rNewString) +{ + m_aSearchOpt.searchString = rNewString; +} + +const OUString& SvxSearchItem::GetReplaceString() const +{ + return m_aSearchOpt.replaceString; +} + +void SvxSearchItem::SetReplaceString(const OUString& rNewString) +{ + m_aSearchOpt.replaceString = rNewString; +} + +bool SvxSearchItem::GetWordOnly() const +{ + return 0 != (m_aSearchOpt.searchFlag & + css::util::SearchFlags::NORM_WORD_ONLY); +} + +bool SvxSearchItem::GetExact() const +{ + return !(m_aSearchOpt.transliterateFlags & TransliterationFlags::IGNORE_CASE); +} + +bool SvxSearchItem::GetSelection() const +{ + return 0 != (m_aSearchOpt.searchFlag & css::util::SearchFlags::REG_NOT_BEGINOFLINE); +} + +bool SvxSearchItem::GetRegExp() const +{ + // Ensure old and new algorithm types are in sync until all places are + // adapted to use only new types. + assert( (m_aSearchOpt.algorithmType == css::util::SearchAlgorithms_REGEXP) == + (m_aSearchOpt.AlgorithmType2 == css::util::SearchAlgorithms2::REGEXP)); + return m_aSearchOpt.AlgorithmType2 == css::util::SearchAlgorithms2::REGEXP ; +} + +bool SvxSearchItem::GetWildcard() const +{ + // Ensure old and new algorithm types are in sync, in this case old is not + // REGEXP or APPROXIMATE. + assert( m_aSearchOpt.AlgorithmType2 != css::util::SearchAlgorithms2::WILDCARD || + (m_aSearchOpt.algorithmType != css::util::SearchAlgorithms_REGEXP && + m_aSearchOpt.algorithmType != css::util::SearchAlgorithms_APPROXIMATE) ); + return m_aSearchOpt.AlgorithmType2 == css::util::SearchAlgorithms2::WILDCARD ; +} + +bool SvxSearchItem::IsLEVRelaxed() const +{ + return 0 != (m_aSearchOpt.searchFlag & css::util::SearchFlags::LEV_RELAXED); +} + +sal_uInt16 SvxSearchItem::GetLEVOther() const +{ + return static_cast(m_aSearchOpt.changedChars); +} + +void SvxSearchItem::SetLEVOther( sal_uInt16 nVal ) +{ + m_aSearchOpt.changedChars = nVal; +} + +sal_uInt16 SvxSearchItem::GetLEVShorter() const +{ + return static_cast(m_aSearchOpt.insertedChars); +} + +void SvxSearchItem::SetLEVShorter( sal_uInt16 nVal ) +{ + m_aSearchOpt.insertedChars = nVal; +} + +sal_uInt16 SvxSearchItem::GetLEVLonger() const +{ + return static_cast(m_aSearchOpt.deletedChars); +} + +void SvxSearchItem::SetLEVLonger( sal_uInt16 nVal ) +{ + m_aSearchOpt.deletedChars = nVal; +} + +bool SvxSearchItem::IsLevenshtein() const +{ + // Ensure old and new algorithm types are in sync until all places are + // adapted to use only new types. + assert( (m_aSearchOpt.algorithmType == css::util::SearchAlgorithms_APPROXIMATE) == + (m_aSearchOpt.AlgorithmType2 == css::util::SearchAlgorithms2::APPROXIMATE)); + return m_aSearchOpt.AlgorithmType2 == css::util::SearchAlgorithms2::APPROXIMATE; +} + +const i18nutil::SearchOptions2 & SvxSearchItem::GetSearchOptions() const +{ + return m_aSearchOpt; +} + +void SvxSearchItem::SetSearchOptions( const i18nutil::SearchOptions2 &rOpt ) +{ + m_aSearchOpt = rOpt; +} + +TransliterationFlags SvxSearchItem::GetTransliterationFlags() const +{ + return m_aSearchOpt.transliterateFlags; +} + +bool SvxSearchItem::IsMatchFullHalfWidthForms() const +{ + return bool(m_aSearchOpt.transliterateFlags & TransliterationFlags::IGNORE_WIDTH); +} + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/stritem.hxx b/include/svl/stritem.hxx new file mode 100644 index 000000000..fe3695f79 --- /dev/null +++ b/include/svl/stritem.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_STRITEM_HXX +#define INCLUDED_SVL_STRITEM_HXX + +#include +#include + + +class SVL_DLLPUBLIC SfxStringItem: public CntUnencodedStringItem +{ +public: + static SfxPoolItem* CreateDefault(); + + SfxStringItem(sal_uInt16 which = 0): CntUnencodedStringItem(which) {} + + SfxStringItem(sal_uInt16 which, const OUString & rValue): + CntUnencodedStringItem(which, rValue) {} + + virtual SfxStringItem* Clone(SfxItemPool * = nullptr) const override; + + void dumpAsXml(xmlTextWriterPtr pWriter) const override; + +}; + +#endif // INCLUDED_SVL_STRITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/style.hxx b/include/svl/style.hxx new file mode 100644 index 000000000..b5b7aa3ad --- /dev/null +++ b/include/svl/style.hxx @@ -0,0 +1,359 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_STYLE_HXX +#define INCLUDED_SVL_STYLE_HXX + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// This is used as a flags enum in sw/, but only there, +// so I don't pull in o3tl::typed_flags here +enum class SfxStyleFamily { + None = 0x00, + Char = 0x01, + Para = 0x02, + Frame = 0x04, + Page = 0x08, + Pseudo = 0x10, + Table = 0x20, + Cell = 0x40, + All = 0x7fff +}; + +enum class SfxStyleSearchBits { + // sc/calc styles + ScStandard = 0x0001, + + // sw/writer styles + SwText = 0x0001, + SwChapter = 0x0002, + SwList = 0x0004, + SwIndex = 0x0008, + SwExtra = 0x0010, + SwHtml = 0x0020, + SwCondColl = 0x0040, + + Auto = 0x0000, ///< automatic: flags from application + Hidden = 0x0200, ///< hidden styles (search mask) + ReadOnly = 0x2000, ///< readonly styles (search mask) + Used = 0x4000, ///< used styles (search mask) + UserDefined = 0x8000, ///< user defined styles (search mask) + AllVisible = 0xe07f, ///< all visible styles + All = 0xe27f, ///< all styles +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + + +class SfxItemSet; +class SfxItemPool; +class SfxStyleSheetBasePool; +class SvStream; + +namespace svl { class IndexedStyleSheets; } +/* +Everyone changing instances of SfxStyleSheetBasePool or SfxStyleSheetBase +must broadcast this using broadcasts. +The class is used for this, it contains an Action-Id and a +pointer to the . The actions are: + +#define SfxHintId::StyleSheetCreated // style is created +#define SfxHintId::StyleSheetModified // style is modified +#define SfxHintId::StyleSheetChanged // style is replaced +#define SfxHintId::StyleSheetErased // style is deleted + +The following methods already broadcast themself + +SfxSimpleHint(SfxHintId::Dying) from: + SfxStyleSheetBasePool::~SfxStyleSheetBasePool() + +SfxStyleSheetHint( SfxHintId::StyleSheetCreated, *p ) from: + SfxStyleSheetBasePool::Make( const String& rName, + SfxStyleFamily eFam, sal_uInt16 mask) + +SfxStyleSheetHint( SfxHintId::StyleSheetChanged, *pNew ) from: + SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet ) + +SfxStyleSheetHint( SfxHintId::StyleSheetErased, *p ) from: + SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p ) + SfxStyleSheetBasePool::Clear() +*/ + +class SVL_DLLPUBLIC SfxStyleSheetBase : public comphelper::OWeakTypeObject +{ +private: + friend class SfxStyleSheetBasePool; + +protected: + SfxStyleSheetBasePool* m_pPool; // related pool + SfxStyleFamily nFamily; + + OUString aName, aParent, aFollow; + OUString aHelpFile; // name of the help file + SfxItemSet* pSet; // ItemSet + SfxStyleSearchBits nMask; // Flags + + sal_uLong nHelpId; // help ID + + bool bMySet; // sal_True: delete Set in dtor + bool bHidden; + + SfxStyleSheetBase( const OUString&, SfxStyleSheetBasePool*, SfxStyleFamily eFam, SfxStyleSearchBits mask ); + SfxStyleSheetBase( const SfxStyleSheetBase& ); + virtual ~SfxStyleSheetBase() override; + +public: + + // returns the internal name of this style + const OUString& GetName() const; + + // sets the internal name of this style. + // + // If the name of a style is changed, then the styles container needs to be + // reindexed (see IndexedStyleSheets). If you set bReindexNow to false to + // defer that indexing, then you must call the Reindex manually on the + // SfxStyleSheetBasePool parent. + virtual bool SetName(const OUString& rNewName, bool bReindexNow = true); + + virtual const OUString& GetParent() const; + virtual bool SetParent( const OUString& ); + virtual const OUString& GetFollow() const; + virtual bool SetFollow( const OUString& ); + virtual bool HasFollowSupport() const; // Default true + virtual bool HasParentSupport() const; // Default true + virtual bool HasClearParentSupport() const; // Default false + virtual bool IsUsed() const; // Default true + virtual OUString GetDescription( MapUnit eMetric ); + + virtual OUString GetUsedBy() { return OUString(); } + + SfxStyleSheetBasePool* GetPool() { return m_pPool; } + SfxStyleFamily GetFamily() const { return nFamily; } + SfxStyleSearchBits GetMask() const { return nMask; } + void SetMask( SfxStyleSearchBits mask) { nMask = mask; } + bool IsUserDefined() const + { return bool( nMask & SfxStyleSearchBits::UserDefined); } + + virtual bool IsHidden() const { return bHidden; } + virtual void SetHidden( bool bValue ); + + virtual sal_uLong GetHelpId( OUString& rFile ); + virtual void SetHelpId( const OUString& r, sal_uLong nId ); + + virtual SfxItemSet& GetItemSet(); + /// Due to writer's usual lack of sanity this is a separate function for + /// preview only; it shall not create the style in case it does not exist. + /// If the style has parents, it is _not_ required that the returned item + /// set has parents (i.e. use it for display purposes only). + virtual std::optional GetItemSetForPreview(); + + /// Fix for expensive dynamic_cast + virtual bool isScStyleSheet() const { return false; } +}; + +/* Class to iterate and search on a SfxStyleSheetBasePool */ +class SVL_DLLPUBLIC SfxStyleSheetIterator +{ +public: + /** Constructor. + * The iterator will only iterate over style sheets which have the family \p eFam + */ + SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase, + SfxStyleFamily eFam, SfxStyleSearchBits n=SfxStyleSearchBits::All ); + SfxStyleSearchBits GetSearchMask() const; + SfxStyleFamily GetSearchFamily() const; + virtual sal_Int32 Count(); + virtual SfxStyleSheetBase *operator[](sal_Int32 nIdx); + virtual SfxStyleSheetBase* First(); + virtual SfxStyleSheetBase* Next(); + virtual SfxStyleSheetBase* Find(const OUString& rStr); + virtual ~SfxStyleSheetIterator(); + + bool SearchUsed() const { return bSearchUsed; } + +protected: + + SfxStyleSheetBasePool* pBasePool; + SfxStyleFamily nSearchFamily; + SfxStyleSearchBits nMask; + + +private: + SVL_DLLPRIVATE bool IsTrivialSearch() const; + + SfxStyleSheetBase* pCurrentStyle; + sal_Int32 mnCurrentPosition; + bool bSearchUsed; + +friend class SfxStyleSheetBasePool; +}; + +class SfxStyleSheetBasePool_Impl; + +class SVL_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster, public comphelper::OWeakTypeObject +{ +friend class SfxStyleSheetIterator; +friend class SfxStyleSheetBase; + + std::unique_ptr pImpl; + + SfxStyleSheetIterator& GetIterator_Impl(SfxStyleFamily eFamily, SfxStyleSearchBits eMask); +protected: + SfxStyleSheetIterator* GetCachedIterator(); + + SfxItemPool& rPool; + + void ChangeParent(std::u16string_view rOld, const OUString& rNew, SfxStyleFamily eFamily, bool bVirtual = true); + virtual rtl::Reference Create( const OUString&, SfxStyleFamily, SfxStyleSearchBits ); + virtual rtl::Reference Create( const SfxStyleSheetBase& ); + + virtual ~SfxStyleSheetBasePool() override; + + void StoreStyleSheet(const rtl::Reference< SfxStyleSheetBase >&); + + /** Obtain the indexed style sheets. + */ + const svl::IndexedStyleSheets& + GetIndexedStyleSheets() const; + SfxStyleSheetBase* GetStyleSheetByPositionInIndex(unsigned pos); + +public: + SfxStyleSheetBasePool( SfxItemPool& ); + SfxStyleSheetBasePool( const SfxStyleSheetBasePool& ); + + SfxItemPool& GetPool() { return rPool;} + const SfxItemPool& GetPool() const { return rPool;} + + virtual std::unique_ptr CreateIterator(SfxStyleFamily, SfxStyleSearchBits nMask = SfxStyleSearchBits::All); + + virtual SfxStyleSheetBase& Make(const OUString&, + SfxStyleFamily eFam, + SfxStyleSearchBits nMask = SfxStyleSearchBits::All); + + virtual void Remove( SfxStyleSheetBase* ); + void Insert( SfxStyleSheetBase* ); + + void Clear(); + + SfxStyleSheetBasePool& operator=( const SfxStyleSheetBasePool& ); + SfxStyleSheetBasePool& operator+=( const SfxStyleSheetBasePool& ); + + SfxStyleSheetBase* First(SfxStyleFamily eFamily, SfxStyleSearchBits eMask = SfxStyleSearchBits::All); + SfxStyleSheetBase* Next(); + virtual SfxStyleSheetBase* Find( const OUString&, SfxStyleFamily eFam, SfxStyleSearchBits n=SfxStyleSearchBits::All ); + + virtual bool SetParent(SfxStyleFamily eFam, + const OUString &rStyle, + const OUString &rParent); + + void Reindex(); + /** Add a style sheet. + * Not an actual public function. Do not call it from non-subclasses. + */ + void Add( const SfxStyleSheetBase& ); +}; + +class SVL_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase, + public SfxListener, public SfxBroadcaster, public svl::StyleSheetUser +{ +public: + + SfxStyleSheet( const OUString&, const SfxStyleSheetBasePool&, SfxStyleFamily, SfxStyleSearchBits ); + SfxStyleSheet( const SfxStyleSheet& ); + + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; + + virtual bool isUsedByModel() const override; + + virtual bool SetParent( const OUString& ) override; + +protected: + virtual ~SfxStyleSheet() override; +}; + +class SVL_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool +{ +protected: + using SfxStyleSheetBasePool::Create; + virtual rtl::Reference Create(const OUString&, SfxStyleFamily, SfxStyleSearchBits mask) override; + +public: + SfxStyleSheetPool( SfxItemPool const& ); +}; + + +class SVL_DLLPUBLIC SfxStyleSheetPoolHint final : public SfxHint +{ +public: + SfxStyleSheetPoolHint() {} +}; + + +class SVL_DLLPUBLIC SfxStyleSheetHint: public SfxHint +{ + SfxStyleSheetBase* pStyleSh; +public: + SfxStyleSheetHint( SfxHintId, SfxStyleSheetBase& ); + SfxStyleSheetBase* GetStyleSheet() const + { return pStyleSh; } +}; + +class UNLESS_MERGELIBS(SVL_DLLPUBLIC) SfxStyleSheetModifiedHint final : public SfxStyleSheetHint +{ + OUString aName; + +public: + SfxStyleSheetModifiedHint( OUString aOld, + SfxStyleSheetBase& ); + const OUString& GetOldName() const { return aName; } +}; + +class SVL_DLLPUBLIC SfxUnoStyleSheet : public cppu::ImplInheritanceHelper +{ +public: + SfxUnoStyleSheet( const OUString& _rName, const SfxStyleSheetBasePool& _rPool, SfxStyleFamily _eFamily, SfxStyleSearchBits _nMask ); + + static SfxUnoStyleSheet* getUnoStyleSheet( const css::uno::Reference< css::style::XStyle >& xStyle ); + + // XUnoTunnel + static const css::uno::Sequence< ::sal_Int8 >& getUnoTunnelId(); + virtual ::sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< ::sal_Int8 >& aIdentifier ) override; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/stylepool.hxx b/include/svl/stylepool.hxx new file mode 100644 index 000000000..0a22cb1f7 --- /dev/null +++ b/include/svl/stylepool.hxx @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_STYLEPOOL_HXX +#define INCLUDED_SVL_STYLEPOOL_HXX + +#include +#include +#include + +class StylePoolImpl; +class IStylePoolIteratorAccess; + +class SVL_DLLPUBLIC StylePool final +{ +private: + std::unique_ptr pImpl; +public: + explicit StylePool( SfxItemSet const * pIgnorableItems = nullptr ); + + /** Insert a SfxItemSet into the style pool. + + The pool makes a copy of the provided SfxItemSet. + + @param SfxItemSet + the SfxItemSet to insert + + @param pParentName + Name of the parent of rSet. If set, createIterator() can be more deterministic by iterating + over item sets ordered by parent names. + + @return a shared pointer to the SfxItemSet + */ + std::shared_ptr insertItemSet( const SfxItemSet& rSet, const OUString* pParentName = nullptr ); + + /** Create an iterator + + The iterator walks through the StylePool + OD 2008-03-07 #i86923# + introduce optional parameter to control, if unused SfxItemsSet are skipped or not + introduce optional parameter to control, if ignorable items are skipped or not + + @attention every change, e.g. destruction, of the StylePool could cause undefined effects. + + @param bSkipUnusedItemSets + input parameter - boolean, indicating if unused SfxItemSets are skipped or not + + @param bSkipIgnorableItems + input parameter - boolean, indicating if ignorable items are skipped or not + + @postcond the iterator "points before the first" SfxItemSet of the pool. + The first StylePoolIterator::getNext() call will deliver the first SfxItemSet. + */ + std::unique_ptr createIterator( const bool bSkipUnusedItemSets = false, + const bool bSkipIgnorableItems = false ); + + ~StylePool(); + + static OUString nameOf( const std::shared_ptr& pSet ); +}; + +class SVL_DLLPUBLIC IStylePoolIteratorAccess +{ +public: + /** Delivers a shared pointer to the next SfxItemSet of the pool + If there is no more SfxItemSet, the delivered share_pointer is empty. + */ + virtual std::shared_ptr getNext() = 0; + virtual ~IStylePoolIteratorAccess() {}; +}; +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/stylesheetuser.hxx b/include/svl/stylesheetuser.hxx new file mode 100644 index 000000000..ba69268da --- /dev/null +++ b/include/svl/stylesheetuser.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_STYLESHEETUSER_HXX +#define INCLUDED_SVL_STYLESHEETUSER_HXX + +#include + +#include + +namespace svl +{ +/** Test whether object that uses a stylesheet is used itself. + + This interface should be implemented by all classes that use + a SfxStyleSheet (and listen on it). It can be queried by the stylesheet + to determine if it is really used. + */ +class SAL_DLLPUBLIC_RTTI StyleSheetUser +{ +public: + /** Test whether this object is used. + + @return true, if the object is used, false otherwise + */ + virtual bool isUsedByModel() const = 0; + +protected: + ~StyleSheetUser() {} +}; +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/svdde.hxx b/include/svl/svdde.hxx new file mode 100644 index 000000000..e8b808ea1 --- /dev/null +++ b/include/svl/svdde.hxx @@ -0,0 +1,326 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_SVDDE_HXX +#define INCLUDED_SVL_SVDDE_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +class DdeString; +class DdeConnection; +class DdeTopic; +class DdeService; +struct DdeDataImp; +struct DdeImp; +struct DdeItemImpData; +struct Conversation; + +typedef ::std::vector< DdeService* > DdeServices; + + +class SVL_DLLPUBLIC DdeData +{ + friend class DdeInternal; + friend class DdeService; + friend class DdeConnection; + friend class DdeTransaction; + std::unique_ptr xImp; + + SVL_DLLPRIVATE void Lock(); + + void SetFormat( SotClipboardFormatId nFmt ); + +public: + DdeData(); + DdeData(SAL_UNUSED_PARAMETER const void*, SAL_UNUSED_PARAMETER tools::Long, SAL_UNUSED_PARAMETER SotClipboardFormatId = SotClipboardFormatId::STRING); + DdeData(SAL_UNUSED_PARAMETER const OUString&); + DdeData(const DdeData&); + DdeData(DdeData&&) noexcept; + ~DdeData(); + + void const * getData() const; + tools::Long getSize() const; + + SotClipboardFormatId GetFormat() const; + + DdeData& operator=(const DdeData&); + DdeData& operator=(DdeData&&) noexcept; + + static sal_uInt32 GetExternalFormat(SotClipboardFormatId nFmt); + static SotClipboardFormatId GetInternalFormat(sal_uLong nFmt); +}; + + +class SVL_DLLPUBLIC DdeTransaction +{ +public: + void Data( const DdeData* ); + void Done( bool bDataValid ); +protected: + DdeConnection& rDde; + DdeData aDdeData; + DdeString* pName; + short nType; + sal_IntPtr nId; + sal_IntPtr nTime; + Link aData; + Link aDone; + bool bBusy; + + DdeTransaction( DdeConnection&, SAL_UNUSED_PARAMETER const OUString&, SAL_UNUSED_PARAMETER tools::Long = 0 ); + +public: + virtual ~DdeTransaction(); + + bool IsBusy() const { return bBusy; } + OUString GetName() const; + + void Execute(); + + void SetDataHdl( const Link& rLink ) { aData = rLink; } + const Link& GetDataHdl() const { return aData; } + + void SetDoneHdl( const Link& rLink ) { aDone = rLink; } + const Link& GetDoneHdl() const { return aDone; } + + void SetFormat( SotClipboardFormatId nFmt ) { aDdeData.SetFormat( nFmt ); } + SotClipboardFormatId GetFormat() const { return aDdeData.GetFormat(); } + + tools::Long GetError() const; + +private: + friend class DdeInternal; + friend class DdeConnection; + + DdeTransaction( const DdeTransaction& ) = delete; + const DdeTransaction& operator= ( const DdeTransaction& ) = delete; + +}; + + +class SVL_DLLPUBLIC DdeLink : public DdeTransaction +{ + Link aNotify; + +public: + DdeLink( DdeConnection&, const OUString&, tools::Long = 0 ); + virtual ~DdeLink() override; + + void SetNotifyHdl( const Link& rLink ) { aNotify = rLink; } + const Link& GetNotifyHdl() const { return aNotify; } + void Notify(); +}; + + +class SVL_DLLPUBLIC DdeHotLink : public DdeLink +{ +public: + DdeHotLink( DdeConnection&, const OUString& ); +}; + + +class SVL_DLLPUBLIC DdeRequest : public DdeTransaction +{ +public: + DdeRequest( DdeConnection&, const OUString&, tools::Long = 0 ); +}; + + +class SVL_DLLPUBLIC DdePoke : public DdeTransaction +{ +public: + DdePoke( DdeConnection&, const OUString&, SAL_UNUSED_PARAMETER const DdeData&, tools::Long = 0 ); +}; + + +class SVL_DLLPUBLIC DdeExecute : public DdeTransaction +{ +public: + DdeExecute( DdeConnection&, const OUString&, tools::Long = 0 ); +}; + + +class SVL_DLLPUBLIC DdeConnection +{ + friend class DdeInternal; + friend class DdeTransaction; + std::vector aTransactions; + DdeString* pService; + DdeString* pTopic; + std::unique_ptr pImp; + +public: + DdeConnection( SAL_UNUSED_PARAMETER const OUString&, SAL_UNUSED_PARAMETER const OUString& ); + ~DdeConnection(); + + tools::Long GetError() const; + + static const std::vector& GetConnections(); + + bool IsConnected(); + + OUString GetServiceName() const; + OUString GetTopicName() const; + +private: + DdeConnection( const DdeConnection& ) = delete; + const DdeConnection& operator= ( const DdeConnection& ) = delete; +}; + + +class SVL_DLLPUBLIC DdeItem +{ + friend class DdeInternal; + friend class DdeTopic; + DdeString* pName; + DdeTopic* pMyTopic; + std::vector* pImpData; + +protected: + sal_uInt8 nType; + +public: + DdeItem( const sal_Unicode* ); + DdeItem( SAL_UNUSED_PARAMETER const OUString& ); + DdeItem( const DdeItem& ); + virtual ~DdeItem(); + + OUString GetName() const; + short GetLinks(); + void NotifyClient(); +}; + + +class SVL_DLLPUBLIC DdeGetPutItem : public DdeItem +{ +public: + DdeGetPutItem( const sal_Unicode* p ); + DdeGetPutItem( const OUString& rStr ); + DdeGetPutItem( const DdeItem& rItem ); + + virtual DdeData* Get( SotClipboardFormatId ); + virtual bool Put( const DdeData* ); + virtual void AdviseLoop( bool ); // Start / Stop AdviseLoop +}; + + +class SVL_DLLPUBLIC DdeTopic +{ + +public: + virtual DdeData* Get(SotClipboardFormatId); + virtual bool Put( const DdeData* ); + virtual bool Execute( const OUString* ); + // Eventually create a new item. return 0 -> Item creation failed + virtual bool MakeItem( const OUString& rItem ); + + // A Warm-/Hot-Link is created. Return true if successful + virtual bool StartAdviseLoop(); + +private: + friend class DdeInternal; + friend class DdeService; + friend class DdeItem; + +private: + DdeString* pName; + OUString aItem; + std::vector aItems; + +public: + DdeTopic( SAL_UNUSED_PARAMETER const OUString& ); + virtual ~DdeTopic(); + + OUString GetName() const; + + void NotifyClient( const OUString& ); + bool IsSystemTopic(); + + void InsertItem( DdeItem* ); // For own superclasses + DdeItem* AddItem( const DdeItem& ); // Will be cloned + void RemoveItem( const DdeItem& ); + const OUString& GetCurItem() const { return aItem; } + const std::vector& GetItems() const { return aItems; } + +private: + DdeTopic( const DdeTopic& ) = delete; + const DdeTopic& operator= ( const DdeTopic& ) = delete; +}; + + +class SVL_DLLPUBLIC DdeService +{ + friend class DdeInternal; + +protected: + OUString Topics(); + OUString Formats(); + OUString SysItems(); + OUString Status(); + + const DdeTopic* GetSysTopic() const { return pSysTopic; } +private: + std::vector aTopics; + std::vector< sal_uInt32 > aFormats; + DdeTopic* pSysTopic; + DdeString* pName; + std::vector> + m_vConv; + short nStatus; + + SVL_DLLPRIVATE bool HasCbFormat( sal_uInt32 ); + +public: + DdeService( SAL_UNUSED_PARAMETER const OUString& ); + virtual ~DdeService(); + + DdeService( const DdeService& ) = delete; + DdeService& operator= ( const DdeService& ) = delete; + + OUString GetName() const; + short GetError() const { return nStatus; } + + static DdeServices& GetServices(); + std::vector& GetTopics() { return aTopics; } + + void AddTopic( const DdeTopic& ); + void RemoveTopic( const DdeTopic& ); + + void AddFormat(SotClipboardFormatId); + void RemoveFormat(SotClipboardFormatId); + bool HasFormat(SotClipboardFormatId); +}; + + +inline tools::Long DdeTransaction::GetError() const +{ + return rDde.GetError(); +} +#endif // INCLUDED_SVL_SVDDE_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/svl.hrc b/include/svl/svl.hrc new file mode 100644 index 000000000..205227377 --- /dev/null +++ b/include/svl/svl.hrc @@ -0,0 +1,37 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_SVL_HRC +#define INCLUDED_SVL_SVL_HRC + +#define NC_(Context, String) TranslateId(Context, reinterpret_cast(u8##String)) + +// Internet Media Type Presentations + +#define STR_SVT_MIMETYPE_CNT_FSYSBOX NC_("STR_SVT_MIMETYPE_CNT_FSYSBOX", "Workplace") +#define STR_FILECTRL_BUTTONTEXT NC_("STR_FILECTRL_BUTTONTEXT", "Browse...") + +// tdf#145919 localizable strings to be shared in vcl and cui modules +#define GRTSTR_PASSED NC_("GRTSTR_PASSED", "PASSED") +#define GRTSTR_QUIRKY NC_("GRTSTR_QUIRKY", "QUIRKY") +#define GRTSTR_FAILED NC_("GRTSTR_FAILED", "FAILED") +#define GRTSTR_SKIPPED NC_("GRTSTR_SKIPPED", "SKIPPED") + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/svldllapi.h b/include/svl/svldllapi.h new file mode 100644 index 000000000..31402a7b1 --- /dev/null +++ b/include/svl/svldllapi.h @@ -0,0 +1,34 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_SVLDLLAPI_H +#define INCLUDED_SVL_SVLDLLAPI_H + +#include + +#if defined(SVL_DLLIMPLEMENTATION) +#define SVL_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define SVL_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define SVL_DLLPRIVATE SAL_DLLPRIVATE + +#endif // INCLUDED_SVL_SVLDLLAPI_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/svlresid.hxx b/include/svl/svlresid.hxx new file mode 100644 index 000000000..5b57aa2c0 --- /dev/null +++ b/include/svl/svlresid.hxx @@ -0,0 +1,21 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_SVL_SVTRESID_HXX +#define INCLUDED_SVL_SVTRESID_HXX + +#include +#include +#include + +SVL_DLLPUBLIC OUString SvlResId(TranslateId sContextAndId); + +#endif // INCLUDED_SVL_SVTRESID_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/typedwhich.hxx b/include/svl/typedwhich.hxx new file mode 100644 index 000000000..cb9efabd5 --- /dev/null +++ b/include/svl/typedwhich.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#ifndef INCLUDED_SVL_TYPEDWHICH_HXX +#define INCLUDED_SVL_TYPEDWHICH_HXX + +#include +#include +#include + +/** + * A very thin wrapper around the sal_uInt16 WhichId whose purpose is mostly to carry type information, + * so that we Put() and Get() the right subclasses of SfxPoolItem for each WhichId. + */ +template class TypedWhichId final +{ +public: + explicit constexpr TypedWhichId(sal_uInt16 nWhich) + : mnWhich(nWhich) + { + } + + /** Up-casting conversion constructor + */ + template + constexpr TypedWhichId(TypedWhichId other, + std::enable_if_t, int> = 0) + : mnWhich(sal_uInt16(other)) + { + } + + constexpr operator sal_uInt16() const { return mnWhich; } + +private: + sal_uInt16 mnWhich; +}; + +template constexpr bool operator==(sal_uInt16 lhs, TypedWhichId const& rhs) +{ + return lhs == sal_uInt16(rhs); +} +template constexpr bool operator!=(sal_uInt16 lhs, TypedWhichId const& rhs) +{ + return lhs != sal_uInt16(rhs); +} +template constexpr bool operator==(TypedWhichId const& lhs, sal_uInt16 rhs) +{ + return sal_uInt16(lhs) == rhs; +} +template constexpr bool operator!=(TypedWhichId const& lhs, sal_uInt16 rhs) +{ + return sal_uInt16(lhs) != rhs; +} + +#endif // INCLUDED_SVL_TYPEDWHICH_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/svl/undo.hxx b/include/svl/undo.hxx new file mode 100644 index 000000000..eff352298 --- /dev/null +++ b/include/svl/undo.hxx @@ -0,0 +1,343 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_UNDO_HXX +#define INCLUDED_SVL_UNDO_HXX + +#include +#include +#include +#include + +#include +#include + +typedef o3tl::strong_int ViewShellId; +typedef o3tl::strong_int ViewShellDocId; + +typedef struct _xmlTextWriter* xmlTextWriterPtr; + +class SVL_DLLPUBLIC SfxRepeatTarget +{ +public: + virtual ~SfxRepeatTarget() = 0; +}; + + +class SVL_DLLPUBLIC SfxUndoContext +{ +public: + /** + * Don't undo the top undo action, but an earlier one. It's the caller's responsibility to + * ensure that the earlier undo action is independent from the following ones. + */ + virtual size_t GetUndoOffset() { return 0; } + + virtual ~SfxUndoContext() = 0; +}; + + +class SVL_DLLPUBLIC SfxUndoAction +{ +public: + SfxUndoAction(); + virtual ~SfxUndoAction() COVERITY_NOEXCEPT_FALSE; + + virtual void Undo(); + virtual void UndoWithContext( SfxUndoContext& i_context ); + virtual void Redo(); + virtual void RedoWithContext( SfxUndoContext& i_context ); + virtual void Repeat(SfxRepeatTarget&); + virtual bool CanRepeat(SfxRepeatTarget&) const; + + virtual bool Merge( SfxUndoAction *pNextAction ); + + virtual OUString GetComment() const; + virtual OUString GetRepeatComment(SfxRepeatTarget&) const; + /// ID of the view shell that created this undo action. + virtual ViewShellId GetViewShellId() const; + /// Timestamp when this undo item was created. + const DateTime& GetDateTime() const; + virtual void dumpAsXml(xmlTextWriterPtr pWriter) const; + +private: + SfxUndoAction( const SfxUndoAction& ) = delete; + SfxUndoAction& operator=( const SfxUndoAction& ) = delete; + + DateTime m_aDateTime; +}; + + +/// is a mark on the Undo stack +typedef sal_Int32 UndoStackMark; +#define MARK_INVALID ::std::numeric_limits< UndoStackMark >::max() + +struct MarkedUndoAction +{ + std::unique_ptr pAction; + ::std::vector< UndoStackMark > aMarks; + + MarkedUndoAction(std::unique_ptr p) : pAction(std::move(p)) {} +}; + +/** do not make use of these implementation details, unless you + really really have to! */ +struct SVL_DLLPUBLIC SfxUndoArray +{ + std::vector maUndoActions; + size_t nMaxUndoActions; + size_t nCurUndoAction; + SfxUndoArray *pFatherUndoArray; + + SfxUndoArray(size_t nMax=0) : + nMaxUndoActions(nMax), nCurUndoAction(0), pFatherUndoArray(nullptr) {} + virtual ~SfxUndoArray(); + + SfxUndoArray& operator=( SfxUndoArray const & ) = delete; // MSVC2017 workaround + SfxUndoArray( SfxUndoArray const & ) = delete; // MSVC2017 workaround + + SfxUndoAction* GetUndoAction(size_t idx) { return maUndoActions[idx].pAction.get(); } + std::unique_ptr Remove(int idx); + void Remove( size_t i_pos, size_t i_count ); + void Insert( std::unique_ptr i_action, size_t i_pos ); +}; + + +/** do not make use of these implementation details, unless you + really really have to! */ +class SVL_DLLPUBLIC SfxListUndoAction final : public SfxUndoAction, public SfxUndoArray + +/* [Explanation] + + UndoAction to composite multiple Undos in one UndoAction. + These actions are used by SfxUndomanager. With < SfxUndoManager::EnterListAction > + you can go one composite level down and with < SfxUndoManager::LeaveListAction > up again. + Redo and Undo work element wise on SfxListUndoActions. +*/ +{ + struct Impl; + std::unique_ptr mpImpl; + +public: + + SfxListUndoAction( + const OUString &rComment, const OUString& rRepeatComment, sal_uInt16 nId, ViewShellId nViewShellId, SfxUndoArray *pFather ); + virtual ~SfxListUndoAction() override; + + virtual void Undo() override; + virtual void UndoWithContext( SfxUndoContext& i_context ) override; + virtual void Redo() override; + virtual void RedoWithContext( SfxUndoContext& i_context ) override; + virtual void Repeat(SfxRepeatTarget&) override; + virtual bool CanRepeat(SfxRepeatTarget&) const override; + + virtual bool Merge( SfxUndoAction *pNextAction ) override; + + virtual OUString GetComment() const override; + /// See SfxUndoAction::GetViewShellId(). + ViewShellId GetViewShellId() const override; + virtual OUString GetRepeatComment(SfxRepeatTarget&) const override; + sal_uInt16 GetId() const; + + void SetComment(const OUString& rComment); + void dumpAsXml(xmlTextWriterPtr pWriter) const override; +}; + + +/** is a callback interface for notifications about state changes of an SfxUndoManager +*/ +class SAL_NO_VTABLE SfxUndoListener +{ +public: + virtual void actionUndone( const OUString& i_actionComment ) = 0; + virtual void actionRedone( const OUString& i_actionComment ) = 0; + virtual void undoActionAdded( const OUString& i_actionComment ) = 0; + virtual void cleared() = 0; + virtual void clearedRedo() = 0; + virtual void resetAll() = 0; + virtual void listActionEntered( const OUString& i_comment ) = 0; + virtual void listActionLeft( const OUString& i_comment ) = 0; + virtual void listActionCancelled() = 0; + +protected: + ~SfxUndoListener() {} +}; + + +namespace svl::undo::impl +{ + class UndoManagerGuard; + class LockGuard; +} + +struct SfxUndoManager_Data; +class SVL_DLLPUBLIC SfxUndoManager +{ + std::unique_ptr< SfxUndoManager_Data > + m_xData; +public: + static bool const CurrentLevel = true; + static bool const TopLevel = false; + + SfxUndoManager( size_t nMaxUndoActionCount = 20 ); + virtual ~SfxUndoManager(); + + void SetMaxUndoActionCount( size_t nMaxUndoActionCount ); + virtual void AddUndoAction( std::unique_ptr pAction, bool bTryMerg=false ); + virtual size_t GetUndoActionCount( bool const i_currentLevel = CurrentLevel ) const; + OUString GetUndoActionComment( size_t nNo=0, bool const i_currentLevel = CurrentLevel ) const; + SfxUndoAction* GetUndoAction( size_t nNo=0 ) const; + /// Get info about all undo actions (comment, view shell id, etc.) + OUString GetUndoActionsInfo() const; + virtual size_t GetRedoActionCount( bool const i_currentLevel = CurrentLevel ) const; + OUString GetRedoActionComment( size_t nNo=0, bool const i_currentLevel = CurrentLevel ) const; + SfxUndoAction* GetRedoAction(size_t nNo = 0) const; + /// Get info about all redo actions (comment, view shell id, etc.) + OUString GetRedoActionsInfo() const; + virtual bool Undo(); + virtual bool Redo(); + /** Clears both the Redo and the Undo stack. + Will assert and bail out when called while within a list action (IsInListAction). + */ + virtual void Clear(); + /** Clears the Redo stack. + Will assert and bail out when called while within a list action (IsInListAction). + */ + virtual void ClearRedo(); + /** leaves any possible open list action (IsInListAction), and clears both the Undo and the + Redo stack. + + Effectively, calling this method is equivalent to while ( IsInListAction() ) LeaveListAction();, + followed by Clear(). The only difference to this calling sequence is that Reset is an + atomic operation, also resulting in only one notification. + */ + void Reset(); + /** determines whether an Undo or Redo is currently running + */ + bool IsDoing() const; + size_t GetRepeatActionCount() const; + OUString GetRepeatActionComment( SfxRepeatTarget &rTarget) const; + bool Repeat( SfxRepeatTarget &rTarget ); + bool CanRepeat( SfxRepeatTarget &rTarget ) const; + virtual void EnterListAction(const OUString &rComment, const OUString& rRepeatComment, sal_uInt16 nId, ViewShellId nViewShellId); + /** Leaves the list action entered with EnterListAction + @return the number of the sub actions in the list which has just been left. Note that in case no such + actions exist, the list action does not contribute to the Undo stack, but is silently removed. + */ + size_t LeaveListAction(); + + /** Leaves the list action entered with EnterListAction, and forcefully merges the previous + action on the stack into the newly created list action. + + Say you have an Undo action A on the stack, then call EnterListAction, followed by one or more calls to + AddUndoAction, followed by a call to LeaveAndMergeListAction. In opposite to LeaveListAction, your Undo + stack will now still contain one undo action: the newly created list action, whose first child is the + original A, whose other children are those you added via AddUndoAction, and whose comment is the same as + the comment of A. + + Effectively, this means that all actions added between EnterListAction and LeaveAndMergeListAction are + hidden from the user. + + @return the number of the sub actions in the list which has just been left. Note that in case no such + actions exist, the list action does not contribute to the Undo stack, but is silently removed. + */ + size_t LeaveAndMergeListAction(); + /// determines whether we're within a ListAction context, i.e. a LeaveListAction/LeaveAndMergeListAction call is pending + bool IsInListAction() const; + /// Determines how many nested list actions are currently open + size_t GetListActionDepth() const; + /** Clears the redo stack and removes the top undo action */ + void RemoveLastUndoAction(); + /** enables (true) or disables (false) recording of undo actions + + If undo actions are added while undo is disabled, they are deleted. + Disabling undo does not clear the current undo buffer! + + Multiple calls to EnableUndo are not cumulative. That is, calling EnableUndo( false ) + twice, and then calling EnableUndo( true ) means that Undo is enable afterwards. + */ + void EnableUndo( bool bEnable ); + /// returns true if undo is currently enabled. + /// This returns false if undo was disabled using EnableUndo( false ) and + /// also during the runtime of the Undo() and Redo() methods. + bool IsUndoEnabled() const; + /// Adds a new listener to be notified about changes in the UndoManager's state + void AddUndoListener( SfxUndoListener& i_listener ); + void RemoveUndoListener( SfxUndoListener& i_listener ); + bool IsEmptyActions() const; + + + /** marks the current top-level element of the Undo stack, and returns a unique ID for it + */ + UndoStackMark MarkTopUndoAction(); + + /** removes a mark given by its ID. + After the call, the mark ID is invalid. + */ + void RemoveMark( UndoStackMark const i_mark ); + + /** determines whether the top action on the Undo stack has a given mark + */ + bool HasTopUndoActionMark( UndoStackMark const i_mark ); + + /** removes the oldest Undo actions from the stack + */ + void RemoveOldestUndoAction(); + + void dumpAsXml(xmlTextWriterPtr pWriter) const; + +protected: + bool UndoWithContext( SfxUndoContext& i_context ); + bool RedoWithContext( SfxUndoContext& i_context ); + + void ImplClearRedo_NoLock( bool const i_currentLevel ); + + /** clears all undo actions on the current level, plus all undo actions on superordinate levels, + as soon as those levels are reached. + + If no list action is active currently, i.e. we're on the top level already, this method is equivalent to + ->Clear. + + Otherwise, the Undo actions on the current level are removed. Upon leaving the current list action, all + undo actions on the then-current level are removed, too. This is continued until the top level is reached. + */ + void ClearAllLevels(); + virtual void EmptyActionsChanged(); + +private: + size_t ImplLeaveListAction( const bool i_merge, ::svl::undo::impl::UndoManagerGuard& i_guard ); + bool ImplAddUndoAction_NoNotify( std::unique_ptr pAction, bool bTryMerge, bool bClearRedo, ::svl::undo::impl::UndoManagerGuard& i_guard ); + void ImplClearRedo( ::svl::undo::impl::UndoManagerGuard& i_guard, bool const i_currentLevel ); + void ImplClearUndo( ::svl::undo::impl::UndoManagerGuard& i_guard ); + void ImplClearCurrentLevel_NoNotify( ::svl::undo::impl::UndoManagerGuard& i_guard ); + size_t ImplGetRedoActionCount_Lock( bool const i_currentLevel = CurrentLevel ) const; + bool ImplIsUndoEnabled_Lock() const; + bool ImplIsInListAction_Lock() const; + void ImplEnableUndo_Lock( bool const i_enable ); + + bool ImplUndo( SfxUndoContext* i_contextOrNull ); + bool ImplRedo( SfxUndoContext* i_contextOrNull ); + void ImplCheckEmptyActions(); + inline bool ImplIsEmptyActions() const; + + friend class ::svl::undo::impl::LockGuard; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/urihelper.hxx b/include/svl/urihelper.hxx new file mode 100644 index 000000000..9f8588c97 --- /dev/null +++ b/include/svl/urihelper.hxx @@ -0,0 +1,173 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_URIHELPER_HXX +#define INCLUDED_SVL_URIHELPER_HXX + +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace uno { class XComponentContext; } + namespace uri { class XUriReference; } +} + +class CharClass; + +namespace URIHelper { + +/** + @ATT + Calling this function with defaulted arguments rMaybeFileHdl = Link() and + bCheckFileExists = true often leads to results that are not intended: + Whenever the given rTheBaseURIRef is a file URL, the given rTheRelURIRef is + relative, and rTheRelURIRef could also be smart-parsed as a non-file URL + (e.g., the relative URL "foo/bar" can be smart-parsed as "http://foo/bar"), + then SmartRel2Abs called with rMaybeFileHdl = Link() and bCheckFileExists = + true returns the non-file URL interpretation. To avoid this, either pass + some non-null rMaybeFileHdl if you want to check generated file URLs for + existence (see URIHelper::GetMaybeFileHdl), or use bCheckFileExists = false + if you want to generate file URLs without checking for their existence. +*/ +SVL_DLLPUBLIC OUString SmartRel2Abs(INetURLObject const & rTheBaseURIRef, + OUString const & rTheRelURIRef, + Link const & rMaybeFileHdl = Link(), + bool bCheckFileExists = true, + bool bIgnoreFragment = false, + INetURLObject::EncodeMechanism eEncodeMechanism = INetURLObject::EncodeMechanism::WasEncoded, + INetURLObject::DecodeMechanism eDecodeMechanism = INetURLObject::DecodeMechanism::ToIUri, + rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8, + FSysStyle eStyle = FSysStyle::Detect); + +SVL_DLLPUBLIC void SetMaybeFileHdl(Link const & rTheMaybeFileHdl); + +SVL_DLLPUBLIC Link const & GetMaybeFileHdl(); + +/** + Converts a URI reference to a relative one, ignoring certain differences (for + example, treating file URLs for case-ignoring file systems + case-insensitively). + + @param context a component context; must not be null + + @param baseUriReference a base URI reference + + @param uriReference a URI reference + + @return a URI reference representing the given uriReference relative to the + given baseUriReference; if the given baseUriReference is not an absolute, + hierarchical URI reference, or the given uriReference is not a valid URI + reference, null is returned + + @exception std::bad_alloc if an out-of-memory condition occurs + + @exception css::uno::RuntimeException if any error occurs + */ +SVL_DLLPUBLIC css::uno::Reference< css::uri::XUriReference > +normalizedMakeRelative( + css::uno::Reference< css::uno::XComponentContext > const & context, + OUString const & baseUriReference, + OUString const & uriReference); + +/** + A variant of normalizedMakeRelative with a simplified interface. + + Internally calls normalizedMakeRelative with the default component context. + + @param baseUriReference a base URI reference, passed to + normalizedMakeRelative + + @param uriReference a URI reference, passed to normalizedMakeRelative + + @return if the XUriReference returned by normalizedMakeRelative is empty, + uriReference is returned unmodified; otherwise, the result of calling + XUriReference::getUriReference on the XUriReference returned by + normalizedMakeRelative is returned + + @exception std::bad_alloc if an out-of-memory condition occurs + + @exception css::uno::RuntimeException if any error occurs + + @deprecated + No code should rely on the default component context. +*/ +SVL_DLLPUBLIC OUString simpleNormalizedMakeRelative( OUString const & baseUriReference, + OUString const & uriReference); + +SVL_DLLPUBLIC OUString FindFirstURLInText(OUString const & rText, + sal_Int32 & rBegin, + sal_Int32 & rEnd, + CharClass const & rCharClass, + INetURLObject::EncodeMechanism eMechanism = INetURLObject::EncodeMechanism::WasEncoded, + rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8); + +/** Remove any password component from both absolute and relative URLs. + + @ATT The current implementation will not remove a password from a + relative URL that has an authority component (e.g., the password is not + removed from the relative ftp URL ). But + since our functions to translate between absolute and relative URLs never + produce relative URLs with authority components, this is no real problem. + + @ATT For relative URLs (or anything not recognized as an absolute URI), + the current implementation will return the input unmodified, not applying + any translations implied by the encode/decode parameters. + + @param rURI An absolute or relative URI reference. + + @param eEncodeMechanism See the general discussion for INetURLObject set- + methods. + + @param eDecodeMechanism See the general discussion for INetURLObject get- + methods. + + @param eCharset See the general discussion for INetURLObject get- and + set-methods. + + @return The input URI with any password component removed. + */ +SVL_DLLPUBLIC OUString removePassword(OUString const & rURI, + INetURLObject::EncodeMechanism eEncodeMechanism, + INetURLObject::DecodeMechanism eDecodeMechanism = INetURLObject::DecodeMechanism::ToIUri, + rtl_TextEncoding eCharset = RTL_TEXTENCODING_UTF8); + +/** Resolve a URL's host component domain name in IDNA syntax to plain DNS + syntax. + + For details, see RFC 5890 "Internationalized Domain Names for Applications + (IDNA): Definitions and Document Framework." + + @param: url An arbitrary string, should be a URI. + + @return If the input matches the syntax of a hierarchical URL, and it has + a host component that matches the IDNA2008 domain name syntax, and that + domain name contains any U-labels, return a version of the input URL with + the host component resolved to plain DNS syntax. Otherwise, return the + input unchanged. +*/ +SVL_DLLPUBLIC OUString resolveIdnaHost(OUString const & url); + +} + +#endif // INCLUDED_SVL_URIHELPER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/urlbmk.hxx b/include/svl/urlbmk.hxx new file mode 100644 index 000000000..e2a090806 --- /dev/null +++ b/include/svl/urlbmk.hxx @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_URLBMK_HXX +#define INCLUDED_SVL_URLBMK_HXX + +#include +#include + + +/** + * This class represents a bookmark that consists of a URL and + * a corresponding description text. + * + * There is an own clipboard format and helper methods to copy + * to and from clipboard and DragServer. + */ +class INetBookmark +{ + OUString aUrl; + OUString aDescr; + +public: + INetBookmark( OUString _aUrl, OUString _aDescr ) + : aUrl(std::move( _aUrl )), aDescr(std::move( _aDescr )) + {} + INetBookmark() + {} + + const OUString& GetURL() const { return aUrl; } + const OUString& GetDescription() const { return aDescr; } +}; + + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/visitem.hxx b/include/svl/visitem.hxx new file mode 100644 index 000000000..4ae5cdd55 --- /dev/null +++ b/include/svl/visitem.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVL_VISITEM_HXX +#define INCLUDED_SVL_VISITEM_HXX + +#include +#include +#include + +class SVL_DLLPUBLIC SfxVisibilityItem final : public SfxPoolItem +{ + css::frame::status::Visibility m_nValue; + +public: + + explicit SfxVisibilityItem(sal_uInt16 which, bool bVisible): + SfxPoolItem(which) + { + m_nValue.bVisible = bVisible; + } + + virtual bool operator ==(const SfxPoolItem & rItem) const override; + + virtual bool GetPresentation(SfxItemPresentation, MapUnit, MapUnit, + OUString & rText, + const IntlWrapper&) + const override; + + virtual bool QueryValue( css::uno::Any& rVal, + sal_uInt8 nMemberId = 0 ) const override; + + virtual bool PutValue( const css::uno::Any& rVal, + sal_uInt8 nMemberId ) override; + + virtual SfxVisibilityItem* Clone(SfxItemPool * = nullptr) const override; + + bool GetValue() const { return m_nValue.bVisible; } +}; + +#endif // INCLUDED_SVL_VISITEM_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/whichranges.hxx b/include/svl/whichranges.hxx new file mode 100644 index 000000000..744a0f2ed --- /dev/null +++ b/include/svl/whichranges.hxx @@ -0,0 +1,128 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +typedef std::pair WhichPair; + +namespace svl +{ +namespace detail +{ +constexpr bool validRange(sal_uInt16 wid1, sal_uInt16 wid2) { return wid1 != 0 && wid1 <= wid2; } + +constexpr bool validGap(sal_uInt16 wid1, sal_uInt16 wid2) { return wid2 > wid1; } + +template constexpr bool validRanges() +{ + return validRange(WID1, WID2); +} + +template +constexpr bool validRanges() +{ + return validRange(WID1, WID2) && validGap(WID2, WID3) && validRanges(); +} + +// The calculations in rangeSize cannot overflow, assuming +// std::size_t is no smaller than sal_uInt16: +constexpr std::size_t rangeSize(sal_uInt16 wid1, sal_uInt16 wid2) +{ + assert(validRange(wid1, wid2)); + return wid2 - wid1 + 1; +} +} + +template struct Items_t +{ + using Array = std::array; + template + static constexpr void fill(typename Array::iterator it) + { + it->first = WID1; + it->second = WID2; + if constexpr (sizeof...(Rest) > 0) + fill(++it); + } + static constexpr Array make() + { + assert(svl::detail::validRanges()); + Array a{}; + fill(a.begin()); + return a; + } + // This is passed to WhichRangesContainer so we can avoid needing to malloc() + // for compile-time data. + static constexpr Array value = make(); +}; + +template inline static constexpr auto Items = Items_t{}; +} + +/** + * Most of the time, the which ranges we point at are a compile-time literal. + * So we take advantage of that, and avoid the cost of allocating our own array and copying into it. + */ +struct SVL_DLLPUBLIC WhichRangesContainer +{ + using const_iterator = WhichPair const*; + + WhichPair const* m_pairs = nullptr; + sal_Int32 m_size = 0; + /** if true, we allocated and need to delete the pairs, if not, we are pointing + * at a global const literal */ + bool m_bOwnRanges = false; + + WhichRangesContainer() = default; + + WhichRangesContainer(std::unique_ptr wids, sal_Int32 nSize) + : m_pairs(wids.release()) + , m_size(nSize) + , m_bOwnRanges(true) + { + } + template + WhichRangesContainer(svl::Items_t) + : m_pairs(svl::Items_t::value.data()) + , m_size(svl::Items_t::value.size()) + , m_bOwnRanges(false) + { + } + WhichRangesContainer(const WhichPair* wids, sal_Int32 nSize); + WhichRangesContainer(sal_uInt16 nWhichStart, sal_uInt16 nWhichEnd); + WhichRangesContainer(WhichRangesContainer const& other) { operator=(other); } + WhichRangesContainer(WhichRangesContainer&& other); + ~WhichRangesContainer(); + + WhichRangesContainer& operator=(WhichRangesContainer&& other); + WhichRangesContainer& operator=(WhichRangesContainer const& other); + + bool operator==(WhichRangesContainer const& other) const; + const_iterator begin() const noexcept { return m_pairs; } + const_iterator end() const noexcept { return begin() + size(); } + bool empty() const noexcept { return m_size == 0; } + sal_Int32 size() const noexcept { return m_size; } + WhichPair const& operator[](sal_Int32 idx) const noexcept + { + assert(idx >= 0 && idx < size() && "index out of range"); + return m_pairs[idx]; + } + void reset(); + + // Adds a range to which ranges, keeping the ranges in valid state (sorted, non-overlapping) + SAL_WARN_UNUSED_RESULT WhichRangesContainer MergeRange(sal_uInt16 nFrom, sal_uInt16 nTo) const; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/include/svl/whiter.hxx b/include/svl/whiter.hxx new file mode 100644 index 000000000..155d02d7f --- /dev/null +++ b/include/svl/whiter.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include + +class SfxItemSet; +class SfxPoolItem; +enum class SfxItemState; + +/** + * Iterates over the which ids and the pool items arrays together (which are stored in parallel arrays). + * Primarily so that we can call GetItemSet on the SfxItemSet and pass in a hint, which avoids + * searching the array the SfxItemSet, which speeds up GetItemState greatly. + */ +class SVL_DLLPUBLIC SfxWhichIter +{ + const SfxItemSet& m_rItemSet; + const WhichPair* m_pCurrentWhichPair; + sal_uInt16 m_nOffsetFromStartOfCurrentWhichPair; + /// Offset into m_ppItems array in SfxItemSet + sal_uInt16 m_nItemsOffset; + +public: + SfxWhichIter(const SfxItemSet& rSet); + + sal_uInt16 GetCurWhich() const; + sal_uInt16 NextWhich(); + sal_uInt16 FirstWhich(); + SfxItemState GetItemState(bool bSrchInParent = true, + const SfxPoolItem** ppItem = nullptr) const; + void ClearItem(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/zforlist.hxx b/include/svl/zforlist.hxx new file mode 100644 index 000000000..4159ce0fb --- /dev/null +++ b/include/svl/zforlist.hxx @@ -0,0 +1,381 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_ZFORLIST_HXX +#define INCLUDED_SVL_ZFORLIST_HXX + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace com::sun::star::i18n { struct Currency; } + +class SvNumberformat; + +#define SV_COUNTRY_LANGUAGE_OFFSET 10000 // Max count of formats per country/language +#define SV_MAX_COUNT_STANDARD_FORMATS 100 // Max count of builtin default formats per CL + +constexpr size_t NF_MAX_FORMAT_SYMBOLS = 100; + +/// The built-in @ Text format, offset within a locale, key in the locale the +/// number formatter was constructed with. +constexpr sal_uInt32 NF_STANDARD_FORMAT_TEXT = SV_MAX_COUNT_STANDARD_FORMATS; + +constexpr sal_uInt32 NUMBERFORMAT_ENTRY_NOT_FOUND = 0xffffffff; /// MAX_ULONG + +enum class SvNumFormatType : sal_Int16 +{ + /** selects all number formats. + */ + ALL = css::util::NumberFormat::ALL, // 0 + /** selects only user-defined number formats. + */ + DEFINED = css::util::NumberFormat::DEFINED, // 1 + /** selects date formats. + */ + DATE = css::util::NumberFormat::DATE, // 2 + /** selects time formats. + */ + TIME = css::util::NumberFormat::TIME, // 4 + /** selects currency formats. + */ + CURRENCY = css::util::NumberFormat::CURRENCY, // 8 + /** selects decimal number formats. + */ + NUMBER = css::util::NumberFormat::NUMBER, // 16 + /** selects scientific number formats. + */ + SCIENTIFIC = css::util::NumberFormat::SCIENTIFIC, // 32 + /** selects number formats for fractions. + */ + FRACTION = css::util::NumberFormat::FRACTION, // 64 + /** selects percentage number formats. + */ + PERCENT = css::util::NumberFormat::PERCENT, // 128 + /** selects text number formats. + */ + TEXT = css::util::NumberFormat::TEXT, // 256 + /** selects number formats which contain date and time. + */ + DATETIME = DATE | TIME, // 6 + /** selects boolean number formats. + */ + LOGICAL = css::util::NumberFormat::LOGICAL, // 1024 + /** is used as a return value if no format exists. + */ + UNDEFINED = css::util::NumberFormat::UNDEFINED, // 2048 + /** @internal is used to flag an empty sub format. + @since LibreOffice 5.1 + */ + EMPTY = css::util::NumberFormat::EMPTY, // 4096 + /** @internal selects a time duration format. + 8192 + TIME (4) + @since LibreOffice 6.2 + */ + DURATION = css::util::NumberFormat::DURATION, // 8196 +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + +/** enum values for SvNumberFormatter::GetFormatIndex + +

    + Builtin standard formats, order should be also the arrangement in the + dialog list box representation.

    + +

    + Date specials:

      +
    • SYSTEM: As set in System Regional Settings. +
    • SYS: short/long defined, order and separators from System Regional Settings. +
    • DEF: short/long and order defined, separators from System Regional Settings. +
    • DIN: all settings hard coded as DIN (Deutsche Industrie Norm) and EN (European Norm) require. +
    • all other: hard coded +
    + + Do NOT insert any new values! + The values here correspond with those in offapi/com/sun/star/i18n/NumberFormatIndex.idl + You may append values though after NF_INDEX_TABLE_LOCALE_DATA_DEFAULTS. + */ +enum NfIndexTableOffset +{ + NF_NUMERIC_START = 0, + + NF_NUMBER_START = NF_NUMERIC_START, + NF_NUMBER_STANDARD = NF_NUMBER_START, // Standard/General + NF_NUMBER_INT, // 0 + NF_NUMBER_DEC2, // 0.00 + NF_NUMBER_1000INT, // #,##0 + NF_NUMBER_1000DEC2, // #,##0.00 + NF_NUMBER_SYSTEM, // #,##0.00 or whatever is set in System Regional Settings + NF_NUMBER_END = NF_NUMBER_SYSTEM, + + NF_SCIENTIFIC_START, + NF_SCIENTIFIC_000E000 = NF_SCIENTIFIC_START, // 0.00E+000 + NF_SCIENTIFIC_000E00, // 0.00E+00 + NF_SCIENTIFIC_END = NF_SCIENTIFIC_000E00, + + NF_PERCENT_START, + NF_PERCENT_INT = NF_PERCENT_START, // 0% + NF_PERCENT_DEC2, // 0.00% + NF_PERCENT_END = NF_PERCENT_DEC2, + + NF_FRACTION_START, + NF_FRACTION_1D = NF_FRACTION_START, // # ?/? + NF_FRACTION_2D, // # ??/?? + NF_FRACTION_END = NF_FRACTION_2D, + + NF_NUMERIC_END = NF_FRACTION_END, + + NF_CURRENCY_START, + NF_CURRENCY_1000INT = NF_CURRENCY_START,// #,##0 DM + NF_CURRENCY_1000DEC2, // #,##0.00 DM + NF_CURRENCY_1000INT_RED, // #,##0 DM negative in red + NF_CURRENCY_1000DEC2_RED, // #,##0.00 DM negative in red + NF_CURRENCY_1000DEC2_CCC, // #,##0.00 DEM currency abbreviation + NF_CURRENCY_1000DEC2_DASHED, // #,##0.-- DM + NF_CURRENCY_END = NF_CURRENCY_1000DEC2_DASHED, + + NF_DATE_START, + NF_DATE_SYSTEM_SHORT = NF_DATE_START, // 08.10.97 + NF_DATE_SYSTEM_LONG, // Wednesday, 8. October 1997 + NF_DATE_SYS_DDMMYY, // 08.10.97 + NF_DATE_SYS_DDMMYYYY, // 08.10.1997 THE edit format, formatindex="21" + NF_DATE_SYS_DMMMYY, // 8. Oct 97 + NF_DATE_SYS_DMMMYYYY, // 8. Oct 1997 + NF_DATE_DIN_DMMMYYYY, // 8. Oct. 1997 DIN + NF_DATE_SYS_DMMMMYYYY, // 8. October 1997 + NF_DATE_DIN_DMMMMYYYY, // 8. October 1997 DIN + NF_DATE_SYS_NNDMMMYY, // Wed, 8. Okt 97 + NF_DATE_DEF_NNDDMMMYY, // Wed 08.Okt 97 + NF_DATE_SYS_NNDMMMMYYYY, // Wed, 8. Oktober 1997 + NF_DATE_SYS_NNNNDMMMMYYYY, // Wednesday, 8. Oktober 1997 + NF_DATE_DIN_MMDD, // 10-08 DIN + NF_DATE_DIN_YYMMDD, // 97-10-08 DIN + NF_DATE_DIN_YYYYMMDD, // 1997-10-08 DIN + NF_DATE_ISO_YYYYMMDD = NF_DATE_DIN_YYYYMMDD, // 1997-10-08 ISO clarify with name, formatindex="33" + NF_DATE_SYS_MMYY, // 10.97 + NF_DATE_SYS_DDMMM, // 08.Oct + NF_DATE_MMMM, // October + NF_DATE_QQJJ, // 4. Quarter 97 + NF_DATE_WW, // week of year + NF_DATE_END = NF_DATE_WW, + + NF_TIME_START, + NF_TIME_HHMM = NF_TIME_START, // HH:MM + NF_TIME_HHMMSS, // HH:MM:SS + NF_TIME_HHMMAMPM, // HH:MM AM/PM + NF_TIME_HHMMSSAMPM, // HH:MM:SS AM/PM + NF_TIME_HH_MMSS, // [HH]:MM:SS formatindex="43" + NF_TIME_MMSS00, // MM:SS,00 formatindex="44" + NF_TIME_HH_MMSS00, // [HH]:MM:SS,00 formatindex="45" + NF_TIME_END = NF_TIME_HH_MMSS00, + + NF_DATETIME_START, + NF_DATETIME_SYSTEM_SHORT_HHMM = NF_DATETIME_START, // 08.10.97 01:23 + NF_DATETIME_SYS_DDMMYYYY_HHMMSS, // 08.10.1997 01:23:45 THE edit format, formatindex="47" + NF_DATETIME_END = NF_DATETIME_SYS_DDMMYYYY_HHMMSS, + + NF_BOOLEAN, // BOOLEAN + NF_TEXT, // @ + + NF_INDEX_TABLE_LOCALE_DATA_DEFAULTS, // == 50, old number of predefined entries, i18npool locale data additions start after this + + // From here on are values of new predefined and built-in formats that are + // not in the original NumberFormatIndex.idl + + // XXX Values appended here must also get a corresponding entry in + // svl/source/numbers/zforlist.cxx indexTable[] in the same order. + + // XXX The dialog's number format shell assumes start/end spans + // (NF_..._START and NF_..._END above) to fill its categories with builtin + // formats, make new formats known to svx/source/items/numfmtsh.cxx + // SvxNumberFormatShell::FillEListWithStd_Impl(), otherwise they will not + // be listed at all. Yes that is ugly. + // DATETIME formats need to be added to + // SvxNumberFormatShell::FillEListWithDateTime_Impl(). + + // New predefined format added to i18npool locale data. + NF_DATETIME_SYS_DDMMYYYY_HHMM = NF_INDEX_TABLE_LOCALE_DATA_DEFAULTS, // 08.10.1997 01:23 formatindex="50" + + // No i18npool defined locale data between here and NF_INDEX_TABLE_ENTRIES. + NF_INDEX_TABLE_RESERVED_START, + + NF_FRACTION_3D = NF_INDEX_TABLE_RESERVED_START, // # ???/??? + NF_FRACTION_2, // # ?/2 + NF_FRACTION_4, // # ?/4 + NF_FRACTION_8, // # ?/8 + NF_FRACTION_16, // # ??/16 + NF_FRACTION_10, // # ??/10 + NF_FRACTION_100, // # ??/100 + + NF_DATETIME_ISO_YYYYMMDD_HHMMSS, // 1997-10-08 01:23:45 ISO (with blank instead of T) + NF_DATETIME_ISO_YYYYMMDD_HHMMSS000, // 1997-10-08 01:23:45.678 not quite ISO with locale's separator + NF_DATETIME_ISO_YYYYMMDDTHHMMSS, // 1997-10-08T01:23:45 ISO + NF_DATETIME_ISO_YYYYMMDDTHHMMSS000, // 1997-10-08T01:23:45,678 ISO with milliseconds and ',' or '.' + + // XXX When adding values here, follow the comment above about + // svx/source/items/numfmtsh.cxx + + NF_INDEX_TABLE_ENTRIES // == 62, reserved to not be used in i18npool locale data. + + // XXX Adding values above may increment the reserved area that can't be + // used by i18npool's locale data FormatCode definitions, see the + // description at i18npool/source/localedata/data/locale.dtd for ELEMENT + // FormatCode what the current convention's value is. In that case, the + // used formatIndex values in i18npool/source/localedata/data/*.xml will + // have to be adjusted. + // Overlapping the area will bail out with a check in + // SvNumberFormatter::ImpInsertFormat() in debug builds. +}; + + +// #45717# IsNumberFormat( "98-10-24", 30, x ), YMD Format set with DMY +// International settings doesn't recognize the string as a date. +/** enum values for SvNumberFormatter::SetEvalDateFormat + +

    How ImpSvNumberInputScan::GetDateRef shall take the + DateFormat order (YMD,DMY,MDY) into account, if called from IsNumberFormat + with a date format to match against. + */ +enum NfEvalDateFormat +{ + /** DateFormat only from International, default. */ + NF_EVALDATEFORMAT_INTL, + + /** DateFormat only from date format passed to function (if any). + If no date format is passed then the DateFormat is taken from International. */ + NF_EVALDATEFORMAT_FORMAT, + + /** First try the DateFormat from International. If it doesn't match a + valid date try the DateFormat from the date format passed. */ + NF_EVALDATEFORMAT_INTL_FORMAT, + + /** First try the DateFormat from the date format passed. If it doesn't + match a valid date try the DateFormat from International. */ + NF_EVALDATEFORMAT_FORMAT_INTL +}; + + +/// This table is std::map because it needs to preserve insertion order, +/// because the formats are roughly ordered from most to least common, and some +/// parts of the UI want to show them in that order. +typedef std::map SvNumberFormatTable; +typedef std::unordered_map SvNumberFormatterIndexTable; +typedef std::unordered_map< sal_uInt32, sal_uInt32> SvNumberFormatterMergeMap; + + +/** Language/country dependent currency entries + */ +class UNLESS_MERGELIBS(SVL_DLLPUBLIC) NfCurrencyEntry final +{ + OUString aSymbol; /// currency symbol + OUString aBankSymbol; /// currency abbreviation + LanguageType eLanguage; /// language/country value + sal_uInt16 nPositiveFormat; /// position of symbol + sal_uInt16 nNegativeFormat; /// position of symbol and type and position of negative sign + sal_uInt16 nDigits; /// count of decimal digits + sal_Unicode cZeroChar; /// which character is used for zeros as last decimal digits + +private: + + // nDecimalFormat := 0, 1, 2 + // #,##0 or #,##0.00 or #,##0.-- is returned + SVL_DLLPRIVATE OUString Impl_BuildFormatStringNumChars( const LocaleDataWrapper&, sal_uInt16 nDecimalFormat) const; + +public: + + NfCurrencyEntry( const LocaleDataWrapper& rLocaleData, + LanguageType eLang ); + NfCurrencyEntry( const css::i18n::Currency & rCurr, + const LocaleDataWrapper& rLocaleData, + LanguageType eLang ); + + /// Symbols and language identical + bool operator==( const NfCurrencyEntry& r ) const; + + const OUString& GetSymbol() const { return aSymbol; } + const OUString& GetBankSymbol() const { return aBankSymbol; } + LanguageType GetLanguage() const { return eLanguage; } + sal_uInt16 GetPositiveFormat() const { return nPositiveFormat; } + sal_uInt16 GetNegativeFormat() const { return nNegativeFormat; } + sal_uInt16 GetDigits() const { return nDigits; } + + /** Only to resolve system locale for currency list. */ + void SetLanguage( LanguageType nLang ) { eLanguage = nLang; } + + /** [$DM-407] (bBank==false) or [$DEM] (bBank==true) + is returned. If bBank==false and + bWithoutExtension==true only [$DM] */ + OUString BuildSymbolString(bool bBank, bool bWithoutExtension = false) const; + + /** #,##0.00 [$DM-407] is returned, separators + from rLoc, incl. minus sign but without [RED] */ + OUString BuildPositiveFormatString(bool bBank, const LocaleDataWrapper&, + sal_uInt16 nDecimalFormat = 1) const; + OUString BuildNegativeFormatString(bool bBank, const LocaleDataWrapper&, + sal_uInt16 nDecimalFormat = 1) const; + + /** [$DM-407] (or [$DEM] if bBank==true) + is appended/prepended to rStr, incl. minus sign */ + void CompletePositiveFormatString(OUStringBuffer& rStr, bool bBank, + sal_uInt16 nPosiFormat) const; + void CompleteNegativeFormatString(OUStringBuffer& rStr, bool bBank, + sal_uInt16 nNegaFormat) const; + + /// rSymStr is appended/prepended to rStr, incl. minus sign + static void CompletePositiveFormatString(OUStringBuffer& rStr, + std::u16string_view rSymStr, sal_uInt16 nPosiFormat); + static void CompleteNegativeFormatString(OUStringBuffer& rStr, + std::u16string_view rSymStr, sal_uInt16 nNegaFormat); + + /** Representation of a currency (symbol position and + negative sign) in other language settings */ + static sal_uInt16 GetEffectivePositiveFormat( sal_uInt16 nIntlFormat, + sal_uInt16 nCurrFormat, bool bBank ); + static sal_uInt16 GetEffectiveNegativeFormat( sal_uInt16 nIntlFormat, + sal_uInt16 nCurrFormat, bool bBank ); + + /// General Unicode Euro symbol + static sal_Unicode GetEuroSymbol() { return u'\x20AC'; } +}; + +typedef std::vector< OUString > NfWSStringsDtor; + +/** Input options to be used with IsNumberFormat() */ +enum class SvNumInputOptions : sal_uInt16 +{ + NONE = 0, + LAX_TIME = 1 ///< allow input of minutes or seconds >59 +}; +namespace o3tl { + template<> struct typed_flags : is_typed_flags {}; +} + + +#endif // INCLUDED_SVL_ZFORLIST_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svl/zformat.hxx b/include/svl/zformat.hxx new file mode 100644 index 000000000..ae57f5c86 --- /dev/null +++ b/include/svl/zformat.hxx @@ -0,0 +1,760 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#ifndef INCLUDED_SVL_ZFORMAT_HXX +#define INCLUDED_SVL_ZFORMAT_HXX + +#include +#include +#include +#include + +namespace utl { + class DigitGroupingIterator; +} + +namespace com::sun::star::i18n { struct NativeNumberXmlAttributes2; } + +class Color; + +class ImpSvNumberformatScan; // format code string scanner +class ImpSvNumberInputScan; // input string scanner +class SvNumberFormatter; + +enum SvNumberformatLimitOps +{ + NUMBERFORMAT_OP_NO = 0, // Undefined, no OP + NUMBERFORMAT_OP_EQ = 1, // Operator = + NUMBERFORMAT_OP_NE = 2, // Operator <> + NUMBERFORMAT_OP_LT = 3, // Operator < + NUMBERFORMAT_OP_LE = 4, // Operator <= + NUMBERFORMAT_OP_GT = 5, // Operator > + NUMBERFORMAT_OP_GE = 6 // Operator >= +}; + +struct ImpSvNumberformatInfo // Struct for FormatInfo +{ + std::vector sStrArray; // Array of symbols + std::vector nTypeArray; // Array of infos + sal_uInt16 nThousand; // Count of group separator sequences + sal_uInt16 nCntPre; // Count of digits before decimal point + sal_uInt16 nCntPost; // Count of digits after decimal point + sal_uInt16 nCntExp; // Count of exponent digits, or AM/PM + SvNumFormatType eScannedType; // Type determined by scan + bool bThousand; // Has group (AKA thousand) separator + + void Copy( const ImpSvNumberformatInfo& rNumFor, sal_uInt16 nCount ); +}; + +// NativeNumber, represent numbers using CJK or other digits if nNum>0, +// eLang specifies the Locale to use. +class SvNumberNatNum +{ + OUString sParams; // For [NatNum12 ordinal-number]-like syntax + LanguageType eLang; + sal_uInt8 nNum; + bool bDBNum :1; // DBNum, to be converted to NatNum + bool bDate :1; // Used in date? (needed for DBNum/NatNum mapping) + bool bSet :1; // If set, since NatNum0 is possible + +public: + + static sal_uInt8 MapDBNumToNatNum( sal_uInt8 nDBNum, LanguageType eLang, bool bDate ); + static sal_uInt8 MapNatNumToDBNum( sal_uInt8 nNatNum, LanguageType eLang, bool bDate ); + + SvNumberNatNum() : eLang( LANGUAGE_DONTKNOW ), nNum(0), + bDBNum(false), bDate(false), bSet(false) {} + bool IsComplete() const { return bSet && eLang != LANGUAGE_DONTKNOW; } + sal_uInt8 GetNatNum() const { return bDBNum ? MapDBNumToNatNum( nNum, eLang, bDate ) : nNum; } + sal_uInt8 GetDBNum() const { return bDBNum ? nNum : MapNatNumToDBNum( nNum, eLang, bDate ); } + LanguageType GetLang() const { return eLang; } + void SetLang( LanguageType e ) { eLang = e; } + void SetNum( sal_uInt8 nNumber, bool bDBNumber ) + { + nNum = nNumber; + bDBNum = bDBNumber; + bSet = true; + } + bool IsSet() const { return bSet; } + void SetDate( bool bDateP ) { bDate = bDateP; } + void SetParams(const OUString& s) { sParams = s; } + OUString const & GetParams() const { return sParams; } +}; + +class CharClass; + +class ImpSvNumFor // One of four subformats of the format code string +{ +public: + ImpSvNumFor(); // Ctor without filling the Info + ~ImpSvNumFor(); + + void Enlarge(sal_uInt16 nCount); // Init of arrays to the right size + + // if pSc is set, it is used to get the Color pointer + void Copy( const ImpSvNumFor& rNumFor, const ImpSvNumberformatScan* pSc ); + + // Access to Info; call Enlarge before! + ImpSvNumberformatInfo& Info() { return aI;} + const ImpSvNumberformatInfo& Info() const { return aI; } + + // Get count of substrings (symbols) + sal_uInt16 GetCount() const { return nStringsCnt;} + + const Color* GetColor() const { return pColor; } + void SetColor(const Color* pCol, OUString const& rName) + { pColor = pCol; sColorName = rName; } + const OUString& GetColorName() const { return sColorName; } + + // new SYMBOLTYPE_CURRENCY in subformat? + bool HasNewCurrency() const; + bool GetNewCurrencySymbol( OUString& rSymbol, OUString& rExtension ) const; + + // [NatNum1], [NatNum2], ... + void SetNatNumNum( sal_uInt8 nNum, bool bDBNum ) { aNatNum.SetNum( nNum, bDBNum ); } + void SetNatNumLang( LanguageType eLang ) { aNatNum.SetLang( eLang ); } + void SetNatNumDate( bool bDate ) { aNatNum.SetDate( bDate ); } + void SetNatNumParams(const OUString& sParams) { aNatNum.SetParams(sParams); } + const SvNumberNatNum& GetNatNum() const { return aNatNum; } + +private: + ImpSvNumberformatInfo aI; // helper struct for remaining information + OUString sColorName; // color name + const Color* pColor; // pointer to color of subformat + sal_uInt16 nStringsCnt; // count of symbols + SvNumberNatNum aNatNum; // DoubleByteNumber + +}; + +class SVL_DLLPUBLIC SvNumberformat +{ + struct SAL_DLLPRIVATE LocaleType + { + enum class Substitute : sal_uInt8 + { + NONE, + TIME, + LONGDATE + }; + + LanguageType meLanguage; + LanguageType meLanguageWithoutLocaleData; + Substitute meSubstitute; + sal_uInt8 mnNumeralShape; + sal_uInt8 mnCalendarType; + + OUString generateCode() const; + + LocaleType(); + LocaleType(sal_uInt32 nRawCode); + + bool isPlainLocale() const; + }; + +public: + // Normal ctor + SvNumberformat( OUString& rString, + ImpSvNumberformatScan* pSc, + ImpSvNumberInputScan* pISc, + sal_Int32& nCheckPos, + LanguageType& eLan, + bool bReplaceBooleanEquivalent = true ); + + // Copy ctor + SvNumberformat( SvNumberformat const & rFormat ); + + // Copy ctor with exchange of format code string scanner (used in merge) + SvNumberformat( SvNumberformat const & rFormat, ImpSvNumberformatScan& rSc ); + + ~SvNumberformat(); + + /// Get type of format, may include css::util::NumberFormat::DEFINED bit + SvNumFormatType GetType() const { return eType; } + + /// Get type of format, does not include css::util::NumberFormat::DEFINED + SvNumFormatType GetMaskedType() const { return eType & ~SvNumFormatType::DEFINED; } + + void SetType(SvNumFormatType eSetType) { eType = eSetType; } + // Standard means the I18N defined standard format of this type + void SetStandard() { bStandard = true; } + bool IsStandard() const { return bStandard; } + + // If this format is an additional built-in format defined by i18n. + void SetAdditionalBuiltin() { bAdditionalBuiltin = true; } + bool IsAdditionalBuiltin() const { return bAdditionalBuiltin; } + + LanguageType GetLanguage() const { return maLocale.meLanguage;} + + /** If the format is a placeholder and needs to be substituted. */ + bool IsSubstituted() const + { + return maLocale.meSubstitute != LocaleType::Substitute::NONE; + } + + /** If the format is a placeholder for the system time format and needs to + be substituted during formatting time. + */ + bool IsSystemTimeFormat() const + { + return maLocale.meSubstitute == LocaleType::Substitute::TIME && maLocale.meLanguage == LANGUAGE_SYSTEM; + } + + /** If the format is a placeholder for the system long date format and needs + to be substituted during formatting time. + */ + bool IsSystemLongDateFormat() const + { + return maLocale.meSubstitute == LocaleType::Substitute::LONGDATE && maLocale.meLanguage == LANGUAGE_SYSTEM; + } + + /** If the format is a MM:SS or [MM]:SS format, or MM:[SS] (sic!) or even + MM:SS.00 or [MM]:SS.00 or MM:[SS].00 + */ + bool IsMinuteSecondFormat() const; + + const OUString& GetFormatstring() const { return sFormatstring; } + + // Build a format string of application defined keywords + OUString GetMappedFormatstring( const NfKeywordTable& rKeywords, + const LocaleDataWrapper& rLoc, + LanguageType nOriginalLang = LANGUAGE_DONTKNOW, + bool bSystemLanguage = false ) const; + + void SetStarFormatSupport( bool b ) { bStarFlag = b; } + + /** + * Get output string from a numeric value that fits the number of + * characters specified. + */ + bool GetOutputString( double fNumber, sal_uInt16 nCharCount, OUString& rOutString ) const; + + bool GetOutputString( double fNumber, OUString& OutString, const Color** ppColor ); + void GetOutputString( std::u16string_view sString, OUString& OutString, const Color** ppColor ); + + // True if type text + bool IsTextFormat() const { return bool(eType & SvNumFormatType::TEXT); } + // True if 4th subformat present + bool HasTextFormat() const + { + return (NumFor[3].GetCount() > 0) || + (NumFor[3].Info().eScannedType == SvNumFormatType::TEXT); + } + + void GetFormatSpecialInfo(bool& bThousand, + bool& IsRed, + sal_uInt16& nPrecision, + sal_uInt16& nLeadingCnt) const; + + /// Get index of subformat (0..3) according to conditions and fNumber value + sal_uInt16 GetSubformatIndex( double fNumber ) const; + + /// Count of decimal precision + sal_uInt16 GetFormatPrecision( sal_uInt16 nIx = 0 ) const + { return NumFor[nIx].Info().nCntPost; } + + /// Count of integer digits + sal_uInt16 GetFormatIntegerDigits( sal_uInt16 nIx = 0 ) const + { return NumFor[nIx].Info().nCntPre; } + + /** Count of hidden integer digits with thousands divisor: + formats like "0," to show only thousands. + + Works only with SvNumFormatType::NUMBER and SvNumFormatType::CURRENCY, + returns 0 otherwise. + + Returns SvNumberFormatter::UNLIMITED_PRECISION for formats that contain + the General keyword. + */ + sal_uInt16 GetThousandDivisorPrecision( sal_uInt16 nIx = 0 ) const; + + //! Read/write access on a special sal_uInt16 component, may only be used on the + //! standard format 0, 10000, ... and only by the number formatter! + struct FormatterPrivateAccess { friend SvNumberFormatter; private: FormatterPrivateAccess() {} }; + sal_uInt16 GetLastInsertKey( const FormatterPrivateAccess& ) const + { return NumFor[0].Info().nThousand; } + void SetLastInsertKey( sal_uInt16 nKey, const FormatterPrivateAccess& ) + { NumFor[0].Info().nThousand = nKey; } + + //! Only onLoad: convert from stored to current system language/country + void ConvertLanguage( SvNumberFormatter& rConverter, + LanguageType eConvertFrom, LanguageType eConvertTo ); + + // Substring of a subformat code nNumFor (0..3) + // nPos == 0xFFFF => last substring + // bString==true: first/last SYMBOLTYPE_STRING or SYMBOLTYPE_CURRENCY + const OUString* GetNumForString( sal_uInt16 nNumFor, sal_uInt16 nPos, + bool bString = false ) const; + + // Subtype of a subformat code nNumFor (0..3) + // nPos == 0xFFFF => last substring + short GetNumForType( sal_uInt16 nNumFor, sal_uInt16 nPos ) const; + + OUString GetPercentString( sal_uInt16 nNumFor = 0 ) const; + + OUString GetDenominatorString( sal_uInt16 nNumFor ) const; + OUString GetNumeratorString( sal_uInt16 nNumFor ) const; + OUString GetIntegerFractionDelimiterString( sal_uInt16 nNumFor ) const; + /// Round fNumber to its fraction representation + double GetRoundFractionValue ( double fNumber ) const; + + /// Create a format string for time with a new precision + OUString GetFormatStringForTimePrecision( int nPrecision ) const; + + + /** If the count of string elements (substrings, ignoring [modifiers] and + so on) in a subformat code nNumFor (0..3) is equal to the given number. + Used by ImpSvNumberInputScan::IsNumberFormatMain() to detect a matched + format. */ + bool IsNumForStringElementCountEqual( sal_uInt16 nNumFor, sal_uInt16 nAllCount, + sal_uInt16 nNumCount ) const + { + if ( nNumFor < 4 ) + { + // First try a simple approach. Note that this is called only + // if all MidStrings did match so far, to verify that all + // strings of the format were matched and not just the starting + // sequence, so we don't have to check if GetCount() includes + // [modifiers] or anything else if both counts are equal. + sal_uInt16 nCnt = NumFor[nNumFor].GetCount(); + if ( nAllCount == nCnt ) + return true; + if ( nAllCount < nCnt ) // check ignoring [modifiers] and so on + return ImpGetNumForStringElementCount( nNumFor ) == + (nAllCount - nNumCount); + } + return false; + } + /** Get the count of numbers among string elements **/ + sal_uInt16 GetNumForNumberElementCount( sal_uInt16 nNumFor ) const; + + /** Get the scanned type of the specified subformat. */ + SvNumFormatType GetNumForInfoScannedType( sal_uInt16 nNumFor ) const + { + return (nNumFor < 4) ? NumFor[nNumFor].Info().eScannedType : SvNumFormatType::UNDEFINED; + } + + // Whether the second subformat code is really for negative numbers + // or another limit set. + bool IsSecondSubformatRealNegative() const + { + return fLimit1 == 0.0 && fLimit2 == 0.0 && + ( (eOp1 == NUMBERFORMAT_OP_GE && eOp2 == NUMBERFORMAT_OP_NO) || + (eOp1 == NUMBERFORMAT_OP_GT && eOp2 == NUMBERFORMAT_OP_LT) || + (eOp1 == NUMBERFORMAT_OP_NO && eOp2 == NUMBERFORMAT_OP_NO) ); + } + + // Whether the first subformat code is really for negative numbers + // or another limit set. + bool IsFirstSubformatRealNegative() const + { + return fLimit1 == 0.0 && fLimit2 == 0.0 && + ((eOp1 == NUMBERFORMAT_OP_LT && + (eOp2 == NUMBERFORMAT_OP_GT || eOp2 == NUMBERFORMAT_OP_EQ || + eOp2 == NUMBERFORMAT_OP_GE || eOp2 == NUMBERFORMAT_OP_NO)) || + (eOp1 == NUMBERFORMAT_OP_LE && + (eOp2 == NUMBERFORMAT_OP_NO || eOp2 == NUMBERFORMAT_OP_GT))); + } + + // Whether the negative format is without a sign or not + bool IsNegativeWithoutSign() const; + + bool IsNegativeInBracket() const; + + bool HasPositiveBracketPlaceholder() const; + + // Whether a new SYMBOLTYPE_CURRENCY is contained in the format + bool HasNewCurrency() const; + + // strip [$-yyy] from all [$xxx-yyy] leaving only xxx's, + static OUString StripNewCurrencyDelimiters( const OUString& rStr ); + + // If a new SYMBOLTYPE_CURRENCY is contained if the format is of type + // css::util::NumberFormat::CURRENCY, and if so the symbol xxx and the extension nnn + // of [$xxx-nnn] are returned + bool GetNewCurrencySymbol( OUString& rSymbol, OUString& rExtension ) const; + + static bool HasStringNegativeSign( const OUString& rStr ); + + /** + Whether a character at position nPos is somewhere between two matching + cQuote or not. + If nPos points to a cQuote, a true is returned on an opening cQuote, + a false is returned on a closing cQuote. + A cQuote between quotes may be escaped by a cEscIn, a cQuote outside of + quotes may be escaped by a cEscOut. + The default '\0' results in no escapement possible. + Defaults are set right according to the "unlogic" of the Numberformatter + */ + static bool IsInQuote( const OUString& rString, sal_Int32 nPos, + sal_Unicode cQuote = '"', + sal_Unicode cEscIn = '\0', sal_Unicode cEscOut = '\\' ); + + /** + Return the position of a matching closing cQuote if the character at + position nPos is between two matching cQuote, otherwise return -1. + If nPos points to an opening cQuote the position of the matching + closing cQuote is returned. + If nPos points to a closing cQuote nPos is returned. + If nPos points into a part which starts with an opening cQuote but has + no closing cQuote, rString.Len() is returned. + Uses IsInQuote internally, so you don't have to call + that prior to a call of this method. + */ + static sal_Int32 GetQuoteEnd( const OUString& rString, sal_Int32 nPos, + sal_Unicode cQuote = '"', + sal_Unicode cEscIn = '\0' ); + + void SetComment( const OUString& rStr ) + { sComment = rStr; } + const OUString& GetComment() const { return sComment; } + + /** Insert the number of blanks into the string that is needed to simulate + the width of character c for underscore formats */ + static sal_Int32 InsertBlanks( OUString& r, sal_Int32 nPos, sal_Unicode c ) + { + sal_Int32 result; + OUStringBuffer sBuff(r); + + result = InsertBlanks(sBuff, nPos, c); + r = sBuff.makeStringAndClear(); + + return result; + } + + /** Insert the number of blanks into the string that is needed to simulate + the width of character c for underscore formats */ + static sal_Int32 InsertBlanks( OUStringBuffer& r, sal_Int32 nPos, sal_Unicode c ); + + /// One of YMD,DMY,MDY if date format + DateOrder GetDateOrder() const; + + /** A coded value of the exact YMD combination used, if date format. + For example: YYYY-MM-DD => ('Y' << 16) | ('M' << 8) | 'D' + or: MM/YY => ('M' << 8) | 'Y' */ + sal_uInt32 GetExactDateOrder() const; + + // used in XML export + void GetConditions( SvNumberformatLimitOps& rOper1, double& rVal1, + SvNumberformatLimitOps& rOper2, double& rVal2 ) const; + const Color* GetColor( sal_uInt16 nNumFor ) const; + void GetNumForInfo( sal_uInt16 nNumFor, SvNumFormatType& rScannedType, + bool& bThousand, sal_uInt16& nPrecision, sal_uInt16& nLeadingCnt ) const; + + // rAttr.Number not empty if NatNum attributes are to be stored + void GetNatNumXml( + css::i18n::NativeNumberXmlAttributes2& rAttr, + sal_uInt16 nNumFor ) const; + + /** Switches to the first non-"gregorian" calendar, but only if the current + calendar is "gregorian"; original calendar name and date/time returned, + but only if calendar switched and rOrgCalendar was empty. */ + void SwitchToOtherCalendar( OUString& rOrgCalendar, double& fOrgDateTime ) const; + + /** Switches to the "gregorian" calendar, but only if the current calendar + is non-"gregorian" and rOrgCalendar is not empty. Thus a preceding + ImpSwitchToOtherCalendar() call should have been placed prior to + calling this method. */ + void SwitchToGregorianCalendar( const OUString& rOrgCalendar, double fOrgDateTime ) const; + +#ifdef THE_FUTURE + /** Switches to the first specified calendar, if any, in subformat nNumFor + (0..3). Original calendar name and date/time returned, but only if + calendar switched and rOrgCalendar was empty. + + @return + if a calendar was specified and switched to, + else. + */ + bool SwitchToSpecifiedCalendar( OUString& rOrgCalendar, double& fOrgDateTime, + sal_uInt16 nNumFor ) const + { + if ( nNumFor < 4 ) + return ImpSwitchToSpecifiedCalendar( rOrgCalendar, + fOrgDateTime, NumFor[nNumFor] ); + return false; + } +#endif + + /// Whether it's a (YY)YY-M(M)-D(D) format. + bool IsIso8601( sal_uInt16 nNumFor ) const + { + if ( nNumFor < 4 ) + return ImpIsIso8601( NumFor[nNumFor]); + return false; + } + +private: + ImpSvNumFor NumFor[4]; // Array for the 4 subformats + OUString sFormatstring; // The format code string + OUString sComment; // Comment, since number formatter version 6 + double fLimit1; // Value for first condition + double fLimit2; // Value for second condition + ImpSvNumberformatScan& rScan; // Format code scanner + LocaleType maLocale; // Language/country of the format, numeral shape and calendar type from Excel. + SvNumberformatLimitOps eOp1; // Operator for first condition + SvNumberformatLimitOps eOp2; // Operator for second condition + SvNumFormatType eType; // Type of format + bool bAdditionalBuiltin; // If this is an additional built-in format defined by i18n + bool bStarFlag; // Take *n format as ESC n + bool bStandard; // If this is a default standard format + bool bIsUsed; // Flag as used for storing + + SVL_DLLPRIVATE sal_uInt16 ImpGetNumForStringElementCount( sal_uInt16 nNumFor ) const; + + SVL_DLLPRIVATE bool ImpIsOtherCalendar( const ImpSvNumFor& rNumFor ) const; + +#ifdef THE_FUTURE + SVL_DLLPRIVATE bool ImpSwitchToSpecifiedCalendar( OUString& rOrgCalendar, + double& fOrgDateTime, + const ImpSvNumFor& rNumFor ) const; +#endif + + /** Whether to use possessive genitive case month name, or partitive case + month name, instead of nominative name (noun). + + @param io_nState + 0: execute check
    + set to 1 if nominative case is returned,
    + set to 2 if genitive case is returned,
    + set to 3 if partitive case is returned
    + 1: don't execute check, return nominative case
    + 2: don't execute check, return genitive case
    + 3: don't execute check, return partitive case
    + + @param eCodeType + a NfKeywordIndex, must designate a month type code + + @returns one of css::i18n::CalendarDisplayCode values + according to eCodeType and the check executed (or passed). + */ + SVL_DLLPRIVATE static sal_Int32 ImpUseMonthCase( int & io_nState, const ImpSvNumFor& rNumFor, NfKeywordIndex eCodeType ); + + /// Whether it's a (YY)YY-M(M)-D(D) format. + SVL_DLLPRIVATE bool ImpIsIso8601( const ImpSvNumFor& rNumFor ) const; + + const CharClass& rChrCls() const; + const LocaleDataWrapper& rLoc() const; + CalendarWrapper& GetCal() const; + const SvNumberFormatter& GetFormatter() const; + + // divide in substrings and color conditions + SVL_DLLPRIVATE short ImpNextSymbol( OUStringBuffer& rString, + sal_Int32& nPos, + OUString& sSymbol ) const; + + // read string until ']' and strip blanks (after condition) + SVL_DLLPRIVATE static sal_Int32 ImpGetNumber( OUStringBuffer& rString, + sal_Int32& nPos, + OUString& sSymbol ); + + /** + * Parse the content of '[$-xxx] or '[$-xxxxxxxx]' and extract the locale + * type from it. Given the string, start parsing at position specified by + * nPos, and store the end position with nPos when the parsing is + * complete. The nPos should point to the '$' before the parsing, and to + * the closing bracket after the parsing. When the content is [$-xxx], + * the xxx part represents the language type (aka LCID) in hex numerals. + * When the content is [$-xxxxxxxx] the last 4 digits represent the LCID + * (again in hex), the next 2 digits represent the calendar type, and the + * 2 highest digits (if exists) is the numeral shape. + * + * @reference + * http://office.microsoft.com/en-us/excel-help/creating-international-number-formats-HA001034635.aspx + * + * @param rString input string + * @param nPos position (see above). + * + * @return struct containing numeral shape, calendar type, and LCID that + * specifies language type. See i18nlangtag/lang.h for a complete + * list of language types. These numbers also correspond with the + * numbers used by Microsoft Office. + */ + SVL_DLLPRIVATE static LocaleType ImpGetLocaleType( const OUString& rString, sal_Int32& nPos ); + + /** Obtain calendar and numerals from a LocaleType that was parsed from a + LCID with ImpGetLocaleType(). + + Inserts a NatNum modifier to rString at nPos if needed as determined + from the numeral code. + + @ATTENTION: may modify maLocale to make it follow + aTmpLocale, in which case also nLang is adapted. + + @returns a string with the calendar if one was determined from the + calendar code, else an empty string. The calendar string needs to be + inserted at a proper position to rString after all bracketed prefixes. + */ + SVL_DLLPRIVATE OUString ImpObtainCalendarAndNumerals( OUStringBuffer & rString, + sal_Int32 nPos, + LanguageType & nLang, + const LocaleType & aTmpLocale ); + + // standard number output + SVL_DLLPRIVATE void ImpGetOutputStandard( double& fNumber, OUString& OutString ) const; + SVL_DLLPRIVATE void ImpGetOutputStandard( double& fNumber, OUStringBuffer& OutString ) const; + SVL_DLLPRIVATE void ImpGetOutputStdToPrecision( double& rNumber, OUString& rOutString, sal_uInt16 nPrecision ) const; + // numbers in input line + SVL_DLLPRIVATE void ImpGetOutputInputLine( double fNumber, OUString& OutString ) const; + + // check subcondition + // OP undefined => -1 + // else 0 or 1 + SVL_DLLPRIVATE static short ImpCheckCondition(double fNumber, + double fLimit, + SvNumberformatLimitOps eOp); + + // Helper function for number strings + // append string symbols, insert leading 0 or ' ', or ... + SVL_DLLPRIVATE bool ImpNumberFill( OUStringBuffer& sStr, + double& rNumber, + sal_Int32& k, + sal_uInt16& j, + sal_uInt16 nIx, + short eSymbolType, + bool bInsertRightBlank = false ); + + // Helper function to fill in the integer part and the group (AKA thousand) separators + SVL_DLLPRIVATE bool ImpNumberFillWithThousands( OUStringBuffer& sStr, + double& rNumber, + sal_Int32 k, + sal_uInt16 j, + sal_uInt16 nIx, + sal_Int32 nDigCnt, + bool bAddDecSep = true ); + + // Helper function to fill in the group (AKA thousand) separators + // or to skip additional digits + SVL_DLLPRIVATE void ImpDigitFill( OUStringBuffer& sStr, + sal_Int32 nStart, + sal_Int32& k, + sal_uInt16 nIx, + sal_Int32 & nDigitCount, + utl::DigitGroupingIterator & ); + + SVL_DLLPRIVATE bool ImpDecimalFill( OUStringBuffer& sStr, + double& rNumber, + sal_Int32 nDecPos, + sal_uInt16 j, + sal_uInt16 nIx, + bool bInteger ); + + /** Calculate each element of fraction: + * integer part, numerator part, denominator part + * @param fNumber value to be represented as fraction. Will contain absolute fractional part + * @param nIx subformat number 0..3 + * @param fIntPart integral part of fraction + * @param nFrac numerator of fraction + * @param nDic denominator of fraction + */ + SVL_DLLPRIVATE void ImpGetFractionElements( double& fNumber, + sal_uInt16 nIx, + double& fIntPart, + sal_Int64& nFrac, + sal_Int64& nDiv ) const; + SVL_DLLPRIVATE bool ImpGetFractionOutput(double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString); + SVL_DLLPRIVATE bool ImpGetScientificOutput(double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString); + + SVL_DLLPRIVATE bool ImpGetDateOutput( double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString ); + SVL_DLLPRIVATE bool ImpGetTimeOutput( double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString ); + SVL_DLLPRIVATE bool ImpGetDateTimeOutput( double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString ); + + // Switches to the "gregorian" calendar if the current calendar is + // non-"gregorian" and the era is a "Dummy" era of a calendar which doesn't + // know a "before" era (like zh_TW ROC or ja_JP Gengou). If switched and + // rOrgCalendar was "gregorian" the string is emptied. If rOrgCalendar was + // empty the previous calendar name and date/time are returned. + SVL_DLLPRIVATE bool ImpFallBackToGregorianCalendar( OUString& rOrgCalendar, double& fOrgDateTime ); + + // Append a "G" short era string of the given calendar. In the case of a + // Gengou calendar this is a one character abbreviation, for other + // calendars the XExtendedCalendar::getDisplayString() method is called. + SVL_DLLPRIVATE static void ImpAppendEraG( OUStringBuffer& OutStringBuffer, const CalendarWrapper& rCal, + sal_Int16 nNatNum ); + + SVL_DLLPRIVATE bool ImpGetLogicalOutput( double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString ); + + SVL_DLLPRIVATE bool ImpGetNumberOutput( double fNumber, + sal_uInt16 nIx, + OUStringBuffer& OutString ); + + SVL_DLLPRIVATE void ImpCopyNumberformat( const SvNumberformat& rFormat ); + + // normal digits or other digits, depending on ImpSvNumFor.aNatNum, + // [NatNum1], [NatNum2], ... + SVL_DLLPRIVATE OUString ImpGetNatNumString( const SvNumberNatNum& rNum, sal_Int64 nVal, + sal_uInt16 nMinDigits ) const; + + OUString ImpIntToString( sal_uInt16 nIx, sal_Int64 nVal, sal_uInt16 nMinDigits = 0 ) const + { + const SvNumberNatNum& rNum = NumFor[nIx].GetNatNum(); + if ( nMinDigits || rNum.IsComplete() ) + { + return ImpGetNatNumString( rNum, nVal, nMinDigits ); + } + return OUString::number(nVal); + } + + // Obtain the string of the fraction of second, without leading "0.", + // rounded to nFractionDecimals (or nFractionDecimals+1 if + // bAddOneRoundingDecimal==true but then truncated at nFractionDecimals, + // for use with the result of tools::Time::GetClock()) with the length of + // nFractionDecimals, unless nMinimumInputLineDecimals>0 is given for input + // line string where extra trailing "0" are discarded. + SVL_DLLPRIVATE sal_uInt16 ImpGetFractionOfSecondString( OUStringBuffer& rBuf, double fFractionOfSecond, + int nFractionDecimals, bool bAddOneRoundingDecimal, sal_uInt16 nIx, sal_uInt16 nMinimumInputLineDecimals ); + + // transliterate according to NativeNumber + SVL_DLLPRIVATE OUString impTransliterateImpl(const OUString& rStr, const SvNumberNatNum& rNum) const; + SVL_DLLPRIVATE void impTransliterateImpl(OUStringBuffer& rStr, const SvNumberNatNum& rNum) const; + SVL_DLLPRIVATE OUString impTransliterateImpl(const OUString& rStr, const SvNumberNatNum& rNum, sal_uInt16 nDateKey) const; + + OUString impTransliterate(const OUString& rStr, const SvNumberNatNum& rNum) const + { + return rNum.IsComplete() ? impTransliterateImpl(rStr, rNum) : rStr; + } + + SVL_DLLPRIVATE void impTransliterate(OUStringBuffer& rStr, const SvNumberNatNum& rNum) const + { + if(rNum.IsComplete()) + { + impTransliterateImpl(rStr, rNum); + } + } + + OUString impTransliterate(const OUString& rStr, const SvNumberNatNum& rNum, sal_uInt16 nDateKey) const + { + return rNum.IsComplete() ? impTransliterateImpl(rStr, rNum, nDateKey) : rStr; + } + +}; + +#endif // INCLUDED_SVL_ZFORMAT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/DocumentToGraphicRenderer.hxx b/include/svtools/DocumentToGraphicRenderer.hxx new file mode 100644 index 000000000..a5dc8e115 --- /dev/null +++ b/include/svtools/DocumentToGraphicRenderer.hxx @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#pragma once + +#include + +#include + +#include + +namespace com :: sun :: star :: awt { class XToolkit; } +namespace com :: sun :: star :: frame { class XModel; } +namespace com :: sun :: star :: lang { class XComponent; } +namespace com :: sun :: star :: view { class XRenderable; } + +namespace com::sun::star { + namespace drawing { + class XShapes; + class XShape; + } + namespace frame { + class XController; + } +} + +class SVT_DLLPUBLIC DocumentToGraphicRenderer +{ + const css::uno::Reference& mxDocument; + + enum DocType { + WRITER, + CALC, + IMPRESS, + UNKNOWN + }; + + css::uno::Reference mxModel; + css::uno::Reference mxController; + css::uno::Reference mxRenderable; + css::uno::Reference mxToolkit; + css::uno::Any maSelection; + DocType meDocType; + std::vector maChapterNames; + + bool hasSelection() const; + + /** Always something even if hasSelection() is false (in which case the + selection is mxDocument). + */ + css::uno::Any getSelection() const; + + sal_Int32 getCurrentPageWriter(); + +public: + DocumentToGraphicRenderer(const css::uno::Reference& xDocument, bool bSelectionOnly); + ~DocumentToGraphicRenderer(); + + sal_Int32 getCurrentPage(); + sal_Int32 getPageCount(); + /** + * Get list of chapter names for a page, current page is set by + * renderToGraphic(). + */ + const std::vector& getChapterNames() const; + + Size getDocumentSizeInPixels( sal_Int32 nCurrentPage ); + + Size getDocumentSizeIn100mm(sal_Int32 nCurrentPage, Point* pDocumentPosition = nullptr, + Point* pCalcPagePosition = nullptr, Size *pCalcPageSize = nullptr); + + Graphic renderToGraphic( sal_Int32 nCurrentPage, Size aDocumentSizePixel, + Size aTargetSizePixel, Color aPageColor, bool bExtOutDevData); + + /** Determine whether rxController has a css::view::XSelectionSupplier at + which either a css::drawing::XShapes or css::drawing::XShape is + selected. XShapes has precedence over XShape. + + Call only if the SelectionOnly property was set. + */ + static bool isShapeSelected( + css::uno::Reference< css::drawing::XShapes > & rxShapes, + css::uno::Reference< css::drawing::XShape > & rxShape, + const css::uno::Reference< css::frame::XController > & rxController ); + + bool isWriter() const; + bool isCalc() const; + bool isImpress() const; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/HtmlWriter.hxx b/include/svtools/HtmlWriter.hxx new file mode 100644 index 000000000..21ccad0cd --- /dev/null +++ b/include/svtools/HtmlWriter.hxx @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#pragma once + +#include +#include +#include +#include + +class SvStream; + +class SVT_DLLPUBLIC HtmlWriter final +{ +private: + std::vector maElementStack; + + SvStream& mrStream; + + bool mbElementOpen; + bool mbCharactersWritten; + bool mbPrettyPrint; + /// XML namespace, in case of XHTML. + OString maNamespace; + +public: + HtmlWriter(SvStream& rStream, std::string_view rNamespace = std::string_view()); + ~HtmlWriter(); + + void prettyPrint(bool b); + + void start(const OString& aElement); + + bool end(const OString& aElement); + void end(); + + void flushStack(); + + static void writeAttribute(SvStream& rStream, std::string_view aAttribute, sal_Int32 aValue); + static void writeAttribute(SvStream& rStream, std::string_view aAttribute, + std::string_view aValue); + + void attribute(std::string_view aAttribute, const char* aValue); + void attribute(std::string_view aAttribute, sal_Int32 aValue); + void attribute(std::string_view aAttribute, std::string_view aValue); + void attribute(std::string_view aAttribute, std::u16string_view aValue); + // boolean attribute e.g. + void attribute(std::string_view aAttribute); + + void single(const OString& aContent); + void endAttribute(); + + /// Writes character data. + void characters(std::string_view rChars); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/PlaceEditDialog.hxx b/include/svtools/PlaceEditDialog.hxx new file mode 100644 index 000000000..931aad16f --- /dev/null +++ b/include/svtools/PlaceEditDialog.hxx @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include +#include +#include + +#include +#include + +class Place; +class DetailsContainer; + +class UNLESS_MERGELIBS(SVT_DLLPUBLIC) PlaceEditDialog final : public weld::GenericDialogController +{ +private: + std::shared_ptr m_xCurrentDetails; + /** Vector holding the details UI control for each server type. + + The elements in this vector need to match the order in the type listbox, e.g. + the m_aDetailsContainer[0] will be shown for the type corresponding to entry 0 + in the listbox. + */ + std::vector> m_aDetailsContainers; + + sal_Int32 m_nCurrentType; + + bool m_bLabelChanged; + bool m_bShowPassword; + +public: + std::unique_ptr m_xEDServerName; + std::unique_ptr m_xLBServerType; + std::unique_ptr m_xEDUsername; + std::unique_ptr m_xFTUsernameLabel; + std::unique_ptr m_xBTOk; + std::unique_ptr m_xBTCancel; + std::unique_ptr m_xBTDelete; + std::unique_ptr m_xBTRepoRefresh; + std::unique_ptr m_xCBPassword; + std::unique_ptr m_xEDPassword; + std::unique_ptr m_xFTPasswordLabel; + std::unique_ptr m_xTypeGrid; + + std::unique_ptr m_xRepositoryBox; + std::unique_ptr m_xFTRepository; + std::unique_ptr m_xLBRepository; + + std::unique_ptr m_xEDShare; + std::unique_ptr m_xFTShare; + + std::unique_ptr m_xDetailsGrid; + std::unique_ptr m_xHostBox; + std::unique_ptr m_xEDHost; + std::unique_ptr m_xFTHost; + std::unique_ptr m_xEDPort; + std::unique_ptr m_xFTPort; + std::unique_ptr m_xEDRoot; + std::unique_ptr m_xFTRoot; + + std::unique_ptr m_xCBDavs; + +public: + PlaceEditDialog(weld::Window* pParent); + PlaceEditDialog(weld::Window* pParent, const std::shared_ptr& rPlace); + virtual ~PlaceEditDialog() override; + + // Returns a place instance with given information + std::shared_ptr GetPlace(); + + OUString GetServerName() const { return m_xEDServerName->get_text(); } + OUString GetServerUrl(); + OUString GetPassword() const { return m_xEDPassword->get_text(); }; + OUString GetUser() const { return m_xEDUsername->get_text(); }; + bool IsRememberChecked() const { return m_xCBPassword->get_active(); } + + void ShowPasswordControl() { m_bShowPassword = true; } + +private: + void InitDetails(); + + DECL_DLLPRIVATE_LINK(OKHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(DelHdl, weld::Button&, void); + DECL_DLLPRIVATE_LINK(EditHdl, DetailsContainer*, void); + DECL_DLLPRIVATE_LINK(ModifyHdl, weld::Entry&, void); + void SelectType(bool bSkipSeparator); + DECL_DLLPRIVATE_LINK(SelectTypeHdl, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(EditLabelHdl, weld::Entry&, void); + DECL_DLLPRIVATE_LINK(EditUsernameHdl, weld::Entry&, void); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/acceleratorexecute.hxx b/include/svtools/acceleratorexecute.hxx new file mode 100644 index 000000000..5acf9bcd2 --- /dev/null +++ b/include/svtools/acceleratorexecute.hxx @@ -0,0 +1,206 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +#include +#include + +namespace com :: sun :: star :: frame { class XDispatchProvider; } +namespace com :: sun :: star :: frame { class XFrame; } +namespace com :: sun :: star :: frame { class XModel; } +namespace com :: sun :: star :: ui { class XAcceleratorConfiguration; } +namespace com :: sun :: star :: uno { class XComponentContext; } +namespace com :: sun :: star :: util { class XURLTransformer; } + + +namespace svt +{ + + +/** + @descr implements a helper, which can be used to + convert vcl key codes into awt key codes ... + and reverse. + + Further such key code can be triggered. + Doing so different accelerator + configurations are merged together; a suitable + command registered for the given key code is searched + and will be dispatched. + + @attention + + Because execution of an accelerator command can be dangerous + (in case it force an office shutdown for key "ALT+F4"!) + all internal dispatches are done asynchronous. + Means that the trigger call doesn't wait till the dispatch + is finished. You can call very often. All requests will be + queued internal and dispatched ASAP. + + Of course this queue will be stopped if the environment + will be destructed... + */ +class SVT_DLLPUBLIC AcceleratorExecute final +{ + // member + private: + std::mutex m_aLock; + + /** TODO document me */ + css::uno::Reference< css::uno::XComponentContext > m_xContext; + + /** TODO document me */ + css::uno::Reference< css::util::XURLTransformer > m_xURLParser; + + /** TODO document me */ + css::uno::Reference< css::frame::XDispatchProvider > m_xDispatcher; + + /** TODO document me */ + css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xGlobalCfg; + css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xModuleCfg; + css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xDocCfg; + // interface + public: + + + /** @short factory method to create new accelerator + helper instance. + + @descr Such helper instance must be initialized at first. + So it can know its environment (global/module or + document specific). + + Afterwards it can be used to execute incoming + accelerator requests. + + The "end of life" of such helper can be reached as follow: + + - delete the object + => If it stands currently in its execute method, they will + be finished. All further queued requests will be removed + and further not executed! + + - "let it stay alone" + => All currently queued events will be finished. The + helper kills itself afterwards. A shutdown of the + environment will be recognized ... The helper stop its + work immediately then! + */ + static std::unique_ptr createAcceleratorHelper(); + + + /** @short fight against inlining ... */ + ~AcceleratorExecute(); + + + /** @short init this instance. + + @descr It must be called as first method after creation. + And further it can be called more than once... + but at least it should be used one times only. + Otherwise nobody can say, which asynchronous + executions will be used inside the old and which one + will be used inside the new environment. + + @param rxContext + reference to a uno service manager. + + @param xEnv + if it points to a valid frame it will be used + to execute the dispatch there. Further the frame + is used to locate the right module configuration + and use it merged together with the document and + the global configuration. + + If this parameter is set to NULL, the global configuration + is used only. Further the global Desktop instance is + used for dispatch. + */ + void init(const css::uno::Reference< css::uno::XComponentContext >& rxContext, + const css::uno::Reference< css::frame::XFrame >& xEnv ); + + + /** @short trigger this accelerator. + + @descr The internal configurations are used to find + as suitable command for this key code. + This command will be queued and executed later + asynchronous. + + @param aKey + specify the accelerator for execute. + + @return [bool] + true if this key is configured and match to a command. + Attention: This state does not mean the success state + of the corresponding execute. Because it's done asynchronously! + */ + bool execute(const vcl::KeyCode& aKey); + bool execute(const css::awt::KeyEvent& aKey); + + /** search the command for the given key event. + * + * @param aKey The key event + * @return The command or an empty string if the key event could not be found. + */ + OUString findCommand(const css::awt::KeyEvent& aKey); + + /** TODO document me */ + static css::awt::KeyEvent st_VCLKey2AWTKey(const vcl::KeyCode& aKey); + static vcl::KeyCode st_AWTKey2VCLKey(const css::awt::KeyEvent& aKey); + + + /** TODO document me */ + static css::uno::Reference< css::ui::XAcceleratorConfiguration > st_openModuleConfig(const css::uno::Reference< css::uno::XComponentContext >& rxContext , + const css::uno::Reference< css::frame::XFrame >& xFrame); + + + /** TODO document me */ + static css::uno::Reference< css::ui::XAcceleratorConfiguration > st_openDocConfig(const css::uno::Reference< css::frame::XModel >& xModel); + + + // internal + private: + + + /** @short allow creation of instances of this class + by using our factory only! + */ + SVT_DLLPRIVATE AcceleratorExecute(); + + AcceleratorExecute(const AcceleratorExecute& rCopy) = delete; + void operator=(const AcceleratorExecute&) = delete; + + /** TODO document me */ + SVT_DLLPRIVATE OUString impl_ts_findCommand(const css::awt::KeyEvent& aKey); + + + /** TODO document me */ + SVT_DLLPRIVATE css::uno::Reference< css::util::XURLTransformer > impl_ts_getURLParser(); +}; + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/accessibilityoptions.hxx b/include/svtools/accessibilityoptions.hxx new file mode 100644 index 000000000..2733cfa0e --- /dev/null +++ b/include/svtools/accessibilityoptions.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include + +class SvtAccessibilityOptions_Impl; + +class SVT_DLLPUBLIC SvtAccessibilityOptions final : + public utl::detail::Options +{ +private: + static SvtAccessibilityOptions_Impl* sm_pSingleImplConfig; + static sal_Int32 sm_nAccessibilityRefCount; + +public: + SvtAccessibilityOptions(); + virtual ~SvtAccessibilityOptions() override; + + // get & set config entries + bool GetIsAllowAnimatedGraphics() const; + bool GetIsAllowAnimatedText() const; + bool GetIsAutomaticFontColor() const; + bool IsSelectionInReadonly() const; + + void SetVCLSettings(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/addresstemplate.hxx b/include/svtools/addresstemplate.hxx new file mode 100644 index 000000000..04ce8d9be --- /dev/null +++ b/include/svtools/addresstemplate.hxx @@ -0,0 +1,128 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace com :: sun :: star :: container { class XNameAccess; } +namespace com :: sun :: star :: sdbc { class XDataSource; } +namespace com :: sun :: star :: sdb { class XDatabaseContext; } +namespace com :: sun :: star :: uno { class XComponentContext; } +namespace com :: sun :: star :: util { struct AliasProgrammaticPair; } + +#define FIELD_PAIRS_VISIBLE 5 +#define FIELD_CONTROLS_VISIBLE 2 * FIELD_PAIRS_VISIBLE + +namespace svt +{ + // = AddressBookSourceDialog + struct AddressBookSourceDialogData; + class UNLESS_MERGELIBS(SVT_DLLPUBLIC) AddressBookSourceDialog final : public weld::GenericDialogController + { + public: + AddressBookSourceDialog(weld::Window* _pParent, + const css::uno::Reference< css::uno::XComponentContext >& _rxORB ); + + /** if you use this ctor, the dialog +

    • will not store it's data in the configuration (nor initially retrieve it from there)
    • +
    • will not allow to change the data source name
    • +
    • will not allow to change the table name
    • +
    • will not allow to call the data source administration dialog
    • +
    + + @param _rxORB + a service factory to use for various UNO related needs + @param _rxTransientDS + the data source to obtain connections from + @param _rDataSourceName + the to-be name of _rxTransientDS. This is only for displaying this + name to the user, since the dialog completely works on _rxTransientDS, + and doesn't allow to change this. + @param _rTable + the table name to display. It must refer to a valid table, relative to a connection + obtained from _rxTransientDS + */ + AddressBookSourceDialog(weld::Window* _pParent, + const css::uno::Reference< css::uno::XComponentContext >& _rxORB, + const css::uno::Reference< css::sdbc::XDataSource >& _rxTransientDS, + const OUString& _rDataSourceName, + const OUString& _rTable, + const css::uno::Sequence< css::util::AliasProgrammaticPair >& _rMapping + ); + + virtual ~AddressBookSourceDialog() override; + + // to be used if the object was constructed for editing a field mapping only + void getFieldMapping( + css::uno::Sequence< css::util::AliasProgrammaticPair >& _rMapping) const; + + private: + void implConstruct(); + + // implementations + void implScrollFields(sal_Int32 nPos, bool bAdjustFocus, bool bAdjustScrollbar); + static void implSelectField(weld::ComboBox* pBox, const OUString& rText); + + void resetTables(); + void resetFields(); + + // fill in the data sources listbox + void initializeDatasources(); + + // initialize the dialog from the configuration data + void loadConfiguration(); + + DECL_DLLPRIVATE_LINK(OnFieldScroll, weld::ScrolledWindow&, void); + DECL_DLLPRIVATE_LINK(OnFieldSelect, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(OnAdministrateDatasources, weld::Button&, void); + DECL_DLLPRIVATE_STATIC_LINK(AddressBookSourceDialog, OnComboGetFocus, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(OnComboLoseFocus, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(OnComboSelect, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(OnOkClicked, weld::Button&, void); + DECL_DLLPRIVATE_LINK(OnDelayedInitialize, void*, void); + + // string to display for "no selection" + const OUString m_sNoFieldSelection; + + /// the DatabaseContext for selecting data sources + css::uno::Reference< css::sdb::XDatabaseContext > + m_xDatabaseContext; + // the ORB for creating objects + css::uno::Reference< css::uno::XComponentContext > + m_xORB; + css::uno::Reference< css::container::XNameAccess > + m_xCurrentDatasourceTables; + + // Controls + std::unique_ptr m_xDatasource; + std::unique_ptr m_xAdministrateDatasources; + std::unique_ptr m_xTable; + std::unique_ptr m_xFieldScroller; + std::unique_ptr m_xOKButton; + std::unique_ptr m_xGrid; + + std::unique_ptr m_pImpl; + }; +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/apearcfg.hxx b/include/svtools/apearcfg.hxx new file mode 100644 index 000000000..900155856 --- /dev/null +++ b/include/svtools/apearcfg.hxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include + +class Application; +enum class MouseMiddleButtonAction; + +enum class SnapType { + ToButton = 0, + ToMiddle, + NONE +}; + +enum class DragMode { + FullWindow, + Frame, + SystemDep +}; + + +class SVT_DLLPUBLIC SvtTabAppearanceCfg final : public utl::ConfigItem +{ + DragMode nDragMode ; + SnapType nSnapMode ; + MouseMiddleButtonAction nMiddleMouse; + short nAAMinPixelHeight ; + bool bFontAntialiasing ; + + bool bMenuMouseFollow ; + + static bool bInitialized ; + + SVT_DLLPRIVATE static const css::uno::Sequence& GetPropertyNames(); + virtual void ImplCommit() override; + +public: + SvtTabAppearanceCfg( ); + virtual ~SvtTabAppearanceCfg( ) override; + + virtual void Notify( const css::uno::Sequence< OUString >& _rPropertyNames) override; + + DragMode GetDragMode () const { return nDragMode; } + + SnapType GetSnapMode () const { return nSnapMode; } + void SetSnapMode ( SnapType nSet ); + + MouseMiddleButtonAction GetMiddleMouseButton () const { return nMiddleMouse; } + void SetMiddleMouseButton ( MouseMiddleButtonAction nSet ); + + void SetApplicationDefaults ( Application* pApp ); + + bool IsMenuMouseFollow() const{return bMenuMouseFollow;} + + void SetFontAntiAliasing( bool bSet ) { bFontAntialiasing = bSet; SetModified(); } + bool IsFontAntiAliasing() const { return bFontAntialiasing; } + + sal_uInt16 GetFontAntialiasingMinPixelHeight( ) const { return nAAMinPixelHeight; } + void SetFontAntialiasingMinPixelHeight( sal_uInt16 _nMinHeight ) { nAAMinPixelHeight = _nMinHeight; SetModified(); } + + static bool IsInitialized() { return bInitialized; } + static void SetInitialized() { bInitialized = true; } +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/asynclink.hxx b/include/svtools/asynclink.hxx new file mode 100644 index 000000000..ae5139e32 --- /dev/null +++ b/include/svtools/asynclink.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +class Timer; +struct ImplSVEvent; + +namespace svtools { + +class UNLESS_MERGELIBS(SVT_DLLPUBLIC) AsynchronLink +{ + Link _aLink; + ImplSVEvent* _nEventId; + void* _pArg; + std::mutex _aMutex; + + DECL_DLLPRIVATE_LINK( HandleCall_PostUserEvent, void*, void ); + +public: + AsynchronLink( const Link& rLink ) + : _aLink( rLink ) + , _nEventId( nullptr ) + , _pArg( nullptr ) + {} + AsynchronLink() + : _nEventId( nullptr ) + , _pArg( nullptr ) + {} + ~AsynchronLink(); + + void operator=( const Link& rLink ) { _aLink = rLink; } + void Call( void* pObj, bool bAllowDoubles = false ); + void ClearPendingCall( ); +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/bindablecontrolhelper.hxx b/include/svtools/bindablecontrolhelper.hxx new file mode 100644 index 000000000..8ec4762d2 --- /dev/null +++ b/include/svtools/bindablecontrolhelper.hxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + +namespace com :: sun :: star :: frame { class XModel; } +namespace com :: sun :: star :: uno { class XInterface; } + +namespace svt +{ + + + //= GraphicAccess + + /** helper class for obtaining streams (which also can be used with the ImageProducer) + from a resource + */ + namespace BindableControlHelper + { + SVT_DLLPUBLIC void ApplyListSourceAndBindableData( const css::uno::Reference< css::frame::XModel >& xModel, const css::uno::Reference< css::uno::XInterface >& rObj, const OUString& rsCtrlSource, const OUString& rsRowSource, sal_uInt16 nRefTab = 0 ); + } + + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/borderhelper.hxx b/include/svtools/borderhelper.hxx new file mode 100644 index 000000000..c7169d767 --- /dev/null +++ b/include/svtools/borderhelper.hxx @@ -0,0 +1,47 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +class OutputDevice; +class Point; + +enum class SvxBorderLineStyle : sal_Int16; + +namespace svtools { + +SVT_DLLPUBLIC std::vector GetLineDashing( SvxBorderLineStyle nDashing, double fScale ); + +SVT_DLLPUBLIC basegfx::B2DPolyPolygon ApplyLineDashing( + const basegfx::B2DPolygon& rPolygon, SvxBorderLineStyle nDashing, double fScale ); + +SVT_DLLPUBLIC void DrawLine( OutputDevice& rDev, const basegfx::B2DPoint& rBeg, + const basegfx::B2DPoint& rEnd, sal_uInt32 nWidth, SvxBorderLineStyle nDashing ); + +SVT_DLLPUBLIC void DrawLine( OutputDevice& rDev, const Point& rBeg, + const Point& rEnd, sal_uInt32 nWidth, SvxBorderLineStyle nDashing ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/borderline.hxx b/include/svtools/borderline.hxx new file mode 100644 index 000000000..36780bddf --- /dev/null +++ b/include/svtools/borderline.hxx @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +/** + Class computing border widths shared between Line style listbox and the + SvxBorderLine implementation. + + This class doesn't know anything about units: it all depends on the different + values set. A border is composed of 2 lines separated by a gap. The computed + widths are the ones of each line and the gap and they can either be fix or vary. + + The #m_nflags member will define which widths will vary (value 0 means that all + widths are fixed). The available flags are: + - CHANGE_LINE1 + - CHANGE_LINE2 + - CHANGE_DIST + + For each line, the rate member is used as a multiplication factor is the width + isn't fixed. Otherwise it is the width in the unit expected by the client code. + */ +enum class BorderWidthImplFlags +{ + FIXED = 0, + CHANGE_LINE1 = 1, + CHANGE_LINE2 = 2, + CHANGE_DIST = 4, +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} +class SVT_DLLPUBLIC BorderWidthImpl +{ + BorderWidthImplFlags m_nFlags; + double m_nRate1; + double m_nRate2; + double m_nRateGap; + +public: + + BorderWidthImpl( BorderWidthImplFlags nFlags = BorderWidthImplFlags::CHANGE_LINE1, double nRate1 = 0.0, + double nRate2 = 0.0, double nRateGap = 0.0 ); + + bool operator== ( const BorderWidthImpl& r ) const; + + tools::Long GetLine1 ( tools::Long nWidth ) const; + tools::Long GetLine2( tools::Long nWidth ) const; + tools::Long GetGap( tools::Long nWidth ) const; + + tools::Long GuessWidth( tools::Long nLine1, tools::Long nLine2, tools::Long nGap ); + + bool IsEmpty( ) const { return (0 == m_nRate1) && (0 == m_nRate2); } + bool IsDouble( ) const { return (0 != m_nRate1) && (0 != m_nRate2); } +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/brwbox.hxx b/include/svtools/brwbox.hxx new file mode 100644 index 000000000..6f65c6b30 --- /dev/null +++ b/include/svtools/brwbox.hxx @@ -0,0 +1,849 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +class BrowserColumn; +class BrowserHeader; +class ScrollBar; +class MeasureStatusBar; + +namespace svt { + class BrowseBoxImpl; +} + +namespace utl { + class AccessibleStateSetHelper; +} + +namespace vcl { + class IAccessibleFactory; +} + +#define BROWSER_INVALIDID SAL_MAX_UINT16 +constexpr sal_Int32 BROWSER_ENDOFSELECTION = SFX_ENDOFSELECTION; + +enum class BrowserMode +{ + NONE = 0x000000, + COLUMNSELECTION = 0x000001, + MULTISELECTION = 0x000002, + KEEPHIGHLIGHT = 0x000008, + HLINES = 0x000010, + VLINES = 0x000020, + + HIDESELECT = 0x000100, + HIDECURSOR = 0x000200, + + NO_HSCROLL = 0x000400, + + AUTO_VSCROLL = 0x001000, + AUTO_HSCROLL = 0x002000, + + TRACKING_TIPS = 0x004000, + + NO_VSCROLL = 0x008000, + + HEADERBAR_NEW = 0x040000, + AUTOSIZE_LASTCOL = 0x080000, + + CURSOR_WO_FOCUS = 0x200000, + // Allows a cursor which is shown even if the control does not have the focus. This does not affect other + // situations which require to temporarily hide the cursor (such as scrolling). + +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +#define BROWSER_NONE 0 +#define BROWSER_SELECT 720 +#define BROWSER_ENHANCESELECTION 722 +#define BROWSER_SELECTDOWN 724 +#define BROWSER_SELECTUP 725 +#define BROWSER_CURSORDOWN 731 +#define BROWSER_CURSORUP 732 +#define BROWSER_CURSORLEFT 733 +#define BROWSER_CURSORRIGHT 734 +#define BROWSER_CURSORPAGEDOWN 735 +#define BROWSER_CURSORPAGEUP 736 +#define BROWSER_CURSORENDOFFILE 741 +#define BROWSER_CURSORTOPOFFILE 742 +#define BROWSER_CURSORENDOFSCREEN 743 +#define BROWSER_CURSORTOPOFSCREEN 744 +#define BROWSER_CURSORHOME 745 +#define BROWSER_CURSOREND 746 +#define BROWSER_SCROLLDOWN 751 +#define BROWSER_SCROLLUP 752 +#define BROWSER_SELECTHOME 753 +#define BROWSER_SELECTEND 754 +#define BROWSER_SELECTCOLUMN 755 +#define BROWSER_MOVECOLUMNLEFT 756 +#define BROWSER_MOVECOLUMNRIGHT 757 + + +class BrowseEvent +{ + VclPtr pWin; + tools::Rectangle aRect; + sal_Int32 nRow; + sal_uInt16 nCol; + sal_uInt16 nColId; + +public: + BrowseEvent( vcl::Window* pWindow, + sal_Int32 nAbsRow, + sal_uInt16 nColumn, sal_uInt16 nColumnId, + const tools::Rectangle& rRect ); + + vcl::Window* GetWindow() const { return pWin; } + sal_Int32 GetRow() const { return nRow; } + sal_uInt16 GetColumn() const { return nCol; } + sal_uInt16 GetColumnId() const { return nColId; } + const tools::Rectangle& GetRect() const { return aRect; } +}; + +class BrowseBox; +class ScrollBarBox; +class BrowserMouseEvent; + +class BrowserDataWin final + :public Control + ,public DragSourceHelper + ,public DropTargetHelper +{ +public: + VclPtr pHeaderBar; // only for BrowserMode::HEADERBAR_NEW + VclPtr pCornerWin; // Window in the corner btw the ScrollBars + bool bInDtor; + AutoTimer aMouseTimer; // recalls MouseMove on dragging out + MouseEvent aRepeatEvt; // a MouseEvent to repeat + Point aLastMousePos; // prevents pseudo-MouseMoves + + OUString aRealRowCount; // to show in VScrollBar + + std::vector aInvalidRegion; // invalidated Rectangles during !UpdateMode + bool bInPaint; // TRUE while in Paint + bool bInCommand; // TRUE while in Command + bool bNoHScroll; // no horizontal scrollbar + bool bNoVScroll; // no vertical scrollbar + bool bAutoHScroll; // autohide horizontaler Scrollbar + bool bAutoVScroll; // autohide horizontaler Scrollbar + bool bUpdateMode; // not SV-UpdateMode because of Invalidate() + bool bAutoSizeLastCol; // last column always fills up window + bool bResizeOnPaint; // outstanding resize-event + bool bUpdateOnUnlock; // Update() while locked + bool bInUpdateScrollbars; // prevents recursions + bool bHadRecursion; // a recursion occurred + bool bCallingDropCallback; // we're in a callback to AcceptDrop or ExecuteDrop currently + sal_uInt16 nUpdateLock; // lock count, don't call Control::Update()! + short nCursorHidden; // new counter for DoHide/ShowCursor + + tools::Long m_nDragRowDividerLimit; + tools::Long m_nDragRowDividerOffset; + +public: + explicit BrowserDataWin( BrowseBox* pParent ); + virtual ~BrowserDataWin() override; + virtual void dispose() override; + + virtual void DataChanged( const DataChangedEvent& rDCEvt ) override; + virtual void Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect) override; + virtual void RequestHelp( const HelpEvent& rHEvt ) override; + virtual void Command( const CommandEvent& rEvt ) override; + virtual void MouseButtonDown( const MouseEvent& rEvt ) override; + virtual void MouseMove( const MouseEvent& rEvt ) override; + DECL_LINK( RepeatedMouseMove, Timer *, void ); + + virtual void MouseButtonUp( const MouseEvent& rEvt ) override; + virtual void KeyInput( const KeyEvent& rEvt ) override; + virtual void Tracking( const TrackingEvent& rTEvt ) override; + + // DropTargetHelper overridables + virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ) override; + virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ) override; + + // DragSourceHelper overridables + virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel ) override; + + + BrowseEvent CreateBrowseEvent( const Point& rPosPixel ); + BrowseBox* GetParent() const; + const OUString& GetRealRowCount() const { return aRealRowCount; } + + void SetUpdateMode( bool bMode ); + bool GetUpdateMode() const { return bUpdateMode; } + void EnterUpdateLock() { ++nUpdateLock; } + void LeaveUpdateLock(); + void Update(); + void DoOutstandingInvalidations(); + void Invalidate( InvalidateFlags nFlags = InvalidateFlags::NONE ) override; + void Invalidate( const tools::Rectangle& rRect, InvalidateFlags nFlags = InvalidateFlags::NONE ) override; + using Control::Invalidate; + +private: + void StartRowDividerDrag( const Point& _rStartPos ); + bool ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent ) const; +}; + +class BrowserMouseEvent: public MouseEvent, public BrowseEvent +{ +public: + BrowserMouseEvent( BrowserDataWin* pWin, const MouseEvent& rEvt ); + BrowserMouseEvent( vcl::Window* pWin, const MouseEvent& rEvt, + sal_Int32 nAbsRow, sal_uInt16 nColumn, sal_uInt16 nColumnId, + const tools::Rectangle& rRect ); +}; + + +class BrowserAcceptDropEvent : public AcceptDropEvent, public BrowseEvent +{ +public: + BrowserAcceptDropEvent( BrowserDataWin* pWin, const AcceptDropEvent& rEvt ); +}; + + +class BrowserExecuteDropEvent : public ExecuteDropEvent, public BrowseEvent +{ +public: + BrowserExecuteDropEvent( BrowserDataWin* pWin, const ExecuteDropEvent& rEvt ); +}; + +// TODO +// The whole selection thingie in this class is somewhat... suspicious to me. +// some oddities: +// * method parameters named like members (and used in both semantics within the method!) +// * the multi selection flag is sometimes used as if it is for row selection, sometimes as if +// it's for column selection, too (and sometimes in an even stranger way :) +// * it is not really defined like all these hundreds selection related flags/methods work together +// and influence each other. I do not understand it very well, but this may be my fault :) +// * There is a GetColumnSelection, but it can't be used to determine the selected columns (at least +// not without a const_cast) +// +// We should clearly define this somewhere in the future. Or, even better, we should re-implement this +// whole class, which is planned for a long time :) +// +// sorry for the ranting. could not resist + +class SVT_DLLPUBLIC BrowseBox + :public Control + ,public DragSourceHelper + ,public DropTargetHelper + ,public vcl::IAccessibleTableProvider +{ + friend class BrowserDataWin; + friend class ::svt::BrowseBoxImpl; + +public: + static const sal_uInt16 HandleColumnId = 0; + +private: + VclPtr pDataWin; // window to display data rows + VclPtr pVScroll; // vertical scrollbar + VclPtr aHScroll; // horizontal scrollbar + VclPtr aStatusBarHeight; // statusbar, just to measure its height + + tools::Long m_nDataRowHeight; // height of a single data-row + sal_uInt16 nTitleLines; // number of lines in title row + sal_uLong nControlAreaWidth; // width of fixed area beneath hscroll + bool bColumnCursor; // single columns and fields selectable + bool bMultiSelection;// allow multiple selected rows + bool bKeepHighlight; // don't hide selection on LoseFocus + + bool bHLines; // draw lines between rows + bool bVLines; // draw lines between columns + bool bBootstrapped; // child windows resized etc. + sal_Int32 nTopRow; // no. of first visible row (0...) + sal_Int32 nCurRow; // no. of row with cursor + sal_Int32 nRowCount; // total number of rows in model + sal_uInt16 nFirstCol; // no. of first visible scrollable column + sal_uInt16 nCurColId; // column id of cursor + + bool bSelecting; + bool bRowDividerDrag; + bool bHit; + bool mbInteractiveRowHeight; + + tools::Long nResizeX; // mouse position at start of resizing + tools::Long nMinResizeX; // never drag more left + tools::Long nDragX; // last dragged column (MouseMove) + sal_uInt16 nResizeCol; // resize this column in MouseMove + bool bResizing; // mouse captured for column resizing + + bool bSelect; /// select or deselect + bool bSelectionIsVisible; // depending on focus + bool bScrolling; // hidden cursor while scrolling + bool bNotToggleSel; // set while in ToggleSelection() etc. + bool bHasFocus; // set/unset in Get/LoseFocus + bool bHideSelect; // hide selection (highlight) + TriState bHideCursor; // hide cursor (frame) + Range aSelRange; // for selection expansion + + ::std::vector< std::unique_ptr > mvCols; // array of column-descriptions + union + { + MultiSelection* pSel; // selected rows for multi-selection + sal_Int32 nSel; // selected row for single-selection + } uRow; + std::unique_ptr pColSel; // selected column-ids + + // fdo#83943, detect if making the cursor position visible is impossible to achieve + struct CursorMoveAttempt + { + sal_Int32 m_nCol; + sal_Int32 m_nRow; + bool m_bScrolledToReachCell; + CursorMoveAttempt(sal_Int32 nCol, sal_Int32 nRow, bool bScrolledToReachCell) + : m_nCol(nCol) + , m_nRow(nRow) + , m_bScrolledToReachCell(bScrolledToReachCell) + { + } + bool operator==(const CursorMoveAttempt& r) const + { + return m_nCol == r.m_nCol && + m_nRow == r.m_nRow && + m_bScrolledToReachCell == r.m_bScrolledToReachCell; + } + bool operator!=(const CursorMoveAttempt& r) const { return !(*this == r); } + }; + std::stack + m_aGotoStack; + + ::std::unique_ptr< ::svt::BrowseBoxImpl > m_pImpl; // impl structure of the BrowseBox object + + bool m_bFocusOnlyCursor; // hide cursor if we don't have the focus + Color m_aCursorColor; // special color for cursor, COL_TRANSPARENT for usual (VCL-painted) "inverted" cursor + BrowserMode m_nCurrentMode; // last argument of SetMode (redundant, as our other members represent the current settings, too) + +private: + SVT_DLLPRIVATE void ConstructImpl(BrowserMode nMode); + SVT_DLLPRIVATE void ExpandRowSelection( const BrowserMouseEvent& rEvt ); + SVT_DLLPRIVATE void ToggleSelection(); + + SVT_DLLPRIVATE void UpdateScrollbars(); + SVT_DLLPRIVATE void AutoSizeLastColumn(); + + SVT_DLLPRIVATE tools::Long ImpGetDataRowHeight() const; + SVT_DLLPRIVATE tools::Rectangle ImplFieldRectPixel( sal_Int32 nRow, sal_uInt16 nColId ) const; + SVT_DLLPRIVATE sal_uInt16 FrozenColCount() const; + + SVT_DLLPRIVATE void ColumnInserted( sal_uInt16 nPos ); + + DECL_DLLPRIVATE_LINK( ScrollHdl, ScrollBar*, void ); + DECL_DLLPRIVATE_LINK( StartDragHdl, HeaderBar*, void ); + + SVT_DLLPRIVATE tools::Long GetFrozenWidth() const; + + SVT_DLLPRIVATE tools::Long GetBarHeight() const; + + bool GoToRow(sal_Int32 nRow, bool bRowColMove, bool bDoNotModifySelection = false ); + + bool GoToColumnId( sal_uInt16 nColId, bool bMakeVisible, bool bRowColMove = false); + void SelectColumnPos( sal_uInt16 nCol, bool _bSelect, bool bMakeVisible); + + void ImplPaintData(OutputDevice& _rOut, const tools::Rectangle& _rRect, bool _bForeignDevice); + + bool PaintCursorIfHiddenOnce() const { return !m_bFocusOnlyCursor && !HasFocus(); } + + sal_uInt16 ToggleSelectedColumn(); + void SetToggledSelectedColumn(sal_uInt16 _nSelectedColumnId); + +protected: + /// retrieves the XAccessible implementation associated with the BrowseBox instance + ::vcl::IAccessibleFactory& getAccessibleFactory(); + +protected: + sal_uInt16 ColCount() const; + + // software plug for database access + // RowCount is counted automatically + // (with the help of RowInserted and RowRemoved), so overriding of + // the method is needless +public: + virtual sal_Int32 GetRowCount() const override; + +protected: + // for display in VScrollBar set it e.g. on "?" + void SetRealRowCount( const OUString &rRealRowCount ); + + // Return Value has to be sal_True always - SeekRow *has* to work! + // (else ASSERT) MI: who integrated that? It must not be like that! + + /** seeks for the given row position + @param nRow + nRow starts at 0 + */ + virtual bool SeekRow( sal_Int32 nRow ) = 0; + void DrawCursor(); + void PaintData(vcl::Window const & rWin, vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect); + virtual void PaintField(vcl::RenderContext& rDev, const tools::Rectangle& rRect, sal_uInt16 nColumnId) const = 0; + // Advice for the subclass: the visible scope of rows has changed. + // The subclass is able to announce changes of the model with the + // help of the methods RowInserted and RowRemoved. Because of the + // new status a paint is induced (SeekRow is called etc). + // + // parameters: nNewTopRow: number of the new TopRow (can get changed from + // VisibleRowsChanged by request of RowInserted and RowDeleted). + // nNumRows: number of visible rows (a partial visible row is counted too) + // + // Possible reason for changing the visible scope: + // - in front of the visible scope rows were inserted or removed, so the + // numbering of the visible scope has changed + // - Scrolling (and thereof resulting in another first visible row) + // - Resize the window + virtual void VisibleRowsChanged( sal_Int32 nNewTopRow, sal_uInt16 nNumRows); + + // number of visible rows in the window (incl. "truncated" rows) + sal_uInt16 GetVisibleRows() const; + sal_Int32 GetTopRow() const { return nTopRow; } + sal_uInt16 GetFirstVisibleColNumber() const { return nFirstCol; } + + // Focus-Rect enable / disable + void DoShowCursor(); + void DoHideCursor(); + short GetCursorHideCount() const; + + virtual VclPtr CreateHeaderBar( BrowseBox* pParent ); + + // HACK(virtual create is not called in Ctor) + void SetHeaderBar( BrowserHeader* ); + + tools::Long CalcReverseZoom(tools::Long nVal) const; + + const DataFlavorExVector& + GetDataFlavors() const; + + bool IsDropFormatSupported( SotClipboardFormatId nFormat ) const; // need this because the base class' IsDropFormatSupported is not const ... + + void DisposeAccessible(); + +protected: + // callbacks for the data window + virtual void ImplStartTracking(); + virtual void ImplEndTracking(); + +public: + BrowseBox( vcl::Window* pParent, WinBits nBits, + BrowserMode nMode = BrowserMode::NONE ); + virtual ~BrowseBox() override; + virtual void dispose() override; + + // override inherited handler + virtual void StateChanged( StateChangedType nStateChange ) override; + virtual void MouseButtonDown( const MouseEvent& rEvt ) override; + virtual void MouseMove( const MouseEvent& rEvt ) override; + virtual void MouseButtonUp( const MouseEvent& rEvt ) override; + virtual void KeyInput( const KeyEvent& rEvt ) override; + virtual void LoseFocus() override; + virtual void GetFocus() override; + virtual void Resize() override; + virtual void Paint( vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect ) override; + virtual void Draw( OutputDevice* pDev, const Point& rPos, SystemTextColorFlags nFlags ) override; + virtual void Command( const CommandEvent& rEvt ) override; + virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel ) override; + + virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ) override; // will forward everything got to the second AcceptDrop method + virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ) override; // will forward everything got to the second ExecuteDrop method + + virtual sal_Int8 AcceptDrop( const BrowserAcceptDropEvent& rEvt ); + virtual sal_Int8 ExecuteDrop( const BrowserExecuteDropEvent& rEvt ); + + // new handlers + virtual void MouseButtonDown( const BrowserMouseEvent& rEvt ); + virtual void MouseButtonUp( const BrowserMouseEvent& rEvt ); + void StartScroll(); + virtual void EndScroll(); + virtual void Select(); + virtual void DoubleClick( const BrowserMouseEvent& rEvt ); + virtual bool IsCursorMoveAllowed( sal_Int32 nNewRow, sal_uInt16 nNewColId ) const; + virtual void CursorMoved(); + virtual void ColumnMoved( sal_uInt16 nColId ); + virtual void ColumnResized( sal_uInt16 nColId ); + /// called when the row height has been changed interactively + virtual void RowHeightChanged(); + virtual tools::Long QueryMinimumRowHeight(); + + // Window-Control (pass to DataWindow) + void SetUpdateMode( bool bUpdate ); + bool GetUpdateMode() const; + + // map-mode and font control + void SetFont( const vcl::Font& rNewFont ); + const vcl::Font& GetFont() const; + void SetTitleFont( const vcl::Font& rNewFont ) + { Control::SetFont( rNewFont ); } + + // inserting, changing, removing and freezing of columns + void InsertHandleColumn( sal_uLong nWidth ); + void InsertDataColumn( sal_uInt16 nItemId, const OUString& rText, + tools::Long nSize, HeaderBarItemBits nBits = HeaderBarItemBits::STDSTYLE, + sal_uInt16 nPos = HEADERBAR_APPEND ); + void SetColumnTitle( sal_uInt16 nColumnId, const OUString &rTitle ); + void SetColumnWidth( sal_uInt16 nColumnId, sal_uLong nWidth ); + void SetColumnPos( sal_uInt16 nColumnId, sal_uInt16 nPos ); + void FreezeColumn( sal_uInt16 nColumnId ); + void RemoveColumn( sal_uInt16 nColumnId ); + void RemoveColumns(); + + // control of title and data row height + void SetDataRowHeight( tools::Long nPixel ); + tools::Long GetDataRowHeight() const; + void SetTitleLines( sal_uInt16 nLines ); + tools::Long GetTitleHeight() const; + + // access to dynamic values of cursor row + OUString GetColumnTitle( sal_uInt16 nColumnId ) const; + tools::Rectangle GetFieldRect( sal_uInt16 nColumnId ) const; + sal_uLong GetColumnWidth( sal_uInt16 nColumnId ) const; + sal_uInt16 GetColumnId( sal_uInt16 nPos ) const; + sal_uInt16 GetColumnPos( sal_uInt16 nColumnId ) const; + bool IsFrozen( sal_uInt16 nColumnId ) const; + + // movement of visible area + sal_Int32 ScrollColumns( sal_Int32 nColumns ); + sal_Int32 ScrollRows( sal_Int32 nRows ); + void MakeFieldVisible( sal_Int32 nRow, sal_uInt16 nColId ); + + // access and movement of cursor + sal_Int32 GetCurRow() const { return nCurRow; } + sal_uInt16 GetCurColumnId() const { return nCurColId; } + bool GoToRow( sal_Int32 nRow ); + bool GoToColumnId( sal_uInt16 nColId ); + bool GoToRowColumnId( sal_Int32 nRow, sal_uInt16 nColId ); + + // selections + virtual void SetNoSelection() override; + virtual void SelectAll() override; + virtual void SelectRow( sal_Int32 nRow, bool _bSelect = true, bool bExpand = true ) override; + void SelectColumnPos( sal_uInt16 nCol, bool _bSelect = true ) + { SelectColumnPos( nCol, _bSelect, true); } + void SelectColumnId( sal_uInt16 nColId ) + { SelectColumnPos( GetColumnPos(nColId), true, true); } + sal_Int32 GetSelectRowCount() const; + sal_uInt16 GetSelectColumnCount() const; + virtual bool IsRowSelected( sal_Int32 nRow ) const override; + bool IsColumnSelected( sal_uInt16 nColumnId ) const; + sal_Int32 FirstSelectedRow(); + sal_Int32 LastSelectedRow(); + sal_Int32 NextSelectedRow(); + const MultiSelection* GetColumnSelection() const { return pColSel.get(); } + const MultiSelection* GetSelection() const + { return bMultiSelection ? uRow.pSel : nullptr; } + + sal_Int32 FirstSelectedColumn( ) const; + + bool IsResizing() const { return bResizing; } + + // access to positions of fields, column and rows + BrowserDataWin& GetDataWindow() const; + tools::Rectangle GetRowRectPixel( sal_Int32 nRow ) const; + tools::Rectangle GetFieldRectPixel( sal_Int32 nRow, sal_uInt16 nColId, + bool bRelToBrowser = true) const; + bool IsFieldVisible( sal_Int32 nRow, sal_uInt16 nColId, + bool bComplete = false ) const; + sal_Int32 GetRowAtYPosPixel( tools::Long nY, + bool bRelToBrowser = true ) const; + sal_uInt16 GetColumnAtXPosPixel( tools::Long nX ) const; + + // invalidations + void Clear(); + void RowRemoved( sal_Int32 nRow, sal_Int32 nNumRows = 1, bool bDoPaint = true ); + void RowModified( sal_Int32 nRow, sal_uInt16 nColId = BROWSER_INVALIDID ); + void RowInserted( sal_Int32 nRow, sal_Int32 nNumRows = 1, bool bDoPaint = true, bool bKeepSelection = false ); + + // miscellaneous + bool ReserveControlArea(sal_uInt16 nWidth = USHRT_MAX); + tools::Rectangle GetControlArea() const; + virtual bool ProcessKey(const KeyEvent& rEvt); + virtual void ChildFocusIn(); + virtual void ChildFocusOut(); + void Dispatch( sal_uInt16 nId ); + void SetMode( BrowserMode nMode ); + BrowserMode GetMode( ) const { return m_nCurrentMode; } + + void SetCursorColor(const Color& _rCol); + + /** specifies that the user is allowed to interactively change the height of a row, + by simply dragging an arbitrary row separator. + + Note that this works only if there's a handle column, since only in this case, + there *is* something for the user to click onto + */ + void EnableInteractiveRowHeight() { mbInteractiveRowHeight = true; } + bool IsInteractiveRowHeightEnabled( ) const { return mbInteractiveRowHeight; } + + /// access to selected methods, to be granted to the BrowserColumn + struct BrowserColumnAccess { friend class BrowserColumn; private: BrowserColumnAccess() { } }; + /** public version of PaintField, with selected access rights for the BrowserColumn + */ + void DoPaintField( OutputDevice& rDev, const tools::Rectangle& rRect, sal_uInt16 nColumnId, BrowserColumnAccess ) const + { PaintField( rDev, rRect, nColumnId ); } + + /** suggests a default width for a column containing a given text + + The width is calculated so that the text fits completely, plus some margin. + */ + sal_uLong GetDefaultColumnWidth( const OUString& _rText ) const; + + /** GetCellText returns the text at the given position + @param _nRow + the number of the row + @param _nColId + the ID of the column + @return + the text out of the cell + */ + virtual OUString GetCellText(sal_Int32 _nRow, sal_uInt16 _nColId) const; + + /** @return + the current column count + */ + sal_uInt16 GetColumnCount() const override { return ColCount(); } + + /** commitBrowseBoxEvent commit the event at all listeners of the browsebox + @param nEventId + the event id + @param rNewValue + the new value + @param rOldValue + the old value + */ + void commitBrowseBoxEvent(sal_Int16 nEventId, + const css::uno::Any& rNewValue, + const css::uno::Any& rOldValue); + + /** commitTableEvent commit the event at all listeners of the table + @param nEventId + the event id + @param rNewValue + the new value + @param rOldValue + the old value + */ + void commitTableEvent(sal_Int16 nEventId, + const css::uno::Any& rNewValue, + const css::uno::Any& rOldValue); + + /** fires an AccessibleEvent relative to a header bar AccessibleContext + + @param nEventId + the event id + @param rNewValue + the new value + @param rOldValue + the old value + */ + void commitHeaderBarEvent(sal_Int16 nEventId, + const css::uno::Any& rNewValue, + const css::uno::Any& rOldValue, + bool _bColumnHeaderBar + ); + + /** returns the Rectangle for either the column header bar or the row header bar + @param _bIsColumnBar + when column header bar is used + @param _bOnScreen + when the rectangle should be calculated OnScreen + @return + the Rectangle + */ + virtual tools::Rectangle calcHeaderRect(bool _bIsColumnBar, bool _bOnScreen = true) override; + + /** calculates the Rectangle of the table + @param _bOnScreen + when the rectangle should be calculated OnScreen + @return + the Rectangle + */ + virtual tools::Rectangle calcTableRect(bool _bOnScreen = true) override; + + /** + @param _nRowId + the current row + @param _nColId + the column id + @param _bOnScreen + when the rectangle should be calculated OnScreen + @return + the Rectangle + */ + virtual tools::Rectangle GetFieldRectPixelAbs(sal_Int32 _nRowId, sal_uInt16 _nColId, bool _bIsHeader, bool _bOnScreen = true) override; + + /// return if and only if the accessible object for this instance has been created and is alive + bool isAccessibleAlive( ) const; + +public: + /** Creates and returns the accessible object of the whole BrowseBox. */ + virtual css::uno::Reference< + css::accessibility::XAccessible > CreateAccessible() override; + + // Children --------------------------------------------------------------- + + /** Creates the accessible object of a data table cell. + @param nRow The row index of the cell. + @param nColumnId The column pos of the cell. + @return The XAccessible interface of the specified cell. */ + virtual css::uno::Reference< + css::accessibility::XAccessible > + CreateAccessibleCell( sal_Int32 nRow, sal_uInt16 nColumnPos ) override; + + /** Creates the accessible object of a row header. + @param nRow The row index of the header. + @return The XAccessible interface of the specified row header. */ + virtual css::uno::Reference< + css::accessibility::XAccessible > + CreateAccessibleRowHeader( sal_Int32 nRow ) override; + + /** Creates the accessible object of a column header. + @param nColumnId The column ID of the header. + @return The XAccessible interface of the specified column header. */ + virtual css::uno::Reference< + css::accessibility::XAccessible > + CreateAccessibleColumnHeader( sal_uInt16 nColumnPos ) override; + + /** @return The count of additional controls of the control area. */ + virtual sal_Int32 GetAccessibleControlCount() const override; + + /** Creates the accessible object of an additional control. + @param nIndex The 0-based index of the control. + @return The XAccessible interface of the specified control. */ + virtual css::uno::Reference< + css::accessibility::XAccessible > + CreateAccessibleControl( sal_Int32 nIndex ) override; + + /** Converts a point relative to the data window origin to a cell address. + @param rnRow Out-parameter that takes the row index. + @param rnColumnId Out-parameter that takes the column ID. + @param rPoint The position in pixels relative to the data window. + @return , if the point could be converted to a valid address. */ + virtual bool ConvertPointToCellAddress( + sal_Int32& rnRow, sal_uInt16& rnColumnId, const Point& rPoint ) override; + + /** Converts a point relative to the row header bar origin to a row header + index. + @param rnRow Out-parameter that takes the row index. + @param rPoint The position in pixels relative to the header bar. + @return , if the point could be converted to a valid index. */ + virtual bool ConvertPointToRowHeader( sal_Int32& rnRow, const Point& rPoint ) override; + + /** Converts a point relative to the column header bar origin to a column + header index. + @param rnColumnId Out-parameter that takes the column ID. + @param rPoint The position in pixels relative to the header bar. + @return , if the point could be converted to a valid index. */ + virtual bool ConvertPointToColumnHeader( sal_uInt16& rnColumnPos, const Point& rPoint ) override; + + /** Converts a point relative to the BrowseBox origin to the index of an + existing control. + @param rnRow Out-parameter that takes the 0-based control index. + @param rPoint The position in pixels relative to the BrowseBox. + @return , if the point could be converted to a valid index. */ + virtual bool ConvertPointToControlIndex( sal_Int32& rnIndex, const Point& rPoint ) override; + + /** return the name of the specified object. + @param eObjType + The type to ask for + @param _nPosition + The position of a tablecell (index position), header bar column/row cell + @return + The name of the specified object. + */ + virtual OUString GetAccessibleObjectName( AccessibleBrowseBoxObjType eObjType,sal_Int32 _nPosition = -1) const override; + + /** return the description of the specified object. + @param eObjType + The type to ask for + @param _nPosition + The position of a tablecell (index position), header bar column/row cell + @return + The description of the specified object. + */ + virtual OUString GetAccessibleObjectDescription( AccessibleBrowseBoxObjType eObjType,sal_Int32 _nPosition = -1) const override; + + /** @return The header text of the specified row. */ + virtual OUString GetRowDescription( sal_Int32 nRow ) const override; + + /** @return The header text of the specified column. */ + virtual OUString GetColumnDescription( sal_uInt16 _nColumn ) const override; + + /** Fills the StateSet with all states (except DEFUNC and SHOWING, done by + the accessible object), depending on the specified object type. */ + virtual void FillAccessibleStateSet( + ::utl::AccessibleStateSetHelper& rStateSet, + AccessibleBrowseBoxObjType eObjType ) const override; + + /** Fills the StateSet with all states for one cell (except DEFUNC and SHOWING, done by + the accessible object). */ + virtual void FillAccessibleStateSetForCell( + ::utl::AccessibleStateSetHelper& _rStateSet, + sal_Int32 _nRow, sal_uInt16 _nColumn ) const override; + + /** Sets focus to current cell of the data table. */ + virtual void GrabTableFocus() override; + + // IAccessibleTableProvider + virtual sal_Int32 GetCurrRow() const override; + virtual sal_uInt16 GetCurrColumn() const override; + virtual bool HasRowHeader() const override; + virtual bool GoToCell( sal_Int32 _nRow, sal_uInt16 _nColumn ) override; + virtual void SelectColumn( sal_uInt16 _nColumn, bool _bSelect = true ) override; + virtual bool IsColumnSelected( sal_Int32 _nColumn ) const override; + virtual sal_Int32 GetSelectedRowCount() const override; + virtual sal_Int32 GetSelectedColumnCount() const override; + virtual void GetAllSelectedRows( css::uno::Sequence< sal_Int32 >& _rRows ) const override; + virtual void GetAllSelectedColumns( css::uno::Sequence< sal_Int32 >& _rColumns ) const override; + virtual bool IsCellVisible( sal_Int32 _nRow, sal_uInt16 _nColumn ) const override; + virtual OUString GetAccessibleCellText(sal_Int32 _nRow, sal_uInt16 _nColPos) const override; + virtual bool GetGlyphBoundRects( const Point& rOrigin, const OUString& rStr, int nIndex, int nLen, std::vector< tools::Rectangle >& rVector ) override; + virtual tools::Rectangle GetWindowExtentsRelative(const vcl::Window *pRelativeWindow) const override; + virtual void GrabFocus() override; + virtual css::uno::Reference< css::accessibility::XAccessible > GetAccessible() override; + virtual vcl::Window* GetAccessibleParentWindow() const override; + virtual vcl::Window* GetWindowInstance() override; + +private: + // the following declares some Window/OutputDevice methods private. This happened in the course + // of CWS warnings01, which pointed out nameclashs in those methods. If the build breaks in some + // upper module, you should investigate whether you really wanted to call base class methods, + // or the versions at this class. In the latter case, use the renamed versions above. + + // ToTop/ToBottom were never property implemented. If you currently call it, this is most probably wrong + // and not doing as intended + using Window::ToTop; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/brwhead.hxx b/include/svtools/brwhead.hxx new file mode 100644 index 000000000..6d753e0ee --- /dev/null +++ b/include/svtools/brwhead.hxx @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +class BrowseBox; + + +class SVT_DLLPUBLIC BrowserHeader: public HeaderBar +{ + VclPtr _pBrowseBox; + +public: + virtual ~BrowserHeader() override; + virtual void dispose() override; +protected: + virtual void Command( const CommandEvent& rCEvt ) override; + virtual void EndDrag() override; + +public: + BrowserHeader( BrowseBox* pParent, WinBits nWinBits = WB_STDHEADERBAR | WB_DRAG ); + +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/cliplistener.hxx b/include/svtools/cliplistener.hxx new file mode 100644 index 000000000..fb0452f67 --- /dev/null +++ b/include/svtools/cliplistener.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace vcl { class Window; } + +class TransferableDataHelper; + +class SVT_DLLPUBLIC TransferableClipboardListener final : public cppu::WeakImplHelper< + css::datatransfer::clipboard::XClipboardListener > +{ + Link aLink; + + void AddRemoveListener( vcl::Window* pWin, bool bAdd ); +public: + // Link is called with a TransferableDataHelper pointer + TransferableClipboardListener( const Link& rCallback ); + virtual ~TransferableClipboardListener() override; + + void AddListener( vcl::Window* pWin ) { AddRemoveListener(pWin, true); } + void RemoveListener( vcl::Window* pWin ) { AddRemoveListener(pWin, false); } + void ClearCallbackLink(); + + // XEventListener + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + // XClipboardListener + virtual void SAL_CALL changedContents( const css::datatransfer::clipboard::ClipboardEvent& event ) override; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/collatorres.hxx b/include/svtools/collatorres.hxx new file mode 100644 index 000000000..9da09b152 --- /dev/null +++ b/include/svtools/collatorres.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +class SVT_DLLPUBLIC CollatorResource +{ +private: + // wrapper for locale specific translations data of collator algorithm + class CollatorResourceData + { + friend class CollatorResource; + + private: + OUString m_aName; + OUString m_aTranslation; + + public: + CollatorResourceData(const OUString& rAlgorithm, const OUString& rTranslation) + : m_aName(rAlgorithm) + , m_aTranslation(rTranslation) + { + } + const OUString& GetAlgorithm() const { return m_aName; } + const OUString& GetTranslation() const { return m_aTranslation; } + }; + std::vector m_aData; + +public: + CollatorResource(); + const OUString& GetTranslation(const OUString& rAlgorithm); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/colorcfg.hxx b/include/svtools/colorcfg.hxx new file mode 100644 index 000000000..562d4a3e4 --- /dev/null +++ b/include/svtools/colorcfg.hxx @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include +#include +#include + + +namespace svtools{ +enum ColorConfigEntry +{ + DOCCOLOR , + DOCBOUNDARIES , + APPBACKGROUND , + OBJECTBOUNDARIES , + TABLEBOUNDARIES , + FONTCOLOR , + LINKS , + LINKSVISITED , + SPELL , + SMARTTAGS , + SHADOWCOLOR , + WRITERTEXTGRID , + WRITERFIELDSHADINGS , + WRITERIDXSHADINGS , + WRITERDIRECTCURSOR , + WRITERSCRIPTINDICATOR, + WRITERSECTIONBOUNDARIES, + WRITERHEADERFOOTERMARK, + WRITERPAGEBREAKS, + HTMLSGML , + HTMLCOMMENT , + HTMLKEYWORD , + HTMLUNKNOWN , + CALCGRID , + CALCPAGEBREAK , + CALCPAGEBREAKMANUAL, + CALCPAGEBREAKAUTOMATIC, + CALCHIDDENROWCOL , + CALCDETECTIVE , + CALCDETECTIVEERROR , + CALCREFERENCE , + CALCNOTESBACKGROUND , + CALCVALUE, + CALCFORMULA, + CALCTEXT, + CALCPROTECTEDBACKGROUND, + DRAWGRID , + BASICIDENTIFIER, + BASICCOMMENT , + BASICNUMBER , + BASICSTRING , + BASICOPERATOR , + BASICKEYWORD , + BASICERROR , + SQLIDENTIFIER, + SQLNUMBER, + SQLSTRING, + SQLOPERATOR, + SQLKEYWORD, + SQLPARAMETER, + SQLCOMMENT, + ColorConfigEntryCount +}; + +class ColorConfig_Impl; +struct ColorConfigValue +{ + + bool bIsVisible; //validity depends on the element type + ::Color nColor; + ColorConfigValue() : bIsVisible(false), nColor(0) {} + bool operator !=(const ColorConfigValue& rCmp) const + { return nColor != rCmp.nColor || bIsVisible != rCmp.bIsVisible;} +}; + +class SVT_DLLPUBLIC ColorConfig final : + public utl::detail::Options +{ + friend class ColorConfig_Impl; +private: + static ColorConfig_Impl* m_pImpl; +public: + ColorConfig(); + virtual ~ColorConfig() override; + + // get the configured value - if bSmart is set the default color setting is provided + // instead of the automatic color + ColorConfigValue GetColorValue(ColorConfigEntry eEntry, bool bSmart = true) const; + static Color GetDefaultColor(ColorConfigEntry eEntry); +}; + +class SVT_DLLPUBLIC EditableColorConfig +{ + std::unique_ptr m_pImpl; + bool m_bModified; +public: + EditableColorConfig(); + ~EditableColorConfig(); + + css::uno::Sequence< OUString > GetSchemeNames() const; + void DeleteScheme(const OUString& rScheme ); + void AddScheme(const OUString& rScheme ); + void LoadScheme(const OUString& rScheme ); + const OUString& GetCurrentSchemeName() const; + void SetCurrentSchemeName(const OUString& rScheme); + + const ColorConfigValue& GetColorValue(ColorConfigEntry eEntry) const; + void SetColorValue(ColorConfigEntry eEntry, const ColorConfigValue& rValue); + void SetModified(); + void ClearModified() {m_bModified = false;} + bool IsModified() const {return m_bModified;} + void Commit(); + + void DisableBroadcast(); + void EnableBroadcast(); +}; +}//namespace svtools + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/colrdlg.hxx b/include/svtools/colrdlg.hxx new file mode 100644 index 000000000..a8785ad8a --- /dev/null +++ b/include/svtools/colrdlg.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +#include + +namespace weld { class Window; } + +namespace svtools +{ + // Select is the default. + // These values must match the constants used in ColorPickerDialog in cui/source/dialogs/colorpicker.cxx + enum class ColorPickerMode { Select = 0, Modify = 2 }; +} + +class SVT_DLLPUBLIC SvColorDialog final +{ +public: + SvColorDialog(); + ~SvColorDialog(); + + void SetColor( const Color& rColor ); + const Color& GetColor() const { return maColor;} + + void SetMode( svtools::ColorPickerMode eMode ); + + short Execute(weld::Window* pParent); + void ExecuteAsync(weld::Window* pParent, const std::function& func); + +private: + Color maColor; + svtools::ColorPickerMode meMode; + ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XAsynchronousExecutableDialog > mxDialog; + std::function m_aResultFunc; + + DECL_DLLPRIVATE_LINK( DialogClosedHdl, css::ui::dialogs::DialogClosedEvent*, void ); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/ctrlbox.hxx b/include/svtools/ctrlbox.hxx new file mode 100644 index 000000000..180fb64bf --- /dev/null +++ b/include/svtools/ctrlbox.hxx @@ -0,0 +1,505 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace weld { class CustomWeld; } + +class BitmapEx; +class BorderWidthImpl; +class FontList; +class VclSimpleEvent; +class VirtualDevice; + +/** Utility class storing the border line width, style and colors. The widths + are defined in Twips. + */ +class ImpLineListData +{ +private: + BorderWidthImpl const m_aWidthImpl; + + Color ( * m_pColor1Fn )( Color ); + Color ( * m_pColor2Fn )( Color ); + Color ( * m_pColorDistFn )( Color, Color ); + + tools::Long m_nMinWidth; + SvxBorderLineStyle m_nStyle; + +public: + ImpLineListData( BorderWidthImpl aWidthImpl, + SvxBorderLineStyle nStyle, tools::Long nMinWidth, Color ( *pColor1Fn )( Color ), + Color ( *pColor2Fn )( Color ), Color ( *pColorDistFn )( Color, Color ) ) : + m_aWidthImpl( aWidthImpl ), + m_pColor1Fn( pColor1Fn ), + m_pColor2Fn( pColor2Fn ), + m_pColorDistFn( pColorDistFn ), + m_nMinWidth( nMinWidth ), + m_nStyle( nStyle ) + { + } + + /** Returns the computed width of the line 1 in twips. */ + tools::Long GetLine1ForWidth( tools::Long nWidth ) const { return m_aWidthImpl.GetLine1( nWidth ); } + + /** Returns the computed width of the line 2 in twips. */ + tools::Long GetLine2ForWidth( tools::Long nWidth ) const { return m_aWidthImpl.GetLine2( nWidth ); } + + /** Returns the computed width of the gap in twips. */ + tools::Long GetDistForWidth( tools::Long nWidth ) const { return m_aWidthImpl.GetGap( nWidth ); } + + Color GetColorLine1( const Color& rMain ) const + { + return ( *m_pColor1Fn )( rMain ); + } + + Color GetColorLine2( const Color& rMain ) const + { + return ( *m_pColor2Fn )( rMain ); + } + + Color GetColorDist( const Color& rMain, const Color& rDefault ) const + { + return ( *m_pColorDistFn )( rMain, rDefault ); + } + + /** Returns the minimum width in twips */ + tools::Long GetMinWidth( ) const { return m_nMinWidth;} + SvxBorderLineStyle GetStyle( ) const { return m_nStyle;} +}; + +enum class SvxBorderLineStyle : sal_Int16; + +typedef ::std::vector< FontMetric > ImplFontList; + +/************************************************************************* + +class LineListBox + +Description + +Allows selection of line styles and sizes. Note that before first insert, +units and window size need to be set. Supported units are typographic point +(pt) and millimeters (mm). For SourceUnit, pt, mm and twips are supported. +All scalar numbers in 1/100 of the corresponding unit. + +Line1 is the outer, Line2 the inner line, Distance is the distance between +these two lines. If Line2 == 0, only Line1 will be shown. Defaults for +source and target unit are FieldUnit::POINT. + +SetColor() sets the line color. + +Remarks + +Contrary to a simple ListBox, user-specific data are not supported. +If UpdateMode is disabled, no data should be read, no selections +should be set, and the return code shall be ignore, as in these are +not defined in this mode. Also the bit WinBit WB_SORT may not be set. + +-------------------------------------------------------------------------- + +class FontNameBox + +Description + +Allows selection of fonts. The ListBox will be filled using Fill parameter, +which is pointer to an FontList object. + +Calling EnableWYSIWYG() enables rendering the font name in the currently +selected font. + +See also + +FontList; FontStyleBox; FontSizeBox; FontNameMenu + +-------------------------------------------------------------------------- + +class FontStyleBox + +Description + +Allows select of FontStyle's. The parameter Fill points to a list +of available font styles for the font. + +Reproduced styles are always added - this could change in future, as +potentially not all applications [Draw,Equation,FontWork] can properly +handle synthetic fonts. On filling, the previous name will be retained +if possible. + +For DontKnow, the FontStyleBox should be filled with OUString(), +so it will contain a list with the default attributes. The currently +shown style probably needs to be reset by the application. + +See also + +FontList; FontNameBox; FontSizeBox; + +-------------------------------------------------------------------------- + +class FontSizeBox + +Description + +Allows selection of font sizes. The values are retrieved via GetValue() +and set via SetValue(). The Fill parameter fills the ListBox with the +available sizes for the passed font. + +All sizes are in 1/10 typographic point (pt). + +The passed FontList must be retained until the next fill call. + +Additionally it supports a relative mod, which allows entering +percentage values. This, eg., can be useful for template dialogs. +This mode can only be enabled, but not disabled again. + +For DontKnow the FontSizeBox should be filled FontMetric(), so it will +contain a list with the standard sizes. Th currently shown size +probably needs to be reset by the application. + +See also + +FontList; FontNameBox; FontStyleBox; FontSizeMenu + +*************************************************************************/ + +inline Color sameColor( Color rMain ) +{ + return rMain; +} + +inline Color sameDistColor( Color /*rMain*/, Color rDefault ) +{ + return rDefault; +} + +class ValueSet; + +class SVT_DLLPUBLIC SvtLineListBox +{ +public: + typedef Color (*ColorFunc)(Color); + typedef Color (*ColorDistFunc)(Color, Color); + + SvtLineListBox(std::unique_ptr pControl); + ~SvtLineListBox(); + + static OUString GetLineStyleName(SvxBorderLineStyle eStyle); + + /** Set the width in Twips */ + void SetWidth(tools::Long nWidth) + { + m_nWidth = nWidth; + UpdateEntries(); + UpdatePreview(); + } + + tools::Long GetWidth() const { return m_nWidth; } + + /** Insert a listbox entry with all widths in Twips. */ + void InsertEntry(const BorderWidthImpl& rWidthImpl, + SvxBorderLineStyle nStyle, tools::Long nMinWidth = 0, + ColorFunc pColor1Fn = &sameColor, + ColorFunc pColor2Fn = &sameColor, + ColorDistFunc pColorDistFn = &sameDistColor); + + void SelectEntry( SvxBorderLineStyle nStyle ); + SvxBorderLineStyle GetSelectEntryStyle() const; + + void SetSourceUnit( FieldUnit eNewUnit ) { eSourceUnit = eNewUnit; } + + void SetColor( const Color& rColor ) + { + aColor = rColor; + UpdateEntries(); + UpdatePreview(); + } + + const Color& GetColor() const { return aColor; } + + void SetSelectHdl(const Link& rLink) { maSelectHdl = rLink; } + + void set_sensitive(bool bSensitive) { m_xControl->set_sensitive(bSensitive); } + +private: + + SVT_DLLPRIVATE void ImpGetLine( tools::Long nLine1, tools::Long nLine2, tools::Long nDistance, + Color nColor1, Color nColor2, Color nColorDist, + SvxBorderLineStyle nStyle, BitmapEx& rBmp ); + + void UpdatePaintLineColor(); // returns sal_True if maPaintCol has changed + DECL_DLLPRIVATE_LINK(ValueSelectHdl, ValueSet*, void); + DECL_DLLPRIVATE_LINK(FocusHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(ToggleHdl, weld::Toggleable&, void); + DECL_DLLPRIVATE_LINK(NoneHdl, weld::Button&, void); + + void UpdateEntries(); + sal_Int32 GetStylePos(sal_Int32 nListPos) const; + + const Color& GetPaintColor() const + { + return maPaintCol; + } + Color GetColorLine1( sal_Int32 nPos ); + Color GetColorLine2( sal_Int32 nPos ); + Color GetColorDist( sal_Int32 nPos ); + + void UpdatePreview(); + + SvtLineListBox( const SvtLineListBox& ) = delete; + SvtLineListBox& operator =( const SvtLineListBox& ) = delete; + + std::unique_ptr m_xControl; + std::unique_ptr m_xBuilder; + std::unique_ptr m_xTopLevel; + std::unique_ptr m_xNoneButton; + std::unique_ptr m_xLineSet; + std::unique_ptr m_xLineSetWin; + + std::vector> m_vLineList; + tools::Long m_nWidth; + ScopedVclPtr aVirDev; + Color aColor; + Color maPaintCol; + FieldUnit eSourceUnit; + Link maSelectHdl; +}; + +class SVT_DLLPUBLIC SvtCalendarBox +{ +public: + SvtCalendarBox(std::unique_ptr pControl, bool bUseLabel = true); + ~SvtCalendarBox(); + + weld::MenuButton& get_button() { return *m_xControl; } + + void set_date(const Date& rDate); + Date get_date() const { return m_xCalendar->get_date(); } + + void set_label(const OUString& rLabel) { m_xControl->set_label(rLabel); } + OUString get_label() const { return m_xControl->get_label(); } + + void set_sensitive(bool bSensitive) { m_xControl->set_sensitive(bSensitive); } + bool get_sensitive() const { return m_xControl->get_sensitive(); } + void set_visible(bool bSensitive) { m_xControl->set_visible(bSensitive); } + void show() { set_visible(true); } + void grab_focus() { m_xControl->grab_focus(); } + + void connect_activated(const Link& rActivatedHdl) { m_aActivatedHdl = rActivatedHdl; } + void connect_selected(const Link& rSelectHdl) { m_aSelectHdl = rSelectHdl; } + + void connect_focus_in(const Link& rLink) { m_xControl->connect_focus_in(rLink); } + void connect_focus_out(const Link& rLink) { m_xControl->connect_focus_out(rLink); } +private: + DECL_DLLPRIVATE_LINK(SelectHdl, weld::Calendar&, void); + DECL_DLLPRIVATE_LINK(ActivateHdl, weld::Calendar&, void); + + bool m_bUseLabel; + + std::unique_ptr m_xControl; + std::unique_ptr m_xBuilder; + std::unique_ptr m_xTopLevel; + std::unique_ptr m_xCalendar; + + Link m_aActivatedHdl; + Link m_aSelectHdl; + + void set_label_from_date(); +}; + +class SVT_DLLPUBLIC FontNameBox +{ +private: + std::unique_ptr m_xComboBox; + std::unique_ptr mpFontList; + size_t mnPreviewProgress; + bool mbWYSIWYG; + OUString maFontMRUEntriesFile; + Idle maUpdateIdle; + + SVT_DLLPRIVATE void ImplDestroyFontList(); + + DECL_DLLPRIVATE_LINK(CustomRenderHdl, weld::ComboBox::render_args, void); + DECL_DLLPRIVATE_LINK(CustomGetSizeHdl, OutputDevice&, Size); + DECL_DLLPRIVATE_LINK(SettingsChangedHdl, VclSimpleEvent&, void); + DECL_DLLPRIVATE_LINK(UpdateHdl, Timer*, void); + + void LoadMRUEntries( const OUString& aFontMRUEntriesFile ); + void SaveMRUEntries( const OUString& aFontMRUEntriesFile ) const; + + OutputDevice& CachePreview(size_t nIndex, Point* pTopLeft); + +public: + FontNameBox(std::unique_ptr p); + ~FontNameBox(); + + void Fill( const FontList* pList ); + + void EnableWYSIWYG(bool bEnable); + bool IsWYSIWYGEnabled() const { return mbWYSIWYG; } + + void connect_changed(const Link& rLink) { m_xComboBox->connect_changed(rLink); } + void connect_focus_in(const Link& rLink) { m_xComboBox->connect_focus_in(rLink); } + void connect_focus_out(const Link& rLink) { m_xComboBox->connect_focus_out(rLink); } + void connect_key_press(const Link& rLink) { m_xComboBox->connect_key_press(rLink); } + int get_active() const { return m_xComboBox->get_active(); } + OUString get_active_text() const { return m_xComboBox->get_active_text(); } + void set_active_or_entry_text(const OUString& rText); + void set_active(int nPos) { m_xComboBox->set_active(nPos); } + int get_count() const { return m_xComboBox->get_count(); } + OUString get_text(int nIndex) const { return m_xComboBox->get_text(nIndex); } + void set_sensitive(bool bSensitive) { m_xComboBox->set_sensitive(bSensitive); } + void save_value() { m_xComboBox->save_value(); } + OUString const& get_saved_value() const { return m_xComboBox->get_saved_value(); } + void select_entry_region(int nStartPos, int nEndPos) { m_xComboBox->select_entry_region(nStartPos, nEndPos); } + bool get_entry_selection_bounds(int& rStartPos, int& rEndPos) { return m_xComboBox->get_entry_selection_bounds(rStartPos, rEndPos); } + void clear() { m_xComboBox->clear(); } + void grab_focus() { m_xComboBox->grab_focus(); } + bool has_focus() const { return m_xComboBox->has_focus(); } + void connect_entry_activate(const Link& rLink) { m_xComboBox->connect_entry_activate(rLink); } + void connect_get_property_tree(const Link& rLink) { m_xComboBox->connect_get_property_tree(rLink); } + void set_entry_width_chars(int nWidth) { m_xComboBox->set_entry_width_chars(nWidth); } + void set_size_request(int nWidth, int nHeight) { m_xComboBox->set_size_request(nWidth, nHeight); } + int get_max_mru_count() const { return m_xComboBox->get_max_mru_count(); } + void set_max_mru_count(int nCount) { m_xComboBox->set_max_mru_count(nCount); } + + // font size is in points, not pixels, e.g. see Window::[G]etPointFont + void set_entry_font(const vcl::Font& rFont) { m_xComboBox->set_entry_font(rFont); } + vcl::Font get_entry_font() { return m_xComboBox->get_entry_font(); } + + void set_tooltip_text(const OUString& rTip) { m_xComboBox->set_tooltip_text(rTip); } + +private: + void InitFontMRUEntriesFile(); + + FontNameBox( const FontNameBox& ) = delete; + FontNameBox& operator =( const FontNameBox& ) = delete; +}; + +class SVT_DLLPUBLIC FontStyleBox +{ + std::unique_ptr m_xComboBox; +public: + FontStyleBox(std::unique_ptr p); + + void Fill(std::u16string_view rName, const FontList* pList); + + void connect_changed(const Link& rLink) { m_xComboBox->connect_changed(rLink); } + OUString get_active_text() const { return m_xComboBox->get_active_text(); } + void set_active_text(const OUString& rText) { m_xComboBox->set_active_text(rText); } + void set_size_request(int nWidth, int nHeight) { m_xComboBox->set_size_request(nWidth, nHeight); } + + void append_text(const OUString& rStr) { m_xComboBox->append_text(rStr); } + void set_sensitive(bool bSensitive) { m_xComboBox->set_sensitive(bSensitive); } + void save_value() { m_xComboBox->save_value(); } + OUString const& get_saved_value() const { return m_xComboBox->get_saved_value(); } + int get_count() const { return m_xComboBox->get_count(); } + int find_text(const OUString& rStr) const { return m_xComboBox->find_text(rStr); } +private: + FontStyleBox(const FontStyleBox& ) = delete; + FontStyleBox& operator=(const FontStyleBox&) = delete; +}; + +class SVT_DLLPUBLIC FontSizeBox +{ + const FontList* pFontList; + int nSavedValue; + int nMin; + int nMax; + FieldUnit eUnit; + sal_uInt16 nDecimalDigits; + sal_uInt16 nRelMin; + sal_uInt16 nRelMax; + sal_uInt16 nRelStep; + short nPtRelMin; + short nPtRelMax; + short nPtRelStep; + bool bRelativeMode:1, + bRelative:1, + bPtRelative:1, + bStdSize:1; + Link m_aChangeHdl; + Link m_aFocusOutHdl; + std::unique_ptr m_xComboBox; + + sal_uInt16 GetDecimalDigits() const { return nDecimalDigits; } + void SetDecimalDigits(sal_uInt16 nDigits) { nDecimalDigits = nDigits; } + FieldUnit GetUnit() const { return eUnit; } + void SetUnit(FieldUnit _eUnit) { eUnit = _eUnit; } + void SetRange(int nNewMin, int nNewMax) { nMin = nNewMin; nMax = nNewMax; } + void SetValue(int nNewValue, FieldUnit eInUnit); + + void InsertValue(int i); + + OUString format_number(int nValue) const; + + DECL_DLLPRIVATE_LINK(ModifyHdl, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK(ReformatHdl, weld::Widget&, void); +public: + FontSizeBox(std::unique_ptr p); + + void Fill(const FontList* pList); + + void EnableRelativeMode(sal_uInt16 nMin, sal_uInt16 nMax, sal_uInt16 nStep = 5); + void EnablePtRelativeMode(short nMin, short nMax, short nStep = 10); + bool IsRelativeMode() const { return bRelativeMode; } + void SetRelative( bool bRelative ); + bool IsRelative() const { return bRelative; } + void SetPtRelative( bool bPtRel ) + { + bPtRelative = bPtRel; + SetRelative(true); + } + bool IsPtRelative() const { return bPtRelative; } + + void connect_changed(const Link& rLink) { m_aChangeHdl = rLink; } + void connect_focus_out(const Link& rLink) { m_aFocusOutHdl = rLink; } + void connect_key_press(const Link& rLink) { m_xComboBox->connect_key_press(rLink); } + OUString get_active_text() const { return m_xComboBox->get_active_text(); } + void set_active_or_entry_text(const OUString& rText); + void set_sensitive(bool bSensitive) { m_xComboBox->set_sensitive(bSensitive); } + void set_size_request(int nWidth, int nHeight) { m_xComboBox->set_size_request(nWidth, nHeight); } + + int get_active() const { return m_xComboBox->get_active(); } + int get_value() const; + void set_value(int nValue); + void save_value() { nSavedValue = get_value(); } + int get_saved_value() const { return nSavedValue; } + bool get_value_changed_from_saved() const { return get_value() != get_saved_value(); } + int get_count() const { return m_xComboBox->get_count(); } + OUString get_text(int i) const { return m_xComboBox->get_text(i); } + void grab_focus() { m_xComboBox->grab_focus(); } + bool has_focus() const { return m_xComboBox->has_focus(); } + void connect_entry_activate(const Link& rLink) { m_xComboBox->connect_entry_activate(rLink); } + void disable_entry_completion() { m_xComboBox->set_entry_completion(false, false); } + void connect_get_property_tree(const Link& rLink) { m_xComboBox->connect_get_property_tree(rLink); } + +private: + FontSizeBox(const FontSizeBox&) = delete; + FontSizeBox& operator=(const FontSizeBox&) = delete; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/ctrltool.hxx b/include/svtools/ctrltool.hxx new file mode 100644 index 000000000..d70a49177 --- /dev/null +++ b/include/svtools/ctrltool.hxx @@ -0,0 +1,213 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +class ImplFontListNameInfo; +class OutputDevice; + +/* + +Description +============ + +class FontList + +This class manages all fonts which can be display on one or two output devices. +Additionally, this class offers methods for generating the StyleName from +bold and italics or the missing attributes from a StyleName. +Furthermore, this class can handle synthetically reproduced fonts. +It also works with several standard controls and standard menus. + +Links: + +class FontNameBox, class FontStyleBox, class FontSizeBox, +class FontNameMenu, class FontSizeMenu + +-------------------------------------------------------------------------- + +FontList::FontList( OutputDevice* pDevice, OutputDevice* pDevice2 = NULL, + bool bAll = true ); + +Constructor of the FontList class. The relevant fonts will be queried from +the OutputDevice. The OutputDevice needs to exist as long as the FontList +class exists. Optionally, a second output device can be given in order to, +e.g., manage the fonts from both, a printer and a screen in a single FontList +and thus also give FontMenus the fonts if both OutputDevices. +The pDevice2 needs to exist as long as the FontList class exists. + +The OutputDevice given first should be the preferred one. This is usually +the printer. Because if two different device fonts (one for the printer and +one for the screen) exist, the ones from the "pDevice" are preferred. + +The third parameter governs whether only scalable or all fonts shall be queried. +With sal_True bitmap fonts will also be queried. +With sal_False vectorized and scalable fonts will be queried. + +-------------------------------------------------------------------------- + +String FontList::GetStyleName( const FontMetric& rFontMetric ) const; + +This method returns the StyleName of a FontMetric. +If no StyleName is set, a name will be generated from the set attributes. + +-------------------------------------------------------------------------- + +OUString FontList::GetFontMapText( const FontMetric& rFontMetric ) const; + +This method returns a Matchstring which indicates the problem that could +arise when using a font. This string should be displayed to the user. + +-------------------------------------------------------------------------- + +FontMetric FontList::Get( const String& rName, const String& rStyleName ) const; + +This method search a FontMetric for the given name and the given style name. +The Stylename can also be a synthetic one. +In that case the relevant FontMetric fields will be set. +If a StyleName is provided, a FontMetric structure without a Stylename can be +returned. To get a representation of the StyleName for displaying it to the user, +call GetStyleName() on this FontMetric structure. + +Links: + +FontList::GetStyleName() + +-------------------------------------------------------------------------- + +FontMetric FontList::Get( const String& rName, FontWeight eWeight, + FontItalic eItalic ) const; + +This method search a FontMetric structure for a provided name and styles. +This method can also return a FontMetric without a Stylename. +To get a representation of the StyleName to be presented to the user +call GetStyleName() with this FontMetric. + +Links: + +FontList::GetStyleName() + +-------------------------------------------------------------------------- + +static const int* FontList::GetStdSizeAry(); + +This method returns the available sizes for the given font. +As all fonts are scalable, standard sizes are returned. +The array contains the heights of the font in tenth (1/10) point. +The last value of the array is 0. +The returned array will destroyed by the FontList. +You should thus not reference the array after the next method call on the +FontList. +*/ + +class SVT_DLLPUBLIC FontList +{ +private: + static const int aStdSizeAry[]; + + OUString maMapBoth; + OUString maMapPrinterOnly; + OUString maMapStyleNotAvailable; + mutable OUString maMapNotAvailable; + OUString maLight; + OUString maLightItalic; + OUString maNormal; + OUString maNormalItalic; + OUString maBold; + OUString maBoldItalic; + OUString maBlack; + OUString maBlackItalic; + VclPtr mpDev; + VclPtr mpDev2; + std::vector> m_Entries; + + SVT_DLLPRIVATE ImplFontListNameInfo* ImplFind( std::u16string_view rSearchName, sal_uInt32* pIndex ) const; + SVT_DLLPRIVATE ImplFontListNameInfo* ImplFindByName( std::u16string_view rStr ) const; + SVT_DLLPRIVATE void ImplInsertFonts(OutputDevice* pDev, bool bInsertData); + +public: + FontList( OutputDevice* pDevice, + OutputDevice* pDevice2 = nullptr); + ~FontList(); + + std::unique_ptr Clone() const; + + OUString GetFontMapText( const FontMetric& rFontMetric ) const; + + const OUString& GetNormalStr() const { return maNormal; } + const OUString& GetItalicStr() const { return maNormalItalic; } + const OUString& GetBoldStr() const { return maBold; } + const OUString& GetBoldItalicStr() const { return maBoldItalic; } + const OUString& GetStyleName( FontWeight eWeight, FontItalic eItalic ) const; + OUString GetStyleName( const FontMetric& rFontMetric ) const; + + FontMetric Get( const OUString& rName, + const OUString& rStyleName ) const; + FontMetric Get( const OUString& rName, + FontWeight eWeight, + FontItalic eItalic ) const; + + bool IsAvailable( std::u16string_view rName ) const; + size_t GetFontNameCount() const + { + return m_Entries.size(); + } + const FontMetric& GetFontName(size_t nFont) const; + sal_Handle GetFirstFontMetric( std::u16string_view rName ) const; + static sal_Handle GetNextFontMetric( sal_Handle hFontMetric ); + static const FontMetric& GetFontMetric( sal_Handle hFontMetric ); + + static const int* GetStdSizeAry() { return aStdSizeAry; } + +private: + FontList( const FontList& ) = delete; + FontList& operator =( const FontList& ) = delete; +}; + +class UNLESS_MERGELIBS(SVT_DLLPUBLIC) FontSizeNames +{ +private: + const struct ImplFSNameItem* mpArray; + sal_Int32 mnElem; + +public: + FontSizeNames( LanguageType eLanguage /* = LANGUAGE_DONTKNOW */ ); + + sal_Int32 Count() const { return mnElem; } + bool IsEmpty() const { return !mnElem; } + + sal_Int32 Name2Size( std::u16string_view ) const; + OUString Size2Name( sal_Int32 ) const; + + OUString GetIndexName( sal_Int32 nIndex ) const; + sal_Int32 GetIndexSize( sal_Int32 nIndex ) const; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/dialogclosedlistener.hxx b/include/svtools/dialogclosedlistener.hxx new file mode 100644 index 000000000..c460c1afa --- /dev/null +++ b/include/svtools/dialogclosedlistener.hxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + + +namespace svt +{ + + + //= ODialogClosedListener + + /** + C++ class to implement a css::ui::dialogs::XDialogClosedListener + */ + class SVT_DLLPUBLIC DialogClosedListener final : + public cppu::WeakImplHelper< css::ui::dialogs::XDialogClosedListener > + { + private: + /** + This link will be called when the dialog was closed. + */ + Link m_aDialogClosedLink; + + public: + DialogClosedListener(); + + void SetDialogClosedLink( const Link& rLink ) { m_aDialogClosedLink = rLink; } + + // XDialogClosedListener methods + virtual void SAL_CALL dialogClosed( const css::ui::dialogs::DialogClosedEvent& aEvent ) override; + + // XEventListener methods + virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override; + }; + + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/editbrowsebox.hxx b/include/svtools/editbrowsebox.hxx new file mode 100644 index 000000000..2297c45a6 --- /dev/null +++ b/include/svtools/editbrowsebox.hxx @@ -0,0 +1,1119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +class BrowserDataWin; + +// EditBrowseBoxFlags (EBBF) +enum class EditBrowseBoxFlags +{ + NONE = 0x0000, +/** if this bit is _not_ set, the handle column will be invalidated upon + changing the row in the browse box. This is for forcing the row picture to + be repainted. If you do not have row pictures or text, you don't need this + invalidation, then you would specify this bit to prevent flicker +*/ + NO_HANDLE_COLUMN_CONTENT = 0x0001, +/** set this bit to activate the cell on a MouseButtonDown, not a MouseButtonUp event + */ + ACTIVATE_ON_BUTTONDOWN = 0x0002, +/** if this bit is set and EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT is _not_ set, the handle + column is drawn with the text contained in column 0 instead of an image +*/ + HANDLE_COLUMN_TEXT = 0x0004, + +/** If this bit is set, tab traveling is somewhat modified
    + If the control gets the focus because the user pressed the TAB key, then the + first or last cell (depending on whether the traveling was cycling forward or backward) + gets activated. + @see Window::GetGetFocusFlags + @see GETFOCUS_* +*/ + SMART_TAB_TRAVEL = 0x0008, + +}; +namespace o3tl +{ + template<> struct typed_flags : is_typed_flags {}; +} + +namespace svt +{ + class ControlBase; + + class SVT_DLLPUBLIC CellController : public SvRefBase + { + friend class EditBrowseBox; + Link maModifyHdl; + + VclPtr pWindow; + bool bSuspended; // if the window is hidden and disabled + + public: + + CellController(ControlBase* pW); + virtual ~CellController() override; + + ControlBase& GetWindow() const { return *const_cast(this)->pWindow; } + + virtual void SaveValue() = 0; + virtual bool IsValueChangedFromSaved() const = 0; + + // commit any current changes. Especially, do any reformatting you need (from input formatting + // to output formatting) here + virtual void CommitModifications(); + + // suspending the controller is not cumulative! + void suspend( ); + void resume( ); + bool isSuspended( ) const { return bSuspended; } + + protected: + virtual bool MoveAllowed(const KeyEvent& rEvt) const; + void SetModifyHdl(const Link& rLink) { maModifyHdl = rLink; } + virtual void ActivatingMouseEvent(const BrowserMouseEvent& rEvt, bool bUp); + virtual void callModifyHdl() { maModifyHdl.Call(nullptr); } + }; + + typedef tools::SvRef CellControllerRef; + + + //= IEditImplementation + + class SVT_DLLPUBLIC IEditImplementation + { + public: + virtual ~IEditImplementation() = 0; + + virtual ControlBase& GetControl() = 0; + + virtual OUString GetText( LineEnd aSeparator ) const = 0; + virtual void SetText( const OUString& _rStr ) = 0; + + virtual bool IsReadOnly() const = 0; + virtual void SetReadOnly( bool bReadOnly ) = 0; + + virtual sal_Int32 GetMaxTextLen() const = 0; + virtual void SetMaxTextLen( sal_Int32 _nMaxLen ) = 0; + + virtual Selection GetSelection() const = 0; + virtual void SetSelection( const Selection& _rSelection ) = 0; + + virtual void ReplaceSelected( const OUString& _rStr ) = 0; + virtual OUString GetSelected( LineEnd aSeparator ) const = 0; + + virtual bool IsValueChangedFromSaved() const = 0; + virtual void SaveValue() = 0; + + virtual bool CanUp() const = 0; + virtual bool CanDown() const = 0; + + virtual void Cut() = 0; + virtual void Copy() = 0; + virtual void Paste() = 0; + + // sets a link to call when the text is changed by the user + void SetModifyHdl(const Link& rLink) + { + m_aModify1Hdl = rLink; + } + + // sets an additional link to call when the text is changed by the user + void SetAuxModifyHdl(const Link& rLink) + { + m_aModify2Hdl = rLink; + } + + private: + Link m_aModify1Hdl; + Link m_aModify2Hdl; + + protected: + void CallModifyHdls() + { + m_aModify1Hdl.Call(nullptr); + m_aModify2Hdl.Call(nullptr); + } + }; + + class SVT_DLLPUBLIC ControlBase : public InterimItemWindow + { + public: + ControlBase(BrowserDataWin* pParent, const OUString& rUIXMLDescription, const OString& rID); + + virtual void SetEditableReadOnly(bool bReadOnly); + + virtual bool ProcessKey(const KeyEvent& rKEvt); + + virtual void SetPointFont(const vcl::Font& rFont) = 0; + + // chain after the FocusInHdl + void SetFocusInHdl(const Link& rHdl) + { + m_aFocusInHdl = rHdl; + } + + // chain after the FocusOutHdl + void SetFocusOutHdl(const Link& rHdl) + { + m_aFocusOutHdl = rHdl; + } + + void SetMousePressHdl(const Link& rHdl) + { + m_aMousePressHdl = rHdl; + } + + void SetMouseReleaseHdl(const Link& rHdl) + { + m_aMouseReleaseHdl = rHdl; + } + + void SetMouseMoveHdl(const Link& rHdl) + { + m_aMouseMoveHdl = rHdl; + } + + void SetKeyInputHdl(const Link& rHdl) + { + m_aKeyInputHdl = rHdl; + } + + void SetKeyReleaseHdl(const Link& rHdl) + { + m_aKeyReleaseHdl = rHdl; + } + + protected: + DECL_DLLPRIVATE_LINK(KeyInputHdl, const KeyEvent&, bool); + DECL_DLLPRIVATE_LINK(KeyReleaseHdl, const KeyEvent&, bool); + DECL_DLLPRIVATE_LINK(FocusInHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(FocusOutHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK(MousePressHdl, const MouseEvent&, bool); + DECL_DLLPRIVATE_LINK(MouseReleaseHdl, const MouseEvent&, bool); + DECL_DLLPRIVATE_LINK(MouseMoveHdl, const MouseEvent&, bool); + private: + Link m_aFocusInHdl; + Link m_aFocusOutHdl; + Link m_aMousePressHdl; + Link m_aMouseReleaseHdl; + Link m_aMouseMoveHdl; + Link m_aKeyInputHdl; + Link m_aKeyReleaseHdl; + }; + + class SVT_DLLPUBLIC EditControlBase : public ControlBase + { + public: + EditControlBase(BrowserDataWin* pParent); + + virtual void SetEditableReadOnly(bool bReadOnly) override + { + m_pEntry->set_editable(!bReadOnly); + } + + virtual void SetPointFont(const vcl::Font& rFont) override + { + m_pEntry->set_font(rFont); + } + + virtual void dispose() override; + + weld::Entry& get_widget() { return *m_pEntry; } + + virtual void connect_changed(const Link& rLink) = 0; + virtual void connect_focus_in(const Link& rLink) = 0; + virtual void connect_focus_out(const Link& rLink) = 0; + virtual void connect_key_press(const Link& rLink) = 0; + + protected: + void InitEditControlBase(weld::Entry* pEntry); + + private: + weld::Entry* m_pEntry; + }; + + class SVT_DLLPUBLIC EditControl : public EditControlBase + { + public: + EditControl(BrowserDataWin* pParent); + + virtual void dispose() override; + + virtual void connect_changed(const Link& rLink) override + { + m_xWidget->connect_changed(rLink); + } + + virtual void connect_focus_in(const Link& rLink) override + { + m_xWidget->connect_focus_in(rLink); + } + + virtual void connect_focus_out(const Link& rLink) override + { + m_xWidget->connect_focus_out(rLink); + } + + virtual void connect_key_press(const Link& rLink) override + { + m_xWidget->connect_key_press(rLink); + } + + protected: + std::unique_ptr m_xWidget; + }; + + class SVT_DLLPUBLIC EntryImplementation final : public IEditImplementation + { + EditControlBase& m_rEdit; + int m_nMaxTextLen; + + DECL_LINK(ModifyHdl, weld::Entry&, void); + public: + EntryImplementation(EditControlBase& rEdit) + : m_rEdit(rEdit) + , m_nMaxTextLen(0) + { + m_rEdit.connect_changed(LINK(this, EntryImplementation, ModifyHdl)); + } + + virtual ControlBase& GetControl() override + { + return m_rEdit; + } + + virtual OUString GetText( LineEnd /*aSeparator*/ ) const override + { + // ignore the line end - this base implementation does not support it + return m_rEdit.get_widget().get_text(); + } + + virtual void SetText( const OUString& _rStr ) override + { + return m_rEdit.get_widget().set_text(_rStr); + } + + virtual bool IsReadOnly() const override + { + return !m_rEdit.get_widget().get_editable(); + } + + virtual void SetReadOnly( bool bReadOnly ) override + { + m_rEdit.SetEditableReadOnly(bReadOnly); + } + + virtual sal_Int32 GetMaxTextLen() const override + { + return m_nMaxTextLen; + } + + virtual void SetMaxTextLen( sal_Int32 nMaxLen ) override + { + m_nMaxTextLen = nMaxLen; + m_rEdit.get_widget().set_max_length(m_nMaxTextLen); + } + + virtual Selection GetSelection() const override + { + int nStartPos, nEndPos; + m_rEdit.get_widget().get_selection_bounds(nStartPos, nEndPos); + return Selection(nStartPos, nEndPos); + } + + virtual void SetSelection( const Selection& rSelection ) override + { + auto nMin = rSelection.Min(); + auto nMax = rSelection.Max(); + m_rEdit.get_widget().select_region(nMin < 0 ? 0 : nMin, nMax == SELECTION_MAX ? -1 : nMax); + } + + virtual void ReplaceSelected( const OUString& rStr ) override + { + m_rEdit.get_widget().replace_selection(rStr); + } + + virtual OUString GetSelected( LineEnd /*aSeparator*/ ) const override + // ignore the line end - this base implementation does not support it + { + int nStartPos, nEndPos; + weld::Entry& rEntry = m_rEdit.get_widget(); + rEntry.get_selection_bounds(nStartPos, nEndPos); + return rEntry.get_text().copy(nStartPos, nEndPos - nStartPos); + } + + virtual bool IsValueChangedFromSaved() const override + { + return m_rEdit.get_widget().get_value_changed_from_saved(); + } + + virtual void SaveValue() override + { + m_rEdit.get_widget().save_value(); + } + + virtual bool CanUp() const override + { + return false; + } + + virtual bool CanDown() const override + { + return false; + } + + virtual void Cut() override + { + m_rEdit.get_widget().cut_clipboard(); + } + + virtual void Copy() override + { + m_rEdit.get_widget().copy_clipboard(); + } + + virtual void Paste() override + { + m_rEdit.get_widget().paste_clipboard(); + } + }; + + //= MultiLineTextCell + + /** a multi line edit which can be used in a cell of an EditBrowseBox + */ + class SVT_DLLPUBLIC MultiLineTextCell final : public ControlBase + { + public: + MultiLineTextCell(BrowserDataWin* pParent); + + virtual void SetEditableReadOnly(bool bReadOnly) override + { + m_xWidget->set_editable(!bReadOnly); + } + + virtual void SetPointFont(const vcl::Font& rFont) override + { + m_xWidget->set_font(rFont); + } + + virtual void GetFocus() override; + + virtual void dispose() override; + + void connect_changed(const Link& rLink) + { + m_xWidget->connect_changed(rLink); + } + + weld::TextView& get_widget() { return *m_xWidget; } + + private: + std::unique_ptr m_xWidget; + + virtual bool ProcessKey(const KeyEvent& rKEvt) override; + }; + + class SVT_DLLPUBLIC MultiLineEditImplementation final : public IEditImplementation + { + MultiLineTextCell& m_rEdit; + int m_nMaxTextLen; + + DECL_LINK(ModifyHdl, weld::TextView&, void); + public: + MultiLineEditImplementation(MultiLineTextCell& rEdit) + : m_rEdit(rEdit) + , m_nMaxTextLen(0) + { + m_rEdit.connect_changed(LINK(this, MultiLineEditImplementation, ModifyHdl)); + } + + virtual ControlBase& GetControl() override + { + return m_rEdit; + } + + virtual OUString GetText(LineEnd aSeparator) const override; + + virtual void SetText(const OUString& rStr) override + { + return m_rEdit.get_widget().set_text(rStr); + } + + virtual bool IsReadOnly() const override + { + return !m_rEdit.get_widget().get_editable(); + } + + virtual void SetReadOnly( bool bReadOnly ) override + { + m_rEdit.SetEditableReadOnly(bReadOnly); + } + + virtual sal_Int32 GetMaxTextLen() const override + { + return m_nMaxTextLen; + } + + virtual void SetMaxTextLen( sal_Int32 nMaxLen ) override + { + m_nMaxTextLen = nMaxLen; + m_rEdit.get_widget().set_max_length(m_nMaxTextLen); + } + + virtual Selection GetSelection() const override + { + int nStartPos, nEndPos; + m_rEdit.get_widget().get_selection_bounds(nStartPos, nEndPos); + return Selection(nStartPos, nEndPos); + } + + virtual void SetSelection( const Selection& rSelection ) override + { + auto nMin = rSelection.Min(); + auto nMax = rSelection.Max(); + m_rEdit.get_widget().select_region(nMin < 0 ? 0 : nMin, nMax == SELECTION_MAX ? -1 : nMax); + } + + virtual void ReplaceSelected( const OUString& rStr ) override + { + m_rEdit.get_widget().replace_selection(rStr); + } + + virtual OUString GetSelected( LineEnd aSeparator ) const override; + + virtual bool IsValueChangedFromSaved() const override + { + return m_rEdit.get_widget().get_value_changed_from_saved(); + } + + virtual void SaveValue() override + { + m_rEdit.get_widget().save_value(); + } + + virtual bool CanUp() const override + { + return m_rEdit.get_widget().can_move_cursor_with_up(); + } + + virtual bool CanDown() const override + { + return m_rEdit.get_widget().can_move_cursor_with_down(); + } + + virtual void Cut() override + { + m_rEdit.get_widget().cut_clipboard(); + } + + virtual void Copy() override + { + m_rEdit.get_widget().copy_clipboard(); + } + + virtual void Paste() override + { + m_rEdit.get_widget().paste_clipboard(); + } + }; + + + //= EditCellController + class SVT_DLLPUBLIC EditCellController : public CellController + { + IEditImplementation* m_pEditImplementation; + bool m_bOwnImplementation; // did we create m_pEditImplementation? + + public: + EditCellController( EditControlBase* _pEdit ); + EditCellController( IEditImplementation* _pImplementation ); + virtual ~EditCellController( ) override; + + const IEditImplementation* GetEditImplementation( ) const { return m_pEditImplementation; } + IEditImplementation* GetEditImplementation( ) { return m_pEditImplementation; } + + virtual bool IsValueChangedFromSaved() const override; + virtual void SaveValue() override; + + void Modify() + { + ModifyHdl(nullptr); + } + + protected: + virtual bool MoveAllowed(const KeyEvent& rEvt) const override; + private: + DECL_LINK(ModifyHdl, LinkParamNone*, void); + }; + + //= CheckBoxControl + class SVT_DLLPUBLIC CheckBoxControl final : public ControlBase + { + std::unique_ptr m_xBox; + weld::TriStateEnabled m_aModeState; + Link m_aToggleLink; + Link m_aModify1Hdl; + Link m_aModify2Hdl; + + public: + CheckBoxControl(BrowserDataWin* pParent); + virtual ~CheckBoxControl() override; + virtual void dispose() override; + + virtual void SetPointFont(const vcl::Font& rFont) override; + + void SetToggleHdl(const Link& rHdl) {m_aToggleLink = rHdl;} + + // sets a link to call when the text is changed by the user + void SetModifyHdl(const Link& rHdl) + { + m_aModify1Hdl = rHdl; + } + + // sets an additional link to call when the text is changed by the user + void SetAuxModifyHdl(const Link& rLink) + { + m_aModify2Hdl = rLink; + } + + void SetState(TriState eState); + TriState GetState() const { return m_xBox->get_state(); } + + void EnableTriState(bool bTriState); + + weld::CheckButton& GetBox() {return *m_xBox;}; + + // for pseudo-click when initially clicking in a cell activates + // the cell and performs a state change on the button as if + // it was clicked on + void Clicked(); + + private: + DECL_DLLPRIVATE_LINK(OnToggle, weld::Toggleable&, void); + + void CallModifyHdls() + { + m_aModify1Hdl.Call(nullptr); + m_aModify2Hdl.Call(nullptr); + } + }; + + //= CheckBoxCellController + class SVT_DLLPUBLIC CheckBoxCellController final : public CellController + { + public: + + CheckBoxCellController(CheckBoxControl* pWin); + weld::CheckButton& GetCheckBox() const; + + virtual bool IsValueChangedFromSaved() const override; + virtual void SaveValue() override; + + private: + virtual void ActivatingMouseEvent(const BrowserMouseEvent& rEvt, bool bUp) override; + DECL_DLLPRIVATE_LINK(ModifyHdl, LinkParamNone*, void); + }; + + //= ComboBoxControl + class SVT_DLLPUBLIC ComboBoxControl final : public ControlBase + { + private: + std::unique_ptr m_xWidget; + Link m_aModify1Hdl; + Link m_aModify2Hdl; + + friend class ComboBoxCellController; + + public: + ComboBoxControl(BrowserDataWin* pParent); + + virtual void SetPointFont(const vcl::Font& rFont) override; + + virtual void SetEditableReadOnly(bool bReadOnly) override + { + m_xWidget->set_entry_editable(!bReadOnly); + } + + weld::ComboBox& get_widget() { return *m_xWidget; } + + // sets a link to call when the selection is changed by the user + void SetModifyHdl(const Link& rHdl) + { + m_aModify1Hdl = rHdl; + } + + // sets an additional link to call when the selection is changed by the user + // bool arg is true when triggered interactively by the user + void SetAuxModifyHdl(const Link& rLink) + { + m_aModify2Hdl = rLink; + } + + void TriggerAuxModify() + { + m_aModify2Hdl.Call(false); + } + + virtual void dispose() override; + + private: + DECL_DLLPRIVATE_LINK(SelectHdl, weld::ComboBox&, void); + + void CallModifyHdls() + { + m_aModify1Hdl.Call(nullptr); + m_aModify2Hdl.Call(true); + } + }; + + //= ComboBoxCellController + class SVT_DLLPUBLIC ComboBoxCellController final : public CellController + { + public: + + ComboBoxCellController(ComboBoxControl* pParent); + weld::ComboBox& GetComboBox() const { return static_cast(GetWindow()).get_widget(); } + + virtual bool IsValueChangedFromSaved() const override; + virtual void SaveValue() override; + + private: + virtual bool MoveAllowed(const KeyEvent& rEvt) const override; + DECL_DLLPRIVATE_LINK(ModifyHdl, LinkParamNone*, void); + }; + + //= ListBoxControl + class SVT_DLLPUBLIC ListBoxControl final : public ControlBase + { + private: + std::unique_ptr m_xWidget; + Link m_aModify1Hdl; + Link m_aModify2Hdl; + + friend class ListBoxCellController; + + public: + ListBoxControl(BrowserDataWin* pParent); + + virtual void SetPointFont(const vcl::Font& rFont) override; + + weld::ComboBox& get_widget() { return *m_xWidget; } + + // sets a link to call when the selection is changed by the user + void SetModifyHdl(const Link& rHdl) + { + m_aModify1Hdl = rHdl; + } + + // sets an additional link to call when the selection is changed, + // bool arg is true when triggered interactively by the user + void SetAuxModifyHdl(const Link& rLink) + { + m_aModify2Hdl = rLink; + } + + void TriggerAuxModify() + { + m_aModify2Hdl.Call(false); + } + + virtual void dispose() override; + private: + DECL_DLLPRIVATE_LINK(SelectHdl, weld::ComboBox&, void); + + void CallModifyHdls() + { + m_aModify1Hdl.Call(nullptr); + m_aModify2Hdl.Call(true); + } + }; + + //= ListBoxCellController + class SVT_DLLPUBLIC ListBoxCellController : public CellController + { + public: + + ListBoxCellController(ListBoxControl* pParent); + weld::ComboBox& GetListBox() const { return static_cast(GetWindow()).get_widget(); } + + virtual bool IsValueChangedFromSaved() const override; + virtual void SaveValue() override; + + protected: + virtual bool MoveAllowed(const KeyEvent& rEvt) const override; + private: + DECL_DLLPRIVATE_LINK(ListBoxSelectHdl, LinkParamNone*, void); + }; + + class SVT_DLLPUBLIC FormattedControlBase : public EditControlBase + { + public: + FormattedControlBase(BrowserDataWin* pParent, bool bSpinVariant); + + virtual void dispose() override; + + virtual void connect_changed(const Link& rLink) override; + virtual void connect_focus_in(const Link& rLink) override; + virtual void connect_focus_out(const Link& rLink) override; + virtual void connect_key_press(const Link& rLink) override; + + weld::EntryFormatter& get_formatter(); + + protected: + bool m_bSpinVariant; + std::unique_ptr m_xEntry; + std::unique_ptr m_xSpinButton; + std::unique_ptr m_xEntryFormatter; + + void InitFormattedControlBase(); + }; + + class SVT_DLLPUBLIC FormattedControl final : public FormattedControlBase + { + public: + FormattedControl(BrowserDataWin* pParent, bool bSpinVariant); + }; + + class SVT_DLLPUBLIC DoubleNumericControl final : public FormattedControlBase + { + public: + DoubleNumericControl(BrowserDataWin* pParent, bool bSpinVariant); + }; + + class SVT_DLLPUBLIC LongCurrencyControl final : public FormattedControlBase + { + public: + LongCurrencyControl(BrowserDataWin* pParent, bool bSpinVariant); + }; + + class SVT_DLLPUBLIC TimeControl final : public FormattedControlBase + { + public: + TimeControl(BrowserDataWin* pParent, bool bSpinVariant); + }; + + class SVT_DLLPUBLIC DateControl final : public FormattedControlBase + { + public: + DateControl(BrowserDataWin* pParent, bool bDropDown); + + void SetDate(const Date& rDate); + + virtual void dispose() override; + private: + std::unique_ptr m_xMenuButton; + std::unique_ptr m_xCalendarBuilder; + std::unique_ptr m_xTopLevel; + std::unique_ptr m_xCalendar; + std::unique_ptr m_xExtras; + std::unique_ptr m_xTodayBtn; + std::unique_ptr m_xNoneBtn; + + DECL_DLLPRIVATE_LINK(ToggleHdl, weld::Toggleable&, void); + DECL_DLLPRIVATE_LINK(ActivateHdl, weld::Calendar&, void); + DECL_DLLPRIVATE_LINK(ImplClickHdl, weld::Button&, void); + }; + + class SVT_DLLPUBLIC PatternControl final : public EditControlBase + { + public: + PatternControl(BrowserDataWin* pParent); + + weld::PatternFormatter& get_formatter() { return *m_xEntryFormatter; } + + virtual void connect_changed(const Link& rLink) override; + virtual void connect_focus_in(const Link& rLink) override; + virtual void connect_focus_out(const Link& rLink) override; + virtual void connect_key_press(const Link& rLink) override; + + virtual void dispose() override; + private: + std::unique_ptr m_xWidget; + std::unique_ptr m_xEntryFormatter; + }; + + //= FormattedFieldCellController + class SVT_DLLPUBLIC FormattedFieldCellController final : public EditCellController + { + public: + FormattedFieldCellController( FormattedControlBase* _pFormatted ); + + virtual void CommitModifications() override; + }; + + //= EditBrowserHeader + class SVT_DLLPUBLIC EditBrowserHeader : public BrowserHeader + { + public: + EditBrowserHeader( BrowseBox* pParent, WinBits nWinBits = WB_BUTTONSTYLE ) + :BrowserHeader(pParent, nWinBits){} + + protected: + virtual void DoubleClick() override; + }; + + + //= EditBrowseBox + class EditBrowseBoxImpl; + class SVT_DLLPUBLIC EditBrowseBox: public BrowseBox + { + friend class EditBrowserHeader; + + enum BrowseInfo + { + COLSELECT = 1, + ROWSELECT = 2, + ROWCHANGE = 4, + COLCHANGE = 8 + }; + + public: + enum RowStatus + { + CLEAN = 0, + CURRENT = 1, + CURRENTNEW = 2, + MODIFIED = 3, + NEW = 4, + DELETED = 5, + PRIMARYKEY = 6, + CURRENT_PRIMARYKEY = 7, + FILTER = 8, + HEADERFOOTER = 9 + }; + + private: + EditBrowseBox(EditBrowseBox const &) = delete; + EditBrowseBox& operator=(EditBrowseBox const &) = delete; + + class BrowserMouseEventPtr + { + std::unique_ptr pEvent; + bool bDown; + + public: + BrowserMouseEventPtr() + : bDown(false) + { + } + + bool Is() const {return pEvent != nullptr;} + bool IsDown() const {return bDown;} + const BrowserMouseEvent* operator->() const {return pEvent.get();} + + SVT_DLLPUBLIC void Clear(); + void Set(const BrowserMouseEvent* pEvt, bool bIsDown); + } aMouseEvent; + + CellControllerRef aController, + aOldController; + + ImplSVEvent * nStartEvent, * nEndEvent, * nCellModifiedEvent; // event ids + VclPtr m_pFocusWhileRequest; + // In ActivateCell, we grab the focus asynchronously, but if between requesting activation + // and the asynchronous event the focus has changed, we won't grab it for ourself. + + sal_Int32 nPaintRow; // row being painted + sal_Int32 nEditRow; + sal_uInt16 nEditCol; + + bool bHasFocus : 1; + mutable bool bPaintStatus : 1; // paint a status (image) in the handle column + bool bActiveBeforeTracking; + + VclPtr pCheckBoxPaint; + + EditBrowseBoxFlags m_nBrowserFlags; + std::unique_ptr< EditBrowseBoxImpl> m_aImpl; + + protected: + VclPtr pHeader; + + BrowserMouseEventPtr& getMouseEvent() { return aMouseEvent; } + + protected: + BrowserHeader* GetHeaderBar() const {return pHeader;} + + virtual VclPtr CreateHeaderBar(BrowseBox* pParent) override; + + // if you want to have an own header ... + virtual VclPtr imp_CreateHeaderBar(BrowseBox* pParent); + + virtual void ColumnMoved(sal_uInt16 nId) override; + virtual void ColumnResized(sal_uInt16 nColId) override; + virtual void Resize() override; + virtual void ArrangeControls(sal_uInt16& nX, sal_uInt16 nY); + virtual bool SeekRow(sal_Int32 nRow) override; + + virtual void GetFocus() override; + virtual void LoseFocus() override; + virtual void KeyInput(const KeyEvent& rEvt) override; + virtual void MouseButtonDown(const BrowserMouseEvent& rEvt) override; + virtual void MouseButtonUp(const BrowserMouseEvent& rEvt) override; + virtual void StateChanged( StateChangedType nType ) override; + virtual void DataChanged( const DataChangedEvent& rDCEvt ) override; + + using BrowseBox::MouseButtonUp; + using BrowseBox::MouseButtonDown; + + virtual bool PreNotify(NotifyEvent& rNEvt ) override; + virtual bool EventNotify(NotifyEvent& rNEvt) override; + + virtual void EndScroll() override; + + // should be used instead of GetFieldRectPixel, 'cause this method here takes into account the borders + tools::Rectangle GetCellRect(sal_Int32 nRow, sal_uInt16 nColId, bool bRelToBrowser = true) const; + virtual sal_uInt32 GetTotalCellWidth(sal_Int32 nRow, sal_uInt16 nColId); + sal_uInt32 GetAutoColumnWidth(sal_uInt16 nColId); + + virtual void PaintStatusCell(OutputDevice& rDev, const tools::Rectangle& rRect) const; + virtual void PaintCell(OutputDevice& rDev, const tools::Rectangle& rRect, sal_uInt16 nColId) const = 0; + + virtual RowStatus GetRowStatus(sal_Int32 nRow) const; + + virtual void RowHeightChanged() override; + + // callbacks for the data window + virtual void ImplStartTracking() override; + virtual void ImplEndTracking() override; + + // when changing a row: + // CursorMoving: cursor is being moved, but GetCurRow() still provides the old row + virtual bool CursorMoving(sal_Int32 nNewRow, sal_uInt16 nNewCol); + + // cursor has been moved + virtual void CursorMoved() override; + + virtual void CellModified(); // called whenever a cell has been modified + virtual bool SaveModified(); // called whenever a cell should be left, and it's content should be saved + // return sal_False prevents leaving the cell + virtual bool SaveRow(); // commit the current row + + virtual bool IsModified() const {return aController.is() && aController->IsValueChangedFromSaved();} + + virtual CellController* GetController(sal_Int32 nRow, sal_uInt16 nCol); + virtual void InitController(CellControllerRef& rController, sal_Int32 nRow, sal_uInt16 nCol); + static void ResizeController(CellControllerRef const & rController, const tools::Rectangle&); + virtual void DoubleClick(const BrowserMouseEvent&) override; + + void ActivateCell() { ActivateCell(GetCurRow(), GetCurColumnId()); } + + // retrieve the image for the row status + Image GetImage(RowStatus) const; + + // inserting columns + // if you don't set a width, this will be calculated automatically + // if the id isn't set the smallest unused will do it ... + virtual sal_uInt16 AppendColumn(const OUString& rName, sal_uInt16 nWidth, sal_uInt16 nPos = HEADERBAR_APPEND, sal_uInt16 nId = sal_uInt16(-1)); + + // called whenever (Shift)Tab or Enter is pressed. If true is returned, these keys + // result in traveling to the next or to th previous cell + virtual bool IsTabAllowed(bool bForward) const; + + virtual bool IsCursorMoveAllowed(sal_Int32 nNewRow, sal_uInt16 nNewColId) const override; + + void PaintTristate(const tools::Rectangle& rRect, const TriState& eState, bool _bEnabled=true) const; + + void AsynchGetFocus(); + // secure starting of StartEditHdl + + public: + EditBrowseBox(vcl::Window* pParent, EditBrowseBoxFlags nBrowserFlags, WinBits nBits, BrowserMode nMode = BrowserMode::NONE ); + virtual ~EditBrowseBox() override; + virtual void dispose() override; + + bool IsEditing() const {return aController.is();} + void InvalidateStatusCell(sal_Int32 nRow) {RowModified(nRow, 0);} + void InvalidateHandleColumn(); + + // late construction + virtual void Init(); + virtual void RemoveRows(); + virtual void Dispatch(sal_uInt16 nId); + + const CellControllerRef& Controller() const { return aController; } + EditBrowseBoxFlags GetBrowserFlags() const { return m_nBrowserFlags; } + void SetBrowserFlags(EditBrowseBoxFlags nFlags); + + virtual void ActivateCell(sal_Int32 nRow, sal_uInt16 nCol, bool bSetCellFocus = true); + virtual void DeactivateCell(bool bUpdate = true); + // Children --------------------------------------------------------------- + + /** @return The count of additional controls of the control area. */ + virtual sal_Int32 GetAccessibleControlCount() const override; + + /** Creates the accessible object of an additional control. + @param nIndex + The 0-based index of the control. + @return + The XAccessible interface of the specified control. */ + virtual css::uno::Reference< css::accessibility::XAccessible > + CreateAccessibleControl( sal_Int32 nIndex ) override; + + /** Sets focus to current cell of the data table. */ + virtual void GrabTableFocus() override; + + virtual tools::Rectangle GetFieldCharacterBounds(sal_Int32 _nRow,sal_Int32 _nColumnPos,sal_Int32 nIndex) override; + virtual sal_Int32 GetFieldIndexAtPoint(sal_Int32 _nRow,sal_Int32 _nColumnPos,const Point& _rPoint) override; + + virtual bool ProcessKey(const KeyEvent& rEvt) override; + + virtual void ChildFocusIn() override; + virtual void ChildFocusOut() override; + + css::uno::Reference< css::accessibility::XAccessible > CreateAccessibleCheckBoxCell(sal_Int32 _nRow, sal_uInt16 _nColumnPos,const TriState& eState); + bool ControlHasFocus() const; + protected: + // creates the accessible which wraps the active cell + void implCreateActiveAccessible( ); + + private: + virtual void PaintField(vcl::RenderContext& rDev, const tools::Rectangle& rRect, + sal_uInt16 nColumnId ) const override; + using Control::ImplInitSettings; + SVT_DLLPRIVATE void ImplInitSettings( bool bFont, bool bForeground, bool bBackground ); + SVT_DLLPRIVATE void DetermineFocus( const GetFocusFlags _nGetFocusFlags = GetFocusFlags::NONE); + inline void EnableAndShow() const; + + SVT_DLLPRIVATE void implActivateCellOnMouseEvent(const BrowserMouseEvent& _rEvt, bool _bUp); + + DECL_DLLPRIVATE_LINK( ModifyHdl, LinkParamNone*, void ); + DECL_DLLPRIVATE_LINK( StartEditHdl, void*, void ); + DECL_DLLPRIVATE_LINK( EndEditHdl, void*, void ); + DECL_DLLPRIVATE_LINK( CellModifiedHdl, void*, void ); + }; + + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/ehdl.hxx b/include/svtools/ehdl.hxx new file mode 100644 index 000000000..2324a5107 --- /dev/null +++ b/include/svtools/ehdl.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +typedef std::pair ErrMsgCode; +SVT_DLLPUBLIC extern const ErrMsgCode RID_ERRHDL[]; +SVT_DLLPUBLIC extern const ErrMsgCode RID_ERRCTX[]; + +namespace weld { class Window; } + +class SVT_DLLPUBLIC SfxErrorContext final : private ErrorContext +{ +public: + SfxErrorContext( + sal_uInt16 nCtxIdP, weld::Window *pWin=nullptr, + const ErrMsgCode* pIds = nullptr, const std::locale& rResLocaleP = SvtResLocale()); + SfxErrorContext( + sal_uInt16 nCtxIdP, const OUString &aArg1, weld::Window *pWin=nullptr, + const ErrMsgCode* pIds = nullptr, const std::locale& rResLocaleP = SvtResLocale()); + bool GetString(ErrCode nErrId, OUString &rStr) override; + +private: + sal_uInt16 nCtxId; + const ErrMsgCode* pIds; + std::locale aResLocale; + OUString aArg1; +}; + +class SVT_DLLPUBLIC SfxErrorHandler : private ErrorHandler +{ +public: + SfxErrorHandler(const ErrMsgCode* pIds, ErrCodeArea lStart, ErrCodeArea lEnd, const std::locale& rResLocale = SvtResLocale()); + virtual ~SfxErrorHandler() override; + +protected: + bool GetErrorString(ErrCode lErrId, OUString &) const; + +private: + + ErrCodeArea lStart; + ErrCodeArea lEnd; + const ErrMsgCode* pIds; + std::locale aResLocale; + + SVT_DLLPRIVATE static void GetClassString(ErrCodeClass lErrId, OUString &); + virtual bool CreateString(const ErrorInfo *, OUString &) const override; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/embedhlp.hxx b/include/svtools/embedhlp.hxx new file mode 100644 index 000000000..e87ebfbf9 --- /dev/null +++ b/include/svtools/embedhlp.hxx @@ -0,0 +1,135 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace com :: sun :: star :: io { class XInputStream; } + +namespace comphelper +{ + class EmbeddedObjectContainer; +} + +namespace com::sun::star::embed { + class XEmbeddedObject; +} + +class OutputDevice; +typedef struct _xmlTextWriter* xmlTextWriterPtr; + +namespace svt { + +struct EmbeddedObjectRef_Impl; + +class SVT_DLLPUBLIC EmbeddedObjectRef +{ + std::unique_ptr mpImpl; + + SVT_DLLPRIVATE std::unique_ptr GetGraphicStream( bool bUpdate ) const; + SVT_DLLPRIVATE void GetReplacement( bool bUpdate ); + SVT_DLLPRIVATE void UpdateOleObject( bool bUpdateOle); + + EmbeddedObjectRef& operator = ( const EmbeddedObjectRef& ) = delete; + +public: + static void DrawPaintReplacement( const tools::Rectangle &rRect, const OUString &rText, OutputDevice *pOut ); + static void DrawShading( const tools::Rectangle &rRect, OutputDevice *pOut ); + static bool TryRunningState( const css::uno::Reference < css::embed::XEmbeddedObject >& ); + static void SetGraphicToContainer( const Graphic& rGraphic, + comphelper::EmbeddedObjectContainer& aContainer, + const OUString& aName, + const OUString& aMediaType ); + + static css::uno::Reference< css::io::XInputStream > GetGraphicReplacementStream( + sal_Int64 nViewAspect, + const css::uno::Reference < css::embed::XEmbeddedObject >&, + OUString* pMediaType ) + noexcept; + + static bool IsChart(const css::uno::Reference < css::embed::XEmbeddedObject >& xObj); + + const css::uno::Reference & operator->() const; + const css::uno::Reference & GetObject() const; + + // default constructed object; needs further assignment before it can be used + EmbeddedObjectRef(); + + // assign a previously default constructed object + void Assign( const css::uno::Reference < css::embed::XEmbeddedObject >& xObj, sal_Int64 nAspect ); + + // create object for a certain view aspect + EmbeddedObjectRef( const css::uno::Reference < css::embed::XEmbeddedObject >& xObj, sal_Int64 nAspect ); + + ~EmbeddedObjectRef(); + EmbeddedObjectRef( const EmbeddedObjectRef& ); + + // assigning to a container enables the object to exchange graphical representations with a storage + void AssignToContainer( comphelper::EmbeddedObjectContainer* pContainer, const OUString& rPersistName ); + comphelper::EmbeddedObjectContainer* GetContainer() const; + + sal_Int64 GetViewAspect() const; + void SetViewAspect( sal_Int64 nAspect ); + const Graphic* GetGraphic() const; + + // the original size of the object ( size of the icon for iconified object ) + // no conversion is done if no target mode is provided + Size GetSize( MapMode const * pTargetMapMode ) const; + + void SetGraphic( const Graphic& rGraphic, const OUString& rMediaType ); + void SetGraphicStream( + const css::uno::Reference< css::io::XInputStream >& xInGrStream, + const OUString& rMediaType ); + + // bUpdateOle = false update the Link-Objects + // = true update the OLE-Objects + void UpdateReplacement( bool bUpdateOle = false ); + void UpdateReplacementOnDemand(); + void Lock( bool bLock = true ); + void Clear(); + bool is() const; + + bool IsLocked() const; + + void SetIsProtectedHdl(const Link& rProtectedHdl); + const Link & GetIsProtectedHdl() const; + + bool IsChart() const; + + OUString GetChartType(); + + // #i104867# + // Provides a graphic version number for the fetchable Graphic during this object's lifetime. Internally, + // that number is incremented at each change of the Graphic. This mechanism is needed to identify if a + // remembered Graphic (e.g. primitives) has changed compared to the current one, but without actively + // fetching the Graphic what would be too expensive e.g. for charts + sal_uInt32 getGraphicVersion() const; + void SetDefaultSizeForChart( const Size& rSizeIn_100TH_MM );//#i103460# charts do not necessarily have an own size within ODF files, in this case they need to use the size settings from the surrounding frame, which is made available with this method + + void dumpAsXml(xmlTextWriterPtr pWriter) const; +}; + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/embedtransfer.hxx b/include/svtools/embedtransfer.hxx new file mode 100644 index 000000000..98bab1683 --- /dev/null +++ b/include/svtools/embedtransfer.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace com :: sun :: star :: embed { class XEmbeddedObject; } + +class Graphic; +class SVT_DLLPUBLIC SvEmbedTransferHelper final : public TransferableHelper +{ +private: + + css::uno::Reference< css::embed::XEmbeddedObject > m_xObj; + std::unique_ptr m_pGraphic; + sal_Int64 m_nAspect; + + OUString maParentShellID; + + virtual void AddSupportedFormats() override; + virtual bool GetData( const css::datatransfer::DataFlavor& rFlavor, const OUString& rDestDoc ) override; + virtual void ObjectReleased() override; + +public: + // object, replacement image, and the aspect + SvEmbedTransferHelper( const css::uno::Reference< css::embed::XEmbeddedObject >& xObj, + const Graphic* pGraphic, + sal_Int64 nAspect ); + virtual ~SvEmbedTransferHelper() override; + + void SetParentShellID( const OUString& rShellID ); + + static void FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc, + const css::uno::Reference< css::embed::XEmbeddedObject >& xObj, + const Graphic* pGraphic, + sal_Int64 nAspect ); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/extcolorcfg.hxx b/include/svtools/extcolorcfg.hxx new file mode 100644 index 000000000..408f8651e --- /dev/null +++ b/include/svtools/extcolorcfg.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include +#include +#include + + +namespace svtools { + +class ExtendedColorConfig_Impl; + +class ExtendedColorConfigValue +{ + OUString m_sName; + OUString m_sDisplayName; + Color m_nColor; + Color m_nDefaultColor; +public: + ExtendedColorConfigValue() : m_nColor(0),m_nDefaultColor(0){} + ExtendedColorConfigValue(const OUString& _sName + ,const OUString& _sDisplayName + ,Color _nColor + ,Color _nDefaultColor) + : m_sName(_sName) + ,m_sDisplayName(_sDisplayName) + ,m_nColor(_nColor) + ,m_nDefaultColor(_nDefaultColor) + {} + + const OUString& getName() const { return m_sName; } + const OUString& getDisplayName() const { return m_sDisplayName; } + Color getColor() const { return m_nColor; } + Color getDefaultColor() const { return m_nDefaultColor; } + + void setColor(Color _nColor) { m_nColor = _nColor; } +}; + +class SVT_DLLPUBLIC ExtendedColorConfig final : public SfxBroadcaster, public SfxListener +{ + friend class ExtendedColorConfig_Impl; +private: + static ExtendedColorConfig_Impl* m_pImpl; +public: + ExtendedColorConfig(); + virtual ~ExtendedColorConfig() override; + + virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) override; + + // get the configured value + ExtendedColorConfigValue GetColorValue(const OUString& _sComponentName,const OUString& _sName)const; + sal_Int32 GetComponentCount() const; + OUString GetComponentName(sal_uInt32 _nPos) const; + OUString GetComponentDisplayName(const OUString& _sComponentName) const; + sal_Int32 GetComponentColorCount(const OUString& _sName) const; + ExtendedColorConfigValue GetComponentColorConfigValue(const OUString& _sComponentName,sal_uInt32 _nPos) const; +}; + +class SVT_DLLPUBLIC EditableExtendedColorConfig +{ + std::unique_ptr m_pImpl; + bool m_bModified; +public: + EditableExtendedColorConfig(); + ~EditableExtendedColorConfig(); + + void DeleteScheme(const OUString& rScheme ); + void AddScheme(const OUString& rScheme ); + void LoadScheme(const OUString& rScheme ); + void SetCurrentSchemeName(const OUString& rScheme); + + sal_Int32 GetComponentCount() const; + OUString GetComponentName(sal_uInt32 _nPos) const; + sal_Int32 GetComponentColorCount(const OUString& _sName) const; + ExtendedColorConfigValue GetComponentColorConfigValue(const OUString& _sName,sal_uInt32 _nPos) const; + void SetColorValue(const OUString& _sComponentName, const ExtendedColorConfigValue& rValue); + void SetModified(); + void ClearModified() {m_bModified = false;} + bool IsModified() const {return m_bModified;} + void Commit(); + + void DisableBroadcast(); + void EnableBroadcast(); +}; +}//namespace svtools + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/filechangedchecker.hxx b/include/svtools/filechangedchecker.hxx new file mode 100644 index 000000000..d50fea631 --- /dev/null +++ b/include/svtools/filechangedchecker.hxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include +#include +#include + +#include + +/** Periodically checks if a file has been modified + + Instances of this class setup a vcl timer to occasionally wake up + check whether file modification time has changed. + */ +class SVT_DLLPUBLIC FileChangedChecker +{ +private: + Timer mTimer; + OUString mFileName; + TimeValue mLastModTime; + ::std::function mpCallback; + + bool SVT_DLLPRIVATE getCurrentModTime(TimeValue& o_rValue) const; + DECL_DLLPRIVATE_LINK(TimerHandler, Timer *, void); + +public: + void resetTimer(); + // bUpdate = true when file has changed, get the return and the object get the new time + // = false when file has changed, only get the return, not change the object + bool hasFileChanged(bool bUpdate = true); + FileChangedChecker(const OUString& rFilename, + const ::std::function& rCallback); + // without Timer function + FileChangedChecker(const OUString& rFilename); +}; diff --git a/include/svtools/fontsubstconfig.hxx b/include/svtools/fontsubstconfig.hxx new file mode 100644 index 000000000..06097cf3b --- /dev/null +++ b/include/svtools/fontsubstconfig.hxx @@ -0,0 +1,41 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +struct SubstitutionStruct +{ + OUString sFont; + OUString sReplaceBy; + bool bReplaceAlways; + bool bReplaceOnScreenOnly; +}; + +namespace svtools +{ + SVT_DLLPUBLIC bool IsFontSubstitutionsEnabled(); + SVT_DLLPUBLIC std::vector GetFontSubstitutions(); + SVT_DLLPUBLIC void SetFontSubstitutions(bool bIsEnabled, std::vector const &); + SVT_DLLPUBLIC void ApplyFontSubstitutionsToVcl(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/genericunodialog.hxx b/include/svtools/genericunodialog.hxx new file mode 100644 index 000000000..467a52382 --- /dev/null +++ b/include/svtools/genericunodialog.hxx @@ -0,0 +1,160 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace com :: sun :: star :: awt { class XWindow; } +namespace com :: sun :: star :: uno { class XComponentContext; } + +class VclWindowEvent; + + +namespace svt +{ + + +#define UNODIALOG_PROPERTY_ID_TITLE 1 +#define UNODIALOG_PROPERTY_ID_PARENT 2 + +inline constexpr OUStringLiteral UNODIALOG_PROPERTY_TITLE = u"Title"; +inline constexpr OUStringLiteral UNODIALOG_PROPERTY_PARENT = u"ParentWindow"; + + typedef cppu::WeakImplHelper< css::ui::dialogs::XExecutableDialog, + css::lang::XServiceInfo, + css::lang::XInitialization > OGenericUnoDialogBase; + + /** abstract base class for implementing UNO objects representing dialogs (com.sun.star.awt::XDialog) + */ + class SVT_DLLPUBLIC OGenericUnoDialog + :public OGenericUnoDialogBase + ,public ::comphelper::OMutexAndBroadcastHelper + ,public ::comphelper::OPropertyContainer + { + protected: + std::unique_ptr m_xDialog; /// the dialog to execute + bool m_bExecuting : 1; /// we're currently executing the dialog + bool m_bTitleAmbiguous : 1; /// m_sTitle has not been set yet + bool m_bInitialized : 1; /// has "initialize" been called? + + // + OUString m_sTitle; /// title of the dialog + css::uno::Reference m_xParent; /// parent window + // + + css::uno::Reference m_aContext; + + protected: + OGenericUnoDialog(const css::uno::Reference< css::uno::XComponentContext >& _rxContext); + virtual ~OGenericUnoDialog() override; + + public: + // UNO + DECLARE_UNO3_DEFAULTS(OGenericUnoDialog, OGenericUnoDialogBase) + virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type& _rType) override; + + // XTypeProvider + virtual css::uno::Sequence SAL_CALL getTypes( ) override; + virtual css::uno::Sequence SAL_CALL getImplementationId( ) override = 0; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override = 0; + virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + virtual css::uno::Sequence SAL_CALL getSupportedServiceNames() override = 0; + + // OPropertySetHelper + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const css::uno::Any& rValue ) override; + virtual sal_Bool SAL_CALL convertFastPropertyValue( css::uno::Any& rConvertedValue, css::uno::Any& rOldValue, sal_Int32 nHandle, const css::uno::Any& rValue) override; + + // XExecutableDialog + virtual void SAL_CALL setTitle( const OUString& aTitle ) override; + virtual sal_Int16 SAL_CALL execute( ) override; + + // XInitialization + virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& aArguments ) override; + + protected: + /** create the concrete dialog instance. Note that m_aMutex is not locked when this method get called, + but the application-wide solar mutex is (to guard the not thread-safe ctor of the dialog). + @param pParent the parent window for the new dialog + */ + virtual std::unique_ptr createDialog(const css::uno::Reference& rParent) = 0; + + /// called to destroy the dialog used. deletes m_pDialog and resets it to NULL + void destroyDialog(); + + /** called after the dialog has been executed + @param _nExecutionResult the execution result as returned by Dialog::Execute + */ + virtual void executedDialog(sal_Int16 /*_nExecutionResult*/) { } + + /** smaller form of initialize.

    + The initialize method is called with a sequence of com.sun.star.uno::Any's, + which is split up into the single elements, which are passed to implInitialize. The default implementation + tries to extract a com.sun.star.beans::PropertyValue from the value a pass it to the + com.sun.star.beans::XPropertySet interface of the object. + */ + virtual void implInitialize(const css::uno::Any& _rValue); + + private: + + /** ensures that m_pDialog is not + + This method does nothing if m_pDialog is already non-. Else, it calls createDialog and does + all necessary initializations of the new dialog instance. + + @precond + m_aMutex is locked + + @return + if and only if m_pDialog is non- upon returning from the method. Note that the only + case where m_pDialog is is when createDialog returned , which is will fire an assertion + in non-product builds. + */ + bool impl_ensureDialog_lck(); + }; + + /// helper class for guarding access to methods of an OGenericUnoDialog + class UnoDialogEntryGuard + { + public: + UnoDialogEntryGuard( OGenericUnoDialog& _rDialog ) + :m_aGuard( _rDialog.GetMutex() ) + { + } + + private: + ::osl::MutexGuard m_aGuard; + }; + + +} // namespace svt + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/helpids.h b/include/svtools/helpids.h new file mode 100644 index 000000000..d6b1da9e7 --- /dev/null +++ b/include/svtools/helpids.h @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +inline constexpr OStringLiteral HID_FILEDLG_LINK_CB = "SVT_HID_FILEDLG_LINK_CB"; +inline constexpr OStringLiteral HID_FILEDLG_PREVIEW_CB = "SVT_HID_FILEDLG_PREVIEW_CB"; +inline constexpr OStringLiteral HID_FILEDLG_STANDARD = "SVT_HID_FILEDLG_STANDARD"; + +// help ids for the different modi of the file picker dialog +inline constexpr OStringLiteral HID_FILESAVE_LEVELUP = "SVT_HID_FILESAVE_LEVELUP"; +inline constexpr OStringLiteral HID_FILESAVE_CREATEDIRECTORY = "SVT_HID_FILESAVE_CREATEDIRECTORY"; +inline constexpr OStringLiteral HID_FILESAVE_FILEVIEW = "SVT_HID_FILESAVE_FILEVIEW"; +inline constexpr OStringLiteral HID_FILESAVE_TEMPLATE = "SVT_HID_FILESAVE_TEMPLATE"; +inline constexpr OStringLiteral HID_FILESAVE_FILEURL = "SVT_HID_FILESAVE_FILEURL"; +inline constexpr OStringLiteral HID_FILESAVE_FILETYPE = "SVT_HID_FILESAVE_FILETYPE"; +inline constexpr OStringLiteral HID_FILESAVE_DOSAVE = "SVT_HID_FILESAVE_DOSAVE"; +inline constexpr OStringLiteral HID_FILESAVE_AUTOEXTENSION = "SVT_HID_FILESAVE_AUTOEXTENSION"; +inline constexpr OStringLiteral HID_FILESAVE_SAVEWITHPASSWORD = "SVT_HID_FILESAVE_SAVEWITHPASSWORD"; +inline constexpr OStringLiteral HID_FILESAVE_CUSTOMIZEFILTER = "SVT_HID_FILESAVE_CUSTOMIZEFILTER"; +inline constexpr OStringLiteral HID_FILESAVE_SELECTION = "SVT_HID_FILESAVE_SELECTION"; +inline constexpr OStringLiteral HID_FILESAVE_DIALOG = "SVT_HID_FILESAVE_DIALOG"; +inline constexpr OStringLiteral HID_FILESAVE_DOPLAY = "SVT_HID_FILESAVE_DOPLAY"; + +inline constexpr OStringLiteral HID_FILEOPEN_LEVELUP = "SVT_HID_FILEOPEN_LEVELUP"; +inline constexpr OStringLiteral HID_FILEOPEN_READONLY = "SVT_HID_FILEOPEN_READONLY"; +inline constexpr OStringLiteral HID_FILEOPEN_VERSION = "SVT_HID_FILEOPEN_VERSION"; +inline constexpr OStringLiteral HID_FILEOPEN_IMAGE_TEMPLATE = "SVT_HID_FILEOPEN_IMAGE_TEMPLATE"; +inline constexpr OStringLiteral HID_FILEOPEN_IMAGE_ANCHOR = "SVT_HID_FILEOPEN_IMAGE_ANCHOR"; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/htmlcfg.hxx b/include/svtools/htmlcfg.hxx new file mode 100644 index 000000000..1ed542867 --- /dev/null +++ b/include/svtools/htmlcfg.hxx @@ -0,0 +1,43 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include + +#define HTML_FONT_COUNT 7 + +// !!!be aware!!!: the following defines are _not_ used as values in the configuration file +// this is because of compatibility reasons +#define HTML_CFG_MSIE 1 // Internet Explorer +#define HTML_CFG_WRITER 2 // Writer +#define HTML_CFG_NS40 3 // Netscape 4.0 + +#define HTML_CFG_MAX HTML_CFG_NS40 + +namespace SvxHtmlOptions +{ +SVT_DLLPUBLIC sal_uInt16 GetFontSize(sal_uInt16 nPos); + +SVT_DLLPUBLIC sal_uInt16 GetExportMode(); + +SVT_DLLPUBLIC bool IsPrintLayoutExtension(); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/htmlkywd.hxx b/include/svtools/htmlkywd.hxx new file mode 100644 index 000000000..9a84cddd3 --- /dev/null +++ b/include/svtools/htmlkywd.hxx @@ -0,0 +1,689 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +// tdf#126879 - drop obsolete DOCTYPE HTML 4.0 and use the HTML5 DOCTYPE declaration +#define OOO_STRING_SVTOOLS_HTML_doctype5 "html" +#define OOO_STRING_SVTOOLS_XHTML_doctype11 \ + "html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" " \ + "\"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\"" + +// these are only switched on +#define OOO_STRING_SVTOOLS_HTML_area "area" +#define OOO_STRING_SVTOOLS_HTML_base "base" +#define OOO_STRING_SVTOOLS_HTML_comment "!--" +#define OOO_STRING_SVTOOLS_HTML_doctype "!DOCTYPE" +#define OOO_STRING_SVTOOLS_HTML_cdata "![cdata[" +#define OOO_STRING_SVTOOLS_HTML_embed "embed" +#define OOO_STRING_SVTOOLS_HTML_horzrule "hr" +#define OOO_STRING_SVTOOLS_HTML_image "img" +#define OOO_STRING_SVTOOLS_HTML_input "input" +#define OOO_STRING_SVTOOLS_HTML_linebreak "br" +#define OOO_STRING_SVTOOLS_HTML_li "li" +#define OOO_STRING_SVTOOLS_HTML_link "link" +#define OOO_STRING_SVTOOLS_HTML_meta "meta" +#define OOO_STRING_SVTOOLS_HTML_nobr "nobr" +#define OOO_STRING_SVTOOLS_HTML_option "option" +#define OOO_STRING_SVTOOLS_HTML_param "param" +#define OOO_STRING_SVTOOLS_HTML_spacer "spacer" + +// these are switched off again +#define OOO_STRING_SVTOOLS_HTML_abbreviation "abbrev" +#define OOO_STRING_SVTOOLS_HTML_acronym "acronym" +#define OOO_STRING_SVTOOLS_HTML_address "address" +#define OOO_STRING_SVTOOLS_HTML_anchor "a" +#define OOO_STRING_SVTOOLS_HTML_applet "applet" +#define OOO_STRING_SVTOOLS_HTML_author "au" +#define OOO_STRING_SVTOOLS_HTML_banner "banner" +#define OOO_STRING_SVTOOLS_HTML_basefont "basefont" +#define OOO_STRING_SVTOOLS_HTML_bigprint "big" +#define OOO_STRING_SVTOOLS_HTML_blink "blink" +#define OOO_STRING_SVTOOLS_HTML_blockquote "blockquote" +#define OOO_STRING_SVTOOLS_HTML_blockquote30 "bq" +#define OOO_STRING_SVTOOLS_HTML_body "body" +#define OOO_STRING_SVTOOLS_HTML_bold "b" +#define OOO_STRING_SVTOOLS_HTML_caption "caption" +#define OOO_STRING_SVTOOLS_HTML_center "center" +#define OOO_STRING_SVTOOLS_HTML_citation "cite" +#define OOO_STRING_SVTOOLS_HTML_code "code" +#define OOO_STRING_SVTOOLS_HTML_col "col" +#define OOO_STRING_SVTOOLS_HTML_colgroup "colgroup" +#define OOO_STRING_SVTOOLS_HTML_credit "credit" +#define OOO_STRING_SVTOOLS_HTML_dd "dd" +#define OOO_STRING_SVTOOLS_HTML_deflist "dl" +#define OOO_STRING_SVTOOLS_HTML_deletedtext "del" +#define OOO_STRING_SVTOOLS_HTML_dirlist "dir" +#define OOO_STRING_SVTOOLS_HTML_division "div" +#define OOO_STRING_SVTOOLS_HTML_dt "dt" +#define OOO_STRING_SVTOOLS_HTML_emphasis "em" +#define OOO_STRING_SVTOOLS_HTML_figure "fig" +#define OOO_STRING_SVTOOLS_HTML_font "font" +#define OOO_STRING_SVTOOLS_HTML_footnote "fn" +#define OOO_STRING_SVTOOLS_HTML_form "form" +#define OOO_STRING_SVTOOLS_HTML_frame "frame" +#define OOO_STRING_SVTOOLS_HTML_frameset "frameset" +#define OOO_STRING_SVTOOLS_HTML_head1 "h1" +#define OOO_STRING_SVTOOLS_HTML_head2 "h2" +#define OOO_STRING_SVTOOLS_HTML_head3 "h3" +#define OOO_STRING_SVTOOLS_HTML_head4 "h4" +#define OOO_STRING_SVTOOLS_HTML_head5 "h5" +#define OOO_STRING_SVTOOLS_HTML_head6 "h6" +#define OOO_STRING_SVTOOLS_HTML_head "head" +#define OOO_STRING_SVTOOLS_HTML_html "html" +#define OOO_STRING_SVTOOLS_HTML_iframe "iframe" +#define OOO_STRING_SVTOOLS_HTML_insertedtext "ins" +#define OOO_STRING_SVTOOLS_HTML_italic "i" +#define OOO_STRING_SVTOOLS_HTML_keyboard "kbd" +#define OOO_STRING_SVTOOLS_HTML_language "lang" +#define OOO_STRING_SVTOOLS_HTML_listheader "lh" +#define OOO_STRING_SVTOOLS_HTML_map "map" +#define OOO_STRING_SVTOOLS_HTML_menulist "menu" +#define OOO_STRING_SVTOOLS_HTML_multicol "multicol" +#define OOO_STRING_SVTOOLS_HTML_noembed "noembed" +#define OOO_STRING_SVTOOLS_HTML_noframe "noframe" +#define OOO_STRING_SVTOOLS_HTML_noframes "noframes" +#define OOO_STRING_SVTOOLS_HTML_noscript "noscript" +#define OOO_STRING_SVTOOLS_HTML_note "note" +#define OOO_STRING_SVTOOLS_HTML_object "object" +#define OOO_STRING_SVTOOLS_HTML_orderlist "ol" +#define OOO_STRING_SVTOOLS_HTML_parabreak "p" +#define OOO_STRING_SVTOOLS_HTML_person "person" +#define OOO_STRING_SVTOOLS_HTML_plaintext "t" +#define OOO_STRING_SVTOOLS_HTML_preformtxt "pre" +#define OOO_STRING_SVTOOLS_HTML_sample "samp" +#define OOO_STRING_SVTOOLS_HTML_script "script" +#define OOO_STRING_SVTOOLS_HTML_select "select" +#define OOO_STRING_SVTOOLS_HTML_shortquote "q" +#define OOO_STRING_SVTOOLS_HTML_smallprint "small" +#define OOO_STRING_SVTOOLS_HTML_span "span" +#define OOO_STRING_SVTOOLS_HTML_strikethrough "s" +#define OOO_STRING_SVTOOLS_HTML_strong "strong" +#define OOO_STRING_SVTOOLS_HTML_style "style" +#define OOO_STRING_SVTOOLS_HTML_subscript "sub" +#define OOO_STRING_SVTOOLS_HTML_superscript "sup" +#define OOO_STRING_SVTOOLS_HTML_table "table" +#define OOO_STRING_SVTOOLS_HTML_tablerow "tr" +#define OOO_STRING_SVTOOLS_HTML_tabledata "td" +#define OOO_STRING_SVTOOLS_HTML_tableheader "th" +#define OOO_STRING_SVTOOLS_HTML_tbody "tbody" +#define OOO_STRING_SVTOOLS_HTML_teletype "tt" +#define OOO_STRING_SVTOOLS_HTML_textarea "textarea" +#define OOO_STRING_SVTOOLS_HTML_tfoot "tfoot" +#define OOO_STRING_SVTOOLS_HTML_thead "thead" +#define OOO_STRING_SVTOOLS_HTML_title "title" +#define OOO_STRING_SVTOOLS_HTML_underline "u" +#define OOO_STRING_SVTOOLS_HTML_unorderlist "ul" +#define OOO_STRING_SVTOOLS_HTML_variable "var" + +// obsolete features +#define OOO_STRING_SVTOOLS_HTML_xmp "xmp" +#define OOO_STRING_SVTOOLS_HTML_listing "listing" + +// proposed features +#define OOO_STRING_SVTOOLS_HTML_definstance "dfn" +#define OOO_STRING_SVTOOLS_HTML_strike "strike" +#define OOO_STRING_SVTOOLS_HTML_comment2 "comment" +#define OOO_STRING_SVTOOLS_HTML_marquee "marquee" +#define OOO_STRING_SVTOOLS_HTML_plaintext2 "plaintext" +#define OOO_STRING_SVTOOLS_HTML_sdfield "sdfield" + +// names for all characters +#define OOO_STRING_SVTOOLS_HTML_C_lt "lt" +#define OOO_STRING_SVTOOLS_HTML_C_gt "gt" +#define OOO_STRING_SVTOOLS_HTML_C_amp "amp" +#define OOO_STRING_SVTOOLS_HTML_C_quot "quot" +#define OOO_STRING_SVTOOLS_HTML_C_Aacute "Aacute" +#define OOO_STRING_SVTOOLS_HTML_C_Agrave "Agrave" +#define OOO_STRING_SVTOOLS_HTML_C_Acirc "Acirc" +#define OOO_STRING_SVTOOLS_HTML_C_Atilde "Atilde" +#define OOO_STRING_SVTOOLS_HTML_C_Aring "Aring" +#define OOO_STRING_SVTOOLS_HTML_C_Auml "Auml" +#define OOO_STRING_SVTOOLS_HTML_C_AElig "AElig" +#define OOO_STRING_SVTOOLS_HTML_C_Ccedil "Ccedil" +#define OOO_STRING_SVTOOLS_HTML_C_Eacute "Eacute" +#define OOO_STRING_SVTOOLS_HTML_C_Egrave "Egrave" +#define OOO_STRING_SVTOOLS_HTML_C_Ecirc "Ecirc" +#define OOO_STRING_SVTOOLS_HTML_C_Euml "Euml" +#define OOO_STRING_SVTOOLS_HTML_C_Iacute "Iacute" +#define OOO_STRING_SVTOOLS_HTML_C_Igrave "Igrave" +#define OOO_STRING_SVTOOLS_HTML_C_Icirc "Icirc" +#define OOO_STRING_SVTOOLS_HTML_C_Iuml "Iuml" +#define OOO_STRING_SVTOOLS_HTML_C_ETH "ETH" +#define OOO_STRING_SVTOOLS_HTML_C_Ntilde "Ntilde" +#define OOO_STRING_SVTOOLS_HTML_C_Oacute "Oacute" +#define OOO_STRING_SVTOOLS_HTML_C_Ograve "Ograve" +#define OOO_STRING_SVTOOLS_HTML_C_Ocirc "Ocirc" +#define OOO_STRING_SVTOOLS_HTML_C_Otilde "Otilde" +#define OOO_STRING_SVTOOLS_HTML_C_Ouml "Ouml" +#define OOO_STRING_SVTOOLS_HTML_C_Oslash "Oslash" +#define OOO_STRING_SVTOOLS_HTML_C_Uacute "Uacute" +#define OOO_STRING_SVTOOLS_HTML_C_Ugrave "Ugrave" +#define OOO_STRING_SVTOOLS_HTML_C_Ucirc "Ucirc" +#define OOO_STRING_SVTOOLS_HTML_C_Uuml "Uuml" +#define OOO_STRING_SVTOOLS_HTML_C_Yacute "Yacute" +#define OOO_STRING_SVTOOLS_HTML_C_THORN "THORN" +#define OOO_STRING_SVTOOLS_HTML_C_szlig "szlig" +#define OOO_STRING_SVTOOLS_HTML_S_aacute "aacute" +#define OOO_STRING_SVTOOLS_HTML_S_agrave "agrave" +#define OOO_STRING_SVTOOLS_HTML_S_acirc "acirc" +#define OOO_STRING_SVTOOLS_HTML_S_atilde "atilde" +#define OOO_STRING_SVTOOLS_HTML_S_aring "aring" +#define OOO_STRING_SVTOOLS_HTML_S_auml "auml" +#define OOO_STRING_SVTOOLS_HTML_S_aelig "aelig" +#define OOO_STRING_SVTOOLS_HTML_S_ccedil "ccedil" +#define OOO_STRING_SVTOOLS_HTML_S_eacute "eacute" +#define OOO_STRING_SVTOOLS_HTML_S_egrave "egrave" +#define OOO_STRING_SVTOOLS_HTML_S_ecirc "ecirc" +#define OOO_STRING_SVTOOLS_HTML_S_euml "euml" +#define OOO_STRING_SVTOOLS_HTML_S_iacute "iacute" +#define OOO_STRING_SVTOOLS_HTML_S_igrave "igrave" +#define OOO_STRING_SVTOOLS_HTML_S_icirc "icirc" +#define OOO_STRING_SVTOOLS_HTML_S_iuml "iuml" +#define OOO_STRING_SVTOOLS_HTML_S_eth "eth" +#define OOO_STRING_SVTOOLS_HTML_S_ntilde "ntilde" +#define OOO_STRING_SVTOOLS_HTML_S_oacute "oacute" +#define OOO_STRING_SVTOOLS_HTML_S_ograve "ograve" +#define OOO_STRING_SVTOOLS_HTML_S_ocirc "ocirc" +#define OOO_STRING_SVTOOLS_HTML_S_otilde "otilde" +#define OOO_STRING_SVTOOLS_HTML_S_ouml "ouml" +#define OOO_STRING_SVTOOLS_HTML_S_oslash "oslash" +#define OOO_STRING_SVTOOLS_HTML_S_uacute "uacute" +#define OOO_STRING_SVTOOLS_HTML_S_ugrave "ugrave" +#define OOO_STRING_SVTOOLS_HTML_S_ucirc "ucirc" +#define OOO_STRING_SVTOOLS_HTML_S_uuml "uuml" +#define OOO_STRING_SVTOOLS_HTML_S_yacute "yacute" +#define OOO_STRING_SVTOOLS_HTML_S_thorn "thorn" +#define OOO_STRING_SVTOOLS_HTML_S_yuml "yuml" +#define OOO_STRING_SVTOOLS_HTML_S_acute "acute" +#define OOO_STRING_SVTOOLS_HTML_S_brvbar "brvbar" +#define OOO_STRING_SVTOOLS_HTML_S_cedil "cedil" +#define OOO_STRING_SVTOOLS_HTML_S_cent "cent" +#define OOO_STRING_SVTOOLS_HTML_S_copy "copy" +#define OOO_STRING_SVTOOLS_HTML_S_curren "curren" +#define OOO_STRING_SVTOOLS_HTML_S_deg "deg" +#define OOO_STRING_SVTOOLS_HTML_S_divide "divide" +#define OOO_STRING_SVTOOLS_HTML_S_frac12 "frac12" +#define OOO_STRING_SVTOOLS_HTML_S_frac14 "frac14" +#define OOO_STRING_SVTOOLS_HTML_S_frac34 "frac34" +#define OOO_STRING_SVTOOLS_HTML_S_iexcl "iexcl" +#define OOO_STRING_SVTOOLS_HTML_S_iquest "iquest" +#define OOO_STRING_SVTOOLS_HTML_S_laquo "laquo" +#define OOO_STRING_SVTOOLS_HTML_S_macr "macr" +#define OOO_STRING_SVTOOLS_HTML_S_micro "micro" +#define OOO_STRING_SVTOOLS_HTML_S_middot "middot" +#define OOO_STRING_SVTOOLS_HTML_S_nbsp "nbsp" +#define OOO_STRING_SVTOOLS_HTML_S_not "not" +#define OOO_STRING_SVTOOLS_HTML_S_ordf "ordf" +#define OOO_STRING_SVTOOLS_HTML_S_ordm "ordm" +#define OOO_STRING_SVTOOLS_HTML_S_para "para" +#define OOO_STRING_SVTOOLS_HTML_S_plusmn "plusmn" +#define OOO_STRING_SVTOOLS_HTML_S_pound "pound" +#define OOO_STRING_SVTOOLS_HTML_S_raquo "raquo" +#define OOO_STRING_SVTOOLS_HTML_S_reg "reg" +#define OOO_STRING_SVTOOLS_HTML_S_sect "sect" +#define OOO_STRING_SVTOOLS_HTML_S_shy "shy" +#define OOO_STRING_SVTOOLS_HTML_S_sup1 "sup1" +#define OOO_STRING_SVTOOLS_HTML_S_sup2 "sup2" +#define OOO_STRING_SVTOOLS_HTML_S_sup3 "sup3" +#define OOO_STRING_SVTOOLS_HTML_S_times "times" +#define OOO_STRING_SVTOOLS_HTML_S_uml "uml" +#define OOO_STRING_SVTOOLS_HTML_S_yen "yen" + +// HTML4 +#define OOO_STRING_SVTOOLS_HTML_S_alefsym "alefsym" +#define OOO_STRING_SVTOOLS_HTML_S_Alpha "Alpha" +#define OOO_STRING_SVTOOLS_HTML_S_alpha "alpha" +#define OOO_STRING_SVTOOLS_HTML_S_and "and" +#define OOO_STRING_SVTOOLS_HTML_S_ang "ang" +#define OOO_STRING_SVTOOLS_HTML_S_asymp "asymp" +#define OOO_STRING_SVTOOLS_HTML_S_bdquo "bdquo" +#define OOO_STRING_SVTOOLS_HTML_S_Beta "Beta" +#define OOO_STRING_SVTOOLS_HTML_S_beta "beta" +#define OOO_STRING_SVTOOLS_HTML_S_bull "bull" +#define OOO_STRING_SVTOOLS_HTML_S_cap "cap" +#define OOO_STRING_SVTOOLS_HTML_S_chi "chi" +#define OOO_STRING_SVTOOLS_HTML_S_Chi "Chi" +#define OOO_STRING_SVTOOLS_HTML_S_circ "circ" +#define OOO_STRING_SVTOOLS_HTML_S_clubs "clubs" +#define OOO_STRING_SVTOOLS_HTML_S_cong "cong" +#define OOO_STRING_SVTOOLS_HTML_S_crarr "crarr" +#define OOO_STRING_SVTOOLS_HTML_S_cup "cup" +#define OOO_STRING_SVTOOLS_HTML_S_dagger "dagger" +#define OOO_STRING_SVTOOLS_HTML_S_Dagger "Dagger" +#define OOO_STRING_SVTOOLS_HTML_S_darr "darr" +#define OOO_STRING_SVTOOLS_HTML_S_dArr "dArr" +#define OOO_STRING_SVTOOLS_HTML_S_Delta "Delta" +#define OOO_STRING_SVTOOLS_HTML_S_delta "delta" +#define OOO_STRING_SVTOOLS_HTML_S_diams "diams" +#define OOO_STRING_SVTOOLS_HTML_S_empty "empty" +#define OOO_STRING_SVTOOLS_HTML_S_emsp "emsp" +#define OOO_STRING_SVTOOLS_HTML_S_ensp "ensp" +#define OOO_STRING_SVTOOLS_HTML_S_Epsilon "Epsilon" +#define OOO_STRING_SVTOOLS_HTML_S_epsilon "epsilon" +#define OOO_STRING_SVTOOLS_HTML_S_equiv "equiv" +#define OOO_STRING_SVTOOLS_HTML_S_Eta "Eta" +#define OOO_STRING_SVTOOLS_HTML_S_eta "eta" +#define OOO_STRING_SVTOOLS_HTML_S_euro "euro" +#define OOO_STRING_SVTOOLS_HTML_S_exist "exist" +#define OOO_STRING_SVTOOLS_HTML_S_fnof "fnof" +#define OOO_STRING_SVTOOLS_HTML_S_forall "forall" +#define OOO_STRING_SVTOOLS_HTML_S_frasl "frasl" +#define OOO_STRING_SVTOOLS_HTML_S_Gamma "Gamma" +#define OOO_STRING_SVTOOLS_HTML_S_gamma "gamma" +#define OOO_STRING_SVTOOLS_HTML_S_ge "ge" +#define OOO_STRING_SVTOOLS_HTML_S_harr "harr" +#define OOO_STRING_SVTOOLS_HTML_S_hArr "hArr" +#define OOO_STRING_SVTOOLS_HTML_S_hearts "hearts" +#define OOO_STRING_SVTOOLS_HTML_S_hellip "hellip" +#define OOO_STRING_SVTOOLS_HTML_S_image "image" +#define OOO_STRING_SVTOOLS_HTML_S_infin "infin" +#define OOO_STRING_SVTOOLS_HTML_S_int "int" +#define OOO_STRING_SVTOOLS_HTML_S_Iota "Iota" +#define OOO_STRING_SVTOOLS_HTML_S_iota "iota" +#define OOO_STRING_SVTOOLS_HTML_S_isin "isin" +#define OOO_STRING_SVTOOLS_HTML_S_Kappa "Kappa" +#define OOO_STRING_SVTOOLS_HTML_S_kappa "kappa" +#define OOO_STRING_SVTOOLS_HTML_S_Lambda "Lambda" +#define OOO_STRING_SVTOOLS_HTML_S_lambda "lambda" +#define OOO_STRING_SVTOOLS_HTML_S_lang "lang" +#define OOO_STRING_SVTOOLS_HTML_S_larr "larr" +#define OOO_STRING_SVTOOLS_HTML_S_lArr "lArr" +#define OOO_STRING_SVTOOLS_HTML_S_lceil "lceil" +#define OOO_STRING_SVTOOLS_HTML_S_ldquo "ldquo" +#define OOO_STRING_SVTOOLS_HTML_S_le "le" +#define OOO_STRING_SVTOOLS_HTML_S_lfloor "lfloor" +#define OOO_STRING_SVTOOLS_HTML_S_lowast "lowast" +#define OOO_STRING_SVTOOLS_HTML_S_loz "loz" +#define OOO_STRING_SVTOOLS_HTML_S_lrm "lrm" +#define OOO_STRING_SVTOOLS_HTML_S_lsaquo "lsaquo" +#define OOO_STRING_SVTOOLS_HTML_S_lsquo "lsquo" +#define OOO_STRING_SVTOOLS_HTML_S_mdash "mdash" +#define OOO_STRING_SVTOOLS_HTML_S_minus "minus" +#define OOO_STRING_SVTOOLS_HTML_S_Mu "Mu" +#define OOO_STRING_SVTOOLS_HTML_S_mu "mu" +#define OOO_STRING_SVTOOLS_HTML_S_nabla "nabla" +#define OOO_STRING_SVTOOLS_HTML_S_ndash "ndash" +#define OOO_STRING_SVTOOLS_HTML_S_ne "ne" +#define OOO_STRING_SVTOOLS_HTML_S_ni "ni" +#define OOO_STRING_SVTOOLS_HTML_S_notin "notin" +#define OOO_STRING_SVTOOLS_HTML_S_nsub "nsub" +#define OOO_STRING_SVTOOLS_HTML_S_Nu "Nu" +#define OOO_STRING_SVTOOLS_HTML_S_nu "nu" +#define OOO_STRING_SVTOOLS_HTML_S_OElig "OElig" +#define OOO_STRING_SVTOOLS_HTML_S_oelig "oelig" +#define OOO_STRING_SVTOOLS_HTML_S_oline "oline" +#define OOO_STRING_SVTOOLS_HTML_S_Omega "Omega" +#define OOO_STRING_SVTOOLS_HTML_S_omega "omega" +#define OOO_STRING_SVTOOLS_HTML_S_Omicron "Omicron" +#define OOO_STRING_SVTOOLS_HTML_S_omicron "omicron" +#define OOO_STRING_SVTOOLS_HTML_S_oplus "oplus" +#define OOO_STRING_SVTOOLS_HTML_S_or "or" +#define OOO_STRING_SVTOOLS_HTML_S_otimes "otimes" +#define OOO_STRING_SVTOOLS_HTML_S_part "part" +#define OOO_STRING_SVTOOLS_HTML_S_permil "permil" +#define OOO_STRING_SVTOOLS_HTML_S_perp "perp" +#define OOO_STRING_SVTOOLS_HTML_S_Phi "Phi" +#define OOO_STRING_SVTOOLS_HTML_S_phi "phi" +#define OOO_STRING_SVTOOLS_HTML_S_Pi "Pi" +#define OOO_STRING_SVTOOLS_HTML_S_pi "pi" +#define OOO_STRING_SVTOOLS_HTML_S_piv "piv" +#define OOO_STRING_SVTOOLS_HTML_S_prime "prime" +#define OOO_STRING_SVTOOLS_HTML_S_Prime "Prime" +#define OOO_STRING_SVTOOLS_HTML_S_prod "prod" +#define OOO_STRING_SVTOOLS_HTML_S_prop "prop" +#define OOO_STRING_SVTOOLS_HTML_S_Psi "Psi" +#define OOO_STRING_SVTOOLS_HTML_S_psi "psi" +#define OOO_STRING_SVTOOLS_HTML_S_radic "radic" +#define OOO_STRING_SVTOOLS_HTML_S_rang "rang" +#define OOO_STRING_SVTOOLS_HTML_S_rarr "rarr" +#define OOO_STRING_SVTOOLS_HTML_S_rArr "rArr" +#define OOO_STRING_SVTOOLS_HTML_S_rceil "rceil" +#define OOO_STRING_SVTOOLS_HTML_S_rdquo "rdquo" +#define OOO_STRING_SVTOOLS_HTML_S_real "real" +#define OOO_STRING_SVTOOLS_HTML_S_rfloor "rfloor" +#define OOO_STRING_SVTOOLS_HTML_S_Rho "Rho" +#define OOO_STRING_SVTOOLS_HTML_S_rho "rho" +#define OOO_STRING_SVTOOLS_HTML_S_rlm "rlm" +#define OOO_STRING_SVTOOLS_HTML_S_rsaquo "rsaquo" +#define OOO_STRING_SVTOOLS_HTML_S_rsquo "rsquo" +#define OOO_STRING_SVTOOLS_HTML_S_sbquo "sbquo" +#define OOO_STRING_SVTOOLS_HTML_S_Scaron "Scaron" +#define OOO_STRING_SVTOOLS_HTML_S_scaron "scaron" +#define OOO_STRING_SVTOOLS_HTML_S_sdot "sdot" +#define OOO_STRING_SVTOOLS_HTML_S_Sigma "Sigma" +#define OOO_STRING_SVTOOLS_HTML_S_sigma "sigma" +#define OOO_STRING_SVTOOLS_HTML_S_sigmaf "sigmaf" +#define OOO_STRING_SVTOOLS_HTML_S_sim "sim" +#define OOO_STRING_SVTOOLS_HTML_S_spades "spades" +#define OOO_STRING_SVTOOLS_HTML_S_sub "sub" +#define OOO_STRING_SVTOOLS_HTML_S_sube "sube" +#define OOO_STRING_SVTOOLS_HTML_S_sum "sum" +#define OOO_STRING_SVTOOLS_HTML_S_sup "sup" +#define OOO_STRING_SVTOOLS_HTML_S_supe "supe" +#define OOO_STRING_SVTOOLS_HTML_S_Tau "Tau" +#define OOO_STRING_SVTOOLS_HTML_S_tau "tau" +#define OOO_STRING_SVTOOLS_HTML_S_there4 "there4" +#define OOO_STRING_SVTOOLS_HTML_S_Theta "Theta" +#define OOO_STRING_SVTOOLS_HTML_S_theta "theta" +#define OOO_STRING_SVTOOLS_HTML_S_thetasym "thetasym" +#define OOO_STRING_SVTOOLS_HTML_S_thinsp "thinsp" +#define OOO_STRING_SVTOOLS_HTML_S_tilde "tilde" +#define OOO_STRING_SVTOOLS_HTML_S_trade "trade" +#define OOO_STRING_SVTOOLS_HTML_S_uarr "uarr" +#define OOO_STRING_SVTOOLS_HTML_S_uArr "uArr" +#define OOO_STRING_SVTOOLS_HTML_S_upsih "upsih" +#define OOO_STRING_SVTOOLS_HTML_S_Upsilon "Upsilon" +#define OOO_STRING_SVTOOLS_HTML_S_upsilon "upsilon" +#define OOO_STRING_SVTOOLS_HTML_S_weierp "weierp" +#define OOO_STRING_SVTOOLS_HTML_S_Xi "Xi" +#define OOO_STRING_SVTOOLS_HTML_S_xi "xi" +#define OOO_STRING_SVTOOLS_HTML_S_Yuml "Yuml" +#define OOO_STRING_SVTOOLS_HTML_S_Zeta "Zeta" +#define OOO_STRING_SVTOOLS_HTML_S_zeta "zeta" +#define OOO_STRING_SVTOOLS_HTML_S_zwj "zwj" +#define OOO_STRING_SVTOOLS_HTML_S_zwnj "zwnj" + +// HTML attribute tokens (=options) + +// attributes without value +#define OOO_STRING_SVTOOLS_HTML_O_checked "checked" +#define OOO_STRING_SVTOOLS_HTML_O_compact "compact" +#define OOO_STRING_SVTOOLS_HTML_O_declare "declare" +#define OOO_STRING_SVTOOLS_HTML_O_disabled "disabled" +#define OOO_STRING_SVTOOLS_HTML_O_ismap "ismap" +#define OOO_STRING_SVTOOLS_HTML_O_mayscript "mayscript" +#define OOO_STRING_SVTOOLS_HTML_O_multiple "multiple" +#define OOO_STRING_SVTOOLS_HTML_O_nohref "nohref" +#define OOO_STRING_SVTOOLS_HTML_O_noresize "noresize" +#define OOO_STRING_SVTOOLS_HTML_O_noshade "noshade" +#define OOO_STRING_SVTOOLS_HTML_O_nowrap "nowrap" +#define OOO_STRING_SVTOOLS_HTML_O_sdfixed "sdfixed" +#define OOO_STRING_SVTOOLS_HTML_O_selected "selected" + +// attributes with a string as value +#define OOO_STRING_SVTOOLS_HTML_O_accesskey "accesskey" +#define OOO_STRING_SVTOOLS_HTML_O_accept "accept" +#define OOO_STRING_SVTOOLS_HTML_O_alt "alt" +#define OOO_STRING_SVTOOLS_HTML_O_axis "axis" +#define OOO_STRING_SVTOOLS_HTML_O_char "char" +#define OOO_STRING_SVTOOLS_HTML_O_charset "charset" +#define OOO_STRING_SVTOOLS_HTML_O_class "class" +#define OOO_STRING_SVTOOLS_HTML_O_code "code" +#define OOO_STRING_SVTOOLS_HTML_O_codetype "codetype" +#define OOO_STRING_SVTOOLS_HTML_O_content "content" +#define OOO_STRING_SVTOOLS_HTML_O_coords "coords" +#define OOO_STRING_SVTOOLS_HTML_O_enctype "enctype" +#define OOO_STRING_SVTOOLS_HTML_O_face "face" +#define OOO_STRING_SVTOOLS_HTML_O_frameborder "frameborder" +#define OOO_STRING_SVTOOLS_HTML_O_httpequiv "http-equiv" +#define OOO_STRING_SVTOOLS_HTML_O_language "language" +#define OOO_STRING_SVTOOLS_HTML_O_name "name" +#define OOO_STRING_SVTOOLS_HTML_O_prompt "prompt" +#define OOO_STRING_SVTOOLS_HTML_O_shape "shape" +#define OOO_STRING_SVTOOLS_HTML_O_standby "standby" +#define OOO_STRING_SVTOOLS_HTML_O_style "style" +#define OOO_STRING_SVTOOLS_HTML_O_title "title" +#define OOO_STRING_SVTOOLS_HTML_O_value "value" +#define OOO_STRING_SVTOOLS_HTML_O_SDval "sdval" +#define OOO_STRING_SVTOOLS_HTML_O_SDnum "sdnum" +#define OOO_STRING_SVTOOLS_HTML_O_sdlibrary "sdlibrary" +#define OOO_STRING_SVTOOLS_HTML_O_sdmodule "sdmodule" +#define OOO_STRING_SVTOOLS_HTML_O_sdevent "sdevent-" +#define OOO_STRING_SVTOOLS_HTML_O_sdaddparam "sdaddparam-" + +// attributes with an SGML identifier as value +#define OOO_STRING_SVTOOLS_HTML_O_id "id" +#define OOO_STRING_SVTOOLS_HTML_O_target "target" +#define OOO_STRING_SVTOOLS_HTML_O_to "to" + +// attributes with a URI as value +#define OOO_STRING_SVTOOLS_HTML_O_action "action" +#define OOO_STRING_SVTOOLS_HTML_O_archive "archive" +#define OOO_STRING_SVTOOLS_HTML_O_background "background" +#define OOO_STRING_SVTOOLS_HTML_O_classid "classid" +#define OOO_STRING_SVTOOLS_HTML_O_codebase "codebase" +#define OOO_STRING_SVTOOLS_HTML_O_data "data" +#define OOO_STRING_SVTOOLS_HTML_O_href "href" +#define OOO_STRING_SVTOOLS_HTML_O_script "script" +#define OOO_STRING_SVTOOLS_HTML_O_src "src" +#define OOO_STRING_SVTOOLS_HTML_O_usemap "usemap" + +// attributes with a colour as value (all Netscape) +#define OOO_STRING_SVTOOLS_HTML_O_alink "alink" +#define OOO_STRING_SVTOOLS_HTML_O_bgcolor "bgcolor" +#define OOO_STRING_SVTOOLS_HTML_O_bordercolor "bordercolor" +#define OOO_STRING_SVTOOLS_HTML_O_bordercolorlight "bordercolorlight" +#define OOO_STRING_SVTOOLS_HTML_O_bordercolordark "bordercolordark" +#define OOO_STRING_SVTOOLS_HTML_O_color "color" +#define OOO_STRING_SVTOOLS_HTML_O_link "link" +#define OOO_STRING_SVTOOLS_HTML_O_text "text" +#define OOO_STRING_SVTOOLS_HTML_O_vlink "vlink" + +// attributes with a numerical value +#define OOO_STRING_SVTOOLS_HTML_O_border "border" +#define OOO_STRING_SVTOOLS_HTML_O_cellspacing "cellspacing" +#define OOO_STRING_SVTOOLS_HTML_O_cellpadding "cellpadding" +#define OOO_STRING_SVTOOLS_HTML_O_charoff "charoff" +#define OOO_STRING_SVTOOLS_HTML_O_colspan "colspan" +#define OOO_STRING_SVTOOLS_HTML_O_framespacing "framespacing" +#define OOO_STRING_SVTOOLS_HTML_O_gutter "gutter" +#define OOO_STRING_SVTOOLS_HTML_O_height "height" +#define OOO_STRING_SVTOOLS_HTML_O_hspace "hspace" +#define OOO_STRING_SVTOOLS_HTML_O_left "left" +#define OOO_STRING_SVTOOLS_HTML_O_loop "loop" +#define OOO_STRING_SVTOOLS_HTML_O_marginheight "marginheight" +#define OOO_STRING_SVTOOLS_HTML_O_marginwidth "marginwidth" +#define OOO_STRING_SVTOOLS_HTML_O_maxlength "maxlength" +#define OOO_STRING_SVTOOLS_HTML_O_rowspan "rowspan" +#define OOO_STRING_SVTOOLS_HTML_O_scrollamount "scrollamount" +#define OOO_STRING_SVTOOLS_HTML_O_scrolldelay "scrolldelay" +#define OOO_STRING_SVTOOLS_HTML_O_span "span" +#define OOO_STRING_SVTOOLS_HTML_O_tabindex "tabindex" +#define OOO_STRING_SVTOOLS_HTML_O_vspace "vspace" +#define OOO_STRING_SVTOOLS_HTML_O_width "width" +#define OOO_STRING_SVTOOLS_HTML_O_zindex "z-index" + +// attributes with enum values +#define OOO_STRING_SVTOOLS_HTML_O_behavior "behavior" +#define OOO_STRING_SVTOOLS_HTML_O_clear "clear" +#define OOO_STRING_SVTOOLS_HTML_O_dir "dir" +#define OOO_STRING_SVTOOLS_HTML_O_direction "direction" +#define OOO_STRING_SVTOOLS_HTML_O_format "format" +#define OOO_STRING_SVTOOLS_HTML_O_frame "frame" +#define OOO_STRING_SVTOOLS_HTML_O_lang "lang" +#define OOO_STRING_SVTOOLS_XHTML_O_lang "xml:lang" +#define OOO_STRING_SVTOOLS_HTML_O_method "method" +#define OOO_STRING_SVTOOLS_HTML_O_rel "rel" +#define OOO_STRING_SVTOOLS_HTML_O_rev "rev" +#define OOO_STRING_SVTOOLS_HTML_O_rules "rules" +#define OOO_STRING_SVTOOLS_HTML_O_scrolling "scrolling" +#define OOO_STRING_SVTOOLS_HTML_O_sdreadonly "readonly" +#define OOO_STRING_SVTOOLS_HTML_O_subtype "subtype" +#define OOO_STRING_SVTOOLS_HTML_O_type "type" +#define OOO_STRING_SVTOOLS_HTML_O_valign "valign" +#define OOO_STRING_SVTOOLS_HTML_O_valuetype "valuetype" +#define OOO_STRING_SVTOOLS_HTML_O_wrap "wrap" + +// attributes with script code as value +#define OOO_STRING_SVTOOLS_HTML_O_onblur "onblur" +#define OOO_STRING_SVTOOLS_HTML_O_onchange "onchange" +#define OOO_STRING_SVTOOLS_HTML_O_onclick "onclick" +#define OOO_STRING_SVTOOLS_HTML_O_onfocus "onfocus" +#define OOO_STRING_SVTOOLS_HTML_O_onload "onload" +#define OOO_STRING_SVTOOLS_HTML_O_onmouseover "onmouseover" +#define OOO_STRING_SVTOOLS_HTML_O_onreset "onreset" +#define OOO_STRING_SVTOOLS_HTML_O_onselect "onselect" +#define OOO_STRING_SVTOOLS_HTML_O_onsubmit "onsubmit" +#define OOO_STRING_SVTOOLS_HTML_O_onunload "onunload" +#define OOO_STRING_SVTOOLS_HTML_O_onabort "onabort" +#define OOO_STRING_SVTOOLS_HTML_O_onerror "onerror" +#define OOO_STRING_SVTOOLS_HTML_O_onmouseout "onmouseout" +#define OOO_STRING_SVTOOLS_HTML_O_SDonblur "sdonblur" +#define OOO_STRING_SVTOOLS_HTML_O_SDonchange "sdonchange" +#define OOO_STRING_SVTOOLS_HTML_O_SDonclick "sdonclick" +#define OOO_STRING_SVTOOLS_HTML_O_SDonfocus "sdonfocus" +#define OOO_STRING_SVTOOLS_HTML_O_SDonload "sdonload" +#define OOO_STRING_SVTOOLS_HTML_O_SDonmouseover "sdonmouseover" +#define OOO_STRING_SVTOOLS_HTML_O_SDonreset "sdonreset" +#define OOO_STRING_SVTOOLS_HTML_O_SDonselect "sdonselect" +#define OOO_STRING_SVTOOLS_HTML_O_SDonsubmit "sdonsubmit" +#define OOO_STRING_SVTOOLS_HTML_O_SDonunload "sdonunload" +#define OOO_STRING_SVTOOLS_HTML_O_SDonabort "sdonabort" +#define OOO_STRING_SVTOOLS_HTML_O_SDonerror "sdonerror" +#define OOO_STRING_SVTOOLS_HTML_O_SDonmouseout "sdonmouseout" + +// attributes with context-dependent values +#define OOO_STRING_SVTOOLS_HTML_O_align "align" +#define OOO_STRING_SVTOOLS_HTML_O_cols "cols" +#define OOO_STRING_SVTOOLS_HTML_O_rows "rows" +#define OOO_STRING_SVTOOLS_HTML_O_start "start" +#define OOO_STRING_SVTOOLS_HTML_O_size "size" + +// values of +#define OOO_STRING_SVTOOLS_HTML_IT_text "text" +#define OOO_STRING_SVTOOLS_HTML_IT_password "password" +#define OOO_STRING_SVTOOLS_HTML_IT_checkbox "checkbox" +#define OOO_STRING_SVTOOLS_HTML_IT_radio "radio" +#define OOO_STRING_SVTOOLS_HTML_IT_range "range" +#define OOO_STRING_SVTOOLS_HTML_IT_scribble "scribble" +#define OOO_STRING_SVTOOLS_HTML_IT_file "file" +#define OOO_STRING_SVTOOLS_HTML_IT_hidden "hidden" +#define OOO_STRING_SVTOOLS_HTML_IT_submit "submit" +#define OOO_STRING_SVTOOLS_HTML_IT_image "image" +#define OOO_STRING_SVTOOLS_HTML_IT_reset "reset" +#define OOO_STRING_SVTOOLS_HTML_IT_button "button" + +// values of +#define OOO_STRING_SVTOOLS_HTML_TF_void "void" +#define OOO_STRING_SVTOOLS_HTML_TF_above "above" +#define OOO_STRING_SVTOOLS_HTML_TF_below "below" +#define OOO_STRING_SVTOOLS_HTML_TF_hsides "hsides" +#define OOO_STRING_SVTOOLS_HTML_TF_lhs "lhs" +#define OOO_STRING_SVTOOLS_HTML_TF_rhs "rhs" +#define OOO_STRING_SVTOOLS_HTML_TF_vsides "vsides" +#define OOO_STRING_SVTOOLS_HTML_TF_box "box" +#define OOO_STRING_SVTOOLS_HTML_TF_border "border" + +// values of
    +#define OOO_STRING_SVTOOLS_HTML_TR_none "none" +#define OOO_STRING_SVTOOLS_HTML_TR_groups "groups" +#define OOO_STRING_SVTOOLS_HTML_TR_rows "rows" +#define OOO_STRING_SVTOOLS_HTML_TR_cols "cols" +#define OOO_STRING_SVTOOLS_HTML_TR_all "all" + +// values of +#define OOO_STRING_SVTOOLS_HTML_AL_left "left" +#define OOO_STRING_SVTOOLS_HTML_AL_center "center" +#define OOO_STRING_SVTOOLS_HTML_AL_middle "middle" +#define OOO_STRING_SVTOOLS_HTML_AL_right "right" +#define OOO_STRING_SVTOOLS_HTML_AL_justify "justify" +#define OOO_STRING_SVTOOLS_HTML_AL_char "char" +#define OOO_STRING_SVTOOLS_HTML_AL_all "all" + +// values of , +#define OOO_STRING_SVTOOLS_HTML_VA_top "top" +#define OOO_STRING_SVTOOLS_HTML_VA_middle "middle" +#define OOO_STRING_SVTOOLS_HTML_VA_bottom "bottom" +#define OOO_STRING_SVTOOLS_HTML_VA_baseline "baseline" +#define OOO_STRING_SVTOOLS_HTML_VA_texttop "texttop" +#define OOO_STRING_SVTOOLS_HTML_VA_absmiddle "absmiddle" +#define OOO_STRING_SVTOOLS_HTML_VA_absbottom "absbottom" + +// values of +#define OOO_STRING_SVTOOLS_HTML_SH_rect "rect" +#define OOO_STRING_SVTOOLS_HTML_SH_rectangle "rectangle" +#define OOO_STRING_SVTOOLS_HTML_SH_circ "circ" +#define OOO_STRING_SVTOOLS_HTML_SH_circle "circle" +#define OOO_STRING_SVTOOLS_HTML_SH_poly "poly" +#define OOO_STRING_SVTOOLS_HTML_SH_polygon "polygon" + +#define OOO_STRING_SVTOOLS_HTML_LG_starbasic "starbasic" +#define OOO_STRING_SVTOOLS_HTML_LG_javascript "javascript" +#define OOO_STRING_SVTOOLS_HTML_LG_javascript11 "javascript1.1" +#define OOO_STRING_SVTOOLS_HTML_LG_livescript "livescript" + +// a few values for StarBASIC-Support +#define OOO_STRING_SVTOOLS_HTML_SB_library "$LIBRARY:" +#define OOO_STRING_SVTOOLS_HTML_SB_module "$MODULE:" + +// values of +#define OOO_STRING_SVTOOLS_HTML_METHOD_get "get" +#define OOO_STRING_SVTOOLS_HTML_METHOD_post "post" + +// values of +#define OOO_STRING_SVTOOLS_HTML_META_refresh "refresh" +#define OOO_STRING_SVTOOLS_HTML_META_generator "generator" +#define OOO_STRING_SVTOOLS_HTML_META_author "author" +#define OOO_STRING_SVTOOLS_HTML_META_classification "classification" +#define OOO_STRING_SVTOOLS_HTML_META_description "description" +#define OOO_STRING_SVTOOLS_HTML_META_keywords "keywords" +#define OOO_STRING_SVTOOLS_HTML_META_changed "changed" +#define OOO_STRING_SVTOOLS_HTML_META_changedby "changedby" +#define OOO_STRING_SVTOOLS_HTML_META_created "created" +#define OOO_STRING_SVTOOLS_HTML_META_content_type "content-type" +#define OOO_STRING_SVTOOLS_HTML_META_content_script_type "content-script-type" +#define OOO_STRING_SVTOOLS_HTML_META_sdendnote "sdendnote" +#define OOO_STRING_SVTOOLS_HTML_META_sdfootnote "sdfootnote" + +// values of
      +#define OOO_STRING_SVTOOLS_HTML_ULTYPE_disc "disc" +#define OOO_STRING_SVTOOLS_HTML_ULTYPE_square "square" +#define OOO_STRING_SVTOOLS_HTML_ULTYPE_circle "circle" + +// values of +#define OOO_STRING_SVTOOLS_HTML_BEHAV_scroll "scroll" +#define OOO_STRING_SVTOOLS_HTML_BEHAV_slide "slide" +#define OOO_STRING_SVTOOLS_HTML_BEHAV_alternate "alternate" + +// values of +#define OOO_STRING_SVTOOLS_HTML_LOOP_infinite "infinite" +#define OOO_STRING_SVTOOLS_HTML_SPTYPE_block "block" +#define OOO_STRING_SVTOOLS_HTML_SPTYPE_horizontal "horizontal" +#define OOO_STRING_SVTOOLS_HTML_SPTYPE_vertical "vertical" + +// internal graphics names +#define OOO_STRING_SVTOOLS_HTML_private_image "private:image/" +#define OOO_STRING_SVTOOLS_HTML_internal_icon "internal-icon-" +#define OOO_STRING_SVTOOLS_HTML_INT_ICON_baddata "baddata" +#define OOO_STRING_SVTOOLS_HTML_INT_ICON_delayed "delayed" +#define OOO_STRING_SVTOOLS_HTML_INT_ICON_embed "embed" +#define OOO_STRING_SVTOOLS_HTML_INT_ICON_insecure "insecure" +#define OOO_STRING_SVTOOLS_HTML_INT_ICON_notfound "notfound" +#define OOO_STRING_SVTOOLS_HTML_sdendnote "sdendnote" +#define OOO_STRING_SVTOOLS_HTML_sdendnote_anc "sdendnoteanc" +#define OOO_STRING_SVTOOLS_HTML_sdendnote_sym "sdendnotesym" +#define OOO_STRING_SVTOOLS_HTML_sdfootnote "sdfootnote" +#define OOO_STRING_SVTOOLS_HTML_sdfootnote_anc "sdfootnoteanc" +#define OOO_STRING_SVTOOLS_HTML_sdfootnote_sym "sdfootnotesym" +#define OOO_STRING_SVTOOLS_HTML_FTN_anchor "anc" +#define OOO_STRING_SVTOOLS_HTML_FTN_symbol "sym" +#define OOO_STRING_SVTOOLS_HTML_WW_off "off" +#define OOO_STRING_SVTOOLS_HTML_WW_hard "hard" +#define OOO_STRING_SVTOOLS_HTML_WW_soft "soft" +#define OOO_STRING_SVTOOLS_HTML_WW_virtual "virtual" +#define OOO_STRING_SVTOOLS_HTML_WW_physical "physical" +#define OOO_STRING_SVTOOLS_HTML_on "on" +#define OOO_STRING_SVTOOLS_HTML_ET_url "application/x-www-form-urlencoded" +#define OOO_STRING_SVTOOLS_HTML_ET_multipart "multipart/form-data" +#define OOO_STRING_SVTOOLS_HTML_ET_text "text/plain" + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/htmlout.hxx b/include/svtools/htmlout.hxx new file mode 100644 index 000000000..8bd34b5f1 --- /dev/null +++ b/include/svtools/htmlout.hxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + +#include +#include +#include +#include + +class Color; +class ImageMap; +class HtmlWriter; +class SvStream; +class SvNumberFormatter; + +struct HTMLOutEvent +{ + const char *pBasicName; + const char *pJavaName; + SvMacroItemId nEvent; +}; + +struct HTMLOutFuncs +{ + SVT_DLLPUBLIC static OString ConvertStringToHTML( const OUString& sSrc, + OUString *pNonConvertableChars = nullptr ); + + SVT_DLLPUBLIC static SvStream& Out_AsciiTag( SvStream&, std::string_view rStr, + bool bOn = true); + SVT_DLLPUBLIC static SvStream& Out_Char( SvStream&, sal_uInt32 cChar, + OUString *pNonConvertableChars = nullptr ); + SVT_DLLPUBLIC static SvStream& Out_String( SvStream&, const OUString&, + OUString *pNonConvertableChars = nullptr ); + SVT_DLLPUBLIC static SvStream& Out_Hex( SvStream&, sal_uInt32 nHex, sal_uInt8 nLen ); + SVT_DLLPUBLIC static SvStream& Out_Color( SvStream&, const Color&, bool bXHTML = false ); + SVT_DLLPUBLIC static SvStream& Out_ImageMap( SvStream&, const OUString&, const ImageMap&, const OUString&, + const HTMLOutEvent *pEventTable, + bool bOutStarBasic, + const char *pDelim, + const char *pIndentArea, + const char *pIndentMap, + OUString *pNonConvertableChars = nullptr ); + SVT_DLLPUBLIC static SvStream& FlushToAscii( SvStream& ); + + SVT_DLLPUBLIC static SvStream& OutScript( SvStream& rStrm, + const OUString& rBaseURL, + std::u16string_view rSource, + const OUString& rLanguage, + ScriptType eScriptType, + const OUString& rSrc, + const OUString *pSBLibrary, + const OUString *pSBModule, + OUString *pNonConvertableChars = nullptr ); + + // the 3rd parameter is an array of HTMLOutEvents which is terminated + // by an entry that consists only of 0s + SVT_DLLPUBLIC static SvStream& Out_Events( SvStream&, const SvxMacroTableDtor&, + const HTMLOutEvent*, bool bOutStarBasic, + OUString *pNonConvertableChars = nullptr ); + + //
    + SVT_DLLPUBLIC static OString CreateTableDataOptionsValNum( + bool bValue, double fVal, sal_uInt32 nFormat, + SvNumberFormatter& rFormatter, + OUString *pNonConvertableChars = nullptr); + SVT_DLLPUBLIC static bool PrivateURLToInternalImg( OUString& rURL ); +}; + +struct HtmlWriterHelper +{ + SVT_DLLPUBLIC static void applyColor( HtmlWriter& rHtmlWriter, std::string_view aAttributeName, const Color& rColor); + SVT_DLLPUBLIC static void applyEvents(HtmlWriter& rHtmlWriter, const SvxMacroTableDtor& rMacroTable, const HTMLOutEvent* pEventTable, bool bOutStarBasic); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/htmltokn.h b/include/svtools/htmltokn.h new file mode 100644 index 000000000..9dca8a8f3 --- /dev/null +++ b/include/svtools/htmltokn.h @@ -0,0 +1,479 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace rtl { + class OUString; +}; +enum class HtmlOptionId; +enum class HtmlTokenId : sal_Int16; + +// search the char for the CharName +sal_Unicode GetHTMLCharName( std::u16string_view rName ); + +// search the TokenID for the token +SVT_DLLPUBLIC HtmlTokenId GetHTMLToken( std::u16string_view rName ); + +// search the TokenId for an attribute token +HtmlOptionId GetHTMLOption( std::u16string_view rName ); + +// search the 24-bit color for a color name (not found = SAL_MAX_UINT32) +SVT_DLLPUBLIC sal_uInt32 GetHTMLColor( const rtl::OUString& rName ); + +enum class HtmlTokenId : sal_Int16 +{ + INVALID = -1, + NONE = 0, +// always starting from 256 on, greater than a char + TEXTTOKEN = 0x100, + SINGLECHAR, + NEWPARA, + TABCHAR, + RAWDATA, + LINEFEEDCHAR, + + // these will only be turned on + AREA, // Netscape 2.0 + BASE, // HTML 3.0 + COMMENT, + CDATA, + DUMMY, // so ONOFF_START is even + DOCTYPE, + EMBED, // Netscape 2.0 ignore + HORZRULE, // ignore + IMAGE, // ignore + INPUT, // ignore + LINEBREAK, //
    ->
    + LINK, // HTML 3.0 + META, // HTML 3.0 ignore + OPTION, // ignore + PARAM, // HotJava + SPACER, // Netscape 3.0b5 // ignore + + // tokens recognised using HTML character + NONBREAKSPACE, + SOFTHYPH, + + // these will be turned back off, + // the off value is always located behind (+1) !! + ONOFF_START, + ABBREVIATION_ON = ONOFF_START, // HTML 3.0 + ABBREVIATION_OFF, // HTML 3.0 + ACRONYM_ON, // HTML 3.0 + ACRONYM_OFF, // HTML 3.0 + ADDRESS_ON, + ADDRESS_OFF, + ANCHOR_ON, + ANCHOR_OFF, + APPLET_ON, // HotJava + APPLET_OFF, // HotJava + AUTHOR_ON, // HTML 3.0 + AUTHOR_OFF, // HTML 3.0 + BANNER_ON, // HTML 3.0 + BANNER_OFF, // HTML 3.0 + BASEFONT_ON, // Netscape + BASEFONT_OFF, // Netscape + BIGPRINT_ON, // HTML 3.0 + BIGPRINT_OFF, // HTML 3.0 + BLINK_ON, // Netscape + BLINK_OFF, // Netscape + BLOCKQUOTE30_ON, // HTML 3.0 + BLOCKQUOTE30_OFF, // HTML 3.0 + BLOCKQUOTE_ON, + BLOCKQUOTE_OFF, + BODY_ON, + BODY_OFF, + BOLD_ON, + BOLD_OFF, + CAPTION_ON, // HTML 3.0 + CAPTION_OFF, // HTML 3.0 + CENTER_ON, // Netscape + CENTER_OFF, // Netscape + CITATION_ON, + CITATION_OFF, + CODE_ON, + CODE_OFF, + COL_ON, // HTML3 Table Model Draft + COL_OFF, // HTML3 Table Model Draft + COLGROUP_ON, // HTML3 Table Model Draft + COLGROUP_OFF, // HTML3 Table Model Draft + CREDIT_ON, // HTML 3.0 + CREDIT_OFF, // HTML 3.0 + DD_ON, + DD_OFF, + DEFLIST_ON, + DEFLIST_OFF, + DELETEDTEXT_ON, // HTML 3.0 + DELETEDTEXT_OFF, // HTML 3.0 + DIRLIST_ON, + DIRLIST_OFF, + DIVISION_ON, // HTML 3.0 + DIVISION_OFF, // HTML 3.0 + DT_ON, + DT_OFF, + EMPHASIS_ON, + EMPHASIS_OFF, + FIGURE_ON, // HTML 3.0 + FIGURE_OFF, // HTML 3.0 + FONT_ON, // Netscape + FONT_OFF, // Netscape + FOOTNOTE_ON, // HTML 3.0 + FOOTNOTE_OFF, // HTML 3.0 + FORM_ON, + FORM_OFF, + FRAME_ON, // Netscape 2.0 + FRAME_OFF, // Netscape 2.0 + FRAMESET_ON, // Netscape 2.0 + FRAMESET_OFF, // Netscape 2.0 + HEAD1_ON, + HEAD1_OFF, + HEAD2_ON, + HEAD2_OFF, + HEAD3_ON, + HEAD3_OFF, + HEAD4_ON, + HEAD4_OFF, + HEAD5_ON, + HEAD5_OFF, + HEAD6_ON, + HEAD6_OFF, + HEAD_ON, + HEAD_OFF, + HTML_ON, + HTML_OFF, + IFRAME_ON, // IE 3.0b2 + IFRAME_OFF, // IE 3.0b2 + INSERTEDTEXT_ON, // HTML 3.0 + INSERTEDTEXT_OFF, // HTML 3.0 + ITALIC_ON, + ITALIC_OFF, + KEYBOARD_ON, + KEYBOARD_OFF, + LANGUAGE_ON, // HTML 3.0 + LANGUAGE_OFF, // HTML 3.0 + LISTHEADER_ON, // HTML 3.0 + LISTHEADER_OFF, // HTML 3.0 + LI_ON, + LI_OFF, + MAP_ON, // Netscape 2.0 + MAP_OFF, // Netscape 2.0 + MENULIST_ON, + MENULIST_OFF, + MULTICOL_ON, // Netscape 3.0b5 + MULTICOL_OFF, // Netscape 3.0b5 + NOBR_ON, // Netscape + NOBR_OFF, // Netscape + NOEMBED_ON, // Netscape 2.0 + NOEMBED_OFF, // Netscape 2.0 + NOFRAMES_ON, // Netscape 2.0 + NOFRAMES_OFF, // Netscape 2.0 + NOSCRIPT_ON, // Netscape 2.0 + NOSCRIPT_OFF, // Netscape 3.0 + NOTE_ON, // HTML 3.0 + NOTE_OFF, // HTML 3.0 + OBJECT_ON, // HotJava + OBJECT_OFF, // HotJava + ORDERLIST_ON, + ORDERLIST_OFF, + PARABREAK_ON, + PARABREAK_OFF, + PERSON_ON, // HTML 3.0 + PERSON_OFF, // HTML 3.0 + PLAINTEXT_ON, // HTML 3.0 + PLAINTEXT_OFF, // HTML 3.0 + PREFORMTXT_ON, + PREFORMTXT_OFF, + SAMPLE_ON, + SAMPLE_OFF, + SCRIPT_ON, // HTML 3.2 + SCRIPT_OFF, // HTML 3.2 + SELECT_ON, + SELECT_OFF, + SHORTQUOTE_ON, // HTML 3.0 + SHORTQUOTE_OFF, // HTML 3.0 + SMALLPRINT_ON, // HTML 3.0 + SMALLPRINT_OFF, // HTML 3.0 + SPAN_ON, // Style Sheets + SPAN_OFF, // Style Sheets + STRIKETHROUGH_ON, // HTML 3.0 + STRIKETHROUGH_OFF, // HTML 3.0 + STRONG_ON, + STRONG_OFF, + STYLE_ON, // HTML 3.0 + STYLE_OFF, // HTML 3.0 + SUBSCRIPT_ON, // HTML 3.0 + SUBSCRIPT_OFF, // HTML 3.0 + SUPERSCRIPT_ON, // HTML 3.0 + SUPERSCRIPT_OFF, // HTML 3.0 + TABLE_ON, // HTML 3.0 + TABLE_OFF, // HTML 3.0 + TABLEDATA_ON, // HTML 3.0 + TABLEDATA_OFF, // HTML 3.0 + TABLEHEADER_ON, // HTML 3.0 + TABLEHEADER_OFF, // HTML 3.0 + TABLEROW_ON, // HTML 3.0 + TABLEROW_OFF, // HTML 3.0 + TBODY_ON, // HTML3 Table Model Draft + TBODY_OFF, // HTML3 Table Model Draft + TELETYPE_ON, + TELETYPE_OFF, + TEXTAREA_ON, + TEXTAREA_OFF, + TFOOT_ON, // HTML3 Table Model Draft + TFOOT_OFF, // HTML3 Table Model Draft + THEAD_ON, // HTML3 Table Model Draft + THEAD_OFF, // HTML3 Table Model Draft + TITLE_ON, + TITLE_OFF, + UNDERLINE_ON, + UNDERLINE_OFF, + UNORDERLIST_ON, + UNORDERLIST_OFF, + VARIABLE_ON, + VARIABLE_OFF, + + // obsolete features + XMP_ON, + XMP_OFF, + LISTING_ON, + LISTING_OFF, + + // proposed features + DEFINSTANCE_ON, + DEFINSTANCE_OFF, + STRIKE_ON, + STRIKE_OFF, + + UNKNOWNCONTROL_ON, + UNKNOWNCONTROL_OFF, + + // Microsoft features + COMMENT2_ON, // HTML 2.0 ? + COMMENT2_OFF, // HTML 2.0 ? + MARQUEE_ON, + MARQUEE_OFF, + PLAINTEXT2_ON, // HTML 2.0 ? + PLAINTEXT2_OFF, // HTML 2.0 ? + + SDFIELD_ON, + SDFIELD_OFF +}; + +constexpr bool isOffToken(HtmlTokenId nToken) +{ + return (nToken == HtmlTokenId::NONE || nToken >= HtmlTokenId::ONOFF_START) + ? (1 & static_cast(nToken)) + : throw std::logic_error("Assertion failed!"); // C++11 does not do assert in constexpr +} + +constexpr HtmlTokenId getOnToken(HtmlTokenId nToken) +{ + return (nToken == HtmlTokenId::NONE || nToken >= HtmlTokenId::ONOFF_START) + ? HtmlTokenId(~1 & static_cast(nToken)) + : throw std::logic_error("Assertion failed!"); // C++11 does not do assert in constexpr +} + +// HTML attribute token (=Options) + +enum class HtmlOptionId +{ +// always starting from 256 on, greater than a char +BOOL_START = 0x100, + +// attributes without value + CHECKED = BOOL_START, + COMPACT, + DECLARE, // IExplorer 3.0b5 + DISABLED, + ISMAP, + MAYSCRIPT, // Netscape 3.0 + MULTIPLE, + NOHREF, // Netscape + NORESIZE, // Netscape 2.0 + NOSHADE, // Netscape + NOWRAP, + SDFIXED, + SELECTED, +BOOL_END, + +// attributes with a string as value +STRING_START = BOOL_END, + ACCEPT = STRING_START, + ACCESSKEY, + ALT, + AXIS, + CHAR, // HTML3 Table Model Draft + CHARSET, + CLASS, + CODE, // HotJava + CODETYPE, + CONTENT, + COORDS, // Netscape 2.0 + ENCTYPE, + FACE, // IExplorer 2.0 + FRAMEBORDER, // IExplorer 3.0 + HTTPEQUIV, + LANGUAGE, // JavaScript + NAME, + PROMPT, + SHAPE, + STANDBY, + STYLE, // Style Sheets + TITLE, + VALUE, + SDVAL, // StarDiv NumberValue + SDNUM, // StarDiv NumberFormat + SDLIBRARY, + SDMODULE, +STRING_END, + +// attributes with an SGML identifier as value +SGMLID_START = STRING_END, + ID = SGMLID_START, + TARGET, // Netscape 2.0 + TO, +SGMLID_END, + +// attributes with a URI as value +URI_START = SGMLID_END, + ACTION = URI_START, + ARCHIVE, + BACKGROUND, + CLASSID, + CODEBASE, // HotJava + DATA, + HREF, + SCRIPT, + SRC, + USEMAP, // Netscape 2.0 +URI_END, + +// attributes with a color as value (all Netscape) +COLOR_START = URI_END, + ALINK = COLOR_START, + BGCOLOR, + BORDERCOLOR, // IExplorer 2.0 + BORDERCOLORLIGHT, // IExplorer 2.0 + BORDERCOLORDARK, // IExplorer 2.0 + COLOR, + LINK, + TEXT, + VLINK, +COLOR_END, + +// attributes with a numeric value +NUMBER_START = COLOR_END, + BORDER = NUMBER_START, + CELLSPACING, // HTML3 Table Model Draft + CELLPADDING, // HTML3 Table Model Draft + CHAROFF, // HTML3 Table Model Draft + COLSPAN, + FRAMESPACING, // IExplorer 3.0 + GUTTER, // Netscape 3.0b5 + HEIGHT, + HSPACE, // Netscape + LEFT, + LOOP, // IExplorer 2.0 + MARGINWIDTH, // Netscape 2.0 + MARGINHEIGHT, // Netscape 2.0 + MAXLENGTH, + ROWSPAN, + SCROLLAMOUNT, // IExplorer 2.0 + SCROLLDELAY, // IExplorer 2.0 + SPAN, // HTML3 Table Model Draft + TABINDEX, + VSPACE, // Netscape + WIDTH, + ZINDEX, +NUMBER_END, + +// attributes with Enum values +ENUM_START = NUMBER_END, + BEHAVIOR = ENUM_START, // IExplorer 2.0 + CLEAR, + DIR, + DIRECTION, // IExplorer 2.0 + FORMAT, + FRAME, // HTML3 Table Model Draft + LANG, + METHOD, + REL, + REV, + RULES, // HTML3 Table Model Draft + SCROLLING, // Netscape 2.0 + SDREADONLY, + SUBTYPE, + TYPE, + VALIGN, + VALUETYPE, + WRAP, +ENUM_END, + +// attributes with script code as value +SCRIPT_START = ENUM_END, + ONABORT = SCRIPT_START, // JavaScript + ONBLUR, // JavaScript + ONCHANGE, // JavaScript + ONCLICK, // JavaScript + ONERROR, // JavaScript + ONFOCUS, // JavaScript + ONLOAD, // JavaScript + ONMOUSEOUT, // JavaScript + ONMOUSEOVER, // JavaScript + ONRESET, // JavaScript + ONSELECT, // JavaScript + ONSUBMIT, // JavaScript + ONUNLOAD, // JavaScript + + SDONABORT, // StarBasic + SDONBLUR, // StarBasic + SDONCHANGE, // StarBasic + SDONCLICK, // StarBasic + SDONERROR, // StarBasic + SDONFOCUS, // StarBasic + SDONLOAD, // StarBasic + SDONMOUSEOUT, // StarBasic + SDONMOUSEOVER, // StarBasic + SDONRESET, // StarBasic + SDONSELECT, // StarBasic + SDONSUBMIT, // StarBasic + SDONUNLOAD, // StarBasic +SCRIPT_END, + +// attributes with context dependent values +CONTEXT_START = SCRIPT_END, + ALIGN = CONTEXT_START, + COLS, // Netscape 2.0 vs HTML 2.0 + ROWS, // Netscape 2.0 vs HTML 2.0 + SIZE, + START, +CONTEXT_END, + +// an unknown option +UNKNOWN = CONTEXT_END, +END +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/imagemgr.hxx b/include/svtools/imagemgr.hxx new file mode 100644 index 000000000..a2b48247f --- /dev/null +++ b/include/svtools/imagemgr.hxx @@ -0,0 +1,137 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +enum class SvImageId { + NONE = 0, + START = 3076, // must match to old Id's in SFX! + + Impress = START + 47, + Bitmap = START + 49, + Calc = START + 50, + CalcTemplate = START + 51, + Database = START + 53, + ImpressTemplate = START + 54, + GIF = START + 61, + HTML = START + 63, + JPG = START + 64, + WEBP = START + 65, + Math = START + 68, + MathTemplate = START + 69, + File = START + 74, + PCD = START + 76, + PCT = START + 77, + PCX = START + 78, + SIM = START + 79, + TextFile = START + 80, + TIFF = START + 82, + WMF = START + 84, + Writer = START + 86, + WriterTemplate = START + 87, + FixedDevice = START + 88, + RemoveableDevice = START + 89, + CDRomDevice = START + 90, + NetworkDevice = START + 91, + Table = START + 112, + Folder = START + 113, + DXF = START + 141, + MET = START + 142, + PNG = START + 143, + //retired SGF = START + 144, + //retired SGV = START + 145, + SVM = START + 146, + GlobalDoc = START + 150, + Draw = START + 151, + DrawTemplate = START + 152, + OO_DatabaseDoc = START + 169, + OO_DrawDoc = START + 170, + OO_MathDoc = START + 171, + OO_GlobalDoc = START + 172, + OO_ImpressDoc = START + 173, + OO_CalcDoc = START + 174, + OO_WriterDoc = START + 175, + OO_DrawTemplate = START + 176, + OO_ImpressTemplate = START + 177, + OO_CalcTemplate = START + 178, + OO_WriterTemplate = START + 179, + Extension = START + 180, +}; + + +class Image; +class INetURLObject; + +namespace svtools { + +struct VolumeInfo +{ + bool m_bIsVolume; + bool m_bIsRemote; + bool m_bIsRemoveable; + bool m_bIsFloppy; + bool m_bIsCompactDisc; + + VolumeInfo() : + m_bIsVolume ( false ), + m_bIsRemote ( false ), + m_bIsRemoveable ( false ), + m_bIsFloppy ( false ), + m_bIsCompactDisc( false ) {} + + VolumeInfo( bool _bIsVolume, + bool _bIsRemote, + bool _bIsRemoveable, + bool _bIsFloppy, + bool _bIsCompactDisc ) : + m_bIsVolume ( _bIsVolume ), + m_bIsRemote ( _bIsRemote ), + m_bIsRemoveable ( _bIsRemoveable ), + m_bIsFloppy ( _bIsFloppy ), + m_bIsCompactDisc( _bIsCompactDisc ) {} +}; + +} + +class SvFileInformationManager +{ +private: + static OUString GetDescription_Impl( const INetURLObject& rObject, bool bDetectFolder ); + +public: + SVT_DLLPUBLIC static OUString GetImageId( const INetURLObject& rURL, bool bBig = false ); + SVT_DLLPUBLIC static Image GetImage( + const INetURLObject& rURL, bool bBig = false, + css::uno::Reference const & env + = utl::UCBContentHelper::getDefaultCommandEnvironment()); + SVT_DLLPUBLIC static OUString GetFileImageId( const INetURLObject& rURL ); + SVT_DLLPUBLIC static Image GetImageNoDefault(const INetURLObject& rURL, vcl::ImageType eImageType = vcl::ImageType::Small); + SVT_DLLPUBLIC static OUString GetFolderImageId( const svtools::VolumeInfo& rInfo ); + + SVT_DLLPUBLIC static OUString GetDescription( const INetURLObject& rObject ); + SVT_DLLPUBLIC static OUString GetFileDescription( const INetURLObject& rObject ); + SVT_DLLPUBLIC static OUString GetFolderDescription( const svtools::VolumeInfo& rInfo ); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/imageresourceaccess.hxx b/include/svtools/imageresourceaccess.hxx new file mode 100644 index 000000000..ca76c0909 --- /dev/null +++ b/include/svtools/imageresourceaccess.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include +#include + +#include +#include + +#include + +namespace com :: sun :: star :: io { class XInputStream; } +namespace com :: sun :: star :: uno { class XComponentContext; } + +class SvStream; + +namespace svt::GraphicAccess +{ + +/** Helpers for obtaining streams (which also can be used with the ImageProducer) + from a resource. +*/ + +/** determines whether the given URL denotes an image within a resource */ +UNLESS_MERGELIBS(SVT_DLLPUBLIC) bool isSupportedURL(std::u16string_view rURL); + +/** for a given URL of an image within a resource, this method retrieves an + SvStream for this image. + + This method works for arbitrary URLs denoting an image, since the + css::graphics::GraphicsProvider service is used + to resolve the URL. However, obtaining the stream is expensive (since + the image must be copied), so you are strongly encouraged to only use it + when you know that the image is small enough. +*/ +UNLESS_MERGELIBS(SVT_DLLPUBLIC) std::unique_ptr getImageStream( + css::uno::Reference const & rxContext, + OUString const & rImageResourceURL); + +/** for a given URL of an image within a resource, this method retrieves + a css::io::XInputStream for this image. +*/ +UNLESS_MERGELIBS(SVT_DLLPUBLIC) css::uno::Reference getImageXStream( + css::uno::Reference const & rxContext, + OUString const & rImageResourceURL); + +} // namespace svt::GraphicAccess + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/imgdef.hxx b/include/svtools/imgdef.hxx new file mode 100644 index 000000000..44212cc47 --- /dev/null +++ b/include/svtools/imgdef.hxx @@ -0,0 +1,30 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +enum SfxSymbolsSize +{ + SFX_SYMBOLS_SIZE_SMALL = 0, + SFX_SYMBOLS_SIZE_LARGE = 1, + SFX_SYMBOLS_SIZE_32 = 3, // keep the numbers as they are written into the profile + SFX_SYMBOLS_SIZE_AUTO = 2, +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/indexentryres.hxx b/include/svtools/indexentryres.hxx new file mode 100644 index 000000000..42e809ad8 --- /dev/null +++ b/include/svtools/indexentryres.hxx @@ -0,0 +1,54 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +class SVT_DLLPUBLIC IndexEntryResource +{ +private: + // wrapper for locale specific translations data of indexentry algorithm + class IndexEntryResourceData + { + friend class IndexEntryResource; + + private: + OUString m_aName; + OUString m_aTranslation; + + public: + IndexEntryResourceData(const OUString& rAlgorithm, const OUString& rTranslation) + : m_aName(rAlgorithm) + , m_aTranslation(rTranslation) + { + } + const OUString& GetAlgorithm() const { return m_aName; } + const OUString& GetTranslation() const { return m_aTranslation; } + }; + std::vector m_aData; + +public: + IndexEntryResource(); + const OUString& GetTranslation(const OUString& rAlgorithm); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/inettbc.hxx b/include/svtools/inettbc.hxx new file mode 100644 index 000000000..1789440f6 --- /dev/null +++ b/include/svtools/inettbc.hxx @@ -0,0 +1,107 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include + +class SvtMatchContext_Impl; +class SvtURLBox_Impl; + +class SVT_DLLPUBLIC SvtURLBox +{ + friend class SvtMatchContext_Impl; + friend class SvtURLBox_Impl; + + Idle aChangedIdle; + OUString aBaseURL; + OUString aPlaceHolder; + rtl::Reference pCtx; + std::unique_ptr pImpl; + INetProtocol eSmartProtocol; + bool bOnlyDirectories : 1; + bool bHistoryDisabled : 1; + bool bNoSelection : 1; + + Link aChangeHdl; + Link aFocusInHdl; + Link aFocusOutHdl; + + std::unique_ptr m_xWidget; + + DECL_DLLPRIVATE_LINK( TryAutoComplete, Timer*, void); + SVT_DLLPRIVATE void UpdatePicklistForSmartProtocol_Impl(); + DECL_DLLPRIVATE_LINK( ChangedHdl, weld::ComboBox&, void); + DECL_DLLPRIVATE_LINK( FocusInHdl, weld::Widget&, void); + DECL_DLLPRIVATE_LINK( FocusOutHdl, weld::Widget&, void); + SVT_DLLPRIVATE void Init(); + +public: + SvtURLBox(std::unique_ptr xWidget); + ~SvtURLBox(); + + void set_entry_text(const OUString& rStr) { m_xWidget->set_entry_text(rStr); } + void show() { m_xWidget->show(); } + void clear() { m_xWidget->clear(); } + void connect_entry_activate(const Link& rLink) { m_xWidget->connect_entry_activate(rLink); } + void connect_key_press(const Link& rLink) { m_xWidget->connect_key_press(rLink); } + void connect_changed(const Link& rLink) { aChangeHdl = rLink; } + void trigger_changed() { aChangeHdl.Call(*m_xWidget); } + void connect_focus_in(const Link& rLink) { aFocusInHdl = rLink; } + void connect_focus_out(const Link& rLink) { aFocusOutHdl = rLink; } + void append_text(const OUString& rStr) { m_xWidget->append_text(rStr); } + int find_text(const OUString& rStr) const { return m_xWidget->find_text(rStr); } + OUString get_active_text() const { return m_xWidget->get_active_text(); } + void grab_focus() { m_xWidget->grab_focus(); } + void set_sensitive(bool bSensitive) { m_xWidget->set_sensitive(bSensitive); } + void set_help_id(const OString& rHelpId) { m_xWidget->set_help_id(rHelpId); } + void select_entry_region(int nStartPos, int nEndPos) { m_xWidget->select_entry_region(nStartPos, nEndPos); } + Size get_preferred_size() const { return m_xWidget->get_preferred_size(); } + + void EnableAutocomplete(bool bEnable = true) { m_xWidget->set_entry_completion(bEnable); } + void SetBaseURL( const OUString& rURL ); + const OUString& GetBaseURL() const { return aBaseURL; } + void SetOnlyDirectories( bool bDir ); + void SetNoURLSelection( bool bSet ); + void SetSmartProtocol( INetProtocol eProt ); + INetProtocol GetSmartProtocol() const { return eSmartProtocol; } + OUString GetURL(); + void DisableHistory(); + + weld::ComboBox* getWidget() { return m_xWidget.get(); } + + static OUString ParseSmart( const OUString& aText, const OUString& aBaseURL ); + + void SetPlaceHolder(const OUString& sPlaceHolder) { aPlaceHolder = sPlaceHolder; } + const OUString& GetPlaceHolder() const { return aPlaceHolder; } + bool MatchesPlaceHolder(std::u16string_view sToMatch) const + { + return (!aPlaceHolder.isEmpty() && aPlaceHolder == sToMatch); + } + + void SetFilter(const OUString& _sFilter); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/insdlg.hxx b/include/svtools/insdlg.hxx new file mode 100644 index 000000000..826933bd3 --- /dev/null +++ b/include/svtools/insdlg.hxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +#include +#include + +class SvObjectServer +{ +private: + SvGlobalName aClassName; + OUString aHumanName; + +public: + SvObjectServer( const SvGlobalName & rClassP, const OUString & rHumanP ) : + aClassName( rClassP ), + aHumanName( rHumanP ) {} + + const SvGlobalName & GetClassName() const { return aClassName; } + const OUString & GetHumanName() const { return aHumanName; } +}; + +class SVT_DLLPUBLIC SvObjectServerList +{ +private: + std::vector< SvObjectServer > aObjectServerList; + +public: + const SvObjectServer * Get( std::u16string_view rHumanName ) const; + const SvObjectServer * Get( const SvGlobalName & ) const; + void Remove( const SvGlobalName & ); + void FillInsertObjects(); + size_t Count() const + { + return aObjectServerList.size(); + } + + const SvObjectServer& operator[]( size_t n ) const + { + return aObjectServerList[ n ]; + } +}; + +class SVT_DLLPUBLIC SvPasteObjectHelper +{ +public: + static OUString GetSotFormatUIName( SotClipboardFormatId nId ); + static bool GetEmbeddedName(const TransferableDataHelper& rData, OUString& _rName, OUString& _rSource, SotClipboardFormatId const & _nFormat); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/javacontext.hxx b/include/svtools/javacontext.hxx new file mode 100644 index 000000000..124b191fd --- /dev/null +++ b/include/svtools/javacontext.hxx @@ -0,0 +1,69 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include + +#include + + +namespace com :: sun :: star :: task { class XInteractionHandler; } + +namespace svt +{ +// We cannot derive from cppu::WeakImplHelper because we would export the inline +//generated class. This conflicts with other libraries if they use the same inline +//class. + class SVT_DLLPUBLIC JavaContext final : + public css::uno::XCurrentContext + { + + public: + /** A message box is + only displayed once for a recurring Java error. That is only + the first time JavaInteractionHandler.handle is called with a + particular Request then the message box is shown. Afterwards + nothing happens. + */ + JavaContext( const css::uno::Reference< css::uno::XCurrentContext> & ctx ); + virtual ~JavaContext(); + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( + const css::uno::Type& aType ) override; + + virtual void SAL_CALL acquire() noexcept override; + + virtual void SAL_CALL release() noexcept override; + + // XCurrentContext + virtual css::uno::Any SAL_CALL getValueByName( const OUString& Name ) override; + + private: + JavaContext(JavaContext const &) = delete; + JavaContext& operator = (JavaContext const &) = delete; + + oslInterlockedCount m_aRefCount; + css::uno::Reference< css::uno::XCurrentContext > m_xNextContext; + css::uno::Reference< css::task::XInteractionHandler> m_xHandler; + }; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/javainteractionhandler.hxx b/include/svtools/javainteractionhandler.hxx new file mode 100644 index 000000000..1abeb73a1 --- /dev/null +++ b/include/svtools/javainteractionhandler.hxx @@ -0,0 +1,62 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include + +namespace com :: sun :: star :: task { class XInteractionRequest; } + +inline constexpr OUStringLiteral JAVA_INTERACTION_HANDLER_NAME = u"java-vm.interaction-handler"; + +namespace svt +{ +// We cannot derive from cppu::WeakImplHelper because we would export the inline +//generated class. This conflicts with other libraries if they use the same inline +//class. + +class SVT_DLLPUBLIC JavaInteractionHandler final : + public css::task::XInteractionHandler +{ +public: + JavaInteractionHandler(); + + // XInterface + virtual css::uno::Any SAL_CALL queryInterface( + const css::uno::Type& aType ) override; + + virtual void SAL_CALL acquire() noexcept override; + + virtual void SAL_CALL release() noexcept override; + + // XCurrentContext + virtual void SAL_CALL handle( const css::uno::Reference< css::task::XInteractionRequest >& Request ) override; + +private: + oslInterlockedCount m_aRefCount; + JavaInteractionHandler(JavaInteractionHandler const&) = delete; + JavaInteractionHandler& operator = (JavaInteractionHandler const &) = delete; + SVT_DLLPRIVATE virtual ~JavaInteractionHandler(); +}; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/langhelp.hxx b/include/svtools/langhelp.hxx new file mode 100644 index 000000000..1aa8bcb72 --- /dev/null +++ b/include/svtools/langhelp.hxx @@ -0,0 +1,29 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +#include + +#include + +/** Localize a URI to one of the foundation's webservices + + @param io_rURI + URI to localize - depending on your UI locale, a country local + part is appended to the URI (like "en", or "fr", or "es") + */ +SVT_DLLPUBLIC void localizeWebserviceURI( OUString& io_rURI ); + +OUString SVT_DLLPUBLIC getInstalledLocaleForLanguage(css::uno::Sequence const & installed, OUString const & locale); +OUString SVT_DLLPUBLIC getInstalledLocaleForSystemUILanguage(css::uno::Sequence const & installed, bool bRequestInstallIfMissing, const OUString& rPreferredLocale = OUString()); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/langtab.hxx b/include/svtools/langtab.hxx new file mode 100644 index 000000000..2d71901c1 --- /dev/null +++ b/include/svtools/langtab.hxx @@ -0,0 +1,52 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include + +class LanguageTag; + +class SVT_DLLPUBLIC SvtLanguageTable +{ +public: + + static bool HasLanguageType( const LanguageType eType ); + /** Obtain the UI name for a LanguageType of a language/locale (string + resource STR_ARR_SVT_LANGUAGE_TABLE). + */ + static OUString GetLanguageString( const LanguageType eType ); + /** Obtain the LanguageType for a UI name of a language/locale (string + resource STR_ARR_SVT_LANGUAGE_TABLE). + */ + static LanguageType GetLanguageType( std::u16string_view rStr ); + static sal_uInt32 GetLanguageEntryCount(); + static LanguageType GetLanguageTypeAtIndex( sal_uInt32 nIndex ); + + /** Add a language tag to the table. + */ + static sal_uInt32 AddLanguageTag( const LanguageTag& rLanguageTag ); +}; + +// Add LRE or RLE embedding characters to the string based on the +// String content (see #i78466#, #i32179#) +SVT_DLLPUBLIC OUString ApplyLreOrRleEmbedding( const OUString &rText ); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/languagetoolcfg.hxx b/include/svtools/languagetoolcfg.hxx new file mode 100644 index 000000000..7578ad6ba --- /dev/null +++ b/include/svtools/languagetoolcfg.hxx @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once +#include +#include +#include + +using namespace utl; +using namespace com::sun::star::uno; + +struct LanguageToolOptions_Impl; + +class SVT_DLLPUBLIC SvxLanguageToolOptions final : public utl::ConfigItem +{ +public: + SvxLanguageToolOptions(); + virtual ~SvxLanguageToolOptions() override; + + virtual void Notify(const css::uno::Sequence& _rPropertyNames) override; + static SvxLanguageToolOptions& Get(); + + const OUString& getBaseURL() const; + void setBaseURL(const OUString& rVal); + + const OUString& getUsername() const; + void setUsername(const OUString& rVal); + + OUString getLocaleListURL() const; + OUString getCheckerURL() const; + + const OUString& getApiKey() const; + void setApiKey(const OUString& rVal); + + bool getEnabled() const; + void setEnabled(bool enabled); + +private: + std::unique_ptr pImpl; + void Load(const css::uno::Sequence& rPropertyNames); + virtual void ImplCommit() override; + static const Sequence& GetPropertyNames(); +}; diff --git a/include/svtools/miscopt.hxx b/include/svtools/miscopt.hxx new file mode 100644 index 000000000..190de033c --- /dev/null +++ b/include/svtools/miscopt.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#pragma once + +#include +#include +#include +#include +#include + +template class Link; +class LinkParamNone; + +/*-************************************************************************************************************ + @short forward declaration to our private date container implementation + @descr We use these class as internal member to support small memory requirements. + You can create the container if it is necessary. The class which use these mechanism + is faster and smaller then a complete implementation! +*//*-*************************************************************************************************************/ + +class SvtMiscOptions_Impl; +enum class ToolBoxButtonSize; + +/*-************************************************************************************************************ + @short collect information about misc group + @ATTENTION This class is partially threadsafe. + + @devstatus ready to use +*//*-*************************************************************************************************************/ + +class SVT_DLLPUBLIC SvtMiscOptions final : public utl::detail::Options +{ + public: + SvtMiscOptions(); + virtual ~SvtMiscOptions() override; + + void AddListenerLink( const Link& rLink ); + void RemoveListenerLink( const Link& rLink ); + + sal_Int16 GetSymbolsSize() const; + void SetSymbolsSize( sal_Int16 eSet ); + sal_Int16 GetCurrentSymbolsSize() const; + bool AreCurrentSymbolsLarge() const; + + OUString GetIconTheme() const; + void SetIconTheme(const OUString&); + bool IconThemeWasSetAutomatically() const; + + private: + std::shared_ptr m_pImpl; + +}; // class SvtMiscOptions + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/openfiledroptargetlistener.hxx b/include/svtools/openfiledroptargetlistener.hxx new file mode 100644 index 000000000..56f983e20 --- /dev/null +++ b/include/svtools/openfiledroptargetlistener.hxx @@ -0,0 +1,75 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include + +#include + +#include +#include + +#include + +namespace com :: sun :: star :: frame { class XFrame; } + +namespace com::sun::star::uno { + class XComponentContext; +} + +/** DropTargetListener that takes care of opening a file when it is dropped in the frame. +*/ +class UNLESS_MERGELIBS(SVT_DLLPUBLIC) OpenFileDropTargetListener final : public cppu::WeakImplHelper< css::datatransfer::dnd::XDropTargetListener > +{ + private: + /// uno service manager to create necessary services + css::uno::Reference< css::uno::XComponentContext > m_xContext; + + /// weakreference to target frame (Don't use a hard reference. Owner can't delete us then!) + css::uno::WeakReference< css::frame::XFrame > m_xTargetFrame; + + /// drag/drop info + DataFlavorExVector m_aFormats; + + public: + OpenFileDropTargetListener( const css::uno::Reference< css::uno::XComponentContext >& xContext, + const css::uno::Reference< css::frame::XFrame >& xFrame ); + virtual ~OpenFileDropTargetListener() override; + + public: + // XEventListener + virtual void SAL_CALL disposing ( const css::lang::EventObject& Source ) override; + + // XDropTargetListener + virtual void SAL_CALL drop ( const css::datatransfer::dnd::DropTargetDropEvent& dtde ) override; + virtual void SAL_CALL dragEnter ( const css::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) override; + virtual void SAL_CALL dragExit ( const css::datatransfer::dnd::DropTargetEvent& dte ) override; + virtual void SAL_CALL dragOver ( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) override; + virtual void SAL_CALL dropActionChanged( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) override; + + private: + void implts_BeginDrag( const css::uno::Sequence< css::datatransfer::DataFlavor >& rSupportedDataFlavors ); + void implts_EndDrag(); + bool implts_IsDropFormatSupported( SotClipboardFormatId nFormat ); + void implts_OpenFile( const OUString& rFilePath ); +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/optionsdrawinglayer.hxx b/include/svtools/optionsdrawinglayer.hxx new file mode 100644 index 000000000..5d6316aa3 --- /dev/null +++ b/include/svtools/optionsdrawinglayer.hxx @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +namespace SvtOptionsDrawinglayer +{ + +/*-**************************************************************************************************** + @short interface methods to get and set value of config key "org.openoffice.Office.Common/Drawinglayer/..." + @descr These options describe internal states to enable/disable features of installed office. + + IsOverlayBuffer() + SetOverlayBuffer() => Activate this field for letting Overlay use a buffer + + IsPaintBuffer() + SetPaintBuffer() => Activate this field for letting Paint use a prerender buffer + + GetStripeColorA() + SetStripeColorA() => Set first of two colors which overlay uses to draw stripes + + GetStripeColorB() + SetStripeColorB() => Set second of two colors which overlay uses to draw stripes + + GetStripeLength() + SetStripeLength() => Set length of a single stripe in pixels + + @seealso configuration package "org.openoffice.Office.Common/Drawinglayer" +*//*-*****************************************************************************************************/ + +SVT_DLLPUBLIC bool IsOverlayBuffer(); +SVT_DLLPUBLIC bool IsPaintBuffer(); +SVT_DLLPUBLIC Color GetStripeColorA(); +SVT_DLLPUBLIC Color GetStripeColorB(); +SVT_DLLPUBLIC sal_uInt16 GetStripeLength(); + +// #i73602# +SVT_DLLPUBLIC bool IsOverlayBuffer_Calc(); +SVT_DLLPUBLIC bool IsOverlayBuffer_Writer(); +SVT_DLLPUBLIC bool IsOverlayBuffer_DrawImpress(); + +// #i74769#, #i75172# +SVT_DLLPUBLIC bool IsPaintBuffer_Calc(); +SVT_DLLPUBLIC bool IsPaintBuffer_Writer(); +SVT_DLLPUBLIC bool IsPaintBuffer_DrawImpress(); + +// #i4219# +SVT_DLLPUBLIC sal_uInt32 GetMaximumPaperWidth(); +SVT_DLLPUBLIC sal_uInt32 GetMaximumPaperHeight(); +SVT_DLLPUBLIC sal_uInt32 GetMaximumPaperLeftMargin(); +SVT_DLLPUBLIC sal_uInt32 GetMaximumPaperRightMargin(); +SVT_DLLPUBLIC sal_uInt32 GetMaximumPaperTopMargin(); +SVT_DLLPUBLIC sal_uInt32 GetMaximumPaperBottomMargin(); + +// #i95644# helper to check if AA is allowed on this system. Currently, for WIN it's disabled +// and OutDevSupportType::TransparentRect is checked (this hits XRenderExtension, e.g. +// currently for SunRay as long as not supported there) +SVT_DLLPUBLIC bool IsAAPossibleOnThisSystem(); + +// primitives +SVT_DLLPUBLIC bool IsAntiAliasing(); +SVT_DLLPUBLIC bool IsSnapHorVerLinesToDiscrete(); +SVT_DLLPUBLIC bool IsSolidDragCreate(); +SVT_DLLPUBLIC bool IsRenderDecoratedTextDirect(); +SVT_DLLPUBLIC bool IsRenderSimpleTextDirect(); +SVT_DLLPUBLIC sal_uInt32 GetQuadratic3DRenderLimit(); +SVT_DLLPUBLIC sal_uInt32 GetQuadraticFormControlRenderLimit(); + +SVT_DLLPUBLIC void SetAntiAliasing( bool bOn, bool bTemporary ); + +// #i97672# selection settings +SVT_DLLPUBLIC bool IsTransparentSelection(); +SVT_DLLPUBLIC sal_uInt16 GetTransparentSelectionPercent(); +SVT_DLLPUBLIC sal_uInt16 GetSelectionMaximumLuminancePercent(); + +// get system highlight color, limited to the maximum allowed luminance +// (defined in GetSelectionMaximumLuminancePercent() in SvtOptionsDrawinglayer, +// combined with Application::GetSettings().GetStyleSettings().GetHighlightColor()) +SVT_DLLPUBLIC Color getHilightColor(); + +} // namespace SvtOptionsDrawinglayer + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/include/svtools/parhtml.hxx b/include/svtools/parhtml.hxx new file mode 100644 index 000000000..d05a9e36c --- /dev/null +++ b/include/svtools/parhtml.hxx @@ -0,0 +1,293 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include +#include +#include + +#include +#include + +namespace com :: sun :: star :: uno { template class Reference; } + +namespace com::sun::star { + namespace document { + class XDocumentProperties; + } +} + +class Color; +enum class HtmlOptionId; + +#define HTMLFONTSZ1_DFLT 7 +#define HTMLFONTSZ2_DFLT 10 +#define HTMLFONTSZ3_DFLT 12 +#define HTMLFONTSZ4_DFLT 14 +#define HTMLFONTSZ5_DFLT 18 +#define HTMLFONTSZ6_DFLT 24 +#define HTMLFONTSZ7_DFLT 36 + +enum class HTMLTableFrame { Void, Above, Below, HSides, LHS, RHS, VSides, Box }; + +enum class HTMLTableRules { NONE, Groups, Rows, Cols, All }; + +enum class HTMLInputType +{ + Text = 1, + Password, + Checkbox, + Radio, + Range, + Scribble, + File, + Hidden, + Submit, + Image, + Reset, + Button +}; + +enum class HTMLScriptLanguage +{ + StarBasic, + JavaScript, + Unknown +}; + +template +struct HTMLOptionEnum +{ + const char *pName; // value of an HTML option + EnumT nValue; // and corresponding value of an enum +}; + +/** Representation of an HTML option (=attribute in a start tag). + * The values of the options are always stored as strings. + * The methods GetNumber,... may only be called if the option + * is actually numerical,... + */ +class SVT_DLLPUBLIC HTMLOption +{ + OUString aValue; // value of the option (always as string) + OUString aToken; // name of the option as string + HtmlOptionId nToken; // and respective token + +public: + + HTMLOption( HtmlOptionId nTyp, const OUString& rToken, const OUString& rValue ); + + // name of the option... + HtmlOptionId GetToken() const { return nToken; } // ... as enum + const OUString& GetTokenString() const { return aToken; } // ... as string + + // value of the option ... + const OUString& GetString() const { return aValue; } // ... as string + + sal_uInt32 GetNumber() const; // ... as number + sal_Int32 GetSNumber() const; // ... as number + void GetNumbers( std::vector &rNumbers ) const; // ... as numbers + void GetColor( Color& ) const; // ... as color + + template + EnumT GetEnum( const HTMLOptionEnum *pOptEnums, + EnumT nDflt = static_cast(0) ) const + { + while( pOptEnums->pName ) + { + if( aValue.equalsIgnoreAsciiCaseAscii( pOptEnums->pName ) ) + return pOptEnums->nValue; + pOptEnums++; + } + return nDflt; + } + + template + bool GetEnum( EnumT &rEnum, const HTMLOptionEnum *pOptEnums ) const + { + while( pOptEnums->pName ) + { + if( aValue.equalsIgnoreAsciiCaseAscii( pOptEnums->pName ) ) + { + rEnum = pOptEnums->nValue; + return true; + } + pOptEnums++; + } + return false; + } + + // ... and as a few special enums + HTMLInputType GetInputType() const; // + HTMLTableFrame GetTableFrame() const; // + HTMLTableRules GetTableRules() const; //
    + //SvxAdjust GetAdjust() const; // +}; + +typedef ::std::vector HTMLOptions; + +class SVT_DLLPUBLIC HTMLParser : public SvParser +{ +private: + mutable HTMLOptions maOptions; // options of the start tag + + bool bNewDoc : 1; // read new Doc? + bool bIsInHeader : 1; // scan header section + bool bReadListing : 1; // read listings + bool bReadXMP : 1; // read XMP + bool bReadPRE : 1; // read preformatted text + bool bReadTextArea : 1; // read TEXTAREA + bool bReadScript : 1; // read or + + bool bPre_IgnoreNewPara : 1; // flags for reading of PRE paragraphs + bool bReadNextChar : 1; // true: read NextChar again(JavaScript!) + bool bReadComment : 1; // true: read NextChar again (JavaScript!) + + sal_uInt32 nPre_LinePos; // Pos in the line in the PRE-Tag + + HtmlTokenId mnPendingOffToken; ///< OFF token pending for a ON/OFF ON token + + OUString aEndToken; + + /// XML namespace, in case of XHTML. + OUString maNamespace; + +protected: + OUString sSaveToken; // the read tag as string + + HtmlTokenId ScanText( const sal_Unicode cBreak = 0U ); + + HtmlTokenId GetNextRawToken(); + + // scan next token + virtual HtmlTokenId GetNextToken_() override; + + virtual ~HTMLParser() override; + + void FinishHeader() { bIsInHeader = false; } + + void SetNamespace(std::u16string_view rNamespace); + +public: + HTMLParser( SvStream& rIn, bool bReadNewDoc = true ); + + virtual SvParserState CallParser() override; + + bool IsNewDoc() const { return bNewDoc; } + bool IsInHeader() const { return bIsInHeader; } + bool IsReadListing() const { return bReadListing; } + bool IsReadXMP() const { return bReadXMP; } + bool IsReadPRE() const { return bReadPRE; } + bool IsReadScript() const { return bReadScript; } + bool IsReadStyle() const { return bReadStyle; } + + // start PRE-/LISTING or XMP mode or filter tags respectively + inline void StartPRE(); + void FinishPRE() { bReadPRE = false; } + HtmlTokenId FilterPRE( HtmlTokenId nToken ); + + inline void StartListing(); + void FinishListing() { bReadListing = false; } + HtmlTokenId FilterListing( HtmlTokenId nToken ); + + inline void StartXMP(); + void FinishXMP() { bReadXMP = false; } + HtmlTokenId FilterXMP( HtmlTokenId nToken ); + + void FinishTextArea() { bReadTextArea = false; } + + // finish PRE-/LISTING- and XMP mode + void FinishPREListingXMP() { bReadPRE = bReadListing = bReadXMP = false; } + + // Filter the current token according to the current mode + // (PRE, XMP, ...) and set the flags. Is called by Continue before + // NextToken is called. If you implement own loops or call + // NextToken yourself, you should call this method beforehand. + HtmlTokenId FilterToken( HtmlTokenId nToken ); + + void ReadRawData( const OUString &rEndToken ) { aEndToken = rEndToken; } + + // Token without \-sequences + void UnescapeToken(); + + // Determine the options. pNoConvertToken is the optional token + // of an option, for which the CR/LFs are not deleted from the value + // of the option. + const HTMLOptions& GetOptions( HtmlOptionId const *pNoConvertToken=nullptr ); + + // for asynchronous reading from the SvStream + virtual void Continue( HtmlTokenId nToken ) override; + + +protected: + + static rtl_TextEncoding GetEncodingByMIME( const OUString& rMime ); + + /// template method: called when ParseMetaOptions adds a user-defined meta + virtual void AddMetaUserDefined( OUString const & i_rMetaName ); + +private: + /// parse meta options into XDocumentProperties and encoding + bool ParseMetaOptionsImpl( const css::uno::Reference< css::document::XDocumentProperties>&, + SvKeyValueIterator*, + const HTMLOptions&, + rtl_TextEncoding& rEnc ); + +public: + /// overriding method must call this implementation! + virtual bool ParseMetaOptions( const css::uno::Reference< css::document::XDocumentProperties>&, + SvKeyValueIterator* ); + + void ParseScriptOptions( OUString& rLangString, std::u16string_view rBaseURL, HTMLScriptLanguage& rLang, + OUString& rSrc, OUString& rLibrary, OUString& rModule ); + + // Remove a comment around the content of